diff --git a/README.md b/README.md index 0633b90..82badf3 100644 --- a/README.md +++ b/README.md @@ -72,10 +72,24 @@ 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. + +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 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. +Standard choices also cover where maps run (`map-strategy`: Logic App XSLT, a local function, or a separate Azure Functions project) and how workflows are split (`workflow-topology`: one workflow per orchestration, or receiver, processor, and sender workflows connected through Service Bus topics). To reuse answers across flows, choose **Apply to All Flows** after answering a question, or set `logicAppsMigrationAgent.planning.defaultChoices` (for example `{"messaging": "azure-service-bus", "map-strategy": "azure-function", "workflow-topology": "receiver-processor-sender"}`); matching questions are then answered from settings without prompting, while explicit requests to change choices still ask. + The planner generates **one selected scenario**, not several complete alternatives. It records short option tradeoffs and evidenced modernization opportunities, such as XML parsing with schemas, SQL stored-procedure actions, secret-store adoption, or telemetry modernization. Trigger/broker changes require contract and delivery-semantics checks; a queue behind an HTTP endpoint is not automatically a reason to replace the HTTP trigger. Connector availability and authentication are checked for the selected host. The Planning view keeps a concise decision summary and modernization table in the **Summary** section at the bottom of the overview. Expand **Planning details** for timelines, assumptions, alternatives, and rationale. **Regenerate Plan** reuses choices and preserves history; use **Suggest a Change** to request different choices. The view always displays the current plan used by Conversion, without a saved-version comparison table. DOCX reports include the current plan and saved scenario comparison for stakeholder review. @@ -97,6 +111,19 @@ are likewise evidence-based; the exporter does not infer them or calculate a new complexity score. Planning reports, other source-platform reports, and the interactive tabs retain their existing formats. +Use **Export requirements.md** in the Planning tab to save the finalized plan as a +Markdown `requirements.md` for skill-based build pipelines: decisions, target +architecture and per-workflow Mermaid diagrams, mapping and disposition tables, and +acceptance criteria derived only from the plan. + +### Conversion output + +Each converted flow is generated under `out//` and includes: + +- **Re-runnable tests** in `Tests/`: Logic Apps Standard workflow unit tests with mocked triggers and connectors, map regression tests (the converted XSLT stays the reference when maps move to functions), and schema validation tests. They run with `dotnet test` and need no Azure resources. +- **`TRACEABILITY.md`**, which maps every source artifact to the tasks that implement it and the files they generated. Task cards in the Conversion view also list their source artifacts. +- **Infrastructure templates** in `infra/` when `logicAppsMigrationAgent.azure.provisioningMode` is `offline`. In that mode conversion never signs in to Azure; it tests locally with Azurite and Docker emulators (including the Service Bus emulator) and mocked unit tests. + ## Requirements | Requirement | Purpose | @@ -116,9 +143,12 @@ Configure via `Settings > Extensions > Logic Apps Migration Agent`: | Setting | Description | Default | | -------------------------------------------------- | ------------------------------------------------- | ------------------------------------ | | `logicAppsMigrationAgent.deploymentModel` | Target deployment model for Logic Apps Standard | `workflow-service-plan` | +| `logicAppsMigrationAgent.planning.defaultChoices` | Workspace-wide planning answers (question ID → option ID) applied to every flow; hosting still comes from `deploymentModel` | `{}` | | `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.azure.provisioningMode` | `provision` lets conversion create test resources without a local alternative; `offline` never signs in to Azure and generates Bicep plus local/mocked tests instead | `provision` | +| `logicAppsMigrationAgent.discovery.groupingMode` | How logical groups are detected: `auto` (deterministic for BizTalk), `deterministic`, or `copilot` | `auto` | ## Command Palette @@ -127,6 +157,8 @@ 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 | +| `Logic Apps Migration Agent: Export Logical Group Inventory` | Save a Markdown map of every logical group with its ports and artifacts | ## Architecture @@ -164,9 +196,19 @@ The extension provisions three GitHub Copilot agents into your workspace: | `@migration-planner` | Creates per-flow migration plans with action mappings and gap analysis | | `@migration-converter` | Executes conversion tasks to generate Logic Apps workflows and connections | +### Team standards and skill customization + +The agents follow skills provisioned into `.github/skills//SKILL.md`. The extension owns those files and updates them with new versions. To add your team's rules without losing them on updates: + +- Put rules for one skill in `.github/skills//CUSTOM.md`. They are appended to that skill as a **Customer Overrides** section, which wins when it conflicts with the rest of the skill. +- Put cross-cutting standards (target architecture, naming, broker topics, test conventions) in `.github/skills/customer-standards/SKILL.md`. The agents read it before every other skill. +- If you edited a provisioned `SKILL.md` directly, the next update saves your version as `SKILL.md.bak` and tells you which skills to move into `CUSTOM.md`. + +To keep prompts small, the agents look up component mappings with the `migration_lookupMapping` tool instead of loading the whole `source-to-logic-apps-mapping` skill. Small flows without custom code also skip decompilation and broad reference-doc searches. + ### LM Tools -The extension registers **25 Language Model tools** with VS Code that the AI agents use to read artifacts, store results, and manage the migration workflow. +The extension registers **34 Language Model tools** with VS Code that the AI agents use to read artifacts, look up mappings, store results, and manage the migration workflow. ## Source Flow Visualization @@ -352,7 +394,9 @@ description: One-to-one mapping of every YourPlatform component to its Azure Log Create a `/SKILL.md` variant for each platform-specific skill. The MSMQ and SOAP built-in connector skills are shared fallbacks and apply whenever a -platform maps a source component to those connectors. +platform maps a source component to those connectors. The shared +`automated-test-generation` skill applies to every platform; add a +`/SKILL.md` variant only when your platform needs different test rules. | Skill | Purpose | Agent | | --------------------------------------- | --------------------------------------------------------------------- | ---------------------- | @@ -371,6 +415,7 @@ platform maps a source component to those connectors. | `dotnet-local-functions-logic-apps` | Rules for generating .NET local functions | `@migration-converter` | | `no-stubs-code-generation` | Rules ensuring generated code is complete (no stubs/placeholders) | `@migration-converter` | | `runtime-validation-and-testing` | Rules for runtime validation and testing | `@migration-converter` | +| `automated-test-generation` | Shared rules for re-runnable workflow unit, map and schema tests | `@migration-converter` | | `cloud-deployment-and-testing` | Rules for cloud deployment and testing | `@migration-converter` | **Tip**: Copy an existing platform's skills as a starting point (e.g., `biztalk/SKILL.md`) and adapt the content for your platform. diff --git a/package-lock.json b/package-lock.json index 1b2b2ad..5a08ce9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "logicapps-migration-agent", - "version": "1.18.1", + "version": "1.19.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "logicapps-migration-agent", - "version": "1.18.1", + "version": "1.19.0", "license": "MIT", "dependencies": { "@azure/arm-logic": "^8.2.0", diff --git a/package.json b/package.json index 7dbe333..ad5ffe9 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "logicapps-migration-agent", "displayName": "Logic Apps Migration Agent", "description": "Migrate BizTalk, MuleSoft, and other integration platforms to Azure Logic Apps Standard with AI-powered agent", - "version": "1.18.1", + "version": "1.19.0", "aiKey": "setInGitHubBuild", "publisher": "ms-azuretools", "license": "MIT", @@ -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" @@ -924,6 +938,30 @@ ] } }, + { + "name": "migration_lookupMapping", + "displayName": "Look Up Logic Apps Mapping", + "toolReferenceName": "migration_lookupMapping", + "canBeReferencedInPrompt": true, + "modelDescription": "Look up how specific source components map to Azure Logic Apps Standard (connector, built-in action, service provider ID, operation, notes) without loading the whole source-to-logic-apps-mapping skill. Pass the components as a comma-separated query (adapter, pipeline component, orchestration shape, functoid, connector or protocol names, e.g. 'FILE, WCF-SQL, XMLReceive, Construct Message'). Returns the matching table rows and rules with their section and column headers. Read the full skill only when a lookup finds nothing relevant.", + "userDescription": "Look up Logic Apps equivalents for source components", + "inputSchema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Comma-separated component, adapter, shape or connector names to look up" + }, + "maxResults": { + "type": "number", + "description": "Maximum number of matching rows to return (default 25, max 60)" + } + }, + "required": [ + "query" + ] + } + }, { "name": "migration_searchReferenceWorkflows", "displayName": "Search Reference Workflows", @@ -996,7 +1034,10 @@ }, "action": { "type": "string", - "enum": ["read", "resolve"] + "enum": [ + "read", + "resolve" + ] }, "reconsider": { "type": "boolean", @@ -1004,7 +1045,11 @@ }, "deploymentTarget": { "type": "string", - "enum": ["workflow-service-plan", "hybrid", "ase-v3"], + "enum": [ + "workflow-service-plan", + "hybrid", + "ase-v3" + ], "description": "Only a hosting target explicitly supplied by the user in their request. Saves that answer without asking again. Never infer from source or use a default." }, "questions": { @@ -1042,23 +1087,40 @@ "items": { "type": "object", "properties": { - "id": { "type": "string" }, - "label": { "type": "string", "maxLength": 80 }, + "id": { + "type": "string" + }, + "label": { + "type": "string", + "maxLength": 80 + }, "description": { "type": "string", "maxLength": 240, "description": "Brief benefit/tradeoff and target support caveat" } }, - "required": ["id", "label", "description"] + "required": [ + "id", + "label", + "description" + ] } } }, - "required": ["id", "question", "whyItMatters", "options"] + "required": [ + "id", + "question", + "whyItMatters", + "options" + ] } } }, - "required": ["flowId", "action"] + "required": [ + "flowId", + "action" + ] } }, { @@ -1094,36 +1156,73 @@ "brief": { "type": "object", "properties": { - "scenarioName": { "type": "string" }, + "scenarioName": { + "type": "string" + }, "estimatedTimeline": { "type": "string", "description": "Indicative elapsed timeline and capacity basis, or Not estimated; do not invent precision" }, - "assumptions": { "type": "array", "items": { "type": "string" } }, - "tradeoffs": { "type": "array", "items": { "type": "string" } }, + "assumptions": { + "type": "array", + "items": { + "type": "string" + } + }, + "tradeoffs": { + "type": "array", + "items": { + "type": "string" + } + }, "opportunities": { "type": "array", "items": { "type": "object", "properties": { - "component": { "type": "string" }, - "currentApproach": { "type": "string" }, - "proposedApproach": { "type": "string" }, + "component": { + "type": "string" + }, + "currentApproach": { + "type": "string" + }, + "proposedApproach": { + "type": "string" + }, "disposition": { "type": "string", - "enum": ["applied", "retained", "deferred"] + "enum": [ + "applied", + "retained", + "deferred" + ] + }, + "reason": { + "type": "string" }, - "reason": { "type": "string" }, "evidence": { "type": "string", "description": "Artifact/method/configuration reference and capability validation; no secret values" } }, - "required": ["component", "currentApproach", "proposedApproach", "disposition", "reason", "evidence"] + "required": [ + "component", + "currentApproach", + "proposedApproach", + "disposition", + "reason", + "evidence" + ] } } }, - "required": ["scenarioName", "estimatedTimeline", "assumptions", "tradeoffs", "opportunities"] + "required": [ + "scenarioName", + "estimatedTimeline", + "assumptions", + "tradeoffs", + "opportunities" + ] } }, "required": [ @@ -1559,7 +1658,7 @@ "displayName": "Store Conversion Task Plan", "toolReferenceName": "migration_conversion_storeTaskPlan", "canBeReferencedInPrompt": true, - "modelDescription": "Store the ordered conversion task plan for a flow. The task plan is determined by the agent based on the specific flow's planning results — there is no fixed list of task types. Each task has: id (unique string), type (short label like 'create-integration-account', 'convert-schemas', 'generate-workflow'), name (human-readable), description (short UI card text), executionPrompt (detailed agent instructions for execution), dependsOn (array of prerequisite task IDs), order (1-based execution sequence), and optionally estimatedMinutes and artifactIds. Tasks are displayed in the Conversion webview as an ordered checklist.", + "modelDescription": "Store the ordered conversion task plan for a flow. The task plan is determined by the agent based on the specific flow's planning results — there is no fixed list of task types. Each task has: id (unique string), type (short label like 'create-integration-account', 'convert-schemas', 'generate-workflow', 'generate-tests'), name (human-readable), description (short UI card text), executionPrompt (detailed agent instructions for execution), dependsOn (array of prerequisite task IDs), order (1-based execution sequence), artifactIds (IDs of the source artifacts the task converts or implements — required for schema, map, function, workflow and test tasks; shown to users for traceability), and optionally estimatedMinutes. Unknown artifact IDs are rejected; flow artifacts that no task lists are reported back. Tasks are displayed in the Conversion webview as an ordered checklist.", "userDescription": "Store the conversion task plan for a flow", "inputSchema": { "type": "object", @@ -1624,7 +1723,7 @@ "items": { "type": "string" }, - "description": "Optional artifact IDs this task operates on" + "description": "IDs of the source artifacts this task converts or implements (required for schema, map, function, workflow and test tasks)" }, "estimatedMinutes": { "type": "number", @@ -1776,6 +1875,17 @@ "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.exportFlowGroupInventory", + "title": "Export Logical Group Inventory", + "category": "Logic Apps Migration Agent" + }, { "command": "logicAppsMigrationAgent.openPlanningView", "title": "Open Planning View", @@ -1824,6 +1934,12 @@ "title": "Export Planning Report", "category": "Logic Apps Migration Agent", "icon": "$(file-text)" + }, + { + "command": "logicAppsMigrationAgent.exportPlanMarkdown", + "title": "Export Planning Requirements (Markdown)", + "category": "Logic Apps Migration Agent", + "icon": "$(markdown)" } ], "viewsContainers": { @@ -1932,6 +2048,10 @@ { "command": "logicAppsMigrationAgent.exportPlanReport", "when": "false" + }, + { + "command": "logicAppsMigrationAgent.exportPlanMarkdown", + "when": "false" } ] }, @@ -1953,6 +2073,14 @@ "default": "workflow-service-plan", "markdownDescription": "Target platform deployment model for Logic Apps Standard" }, + "logicAppsMigrationAgent.planning.defaultChoices": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "default": {}, + "markdownDescription": "Workspace-wide answers to planning questions, as a map of question ID to option ID, for example `{\"messaging\": \"azure-service-bus\", \"map-strategy\": \"azure-function\", \"workflow-topology\": \"receiver-processor-sender\"}`. When the planner asks a question with that ID and the option ID is one of the offered options, the answer is applied to every flow without prompting; answers already chosen for a flow are kept. Hosting still comes from `#logicAppsMigrationAgent.deploymentModel#`. Explicit requests to change planning choices still ask." + }, "logicAppsMigrationAgent.azure.subscriptionId": { "type": "string", "default": "", @@ -1967,6 +2095,34 @@ "type": "string", "default": "eastus", "description": "Azure region for provisioning resources" + }, + "logicAppsMigrationAgent.azure.provisioningMode": { + "type": "string", + "enum": [ + "provision", + "offline" + ], + "enumDescriptions": [ + "Conversion may create test resources without a local alternative (for example an Integration Account) in the configured resource group", + "Never sign in to Azure or create resources: generate Bicep for required resources and test locally with emulators and mocked unit tests" + ], + "default": "provision", + "markdownDescription": "Whether conversion may create Azure test resources. Use `offline` when you have no access to create resources in a subscription; the generated project still contains infrastructure templates and runnable tests." + }, + "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..3bdf25a 100644 --- a/resources/agents/migration-analyser.md +++ b/resources/agents/migration-analyser.md @@ -19,6 +19,7 @@ You are a **Migration Analyser** — an expert in integration platform architect | `#migration_searchArtifacts` | Search artifacts by name, schema, or namespace | | `#migration_getMigrationContext` | Get current migration state, platform info, and stage | | `#migration_readReferenceDoc` | Read/search Logic Apps Standard reference docs | +| `#migration_lookupMapping` | Look up the Logic Apps equivalents of specific components in `source-to-logic-apps-mapping` | | `#migration_discovery_storeFlowGroups` | Store detected flow groups and show the flow selector in the webview | | `#migration_discovery_storeMeta` | Store explanation, summary, title, and notes for a flow | | `#migration_discovery_storeArchitecture` | Store the Mermaid architecture diagram for a flow | @@ -35,6 +36,8 @@ You are a **Migration Analyser** — an expert in integration platform architect **Skill location:** All skills are at `.github/skills/{skill-name}/SKILL.md` in the current workspace. Always read from this path — never from extension resources or external locations. +**Team standards:** if `.github/skills/customer-standards/SKILL.md` exists, read it before any other skill — its rules override the other skills. A skill's "Customer Overrides" section (maintained in that skill's `CUSTOM.md`) overrides the rest of that skill. + **Workspace boundary:** ALL file operations (decompilation output, scaffolding, reading/writing) MUST happen within the current migration workspace directory. NEVER read from, write to, or access `out/` folders in source folders, extracted MSI folders, or any other external location. | Skill | When to read | @@ -42,7 +45,7 @@ You are a **Migration Analyser** — an expert in integration platform architect | `detect-logical-groups` | Before detecting flow groups — contains grouping strategy, fallback rules, required output fields | | `analyse-source-design` | Before analysing a flow - contains source reading depth, architecture diagram rules, component analysis priorities, and result storage sequence | | `dependency-and-decompilation-analysis` | Before/during analysis — contains DLL decompilation procedure, source-vs-decompiled precedence, missing dependency classification | -| `source-to-logic-apps-mapping` | Before determining `azureEquivalent` for any component — contains 170+ one-to-one mappings with service provider IDs and operation names | +| `source-to-logic-apps-mapping` | Before determining `azureEquivalent` for any component — look up components with `#migration_lookupMapping`; read the full skill (170+ mappings) only when a lookup finds nothing | | `msmq-built-in-connector` | When the source uses MSMQ or NetMsmq — contains broker topology, networking, delivery, and queue constraints | | `soap-built-in-connector` | When the source uses SOAP or compatible WCF web services — contains WSDL, authentication, and compatibility rules | @@ -52,16 +55,16 @@ 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. +4. Look up every component with `#migration_lookupMapping` (skill `source-to-logic-apps-mapping`), then search reference docs. Follow the applicable skills to record source evidence, mapping decisions, and unresolved requirements. 5. Generate Mermaid architecture diagram per skill `analyse-source-design` §3. 6. Store results in the exact order per skill `analyse-source-design` §5 (storeMeta → storeArchitecture → storeComponents → storeMessageFlow → storeGaps → storePatterns → storeDependencies → finalize). diff --git a/resources/agents/migration-converter.md b/resources/agents/migration-converter.md index 4d29605..fb8b0d4 100644 --- a/resources/agents/migration-converter.md +++ b/resources/agents/migration-converter.md @@ -20,6 +20,7 @@ You are a **Migration Converter** — an expert in converting integration flows | `#migration_readSourceFile` | Read raw source file contents | | `#migration_searchArtifacts` | Search artifacts by name, schema, endpoint | | `#migration_readReferenceDoc` | Read/search Logic Apps Standard reference docs | +| `#migration_lookupMapping` | Look up the Logic Apps equivalents of specific source components | | `#migration_searchReferenceWorkflows` | Search reference workflow examples | | `#migration_readReferenceWorkflow` | Read full JSON of a reference workflow | | `#migration_conversion_storeTaskPlan` | Store the ordered conversion task plan | @@ -32,6 +33,8 @@ You are a **Migration Converter** — an expert in converting integration flows **Skill location:** All skills are at `.github/skills/{skill-name}/SKILL.md` in the current workspace. Always read from this path — never from extension resources or external locations. +**Team standards:** if `.github/skills/customer-standards/SKILL.md` exists, read it before any other skill — its rules override the other skills. A skill's "Customer Overrides" section (maintained in that skill's `CUSTOM.md`) overrides the rest of that skill. + **Workspace boundary:** ALL file operations (decompilation output, scaffolding, code generation, reading/writing) MUST happen within the current migration workspace directory. NEVER read from, write to, or access `out/` folders in source folders, extracted MSI folders, or any other external location. | Skill | When to read | @@ -48,8 +51,9 @@ You are a **Migration Converter** — an expert in converting integration flows | `no-stubs-code-generation` | For ALL code generation tasks — no stubs, no placeholders, real business logic only | | `dependency-and-decompilation-analysis` | When source behavior exists only in .dll/.exe — MUST decompile before implementing | | `runtime-validation-and-testing` | Before validation and testing tasks — contains func start procedure, test matrix, local-first strategy, reporting | +| `automated-test-generation` | Before the `generate-tests` task — workflow unit tests with mocked connectors, map regression and schema tests (`dotnet test`, no Azure) | | `cloud-deployment-and-testing` | Before optional cloud deploy task — contains ARM/Bicep, deployment, cloud testing rules | -| `source-to-logic-apps-mapping` | Before choosing connectors/actions — contains 170+ component mappings | +| `source-to-logic-apps-mapping` | Before choosing connectors/actions — look up components with `#migration_lookupMapping`; read the full skill only when a lookup finds nothing | --- @@ -67,6 +71,8 @@ Follow skill `conversion-task-plan-rules` exactly to determine and order all tas Include the relevant design decisions, source references, and implementation requirements in each task's execution prompt so isolated task execution follows the same plan. +Set each task's `artifactIds` to the source artifacts it converts or implements (schemas, maps, functions, workflows, tests) so users can trace generated files back to the source; the extension keeps `TRACEABILITY.md` in the generated project from these IDs. + ### STEP 3 — Execute Tasks For each task in dependency order: @@ -82,6 +88,7 @@ For each task in dependency order: - Check task dependencies before starting. - Follow skill `workflow-json-generation-rules` §9 (pre-finalize checklist) before storing any workflow. - Follow skill `no-stubs-code-generation` for ALL generated code. +- When the prompt says `AZURE PROVISIONING: OFFLINE`, never sign in to Azure or create resources: generate Bicep under `infra/` and test with local emulators and mocked unit tests (skill `runtime-validation-and-testing` §5a). - Never deviate from the planned design. If a fix requires design changes, STOP and report. ### STEP 4 — Finalize diff --git a/resources/agents/migration-planner.md b/resources/agents/migration-planner.md index b0f0e61..593a823 100644 --- a/resources/agents/migration-planner.md +++ b/resources/agents/migration-planner.md @@ -20,6 +20,7 @@ You are a **Migration Planner** — an expert in translating discovered integrat | `#migration_searchArtifacts` | Search artifacts by name, schema, endpoint | | `#migration_getMigrationContext` | Get current migration state and context | | `#migration_readReferenceDoc` | Read/search Logic Apps Standard reference docs | +| `#migration_lookupMapping` | Look up the Logic Apps equivalents of specific components in `source-to-logic-apps-mapping` | | `#migration_searchReferenceWorkflows` | Search catalog of 113 real Logic Apps Standard reference workflows/connections | | `#migration_readReferenceWorkflow` | Read the full JSON of a reference workflow/connection | | `#migration_planning_storeMeta` | Store planning metadata — call FIRST | @@ -39,6 +40,8 @@ You are a **Migration Planner** — an expert in translating discovered integrat **Skill location:** All skills are at `.github/skills/{skill-name}/SKILL.md` in the current workspace. Always read from this path — never from extension resources or external locations. +**Team standards:** if `.github/skills/customer-standards/SKILL.md` exists, read it before any other skill — its rules override the other skills. A skill's "Customer Overrides" section (maintained in that skill's `CUSTOM.md`) overrides the rest of that skill. + **Workspace boundary:** ALL file operations (decompilation output, scaffolding, reading/writing) MUST happen within the current migration workspace directory. NEVER read from, write to, or access `out/` folders in source folders, extracted MSI folders, or any other external location. | Skill | When to read | @@ -46,7 +49,7 @@ You are a **Migration Planner** — an expert in translating discovered integrat | `logic-apps-planning-rules` | Before planning — contains workflow split policy, coverage requirements, priority ladder, planning store sequence | | `planning-decision-guidance` | Before architecture design — short preflight, hosting checks, modernization scope, and decision handoff | | `dependency-and-decompilation-analysis` | When source behavior exists only in .dll/.exe — MUST decompile before designing | -| `source-to-logic-apps-mapping` | Before choosing connectors/actions — contains 170+ component mappings with service provider IDs | +| `source-to-logic-apps-mapping` | Before choosing connectors/actions — look up components with `#migration_lookupMapping`; read the full skill (170+ mappings) only when a lookup finds nothing | | `workflow-json-generation-rules` | Before generating workflow definitions — contains action selection, splitOn, file trigger semantics, pre-finalize checklist | | `dotnet-local-functions-logic-apps` | Before planning any local function or its consumers - defines supported signatures, result classes, and property expressions | | `connections-json-generation-rules` | Before designing or generating connections - contains connection requirements, formats, and parameters | @@ -80,7 +83,7 @@ Generate a `flowchart TB` showing triggers, workflows, Azure services, and desti ### STEP 5 — Reference Lookup -1. Look up every component in skill `source-to-logic-apps-mapping`. +1. Look up every component with `#migration_lookupMapping` (skill `source-to-logic-apps-mapping`). 2. Search `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` with those names. 3. Use the exact action/trigger types, parameter structure, and (where applicable) provider and `operationId` from references - never invent. Follow the applicable generation skills when adapting references to the source-backed plan. diff --git a/resources/skills/analyse-source-design/biztalk/SKILL.md b/resources/skills/analyse-source-design/biztalk/SKILL.md index b882d4b..0912494 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. @@ -23,7 +24,7 @@ description: Rules for analysing a single flow group's architecture. Covers sour Before classifying any component's Azure equivalent: -1. Read the skill `source-to-logic-apps-mapping` to look up the exact Logic Apps Standard equivalent. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to find the exact Logic Apps Standard equivalent. 2. For EACH protocol/adapter/technology, use the connector name and operation names from that skill as search terms: - Call `migration_readReferenceDoc` with `action="search"` and a TARGETED query. - Call `migration_readReferenceDoc` with `action="read"` for the TOP result. diff --git a/resources/skills/analyse-source-design/mulesoft/SKILL.md b/resources/skills/analyse-source-design/mulesoft/SKILL.md index 467fc55..334be1c 100644 --- a/resources/skills/analyse-source-design/mulesoft/SKILL.md +++ b/resources/skills/analyse-source-design/mulesoft/SKILL.md @@ -21,7 +21,7 @@ description: Rules for analysing a single MuleSoft flow group's architecture. Co Before classifying any component's Azure equivalent: -1. Read the skill `source-to-logic-apps-mapping` to look up the exact Logic Apps Standard equivalent. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to find the exact Logic Apps Standard equivalent. 2. For EACH connector/processor/technology, use the connector name and operation names from that skill as search terms: - Call `migration_readReferenceDoc` with `action="search"` and a TARGETED query. - Call `migration_readReferenceDoc` with `action="read"` for the TOP result. diff --git a/resources/skills/analyse-source-design/tibco/SKILL.md b/resources/skills/analyse-source-design/tibco/SKILL.md index d6703f4..4cd9b0b 100644 --- a/resources/skills/analyse-source-design/tibco/SKILL.md +++ b/resources/skills/analyse-source-design/tibco/SKILL.md @@ -21,7 +21,7 @@ description: Rules for analysing a single TIBCO flow group's architecture. Cover Before classifying any component's Azure equivalent: -1. Read the skill `source-to-logic-apps-mapping` to look up the exact Logic Apps Standard equivalent. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to find the exact Logic Apps Standard equivalent. 2. For EACH connector/processor/technology, use the connector name and operation names from that skill as search terms: - Call `migration_readReferenceDoc` with `action="search"` and a TARGETED query. - Call `migration_readReferenceDoc` with `action="read"` for the TOP result. diff --git a/resources/skills/automated-test-generation/SKILL.md b/resources/skills/automated-test-generation/SKILL.md new file mode 100644 index 0000000..1172d35 --- /dev/null +++ b/resources/skills/automated-test-generation/SKILL.md @@ -0,0 +1,49 @@ +--- +name: automated-test-generation +description: Rules for generating re-runnable automated tests for a converted flow — Logic Apps Standard workflow unit tests with mocked triggers and connectors, map regression tests and schema validation tests — that run with dotnet test and need no Azure access. +--- + +# Skill: Automated Test Generation + +> **Purpose**: Every converted flow ships with tests the customer can re-run locally and in CI without Azure resources. Agent-run checks (`validate-runtime`, `test-workflows`) and reports do not replace them. + +--- + +## 1. Task + +- Type: `generate-tests` (REQUIRED) — after all schema, map, function and workflow tasks; before `validate-runtime`. +- `artifactIds`: the source orchestrations/flows, maps and schemas the tests cover. +- Output root: `{outputProjectRoot}/Tests/` (next to the Logic App project; never inside deployable Logic App content). +- Follow `no-stubs-code-generation`: every test asserts real values derived from the source behavior. + +--- + +## 2. Workflow Unit Tests (Logic Apps Standard testing framework) + +1. Read the reference doc **Create unit tests from Standard workflow definitions** (`migration_readReferenceDoc`, search "unit tests standard workflow definitions") and follow its layout: `Tests///` with `testSettings.config`, `MockOutputs/` classes per mocked operation, and C# MSTest classes using `TestExecutor`, `TestMockDefinition`, trigger mocks and `ActionMock`s. +2. For every workflow, cover the happy path, each error/compensation path (scopes, terminate, retries exhausted) and each decision branch that exists in the source orchestration or flow. +3. Mock the trigger and every connector action (Service Bus, SQL, file, HTTP, SAP, …). Assert the run status and, field by field, the inputs of the mocked outbound actions (for example the message published to a topic or written to a file). +4. Framework limits: integration account and EDI encode/decode actions are not supported. Cover their behavior with the map and schema tests below and list the gap in TEST-REPORT.md. + +--- + +## 3. Map Regression Tests + +1. For every converted map, store input/expected-output pairs under `Tests/TestData/Maps//`. Take samples, in this order, from: BizTalk map test instances (TestMap input/output instance paths in the `.btm`/`.btproj`), sample messages in the source repository, the user's black-box test folder; otherwise generate an instance from the source schema that fills every mapped field and repeats each repeating record at least twice. +2. Expected output must come from the **source** map behavior (embedded or generated XSLT of the source map), never from the new implementation. +3. Tests run the converted XSLT with `XslCompiledTransform` (extension objects for scripting functoids) and compare canonicalized XML, reporting the first differing XPath on failure. +4. When the plan's `map-strategy` is `azure-function` or `local-function`, run the same cases against that implementation and compare its output with the XSLT output — the XSLT remains the regression oracle. + +--- + +## 4. Schema Tests + +For every converted schema, validate at least one valid and one invalid sample (`XmlSchemaSet` for XSD, a JSON Schema validator for JSON). Assert that the valid sample passes and the invalid sample fails for the expected reason. + +--- + +## 5. Project and Execution + +- Put map and schema tests in `Tests/.ArtifactTests/` (MSTest, .NET 8) next to the workflow unit-test folders; reference converted artifacts by relative path, do not copy them. +- `dotnet test` run from `{outputProjectRoot}/Tests` must pass without Azure sign-in, network calls or secrets. Use only synthetic or anonymized test data. +- Record the command and per-category pass/fail counts in TEST-REPORT.md and include every generated test file in `generatedFiles`. diff --git a/resources/skills/cloud-deployment-and-testing/biztalk/SKILL.md b/resources/skills/cloud-deployment-and-testing/biztalk/SKILL.md index 2a56b14..0cbbb7f 100644 --- a/resources/skills/cloud-deployment-and-testing/biztalk/SKILL.md +++ b/resources/skills/cloud-deployment-and-testing/biztalk/SKILL.md @@ -13,6 +13,8 @@ description: Rules for optional cloud deployment and testing of Logic Apps Stand This task is OPTIONAL. The user decides whether to execute or skip it via the UI. It is excluded from "Execute All" and handled separately. +**Offline provisioning mode**: when the prompt says `AZURE PROVISIONING: OFFLINE` (setting `logicAppsMigrationAgent.azure.provisioningMode`), do not sign in to Azure or deploy. Generate the Bicep templates, parameter files and app settings described below under `{outputProjectRoot}/infra/`, write `infra/README.md` with the exact deployment and cloud-test commands for the customer to run, and write `CLOUD-TEST-REPORT.md` stating that the Bicep templates were generated but not deployed, listing those commands and the cloud tests to run. + --- ## 2. Deployment Steps diff --git a/resources/skills/cloud-deployment-and-testing/mulesoft/SKILL.md b/resources/skills/cloud-deployment-and-testing/mulesoft/SKILL.md index 2da5178..d388a70 100644 --- a/resources/skills/cloud-deployment-and-testing/mulesoft/SKILL.md +++ b/resources/skills/cloud-deployment-and-testing/mulesoft/SKILL.md @@ -13,6 +13,8 @@ description: Rules for optional cloud deployment and testing of Logic Apps Stand This task is OPTIONAL. The user decides whether to execute or skip it via the UI. It is excluded from "Execute All" and handled separately. +**Offline provisioning mode**: when the prompt says `AZURE PROVISIONING: OFFLINE` (setting `logicAppsMigrationAgent.azure.provisioningMode`), do not sign in to Azure or deploy. Generate the Bicep templates, parameter files and app settings described below under `{outputProjectRoot}/infra/`, write `infra/README.md` with the exact deployment and cloud-test commands for the customer to run, and write `CLOUD-TEST-REPORT.md` stating that the Bicep templates were generated but not deployed, listing those commands and the cloud tests to run. + --- ## 2. Deployment Steps diff --git a/resources/skills/cloud-deployment-and-testing/tibco/SKILL.md b/resources/skills/cloud-deployment-and-testing/tibco/SKILL.md index 1a3cfb4..9fcccaf 100644 --- a/resources/skills/cloud-deployment-and-testing/tibco/SKILL.md +++ b/resources/skills/cloud-deployment-and-testing/tibco/SKILL.md @@ -13,6 +13,8 @@ description: Rules for optional cloud deployment and testing of Logic Apps Stand This task is OPTIONAL. The user decides whether to execute or skip it via the UI. It is excluded from "Execute All" and handled separately. +**Offline provisioning mode**: when the prompt says `AZURE PROVISIONING: OFFLINE` (setting `logicAppsMigrationAgent.azure.provisioningMode`), do not sign in to Azure or deploy. Generate the Bicep templates, parameter files and app settings described below under `{outputProjectRoot}/infra/`, write `infra/README.md` with the exact deployment and cloud-test commands for the customer to run, and write `CLOUD-TEST-REPORT.md` stating that the Bicep templates were generated but not deployed, listing those commands and the cloud tests to run. + --- ## 2. Deployment Steps diff --git a/resources/skills/conversion-task-plan-rules/biztalk/SKILL.md b/resources/skills/conversion-task-plan-rules/biztalk/SKILL.md index e54bc81..3be29fa 100644 --- a/resources/skills/conversion-task-plan-rules/biztalk/SKILL.md +++ b/resources/skills/conversion-task-plan-rules/biztalk/SKILL.md @@ -45,7 +45,9 @@ After scaffold, add tasks for: - Local functions → using skill `dotnet-local-functions-logic-apps` - Workflows → `{outputLogicAppRoot}//workflow.json` - Connections → `{outputLogicAppRoot}/connections.json` -- Cloud resource provisioning (only for connectors with no local alternative) +- Cloud resource provisioning (only for connectors with no local, Docker or emulator alternative, and only in provisioning mode `provision`). In OFFLINE mode, add a `generate-infrastructure` task instead that writes Bicep under `{outputProjectRoot}/infra/` without deploying; an Integration Account is then generated, not created, and its app settings become documented parameters. +- Map functions (only when the plan's `map-strategy` is `azure-function`): a `generate-map-functions` task that creates an Azure Functions (.NET isolated) project under `{outputProjectRoot}/Functions/` with one function per map; keep the converted XSLT in `Artifacts/Maps` as the regression-test oracle. +- Receiver / processor / sender workflows (only when the plan's `workflow-topology` is `receiver-processor-sender`): one workflow task per receiver, processor and sender workflow, each with its own `artifactIds`, so they can be generated and re-run individually. **IMPORTANT Integration Account decision rule:** @@ -63,6 +65,13 @@ After scaffold, add tasks for: - Any Integration Account provisioning/configuration task MUST put that app setting requirement directly into its `executionPrompt`, not only in the high-level summary. - The task plan MUST make this choice explicit in the artifact task descriptions or execution prompts. +### 2.2b Automated Tests (REQUIRED) + +- Type: `generate-tests` +- After all schema, map, function and workflow tasks; before runtime validation. +- Follow skill `automated-test-generation`: workflow unit tests with mocked connectors, map regression tests and schema tests under `{outputProjectRoot}/Tests/`, runnable with `dotnet test` without Azure. +- `artifactIds`: the source orchestrations/flows, maps and schemas the tests cover. + ### 2.3 Runtime Validation (REQUIRED) - Type: `validate-runtime` @@ -74,7 +83,7 @@ After scaffold, add tasks for: - Type: `test-workflows` - Name: "End to End Testing (Local Environment)" - Must come after runtime validation. -- Full test matrix (see skill `runtime-validation-and-testing`). +- Full test matrix (see skill `runtime-validation-and-testing`), plus `dotnet test` for the generated tests. ### 2.5 Local Black Box Testing (OPTIONAL) @@ -125,7 +134,7 @@ Each task needs: | `executionPrompt` | string | No | Detailed agent-only instructions for execution | | `dependsOn` | string[] | Yes | Prerequisite task IDs | | `order` | number | Yes | 1-based execution sequence | -| `artifactIds` | string[] | No | Artifact IDs this task operates on | +| `artifactIds` | string[] | Yes* | Source artifact IDs this task converts or implements (*may be empty only for scaffold, infrastructure, validation and deployment tasks). Every flow artifact that needs conversion must appear in at least one task. | | `estimatedMinutes` | number | No | Effort estimate | | `optional` | boolean | No | True for user-skippable tasks (e.g. cloud-deploy) | @@ -145,7 +154,7 @@ Each task needs: - For each task, set `description` to a concise user-facing summary (1-2 lines). - Put all detailed implementation steps/rules into `executionPrompt`. -- Workflow generation tasks MUST include: "Read skill `source-to-logic-apps-mapping` first, then search reference workflows." +- Workflow generation tasks MUST include: "Look up components with migration_lookupMapping (skill `source-to-logic-apps-mapping`) first, then search reference workflows." - Connection generation tasks MUST include: "Search with `category=connection` to find exact `connections.json` format." - Local function tasks MUST reference skill `dotnet-local-functions-logic-apps`. - ALL code generation tasks MUST follow skill `no-stubs-code-generation`. diff --git a/resources/skills/conversion-task-plan-rules/mulesoft/SKILL.md b/resources/skills/conversion-task-plan-rules/mulesoft/SKILL.md index b39f824..069a9b8 100644 --- a/resources/skills/conversion-task-plan-rules/mulesoft/SKILL.md +++ b/resources/skills/conversion-task-plan-rules/mulesoft/SKILL.md @@ -39,7 +39,9 @@ After scaffold, add tasks for: - Local functions → using skill `dotnet-local-functions-logic-apps` - Workflows → `{outputLogicAppRoot}//workflow.json` - Connections → `{outputLogicAppRoot}/connections.json` -- Cloud resource provisioning (only for connectors with no local alternative) +- Cloud resource provisioning (only for connectors with no local, Docker or emulator alternative, and only in provisioning mode `provision`). In OFFLINE mode, add a `generate-infrastructure` task instead that writes Bicep under `{outputProjectRoot}/infra/` without deploying; an Integration Account is then generated, not created, and its app settings become documented parameters. +- Map functions (only when the plan's `map-strategy` is `azure-function`): a `generate-map-functions` task that creates an Azure Functions (.NET isolated) project under `{outputProjectRoot}/Functions/` with one function per map; keep the converted XSLT in `Artifacts/Maps` as the regression-test oracle. +- Receiver / processor / sender workflows (only when the plan's `workflow-topology` is `receiver-processor-sender`): one workflow task per receiver, processor and sender workflow, each with its own `artifactIds`, so they can be generated and re-run individually. **IMPORTANT Integration Account decision rule:** @@ -57,6 +59,13 @@ After scaffold, add tasks for: - Any Integration Account provisioning/configuration task MUST put that app setting requirement directly into its `executionPrompt`, not only in the high-level summary. - The task plan MUST make this choice explicit in the artifact task descriptions or execution prompts. +### 2.2b Automated Tests (REQUIRED) + +- Type: `generate-tests` +- After all schema, map, function and workflow tasks; before runtime validation. +- Follow skill `automated-test-generation`: workflow unit tests with mocked connectors, map regression tests and schema tests under `{outputProjectRoot}/Tests/`, runnable with `dotnet test` without Azure. +- `artifactIds`: the source orchestrations/flows, maps and schemas the tests cover. + ### 2.3 Runtime Validation (REQUIRED) - Type: `validate-runtime` @@ -68,7 +77,7 @@ After scaffold, add tasks for: - Type: `test-workflows` - Name: "End to End Testing (Local Environment)" - Must come after runtime validation. -- Full test matrix (see skill `runtime-validation-and-testing`). +- Full test matrix (see skill `runtime-validation-and-testing`), plus `dotnet test` for the generated tests. ### 2.5 Local Black Box Testing (OPTIONAL) @@ -119,7 +128,7 @@ Each task needs: | `executionPrompt` | string | No | Detailed agent-only instructions for execution | | `dependsOn` | string[] | Yes | Prerequisite task IDs | | `order` | number | Yes | 1-based execution sequence | -| `artifactIds` | string[] | No | Artifact IDs this task operates on | +| `artifactIds` | string[] | Yes* | Source artifact IDs this task converts or implements (*may be empty only for scaffold, infrastructure, validation and deployment tasks). Every flow artifact that needs conversion must appear in at least one task. | | `estimatedMinutes` | number | No | Effort estimate | | `optional` | boolean | No | True for user-skippable tasks (e.g. cloud-deploy) | @@ -139,7 +148,7 @@ Each task needs: - For each task, set `description` to a concise user-facing summary (1-2 lines). - Put all detailed implementation steps/rules into `executionPrompt`. -- Workflow generation tasks MUST include: "Read skill `source-to-logic-apps-mapping` first, then search reference workflows." +- Workflow generation tasks MUST include: "Look up components with migration_lookupMapping (skill `source-to-logic-apps-mapping`) first, then search reference workflows." - Connection generation tasks MUST include: "Search with `category=connection` to find exact `connections.json` format." - Local function tasks MUST reference skill `dotnet-local-functions-logic-apps`. - ALL code generation tasks MUST follow skill `no-stubs-code-generation`. diff --git a/resources/skills/conversion-task-plan-rules/tibco/SKILL.md b/resources/skills/conversion-task-plan-rules/tibco/SKILL.md index c4857d2..b1778b9 100644 --- a/resources/skills/conversion-task-plan-rules/tibco/SKILL.md +++ b/resources/skills/conversion-task-plan-rules/tibco/SKILL.md @@ -39,7 +39,9 @@ After scaffold, add tasks for: - Local functions → using skill `dotnet-local-functions-logic-apps` - Workflows → `{outputLogicAppRoot}//workflow.json` - Connections → `{outputLogicAppRoot}/connections.json` -- Cloud resource provisioning (only for connectors with no local alternative) +- Cloud resource provisioning (only for connectors with no local, Docker or emulator alternative, and only in provisioning mode `provision`). In OFFLINE mode, add a `generate-infrastructure` task instead that writes Bicep under `{outputProjectRoot}/infra/` without deploying; an Integration Account is then generated, not created, and its app settings become documented parameters. +- Map functions (only when the plan's `map-strategy` is `azure-function`): a `generate-map-functions` task that creates an Azure Functions (.NET isolated) project under `{outputProjectRoot}/Functions/` with one function per map; keep the converted XSLT in `Artifacts/Maps` as the regression-test oracle. +- Receiver / processor / sender workflows (only when the plan's `workflow-topology` is `receiver-processor-sender`): one workflow task per receiver, processor and sender workflow, each with its own `artifactIds`, so they can be generated and re-run individually. **IMPORTANT Integration Account decision rule:** @@ -57,6 +59,13 @@ After scaffold, add tasks for: - Any Integration Account provisioning/configuration task MUST put that app setting requirement directly into its `executionPrompt`, not only in the high-level summary. - The task plan MUST make this choice explicit in the artifact task descriptions or execution prompts. +### 2.2b Automated Tests (REQUIRED) + +- Type: `generate-tests` +- After all schema, map, function and workflow tasks; before runtime validation. +- Follow skill `automated-test-generation`: workflow unit tests with mocked connectors, map regression tests and schema tests under `{outputProjectRoot}/Tests/`, runnable with `dotnet test` without Azure. +- `artifactIds`: the source orchestrations/flows, maps and schemas the tests cover. + ### 2.3 Runtime Validation (REQUIRED) - Type: `validate-runtime` @@ -68,7 +77,7 @@ After scaffold, add tasks for: - Type: `test-workflows` - Name: "End to End Testing (Local Environment)" - Must come after runtime validation. -- Full test matrix (see skill `runtime-validation-and-testing`). +- Full test matrix (see skill `runtime-validation-and-testing`), plus `dotnet test` for the generated tests. ### 2.5 Local Black Box Testing (OPTIONAL) @@ -119,7 +128,7 @@ Each task needs: | `executionPrompt` | string | No | Detailed agent-only instructions for execution | | `dependsOn` | string[] | Yes | Prerequisite task IDs | | `order` | number | Yes | 1-based execution sequence | -| `artifactIds` | string[] | No | Artifact IDs this task operates on | +| `artifactIds` | string[] | Yes* | Source artifact IDs this task converts or implements (*may be empty only for scaffold, infrastructure, validation and deployment tasks). Every flow artifact that needs conversion must appear in at least one task. | | `estimatedMinutes` | number | No | Effort estimate | | `optional` | boolean | No | True for user-skippable tasks (e.g. cloud-deploy) | @@ -139,7 +148,7 @@ Each task needs: - For each task, set `description` to a concise user-facing summary (1-2 lines). - Put all detailed implementation steps/rules into `executionPrompt`. -- Workflow generation tasks MUST include: "Read skill `source-to-logic-apps-mapping` first, then search reference workflows." +- Workflow generation tasks MUST include: "Look up components with migration_lookupMapping (skill `source-to-logic-apps-mapping`) first, then search reference workflows." - Connection generation tasks MUST include: "Search with `category=connection` to find exact `connections.json` format." - Local function tasks MUST reference skill `dotnet-local-functions-logic-apps`. - ALL code generation tasks MUST follow skill `no-stubs-code-generation`. 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/resources/skills/logic-apps-planning-rules/biztalk/SKILL.md b/resources/skills/logic-apps-planning-rules/biztalk/SKILL.md index 24ad377..7cb5dd5 100644 --- a/resources/skills/logic-apps-planning-rules/biztalk/SKILL.md +++ b/resources/skills/logic-apps-planning-rules/biztalk/SKILL.md @@ -21,6 +21,7 @@ Read and follow `planning-decision-guidance` before architecture generation. Res - Do NOT collapse sub-orchestrations into local functions or merge them into a parent workflow. - Use the Workflow action type (`InvokeWorkflow`) to call child workflows from parent workflows. - You MUST enumerate ALL discovered orchestrations and scenarios (happy path + branch/error/contingency paths) before deciding the workflow split. +- **Receiver → processor → sender topology**: when the resolved `workflow-topology` choice is `receiver-processor-sender`, still map every orchestration to its own processor workflow as above (triggered by its broker subscription), and also plan one receiver workflow per receive location (receive, decode/validate, publish to the broker) and one sender workflow per send port (subscribe from the broker, encode, send), all in one Standard Logic App. Record the broker topics/subscriptions (Service Bus by default) in Azure components and give every action mapping its `workflowName`. Otherwise ports stay triggers/actions of the orchestration's workflow. --- @@ -71,12 +72,14 @@ Do NOT add delete/remove/cleanup actions that remove the trigger input file by d For all **other** (non-custom-code) components: -1. Built-in actions (XmlParse, XmlValidation, Xslt, Compose, Parse JSON, Select, Flat File Decode/Encode) → 2. Expressions → 3. Data Mapper/Liquid → 4. Inline Code → 5. .NET local functions → 6. Azure Functions (last resort). +1. Built-in actions (XmlParse, XmlValidation, Xslt, Compose, Parse JSON, Select, Flat File Decode/Encode) → 2. Expressions → 3. Data Mapper/Liquid → 4. Inline Code → 5. .NET local functions → 6. Azure Functions (last resort, unless the user selected `map-strategy=azure-function` or an approved standard requires them). > **AUTO-APPLY RULE**: Always choose the HIGHEST applicable level without asking the user. If a built-in action exists (e.g. XmlParse for XML processing), use it — do NOT fall back to expressions or ask. > **XML PROCESSING RULE**: For XML parsing, validation, or structured access, ALWAYS use XmlParse / XmlValidation (built-in XML Operations) instead of `xpath()` expressions. XmlParse validates against schemas and returns structured JSON. xpath() skips validation and is verbose. This applies to all BizTalk XMLReceive pipeline replacements. +> **MAP STRATEGY RULE**: Apply the resolved `map-strategy` choice to every map. `azure-function`: record each map's artifact disposition with `uploadDestination: azure-function`, plan an Azure Functions (.NET isolated) component in Azure components, and have workflows call the function (HTTP/Function action) instead of Transform XML; keep the converted XSLT as the test oracle. `local-function`: follow the .NET local-function path (section 3.5). `logic-app-xslt` or unanswered: baseline XSLT in `Artifacts/Maps` with Transform XML. + --- ### 3.4 Runtime Connection Selection @@ -98,7 +101,7 @@ When needed, include the source routing expression, required predefined connecti Before generating any workflow definition: -1. Read the skill `source-to-logic-apps-mapping` to look up the exact Logic Apps Standard equivalent for every component. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to find the exact Logic Apps Standard equivalent for every component. 2. Call `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` to find real reference examples. 3. Use the operation names from the mapping skill as search terms. 4. Copy exact provider IDs, `operationId` values, and configuration structure from references. Only when dynamic connections are needed, read the `DynamicConnections` references and adapt `connectionName` to the source routing expression. diff --git a/resources/skills/logic-apps-planning-rules/mulesoft/SKILL.md b/resources/skills/logic-apps-planning-rules/mulesoft/SKILL.md index d429b52..fb5a00f 100644 --- a/resources/skills/logic-apps-planning-rules/mulesoft/SKILL.md +++ b/resources/skills/logic-apps-planning-rules/mulesoft/SKILL.md @@ -18,6 +18,7 @@ description: Rules for planning the migration of a MuleSoft flow to Azure Logic - Use the Workflow action type (`InvokeWorkflow`) to call child workflows from parent workflows, mirroring the `flow-ref` pattern. - Small, simple sub-flows (2–3 processors, no branching) MAY be inlined into the parent workflow if it simplifies the design — document this explicitly. - You MUST enumerate ALL discovered flows and scenarios (happy path + branch/error/contingency paths) before deciding the workflow split. +- **Receiver → processor → sender topology**: when the resolved `workflow-topology` choice is `receiver-processor-sender` (see `planning-decision-guidance`), still map every flow to its own processor workflow as above (triggered by its broker subscription), and also plan one receiver workflow per inbound listener/source (receive, validate, publish to the broker) and one sender workflow per outbound connector endpoint (subscribe from the broker, send), all in one Standard Logic App. Record the broker topics/subscriptions (Service Bus by default) in Azure components and give every action mapping its `workflowName`. Otherwise listeners and outbound connectors stay triggers/actions of the flow's workflow. --- @@ -68,12 +69,14 @@ Do NOT add delete/remove/cleanup actions that remove the trigger input file by d For all **other** (non-custom-code) components: -1. Built-in actions (HTTP, Compose, Parse JSON, Select, SQL Connector, Service Bus, Transform XML/Xslt, XmlParse, XmlValidation, Flat File Decode/Encode) → 2. Expressions → 3. Data Mapper/Liquid (for DataWeave conversions) → 4. Inline Code → 5. .NET local functions → 6. Azure Functions (last resort). +1. Built-in actions (HTTP, Compose, Parse JSON, Select, SQL Connector, Service Bus, Transform XML/Xslt, XmlParse, XmlValidation, Flat File Decode/Encode) → 2. Expressions → 3. Data Mapper/Liquid (for DataWeave conversions) → 4. Inline Code → 5. .NET local functions → 6. Azure Functions (last resort, unless the user selected `map-strategy=azure-function` or an approved standard requires them). > **AUTO-APPLY RULE**: Always choose the HIGHEST applicable level without asking the user. If a built-in action exists (e.g. SQL Connector for db:select, HTTP for http:request), use it — do NOT fall back to expressions or ask. > **DATAWEAVE PROCESSING RULE**: For DataWeave transformations (`ee:transform`), assess complexity. Simple field mappings (payload.field, basic map/filter) → Liquid templates or Compose actions. Complex scripts with reduce, groupBy, match, custom functions → .NET local functions. Always flag DataWeave conversions as gaps requiring review. +> **MAP STRATEGY RULE**: Apply the resolved `map-strategy` choice to every DataWeave map. `azure-function`: record each map's artifact disposition with `uploadDestination: azure-function`, plan an Azure Functions (.NET isolated) component in Azure components, and have workflows call the function (HTTP/Function action) instead of Transform XML/Liquid actions; keep the converted XSLT or Liquid map as the test oracle. `local-function`: follow the .NET local-function path (section 3.4). `logic-app-xslt` or unanswered: apply the DATAWEAVE PROCESSING RULE above. + --- ### 3.4 Local-Function Result Contracts @@ -89,7 +92,7 @@ For all **other** (non-custom-code) components: Before generating any workflow definition: -1. Read the skill `source-to-logic-apps-mapping` to look up the exact Logic Apps Standard equivalent for every MuleSoft processor. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to find the exact Logic Apps Standard equivalent for every MuleSoft processor. 2. Call `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` to find real reference examples. 3. Use the operation names from the mapping skill as search terms. 4. Copy exact `serviceProviderConfiguration` and `operationId` values from references — do NOT invent these. diff --git a/resources/skills/logic-apps-planning-rules/tibco/SKILL.md b/resources/skills/logic-apps-planning-rules/tibco/SKILL.md index 205850c..f7808f8 100644 --- a/resources/skills/logic-apps-planning-rules/tibco/SKILL.md +++ b/resources/skills/logic-apps-planning-rules/tibco/SKILL.md @@ -18,6 +18,7 @@ description: Rules for planning the migration of a TIBCO flow to Azure Logic App - Use the Workflow action type (`InvokeWorkflow`) to call child workflows from parent workflows, mirroring the `process-call` pattern. - Small, simple sub-processes (2–3 processors, no branching) MAY be inlined into the parent workflow if it simplifies the design — document this explicitly. - You MUST enumerate ALL discovered flows and scenarios (happy path + branch/error/contingency paths) before deciding the workflow split. +- **Receiver → processor → sender topology**: when the resolved `workflow-topology` choice is `receiver-processor-sender` (see `planning-decision-guidance`), still map every process to its own processor workflow as above (triggered by its broker subscription), and also plan one receiver workflow per process starter (receive, validate, publish to the broker) and one sender workflow per outbound endpoint activity (subscribe from the broker, send), all in one Standard Logic App. Record the broker topics/subscriptions (Service Bus by default) in Azure components and give every action mapping its `workflowName`. Otherwise starters and outbound activities stay triggers/actions of the process's workflow. --- @@ -68,12 +69,14 @@ Do NOT add delete/remove/cleanup actions that remove the trigger input file by d For all **other** (non-custom-code) components: -1. Built-in actions (HTTP, Compose, Parse JSON, Select, SQL Connector, Service Bus, Transform XML/Xslt, XmlParse, XmlValidation, Flat File Decode/Encode) → 2. Expressions → 3. Data Mapper/Liquid (for Mapper/XSLT conversions) → 4. Inline Code → 5. .NET local functions → 6. Azure Functions (last resort). +1. Built-in actions (HTTP, Compose, Parse JSON, Select, SQL Connector, Service Bus, Transform XML/Xslt, XmlParse, XmlValidation, Flat File Decode/Encode) → 2. Expressions → 3. Data Mapper/Liquid (for Mapper/XSLT conversions) → 4. Inline Code → 5. .NET local functions → 6. Azure Functions (last resort, unless the user selected `map-strategy=azure-function` or an approved standard requires them). > **AUTO-APPLY RULE**: Always choose the HIGHEST applicable level without asking the user. If a built-in action exists (e.g. SQL Connector for JDBC SQL activities, HTTP for http:request), use it — do NOT fall back to expressions or ask. > **Mapper/XSLT PROCESSING RULE**: For Mapper/XSLT transformations (`mapper activity`), assess complexity. Simple field mappings (process-data field expressions, basic map/filter) → Liquid templates or Compose actions. Complex scripts with reduce, groupBy, match, custom functions → .NET local functions. Always flag Mapper/XSLT conversions as gaps requiring review. +> **MAP STRATEGY RULE**: Apply the resolved `map-strategy` choice to every Mapper/XSLT map. `azure-function`: record each map's artifact disposition with `uploadDestination: azure-function`, plan an Azure Functions (.NET isolated) component in Azure components, and have workflows call the function (HTTP/Function action) instead of Transform XML/Liquid actions; keep the converted XSLT as the test oracle. `local-function`: follow the .NET local-function path (section 3.4). `logic-app-xslt` or unanswered: apply the Mapper/XSLT PROCESSING RULE above. + --- ### 3.4 Local-Function Result Contracts @@ -89,7 +92,7 @@ For all **other** (non-custom-code) components: Before generating any workflow definition: -1. Read the skill `source-to-logic-apps-mapping` to look up the exact Logic Apps Standard equivalent for every TIBCO processor. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to find the exact Logic Apps Standard equivalent for every TIBCO processor. 2. Call `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` to find real reference examples. 3. Use the operation names from the mapping skill as search terms. 4. Copy exact `serviceProviderConfiguration` and `operationId` values from references — do NOT invent these. diff --git a/resources/skills/planning-decision-guidance/SKILL.md b/resources/skills/planning-decision-guidance/SKILL.md index babcb88..c4acb0e 100644 --- a/resources/skills/planning-decision-guidance/SKILL.md +++ b/resources/skills/planning-decision-guidance/SKILL.md @@ -12,12 +12,12 @@ Before designing diagrams, workflow JSON, or conversion tasks: 1. Reuse discovery analysis and read `migration_planning_preflight` with `action="read"`. 2. Resolve hosting first with `action="resolve", questions=[]`. The tool reuses a saved answer or an explicit deploymentModel setting; otherwise it asks one short question. An extension default is not customer consent. Standard includes both Azure-hosted and hybrid hosting. 3. Inspect the relevant source behavior and verify connector/operation, authentication, and network support for the selected host. Reuse reference lookups; do not reanalyse the entire project. -4. Ask only **consequential, unresolved** choices using `action="resolve"` and up to two questions per call. Aim for 1-3 questions total, including hosting. Additional questions are justified only by a real blocker; never guess a critical answer to meet a question budget. +4. Ask only **consequential, unresolved** choices using `action="resolve"` and up to two questions per call. Aim for 1-3 prompted questions total, including hosting; saved answers and configured defaults are applied without a prompt and do not count. Additional questions are justified only by a real blocker; never guess a critical answer to meet a question budget. 5. After all answers are resolved (`ready=true`), generate **one** plan. Compare options using concise descriptions, risks, and effort implications, not multiple full architectures or workflow definitions. On cancellation or error, stop without selecting defaults. Answered choices and pending questions remain saved for resumption. If `ready=false` with `pendingQuestions`, continue preflight only: validate those options for the selected host and resubmit the unresolved questions. A hosting-only call never clears them. Use stable question IDs, a short question, one sentence explaining material impact, and 2-4 supported choices with short tradeoffs. Reuse answered questions when their source/target assumptions still hold. Use `reconsider=true` only for an explicit request to change choices. Do not ask for secrets. -Reconsideration is scoped: with supplied questions, only those questions reopen; with `questions=[]`, only hosting reopens. A changed host invalidates host-dependent answers and returns before asking their old options. Recheck capabilities and resubmit the affected questions for the new host. Changes to an explicit deployment setting refresh configuration-sourced hosting decisions; intentional per-flow user choices remain overrides. +Reconsideration is scoped: with supplied questions, only those questions reopen; with `questions=[]`, only hosting reopens. A changed host invalidates host-dependent answers and returns before asking their old options. Recheck capabilities and resubmit the affected questions for the new host. Changes to an explicit deployment setting refresh configuration-sourced hosting decisions, and changed `planning.defaultChoices` refresh configuration-sourced answers when their questions are resubmitted; intentional per-flow user choices remain overrides. If the user has already explicitly chosen a host in their request, pass `deploymentTarget` instead of asking again. For another explicit answer, supply that question's `answerFromUser` option ID. These fields are **only** for direct user statements, never agent-inferred defaults or recommendations. @@ -25,12 +25,15 @@ If the user has already explicitly chosen a host in their request, pass `deploym Ask when the choice changes hosting/data residency, broker ownership, external contracts, delivery/transaction guarantees, authentication policy, significant cost, or the scope of custom-code refactoring and the source/customer requirements do not settle it. -Choose automatically when the mapping is deterministic and behavior-preserving: action names, workflow layout, supported built-in versus managed equivalent, retry wiring that preserves semantics, or the exact XML/SQL operation **within an approved modernization scope**. Do not ask about each action. +Choose automatically when the mapping is deterministic and behavior-preserving: action names, layout within a workflow, supported built-in versus managed equivalent, retry wiring that preserves semantics, or the exact XML/SQL operation **within an approved modernization scope**. Do not ask about each action. -Examples (only when relevant): +Standard questions (only when relevant): -- `messaging`: "Which broker should handle these messages?" Offer Azure Service Bus, RabbitMQ, or retaining the existing broker only where a verified connector or explicitly costed bridge works for this host. Never invent a native RabbitMQ/MSMQ connector, assume an automatic MSMQ replacement, or treat AMQP products as interchangeable. Capture delivery guarantees, ordering, acknowledgements, transactions, dead-lettering, and infrastructure ownership. +- `messaging`: "Which broker should handle these messages?" Offer `azure-service-bus`, `rabbitmq`, or `retain-existing` (the existing broker) only where a verified connector or explicitly costed bridge works for this host. Never invent a native RabbitMQ/MSMQ connector, assume an automatic MSMQ replacement, or treat AMQP products as interchangeable. Capture delivery guarantees, ordering, acknowledgements, transactions, dead-lettering, and infrastructure ownership. - `modernization`: "Preserve custom code or use native actions where equivalent?" Use options `preserve-code` (baseline/local functions with runtime compatibility checks) and `native-first` (refactor verified equivalents, retain complex business logic). Ask once per flow, only if actual opportunities exist. Baseline remains the safe behavior when no refactoring choice has been approved. +- `map-strategy`: "Where should maps run?" Resolve once per flow, only when the flow has maps; the tool prompts only when no saved or configured answer exists. Options: `logic-app-xslt` (baseline: XSLT in the Logic App `Artifacts/Maps` folder, run with Transform XML), `local-function` (.NET local function in the Logic App), and `azure-function` (separate Azure Functions (.NET isolated) project called by workflows; keep the converted XSLT as the regression-test reference). +- `workflow-topology`: "How should workflows be split?" Resolve only when the flow has inbound and outbound endpoints. Options: `orchestration-per-workflow` (baseline: one workflow per orchestration, ports as triggers/actions) and `receiver-processor-sender` (one receiver workflow per receive location that receives, decodes/validates, and publishes to the broker; one processor workflow or function per orchestration, subscribing from the broker; one sender workflow per send port; all in one Standard Logic App). The latter needs a broker: Service Bus topics/subscriptions by default. +- Use the question IDs `messaging`, `modernization`, `map-strategy`, and `workflow-topology` and the option IDs above verbatim so workspace defaults apply. Answers with source `configuration` come from settings (`deploymentModel` for hosting, `planning.defaultChoices` for the others); reuse them and do not re-ask unless the user explicitly asks to change choices. - A user-requested host, broker, or strategy already recorded in preferences must not be repeatedly questioned. If a later finding invalidates it, explain the blocker and ask only the affected decision. ## 2. Hosting-aware capability checks @@ -75,6 +78,6 @@ For full generation use `startNew=true` on storeMeta; it clears draft artifacts ### Conversion handoff (mandatory) -Read `preferences` and `brief` from `migration_conversion_getPlanningResults` before task derivation and isolated execution. Carry hosting, broker, accepted modernization, authentication constraints, and parity tests into the relevant task's `executionPrompt`. Do not reopen resolved questions or reintroduce rejected baseline mappings. +Read `preferences` and `brief` from `migration_conversion_getPlanningResults` before task derivation and isolated execution. Carry hosting, broker, map strategy, workflow topology, accepted modernization, authentication constraints, and parity tests into the relevant task's `executionPrompt`. Do not reopen resolved questions or reintroduce rejected baseline mappings. For hybrid/ASE, existing Workflow Service Plan cloud deployment examples are **not** applicable defaults. Validate current target-specific prerequisites and deployment procedures before using them. Include prerequisites and gaps explicitly; do not claim deployment support or silently deploy to Azure-hosted Standard. Unresolved blocking platform constraints must be surfaced before creation/deployment, not hidden by a fallback. diff --git a/resources/skills/runtime-validation-and-testing/biztalk/SKILL.md b/resources/skills/runtime-validation-and-testing/biztalk/SKILL.md index 1f9765b..555e6a6 100644 --- a/resources/skills/runtime-validation-and-testing/biztalk/SKILL.md +++ b/resources/skills/runtime-validation-and-testing/biztalk/SKILL.md @@ -71,7 +71,7 @@ If any field is empty, truncated, or contains the wrong value, treat it as a **t During testing, NEVER connect to or use original source platform infrastructure (on-premises SQL servers, file shares, message queues, FTP servers, etc.). - For local-capable connectors (File System, HTTP, Timer) → use LOCAL resources. -- For cloud-only connectors (Service Bus, Event Hubs, etc.) → use ONLY Azure resources provisioned in the configured resource group. +- For cloud-only connectors (Event Hubs, Integration Account, etc.) → use ONLY Azure resources provisioned in the configured resource group, and only in provisioning mode `provision` (see §5a). - Ensure Azurite is running before `func start` (`AzureWebJobsStorage` uses `UseDevelopmentStorage=true`). --- @@ -83,7 +83,16 @@ During testing, NEVER connect to or use original source platform infrastructure - Use `localhost` for HTTP triggers. - For SQL Server, Cosmos DB, SFTP, PostgreSQL, MySQL → use Docker containers. - Check Docker availability with `docker --version`. -- Only provision Azure resources for connectors with NO local/Docker alternative (Service Bus, Event Hubs, Integration Account). +- For Service Bus → use the Azure Service Bus emulator (Docker image `mcr.microsoft.com/azure-messaging/servicebus-emulator` with its SQL Edge dependency and a `Config.json` that declares the flow's queues, topics and subscriptions). Point the connection at it from `local.settings.json` with a connection string ending in `UseDevelopmentEmulator=true;`. The emulator accepts SAS connection strings only, so keep managed identity / Microsoft Entra authentication in the cloud configuration and parameterize the connection per environment. If the built-in connector cannot reach the emulator, cover those paths with the mocked unit tests from `automated-test-generation`. +- Only provision Azure resources for connectors with NO local, Docker or emulator alternative (Event Hubs, Integration Account), and only in provisioning mode `provision`. + +### 5a. Offline Provisioning Mode + +When the prompt says `AZURE PROVISIONING: OFFLINE`, never sign in to Azure, run `az`/`azd` deployment commands, or create resources: + +- Generate Bicep for every Azure resource the flow needs (for example the Service Bus namespace, topics and subscriptions, managed identity role assignments, Integration Account) under `{outputProjectRoot}/infra/` with per-environment parameter files, and document how to deploy it in `infra/README.md`. +- Validate and test locally with Azurite and the Docker emulators; cover connectors without a local alternative with the mocked workflow unit tests from `automated-test-generation`. +- List every live path that could not be exercised, and why, in TEST-REPORT.md instead of failing the task. --- @@ -99,7 +108,7 @@ After testing, generate `TEST-REPORT.md` in the project root with: - Adjustments made during testing. - Design deviations from plan (should be none — see plan adherence). - Deployment notes. -- Re-test instructions with exact commands. +- Re-test instructions with exact commands, including `dotnet test` for the generated test projects and its pass/fail counts (skill `automated-test-generation`). --- diff --git a/resources/skills/runtime-validation-and-testing/mulesoft/SKILL.md b/resources/skills/runtime-validation-and-testing/mulesoft/SKILL.md index 23dfd50..ea6f2ab 100644 --- a/resources/skills/runtime-validation-and-testing/mulesoft/SKILL.md +++ b/resources/skills/runtime-validation-and-testing/mulesoft/SKILL.md @@ -70,7 +70,7 @@ If any field is empty, truncated, or contains the wrong value, treat it as a **t During testing, NEVER connect to or use original source platform infrastructure (on-premises SQL servers, file shares, message queues, FTP servers, etc.). - For local-capable connectors (File System, HTTP, Timer) → use LOCAL resources. -- For cloud-only connectors (Service Bus, Event Hubs, etc.) → use ONLY Azure resources provisioned in the configured resource group. +- For cloud-only connectors (Event Hubs, Integration Account, etc.) → use ONLY Azure resources provisioned in the configured resource group, and only in provisioning mode `provision` (see §5a). - Ensure Azurite is running before `func start` (`AzureWebJobsStorage` uses `UseDevelopmentStorage=true`). --- @@ -82,7 +82,16 @@ During testing, NEVER connect to or use original source platform infrastructure - Use `localhost` for HTTP triggers. - For SQL Server, Cosmos DB, SFTP, PostgreSQL, MySQL → use Docker containers. - Check Docker availability with `docker --version`. -- Only provision Azure resources for connectors with NO local/Docker alternative (Service Bus, Event Hubs, Integration Account). +- For Service Bus → use the Azure Service Bus emulator (Docker image `mcr.microsoft.com/azure-messaging/servicebus-emulator` with its SQL Edge dependency and a `Config.json` that declares the flow's queues, topics and subscriptions). Point the connection at it from `local.settings.json` with a connection string ending in `UseDevelopmentEmulator=true;`. The emulator accepts SAS connection strings only, so keep managed identity / Microsoft Entra authentication in the cloud configuration and parameterize the connection per environment. If the built-in connector cannot reach the emulator, cover those paths with the mocked unit tests from `automated-test-generation`. +- Only provision Azure resources for connectors with NO local, Docker or emulator alternative (Event Hubs, Integration Account), and only in provisioning mode `provision`. + +### 5a. Offline Provisioning Mode + +When the prompt says `AZURE PROVISIONING: OFFLINE`, never sign in to Azure, run `az`/`azd` deployment commands, or create resources: + +- Generate Bicep for every Azure resource the flow needs (for example the Service Bus namespace, topics and subscriptions, managed identity role assignments, Integration Account) under `{outputProjectRoot}/infra/` with per-environment parameter files, and document how to deploy it in `infra/README.md`. +- Validate and test locally with Azurite and the Docker emulators; cover connectors without a local alternative with the mocked workflow unit tests from `automated-test-generation`. +- List every live path that could not be exercised, and why, in TEST-REPORT.md instead of failing the task. --- @@ -98,7 +107,7 @@ After testing, generate `TEST-REPORT.md` in the project root with: - Adjustments made during testing. - Design deviations from plan (should be none — see plan adherence). - Deployment notes. -- Re-test instructions with exact commands. +- Re-test instructions with exact commands, including `dotnet test` for the generated test projects and its pass/fail counts (skill `automated-test-generation`). --- diff --git a/resources/skills/runtime-validation-and-testing/tibco/SKILL.md b/resources/skills/runtime-validation-and-testing/tibco/SKILL.md index 8ffddb6..d6a5b1b 100644 --- a/resources/skills/runtime-validation-and-testing/tibco/SKILL.md +++ b/resources/skills/runtime-validation-and-testing/tibco/SKILL.md @@ -70,7 +70,7 @@ If any field is empty, truncated, or contains the wrong value, treat it as a **t During testing, NEVER connect to or use original source platform infrastructure (on-premises SQL servers, file shares, message queues, FTP servers, etc.). - For local-capable connectors (File System, HTTP, Timer) → use LOCAL resources. -- For cloud-only connectors (Service Bus, Event Hubs, etc.) → use ONLY Azure resources provisioned in the configured resource group. +- For cloud-only connectors (Event Hubs, Integration Account, etc.) → use ONLY Azure resources provisioned in the configured resource group, and only in provisioning mode `provision` (see §5a). - Ensure Azurite is running before `func start` (`AzureWebJobsStorage` uses `UseDevelopmentStorage=true`). --- @@ -82,7 +82,16 @@ During testing, NEVER connect to or use original source platform infrastructure - Use `localhost` for HTTP triggers. - For SQL Server, Cosmos DB, SFTP, PostgreSQL, MySQL → use Docker containers. - Check Docker availability with `docker --version`. -- Only provision Azure resources for connectors with NO local/Docker alternative (Service Bus, Event Hubs, Integration Account). +- For Service Bus → use the Azure Service Bus emulator (Docker image `mcr.microsoft.com/azure-messaging/servicebus-emulator` with its SQL Edge dependency and a `Config.json` that declares the flow's queues, topics and subscriptions). Point the connection at it from `local.settings.json` with a connection string ending in `UseDevelopmentEmulator=true;`. The emulator accepts SAS connection strings only, so keep managed identity / Microsoft Entra authentication in the cloud configuration and parameterize the connection per environment. If the built-in connector cannot reach the emulator, cover those paths with the mocked unit tests from `automated-test-generation`. +- Only provision Azure resources for connectors with NO local, Docker or emulator alternative (Event Hubs, Integration Account), and only in provisioning mode `provision`. + +### 5a. Offline Provisioning Mode + +When the prompt says `AZURE PROVISIONING: OFFLINE`, never sign in to Azure, run `az`/`azd` deployment commands, or create resources: + +- Generate Bicep for every Azure resource the flow needs (for example the Service Bus namespace, topics and subscriptions, managed identity role assignments, Integration Account) under `{outputProjectRoot}/infra/` with per-environment parameter files, and document how to deploy it in `infra/README.md`. +- Validate and test locally with Azurite and the Docker emulators; cover connectors without a local alternative with the mocked workflow unit tests from `automated-test-generation`. +- List every live path that could not be exercised, and why, in TEST-REPORT.md instead of failing the task. --- @@ -98,7 +107,7 @@ After testing, generate `TEST-REPORT.md` in the project root with: - Adjustments made during testing. - Design deviations from plan (should be none — see plan adherence). - Deployment notes. -- Re-test instructions with exact commands. +- Re-test instructions with exact commands, including `dotnet test` for the generated test projects and its pass/fail counts (skill `automated-test-generation`). --- diff --git a/resources/skills/workflow-json-generation-rules/biztalk/SKILL.md b/resources/skills/workflow-json-generation-rules/biztalk/SKILL.md index f05b272..063f85b 100644 --- a/resources/skills/workflow-json-generation-rules/biztalk/SKILL.md +++ b/resources/skills/workflow-json-generation-rules/biztalk/SKILL.md @@ -13,7 +13,7 @@ description: Rules for generating workflow.json files for Logic Apps Standard. C BEFORE writing ANY `workflow.json`: -1. Read the skill `source-to-logic-apps-mapping` to get the Logic Apps equivalent connector, service provider ID, and operation names for each source component. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to get the Logic Apps equivalent connector, service provider ID, and operation names for each source component. 2. Use those operation names to call `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` to get exact `operationId` and `serviceProviderConfiguration` for each trigger/action. 3. If the first search returns no relevant results, RETRY 2-4 more times with different word combinations. 4. Also call `migration_readReferenceDoc` with `action="search"` then `action="read"` to verify connector capabilities. diff --git a/resources/skills/workflow-json-generation-rules/mulesoft/SKILL.md b/resources/skills/workflow-json-generation-rules/mulesoft/SKILL.md index 3534e41..899c1f8 100644 --- a/resources/skills/workflow-json-generation-rules/mulesoft/SKILL.md +++ b/resources/skills/workflow-json-generation-rules/mulesoft/SKILL.md @@ -13,7 +13,7 @@ description: Rules for generating workflow.json files for Logic Apps Standard. C BEFORE writing ANY `workflow.json`: -1. Read the skill `source-to-logic-apps-mapping` to get the Logic Apps equivalent connector, service provider ID, and operation names for each source component. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to get the Logic Apps equivalent connector, service provider ID, and operation names for each source component. 2. Use those operation names to call `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` to get exact `operationId` and `serviceProviderConfiguration` for each trigger/action. 3. If the first search returns no relevant results, RETRY 2-4 more times with different word combinations. 4. Also call `migration_readReferenceDoc` with `action="search"` then `action="read"` to verify connector capabilities. diff --git a/resources/skills/workflow-json-generation-rules/tibco/SKILL.md b/resources/skills/workflow-json-generation-rules/tibco/SKILL.md index c76dcf6..4df8eea 100644 --- a/resources/skills/workflow-json-generation-rules/tibco/SKILL.md +++ b/resources/skills/workflow-json-generation-rules/tibco/SKILL.md @@ -13,7 +13,7 @@ description: Rules for generating workflow.json files for Logic Apps Standard. C BEFORE writing ANY `workflow.json`: -1. Read the skill `source-to-logic-apps-mapping` to get the Logic Apps equivalent connector, service provider ID, and operation names for each source component. +1. Look up each component with `migration_lookupMapping`, which returns the matching rows of skill `source-to-logic-apps-mapping` (read the full skill only when a lookup finds nothing) to get the Logic Apps equivalent connector, service provider ID, and operation names for each source component. 2. Use those operation names to call `migration_searchReferenceWorkflows` and `migration_readReferenceWorkflow` to get exact `operationId` and `serviceProviderConfiguration` for each trigger/action. 3. If the first search returns no relevant results, RETRY 2-4 more times with different word combinations. 4. Also call `migration_readReferenceDoc` with `action="search"` then `action="read"` to verify connector capabilities. diff --git a/src/commands/CommandRegistry.ts b/src/commands/CommandRegistry.ts index ad18bd7..47fae34 100644 --- a/src/commands/CommandRegistry.ts +++ b/src/commands/CommandRegistry.ts @@ -15,6 +15,14 @@ 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 { renderFlowGroupInventoryMarkdown } from '../stages/discovery/FlowGroupInventory'; import { PlanningService } from '../stages/planning'; import { ConversionService } from '../stages/conversion'; import { AgentFileProvisioner } from '../services/AgentFileProvisioner'; @@ -22,7 +30,7 @@ import { DiscoveryWebviewPanel, SourceFlowVisualizer } from '../views/discovery' import { PlanningWebviewPanel } from '../views/planning'; import { ConversionWebviewPanel } from '../views/conversion'; import { UserPrompts } from '../constants/UserMessages'; -import { ChatPrompts } from '../constants/ChatPrompts'; +import { ChatPrompts, ProvisioningMode } from '../constants/ChatPrompts'; import type { GeneratedFlowResult } from '../services/LLMFlowGenerator'; /** @@ -121,6 +129,16 @@ 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', + }, + { + id: 'logicAppsMigrationAgent.exportFlowGroupInventory', + handler: this.handleExportFlowGroupInventory.bind(this), + title: 'Export Logical Group Inventory', + }, // Planning Stage Commands { id: 'logicAppsMigrationAgent.openPlanningView', @@ -169,6 +187,11 @@ export class CommandRegistry implements vscode.Disposable { handler: this.handleExportPlanReport.bind(this), title: 'Export Planning Report', }, + { + id: 'logicAppsMigrationAgent.exportPlanMarkdown', + handler: this.handleExportPlanMarkdown.bind(this), + title: 'Export Planning Requirements (Markdown)', + }, ]; for (const command of commands) { @@ -780,13 +803,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,19 +917,94 @@ 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); + } - // Open webview immediately with a loading spinner - SourceFlowVisualizer.showLoading(extensionUri, 'Detecting logical groups...'); - SourceFlowVisualizer.isInitialGenerating = true; + private getGroupingMode(): FlowGroupingMode { + return resolveGroupingMode( + vscode.workspace + .getConfiguration('logicAppsMigrationAgent') + .get('discovery.groupingMode', 'auto'), + StateManager.getInstance().getState().sourcePlatform + ); + } + + private getProvisioningMode(): ProvisioningMode { + return vscode.workspace + .getConfiguration('logicAppsMigrationAgent.azure') + .get('provisioningMode', 'provision') === 'offline' + ? 'offline' + : 'provision'; + } + + /** + * 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, + keepCurrentGroups = false + ): Promise { + // Initial detection shows a spinner until the agent stores groups. Re-detection keeps + // Home usable with the current groups, so a stopped or failed agent run cannot lock it. + if (!keepCurrentGroups) { + SourceFlowVisualizer.showLoading(extensionUri, 'Detecting logical groups...'); + SourceFlowVisualizer.isInitialGenerating = true; + } try { await vscode.commands.executeCommand('workbench.action.chat.open', { mode: 'agent', query: ChatPrompts.flowGroupDetection(), }); + if (keepCurrentGroups) { + void vscode.window.showInformationMessage(UserPrompts.COPILOT_REDETECTING_GROUPS); + } } catch (error) { - SourceFlowVisualizer.isInitialGenerating = false; + if (!keepCurrentGroups) { + SourceFlowVisualizer.isInitialGenerating = false; + } vscode.window.showErrorMessage( UserPrompts.flowGroupDetectionFailed( error instanceof Error ? error.message : String(error) @@ -896,6 +1013,79 @@ 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; + } + const { DiscoveryCacheService } = await import('../stages/discovery/DiscoveryCacheService'); + await this.startCopilotFlowGroupDetection( + extensionUri, + DiscoveryCacheService.getInstance().hasFlowGroups() + ); + } + + /** + * 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 */ @@ -998,6 +1188,7 @@ export class CommandRegistry implements vscode.Disposable { flowId: flowId as string, artifactList, reconsiderChoices: trigger === 'review-choices', + simpleFlow: SourceFlowVisualizer.isSimpleFlowGroup(flowId as string), }), }); logger.debug('[Planning] Agent chat opened successfully'); @@ -1109,6 +1300,7 @@ export class CommandRegistry implements vscode.Disposable { outputProjectRoot, outputLogicAppName, outputLogicAppRoot, + provisioningMode: this.getProvisioningMode(), }), }); logger.debug('[Conversion] Agent chat opened successfully'); @@ -1267,6 +1459,7 @@ export class CommandRegistry implements vscode.Disposable { outputLogicAppRoot, resourceGroup: rg, location: loc, + provisioningMode: this.getProvisioningMode(), }), }); logger.debug(`[Conversion] Agent chat opened for task: ${taskId}`); @@ -1458,6 +1651,7 @@ export class CommandRegistry implements vscode.Disposable { outputLogicAppRoot, resourceGroup: rg2, location: loc2, + provisioningMode: this.getProvisioningMode(), }), }); logger.debug('[Conversion] Convert All agent chat opened successfully'); @@ -1702,6 +1896,43 @@ export class CommandRegistry implements vscode.Disposable { } } + /** + * Export the finalized plan as a Markdown requirements.md + */ + private async handleExportPlanMarkdown(flowId?: string, planId?: string): Promise { + const logger = LoggingService.getInstance(); + + if (!flowId) { + vscode.window.showWarningMessage('No flow specified for requirements export.'); + return; + } + + logger.debug(`[Export] Generating planning requirements (Markdown) for flow: ${flowId}`); + const { ReportExporterService } = await import('../services/ReportExporterService'); + const exporter = ReportExporterService.getInstance(); + const filePath = await exporter.generatePlanningMarkdown(flowId, planId); + + TelemetryService.getInstance().logStep('report.exported', { + type: 'planning-markdown', + flowId, + success: !!filePath, + }); + + if (filePath) { + const openAction = await vscode.window.showInformationMessage( + `Planning requirements saved successfully.`, + 'Open File', + 'Open Folder' + ); + if (openAction === 'Open File') { + await vscode.commands.executeCommand('vscode.open', vscode.Uri.file(filePath)); + } else if (openAction === 'Open Folder') { + const folderPath = (await import('path')).dirname(filePath); + await vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(folderPath)); + } + } + } + /** * Dispose of all registered commands */ diff --git a/src/constants/ChatPrompts.ts b/src/constants/ChatPrompts.ts index 7f6153a..d7501a8 100644 --- a/src/constants/ChatPrompts.ts +++ b/src/constants/ChatPrompts.ts @@ -13,6 +13,8 @@ * await vscode.commands.executeCommand('workbench.action.chat.open', { mode: 'agent', query }); */ +import { CUSTOMER_STANDARDS_SKILL } from '../services/SkillOverlay'; + // ============================================================================ // Shared prompt fragments (kept minimal — detail lives in skills) // ============================================================================ @@ -21,11 +23,38 @@ const AUTONOMOUS_MODE_SHORT = 'AUTONOMOUS MODE: Execute ALL steps without asking for confirmation. Do NOT pause to ask questions. Run all tool calls directly. '; const SKILL_AUTHORITY = - 'SKILL AUTHORITY: You MUST read every referenced skill BEFORE starting work. Treat skills as authoritative — if this prompt and a skill conflict, the skill wins. Your output will be rejected if it violates a skill. '; + 'SKILL AUTHORITY: You MUST read every referenced skill BEFORE starting work. Treat skills as authoritative — if this prompt and a skill conflict, the skill wins. Your output will be rejected if it violates a skill. ' + + `TEAM STANDARDS: if \`.github/skills/${CUSTOMER_STANDARDS_SKILL}/SKILL.md\` exists, read it first; its rules override the other skills, and a skill's "Customer Overrides" section overrides the rest of that skill. `; const GLOBAL_LOOKUP_POLICY = 'SCOPE POLICY: Start from the selected flow/task artifacts, but if any required dependency, import/using, schema, map, connector, class, or configuration detail is missing or unclear, you MUST expand to full-project lookup using migration_listArtifacts, migration_searchArtifacts, migration_getArtifactDetails, and migration_readSourceFile. Do NOT assume dependencies are group-local. '; +const MAPPING_SKILL_LINE = + '- `source-to-logic-apps-mapping` — component equivalents, service provider IDs, operation names. Look up components with migration_lookupMapping; read the full skill only when a lookup finds nothing relevant\n'; + +const FAST_PATH = + 'FAST PATH: this flow is small and has no custom code. Do not decompile assemblies, look up components with migration_lookupMapping instead of reading the full `source-to-logic-apps-mapping` skill, and run at most one reference-doc search per adapter or connector.\n'; + +/** Whether conversion may create Azure test resources (`provision`) or must stay local (`offline`). */ +export type ProvisioningMode = 'provision' | 'offline'; + +function azureSettings( + resourceGroup: string, + location: string, + mode: ProvisioningMode | undefined, + subscriptionSuffix = '' +): string { + if (mode === 'offline') { + return ( + '\nAZURE PROVISIONING: OFFLINE — do not sign in to Azure, run az/azd deployment commands, or create Azure resources. ' + + 'Generate Bicep for every Azure resource the flow needs under "infra/" in the output project instead, ' + + 'run locally with Azurite and Docker emulators (Service Bus emulator, SQL Server), and cover connectors without a local alternative with mocked unit tests (skill `automated-test-generation`). ' + + `Target values for the generated templates: Resource Group="${resourceGroup}", Location="${location}"${subscriptionSuffix}.\n` + ); + } + return `\nAZURE SETTINGS: Resource Group="${resourceGroup}", Location="${location}"${subscriptionSuffix}.\n`; +} + // ============================================================================ // ChatPrompts class // ============================================================================ @@ -35,6 +64,8 @@ interface PlanForFlowParams { flowId: string; artifactList: string; reconsiderChoices?: boolean; + /** Small flow without custom code: skip decompilation and broad lookups */ + simpleFlow?: boolean; } interface ConversionForFlowParams { @@ -47,6 +78,7 @@ interface ConversionForFlowParams { outputProjectRoot: string; outputLogicAppName: string; outputLogicAppRoot: string; + provisioningMode?: ProvisioningMode; } interface ExecuteSingleTaskParams { @@ -66,6 +98,7 @@ interface ExecuteSingleTaskParams { outputLogicAppRoot: string; resourceGroup: string; location: string; + provisioningMode?: ProvisioningMode; } interface ExecuteAllTasksParams { @@ -86,6 +119,7 @@ interface ExecuteAllTasksParams { outputLogicAppRoot: string; resourceGroup: string; location: string; + provisioningMode?: ProvisioningMode; } interface BlackBoxTestParams { @@ -106,6 +140,8 @@ interface BlackBoxTestParams { interface FlowAnalysisParams { flowName: string; flowId: string; + /** Small flow without custom code: skip decompilation and broad lookups */ + simpleFlow?: boolean; } interface OpenFlowChatParams { @@ -127,6 +163,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.' ); } @@ -141,11 +178,12 @@ export class ChatPrompts { 'DECISION-FIRST PLANNING: Reuse known choices, ask only critical unresolved questions through migration_planning_preflight, then generate ONE selected plan. Make minor behavior-preserving choices yourself. Never generate full alternatives just to compare them. Stop if the user cancels.\n' + SKILL_AUTHORITY + GLOBAL_LOOKUP_POLICY + + (params.simpleFlow ? FAST_PATH : '') + '\nREQUIRED SKILLS (read ALL before starting):\n' + '- `planning-decision-guidance` — concise preflight, hosting compatibility, modernization consent, and decision handoff\n' + '- `logic-apps-planning-rules` — workflow split policy, coverage requirements, planning store sequence\n' + '- `dependency-and-decompilation-analysis` — MUST decompile any .dll/.exe whose source is missing before designing workflows\n' + - '- `source-to-logic-apps-mapping` — component equivalents, service provider IDs, operation names\n' + + MAPPING_SKILL_LINE + '- `workflow-json-generation-rules` — workflow.json authoring, splitOn, file trigger semantics\n' + '- `connections-json-generation-rules` — connections.json format and connector parameters\n' + `\n${params.artifactList}\n` + @@ -158,7 +196,7 @@ export class ChatPrompts { '3. If any dependency or detail cannot be resolved from this flow group context, run full-project artifact search and source reads before finalizing the plan.\n' + '4. Read migration_planning_preflight, resolve hosting first, validate target capabilities, and resolve any critical broker/modernization choices. Follow planning-decision-guidance before designing the selected architecture.\n' + '5. Generate Mermaid flowchart TB showing target architecture.\n' + - '6. Look up every component in skill `source-to-logic-apps-mapping`, then search reference workflows with those names.\n' + + '6. Look up every component with migration_lookupMapping (skill `source-to-logic-apps-mapping`), then search reference workflows with those names.\n' + '7. Store one plan in the order from logic-apps-planning-rules. Call storeMeta with startNew=true and a brief containing scenario, indicative timeline, assumptions, tradeoffs, and evidenced modernization opportunities. Finalize once; history is saved automatically.' ); } @@ -185,10 +223,16 @@ export class ChatPrompts { '- `no-stubs-code-generation` — all code must be fully implemented\n' + '- `dependency-and-decompilation-analysis` — MUST decompile any .dll/.exe whose source is missing before generating tasks\n' + '- `runtime-validation-and-testing` — validation, test matrix, reporting\n' + + '- `automated-test-generation` — re-runnable workflow unit, map and schema tests (dotnet test, no Azure)\n' + '- `cloud-deployment-and-testing` — optional cloud deploy task rules\n' + - '- `source-to-logic-apps-mapping` — component equivalents\n' + + MAPPING_SKILL_LINE + '- `dotnet-local-functions-logic-apps` — .NET local function project structure\n' + - `\nAZURE SETTINGS: Resource Group="${params.azureResourceGroup}", Location="${params.azureLocation}"${subscriptionSuffix}.\n` + + azureSettings( + params.azureResourceGroup, + params.azureLocation, + params.provisioningMode, + subscriptionSuffix + ) + `OUTPUT PATHS: Workspace root="${params.outputProjectRoot}/", Logic App="${params.outputLogicAppRoot}/", ` + `Workspace file="${params.outputProjectRoot}/${params.outputProjectName}.code-workspace".\n` + `Scaffold params: workspaceName="${params.outputProjectName}", logicAppName="${params.outputLogicAppName}".\n` + @@ -212,8 +256,8 @@ export class ChatPrompts { SKILL_AUTHORITY + GLOBAL_LOOKUP_POLICY + '\nREQUIRED SKILLS: Read `workflow-json-generation-rules`, `connections-json-generation-rules`, `no-stubs-code-generation`, ' + - '`dependency-and-decompilation-analysis` (decompile .dll/.exe when source is unavailable), `runtime-validation-and-testing`, `source-to-logic-apps-mapping` as needed for this task type.\n' + - `\nAZURE SETTINGS: Resource Group="${params.resourceGroup}", Location="${params.location}".\n` + + '`dependency-and-decompilation-analysis` (decompile .dll/.exe when source is unavailable), `runtime-validation-and-testing`, `automated-test-generation`, `source-to-logic-apps-mapping` (look up components with migration_lookupMapping) as needed for this task type.\n' + + azureSettings(params.resourceGroup, params.location, params.provisioningMode) + `OUTPUT PATHS: Project="${params.outputProjectRoot}/", LogicApp="${params.outputLogicAppRoot}/".\n` + `\nTask details:\n- Type: ${params.taskType}\n- Description: ${params.taskDescription}\n` + `- Execution Prompt: ${params.taskExecutionPrompt}\n- Order: ${params.taskOrder}\n- Dependencies: ${params.taskDependsOn}\n` + @@ -244,8 +288,9 @@ export class ChatPrompts { '- `no-stubs-code-generation` — all code fully implemented\n' + '- `dependency-and-decompilation-analysis` — MUST decompile any .dll/.exe whose source is missing before implementing\n' + '- `runtime-validation-and-testing` — validation, test matrix, local-first strategy, reporting\n' + - '- `source-to-logic-apps-mapping` — component equivalents\n' + - `\nAZURE SETTINGS: Resource Group="${params.resourceGroup}", Location="${params.location}".\n` + + '- `automated-test-generation` — re-runnable workflow unit, map and schema tests (dotnet test, no Azure)\n' + + MAPPING_SKILL_LINE + + azureSettings(params.resourceGroup, params.location, params.provisioningMode) + `OUTPUT PATHS: Project="${params.outputProjectRoot}/", LogicApp="${params.outputLogicAppRoot}/".\n` + `\nCurrent task:\n- Type: ${params.nextTaskType}\n- Description: ${params.nextTaskDescription}\n` + `- Execution Prompt: ${params.nextTaskExecutionPrompt}\n- Order: ${params.nextTaskOrder}\n- Dependencies: ${params.nextTaskDependsOn}\n` + @@ -273,16 +318,17 @@ export class ChatPrompts { AUTONOMOUS_MODE_SHORT + SKILL_AUTHORITY + GLOBAL_LOOKUP_POLICY + + (params.simpleFlow ? FAST_PATH : '') + '\nREQUIRED SKILLS (read ALL before starting):\n' + '- `analyse-source-design` — source reading depth, Mermaid diagram rules, MessageBox modeling, orchestration shapes, component mapping priority ladder, store tool sequence\n' + '- `dependency-and-decompilation-analysis` — DLL decompilation, missing dependency classification\n' + - '- `source-to-logic-apps-mapping` — component equivalents, service provider IDs, operation names\n' + + MAPPING_SKILL_LINE + `\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' + + '5. Look up every component with migration_lookupMapping (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' + `7. Store discovery results in the exact order specified by skill \`analyse-source-design\` (storeMeta → storeArchitecture → storeComponents → storeMessageFlow → storeGaps → storePatterns → storeDependencies → finalize), all with flowId="${params.flowId}".` ); diff --git a/src/constants/UserMessages.ts b/src/constants/UserMessages.ts index 9858475..9d5c319 100644 --- a/src/constants/UserMessages.ts +++ b/src/constants/UserMessages.ts @@ -38,6 +38,16 @@ export class UserPrompts { return format('Planning choices: {0}', flowId); } + static applyPlanningChoiceToAllFlows(question: string, choice: string): string { + return format( + 'Use "{1}" for "{0}" in all flows of this workspace? Answers already chosen for a flow are kept.', + question, + choice + ); + } + + static readonly BUTTON_APPLY_TO_ALL_FLOWS = 'Apply to All Flows'; + static readonly PLANNING_CHOICES_PAUSED = 'Planning paused. Your answered choices are saved; resume planning when ready.'; @@ -183,6 +193,45 @@ export class UserPrompts { return format('Failed to start flow group detection: {0}', errorMsg); } + static readonly BUTTON_REDETECT_GROUPS = 'Re-detect Groups'; + static readonly COPILOT_REDETECTING_GROUPS = + 'Copilot is re-detecting the logical groups in chat. Home keeps the current groups until new ones are stored.'; + 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.'; + + 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 + ); + } + + static editedSkillsBackedUp(skills: string[]): string { + return format( + 'Updated migration skills you had edited ({0}); your versions were saved as SKILL.md.bak. Move your rules to CUSTOM.md in the same folder so they are kept on future updates.', + skills.join(', ') + ); + } + // ======================================================================== // Command Registry — Dependency Graph // ======================================================================== diff --git a/src/copilot/MigrationLMTools.ts b/src/copilot/MigrationLMTools.ts index 4a86034..ae73d69 100644 --- a/src/copilot/MigrationLMTools.ts +++ b/src/copilot/MigrationLMTools.ts @@ -17,12 +17,21 @@ */ import * as vscode from 'vscode'; +import * as fs from 'fs'; 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 { StateManager } from '../services/StateManager'; +import { searchMappingSkill } from '../services/MappingSkillLookup'; import { ContextBuilder, ContextScope } from './ContextBuilder'; import { SourceFlowVisualizer } from '../views/discovery/SourceFlowVisualizer'; import { GeneratedFlowResult, LLMFlowGenerator, FlowGroup } from '../services/LLMFlowGenerator'; @@ -34,6 +43,12 @@ import { PlanningFileService, PLANNING_FILES } from '../stages/planning/Planning import { validateWorkflowDefinition } from '../workflowSchema'; import { ConversionService } from '../stages/conversion/ConversionService'; import { ConversionFileService } from '../stages/conversion/ConversionFileService'; +import { + checkTaskArtifacts, + renderTraceabilityMarkdown, + toOutputProjectName, + TraceableArtifact, +} from '../stages/conversion/Traceability'; import { MermaidValidationService } from '../services/MermaidValidationService'; import type { ConversionTask, ConversionTaskOutput, ConversionTaskPlan } from '../stages/conversion/types'; import { PlanningPreflightTool } from './PlanningPreflightTool'; @@ -112,9 +127,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; } @@ -1101,7 +1119,12 @@ class DetectFlowGroupsTool implements vscode.LanguageModelTool g.id === input.groupId); if (group) { @@ -1137,15 +1160,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 +1193,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 +1235,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 +1570,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('; ') @@ -2195,22 +2220,11 @@ class DiscoveryFinalizeTool implements vscode.LanguageModelTool ({ - id: g.id, - name: g.name, - description: g.description, - category: g.category, - artifactIds: g.artifactIds, - })), - ungroupedArtifactIds: flowGroupsResult.ungroupedArtifactIds, - explanation: flowGroupsResult.explanation, - }); + SourceFlowVisualizer.setStaticCachedFlowGroups(flowGroupsResult, true); } // Open the webview with the assembled result @@ -4266,6 +4280,42 @@ class ConversionStoreTaskPlanTool implements vscode.LanguageModelTool ({ id: a.id, name: a.name, type: a.type, sourcePath: a.sourcePath })); + const flowArtifactIds = new Set( + SourceFlowVisualizer.getStaticCachedFlowGroups()?.groups.find( + (g) => g.id === flowId + )?.artifactIds ?? [] + ); + const flowArtifacts = inventoryArtifacts.filter((a) => flowArtifactIds.has(a.id)); + const artifactCheck = + inventoryArtifacts.length > 0 + ? checkTaskArtifacts(tasks, flowArtifacts, inventoryArtifacts) + : undefined; + if (artifactCheck && artifactCheck.unknownReferences.length > 0) { + logger.warn( + `[LMTool] migration_conversion_storeTaskPlan: REJECTED — unknown artifactIds: ${artifactCheck.unknownReferences.map((r) => r.reference).join(', ')}` + ); + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart( + JSON.stringify({ + error: + 'REJECTED: task artifactIds must be IDs (or unique names) of discovered source artifacts so users can trace generated files back to the source. ' + + 'Fix the unknown references and re-submit the task plan.', + unknownReferences: artifactCheck.unknownReferences.slice(0, 20), + flowArtifacts: flowArtifacts + .slice(0, 60) + .map((a) => ({ id: a.id, name: a.name, type: a.type })), + }) + ), + ]); + } + const resolvedArtifactIds = new Map( + (artifactCheck?.tasks ?? []).map((t) => [t.id, t.artifactIds]) + ); + const summarizeForCard = (text: string): string => { const normalized = text.replace(/\s+/g, ' ').trim(); if (!normalized) { @@ -4339,7 +4389,7 @@ class ConversionStoreTaskPlanTool implements vscode.LanguageModelTool ({ id: t.id, name: t.name, order: t.order })), message: `Conversion task plan stored with ${tasks.length} tasks. The tasks are now visible in the Conversion webview. You can proceed to execute tasks when the user asks.`, + ...(artifactCheck && artifactCheck.uncoveredArtifacts.length > 0 + ? { + traceabilityWarning: + 'These flow artifacts are not listed in any task artifactIds, so users cannot see which task converts them. ' + + 'Re-store the task plan with the artifactIds of the tasks that convert or implement them; artifacts that need no conversion can stay unlisted.', + uncoveredArtifacts: artifactCheck.uncoveredArtifacts + .slice(0, 30) + .map((a) => ({ id: a.id, name: a.name, type: a.type })), + } + : {}), }) ), ]); @@ -4452,8 +4512,134 @@ class ConversionStoreTaskPlanTool implements vscode.LanguageModelTool { + async invoke( + options: vscode.LanguageModelToolInvocationOptions, + _token: vscode.CancellationToken + ): Promise { + const query = (options.input.query || '').trim(); + if (!query) { + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart(JSON.stringify({ error: 'query is required' })), + ]); + } + const skill = readMappingSkill(); + if (!skill) { + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart( + JSON.stringify({ + error: 'Mapping skill not found. Read .github/skills/source-to-logic-apps-mapping/SKILL.md instead.', + }) + ), + ]); + } + const limit = Math.min(Math.max(Math.trunc(options.input.maxResults ?? 25), 1), 60); + const matches = searchMappingSkill(skill.markdown, query, limit); + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart( + JSON.stringify({ + query, + matchCount: matches.length, + matches, + instructions: + matches.length > 0 + ? 'These rows come from the authoritative source-to-logic-apps-mapping skill. Use them for azureEquivalent, connector, service provider ID and operation decisions. Look up any component that is not covered with its adapter, shape or connector name.' + : 'No mapping rows matched. Retry with the adapter, shape or connector name (for example "WCF-SQL" or "Construct Message"), or read .github/skills/source-to-logic-apps-mapping/SKILL.md.', + }) + ), + ]); + } + + async prepareInvocation( + options: vscode.LanguageModelToolInvocationPrepareOptions, + _token: vscode.CancellationToken + ): Promise { + return { invocationMessage: `Looking up Logic Apps mappings for: ${options.input.query}` }; + } +} + // --------------- migration_conversion_storeTaskOutput --------------- +/** + * Keep `TRACEABILITY.md` in the generated project (out//) mapping source artifacts + * to the tasks that implement them and the files those tasks generated. + */ +async function writeTraceabilityFile(plan: ConversionTaskPlan): Promise { + const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; + if (!workspaceRoot) { + return; + } + const projectDir = path.join( + workspaceRoot, + 'out', + toOutputProjectName(plan.flowName || plan.flowId) + ); + if (!fs.existsSync(projectDir)) { + return; + } + const artifacts = new Map( + (await InventoryService.getInstance().getAllParsedArtifacts()).map((a) => [ + a.id, + { id: a.id, name: a.name, type: a.type, sourcePath: a.sourcePath }, + ]) + ); + await fs.promises.writeFile( + path.join(projectDir, 'TRACEABILITY.md'), + renderTraceabilityMarkdown(plan, (id) => artifacts.get(id)), + 'utf-8' + ); +} + class ConversionStoreTaskOutputTool implements vscode.LanguageModelTool { async invoke( options: vscode.LanguageModelToolInvocationOptions, @@ -4818,6 +5004,31 @@ class ConversionStoreTaskOutputTool implements vscode.LanguageModelTool + (f || '').replace(/\\/g, '/').toLowerCase() + ); + const hasTestFiles = normalizedGeneratedFiles.some( + (f) => f.includes('/tests/') || f.startsWith('tests/') + ); + if (!hasTestFiles || !summaryLower.includes('dotnet test')) { + logger.warn( + `[LMTool] migration_conversion_storeTaskOutput: REJECTED generate-tests — test files or dotnet test results missing` + ); + logTaskRejected('tests-not-run'); + return new vscode.LanguageModelToolResult([ + new vscode.LanguageModelTextPart( + JSON.stringify({ + error: + 'REJECTED: Automated test generation is complete only when the generated test files under {outputProjectRoot}/Tests/ are listed in generatedFiles ' + + 'and `dotnet test` was run and passed. Follow skill `automated-test-generation` and report the dotnet test pass/fail counts in the summary.', + }) + ), + ]); + } + } + // Enforce local black box testing completeness — BLACKBOX-TEST-REPORT.md is mandatory // Also reject agent self-skips: this task requires user-provided test data via folder picker. if (task && task.type === 'local-blackbox-test') { @@ -4897,6 +5108,14 @@ class ConversionStoreTaskOutputTool implements vscode.LanguageModelTool t.id === taskId); const actualStatus = updatedTask?.status || 'completed'; + if (taskPlan2) { + await writeTraceabilityFile(taskPlan2).catch((traceError) => + logger.debug( + `[LMTool] Failed to update TRACEABILITY.md: ${traceError instanceof Error ? traceError.message : String(traceError)}` + ) + ); + } + logger.debug( `[LMTool] migration_conversion_storeTaskOutput: stored output for task "${taskId}" in flow "${flowId}" (status: ${actualStatus})` ); @@ -5276,6 +5495,7 @@ export function registerMigrationLMTools(context: vscode.ExtensionContext): vsco disposables.push( vscode.lm.registerTool('migration_getDiscoveryAnalysis', new GetDiscoveryAnalysisTool()) ); + disposables.push(vscode.lm.registerTool('migration_lookupMapping', new LookupMappingTool())); // Planning file tools (multi-file architecture) disposables.push( 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..dc2facf 100644 --- a/src/parsers/biztalk/BizTalkProjectParser.ts +++ b/src/parsers/biztalk/BizTalkProjectParser.ts @@ -469,7 +469,8 @@ export class BizTalkProjectParser extends AbstractParser implements IProjectPars for (const refElement of projectRefElements) { const include = getAttr(refElement, 'Include'); if (include) { - references.push(path.resolve(projectDir, include)); + // Project files use Windows separators; resolve them on any OS + references.push(path.resolve(projectDir, include.replace(/[\\/]+/g, path.sep))); } } @@ -570,6 +571,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/AgentFileProvisioner.ts b/src/services/AgentFileProvisioner.ts index 2b1639f..18ac153 100644 --- a/src/services/AgentFileProvisioner.ts +++ b/src/services/AgentFileProvisioner.ts @@ -18,6 +18,14 @@ import * as fs from 'fs'; import { LoggingService } from './LoggingService'; import { WORKFLOW_COMPLETENESS_DECOMPILE_INSTRUCTION } from './DecompilationGuidance'; import { StateManager } from './StateManager'; +import { + composeSkill, + CUSTOM_SKILL_FILE, + isEditedManagedSkill, + sameSkillContent, + withContentHash, +} from './SkillOverlay'; +import { UserPrompts } from '../constants/UserMessages'; // ============================================================================= // Constants @@ -32,13 +40,13 @@ const CONVERTER_AGENT_FILENAME = 'migration-converter.agent.md'; * A version stamp embedded as an HTML comment at the top of the generated file. * Bump this when the prompt content changes so existing files get updated. */ -const ANALYSER_AGENT_VERSION = '2.5.0'; +const ANALYSER_AGENT_VERSION = '2.6.0'; const ANALYSER_VERSION_TAG = ``; -const PLANNER_AGENT_VERSION = '2.10.0'; +const PLANNER_AGENT_VERSION = '2.11.0'; const PLANNER_VERSION_TAG = ``; -const CONVERTER_AGENT_VERSION = '2.21.0'; +const CONVERTER_AGENT_VERSION = '2.22.0'; const CONVERTER_VERSION_TAG = ``; // ============================================================================= @@ -245,7 +253,7 @@ export class AgentFileProvisioner { // Skills // ------------------------------------------------------------------------- - private static readonly SKILLS_VERSION = '10.27.0'; + private static readonly SKILLS_VERSION = '10.28.0'; private static readonly SKILLS_VERSION_TAG = ``; /** @@ -338,6 +346,10 @@ export class AgentFileProvisioner { platformFolder ), }, + { + folder: 'automated-test-generation', + content: this.buildSkillFromResource('automated-test-generation', platformFolder), + }, { folder: 'workflow-json-generation-rules', content: this.buildSkillFromResource( @@ -373,20 +385,36 @@ export class AgentFileProvisioner { }, ]; + const editedSkills: string[] = []; for (const skill of skills) { const skillDir = path.join(skillsDir, skill.folder); await fs.promises.mkdir(skillDir, { recursive: true }); const skillFile = path.join(skillDir, 'SKILL.md'); - // Check version — skip if already at current version + const customFile = path.join(skillDir, CUSTOM_SKILL_FILE); + const custom = fs.existsSync(customFile) + ? fs.readFileSync(customFile, 'utf-8') + : undefined; + const content = withContentHash(composeSkill(skill.content, custom, skill.folder)); if (fs.existsSync(skillFile)) { const existing = fs.readFileSync(skillFile, 'utf-8'); - if (existing.includes(AgentFileProvisioner.SKILLS_VERSION_TAG)) { + if (sameSkillContent(existing, content)) { continue; } + // Keep direct edits before updating; teams should move them to CUSTOM.md + if (isEditedManagedSkill(existing)) { + await fs.promises.writeFile(`${skillFile}.bak`, existing, 'utf-8'); + editedSkills.push(skill.folder); + } } - await fs.promises.writeFile(skillFile, skill.content, 'utf-8'); + await fs.promises.writeFile(skillFile, content, 'utf-8'); this.logger.debug(`[AgentFileProvisioner] Provisioned skill: ${skill.folder}/SKILL.md`); } + if (editedSkills.length > 0) { + this.logger.warn( + `[AgentFileProvisioner] Backed up edited skills before updating: ${editedSkills.join(', ')}` + ); + void vscode.window.showWarningMessage(UserPrompts.editedSkillsBackedUp(editedSkills)); + } } /** diff --git a/src/services/LLMFlowGenerator.ts b/src/services/LLMFlowGenerator.ts index 763bcef..b7b3e9e 100644 --- a/src/services/LLMFlowGenerator.ts +++ b/src/services/LLMFlowGenerator.ts @@ -10,6 +10,7 @@ */ import { ParsedArtifact } from '../stages/discovery/types'; +import { simpleName } from '../stages/discovery/FlowGroupDetector'; /** * Component detail for educational view @@ -122,7 +123,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 +133,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 +162,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,16 +539,16 @@ 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 + // Find artifacts that define this source schema (exact simple name: + // substring matches link "Order" to "PurchaseOrder") for (const [schemaKey, schemaArtifactIds] of artifactsBySchema) { - if ( - sourceRef.includes(schemaKey) || - schemaKey.includes(sourceRef.replace(/.*\//, '')) - ) { + if (simpleName(sourceRef) === simpleName(schemaKey)) { for (const saId of schemaArtifactIds) { if (saId !== a.id) { connections.push({ @@ -538,10 +565,7 @@ export class LLMFlowGenerator { if (targetRef) { for (const [schemaKey, schemaArtifactIds] of artifactsBySchema) { - if ( - targetRef.includes(schemaKey) || - schemaKey.includes(targetRef.replace(/.*\//, '')) - ) { + if (simpleName(targetRef) === simpleName(schemaKey)) { for (const saId of schemaArtifactIds) { if (saId !== a.id) { connections.push({ @@ -682,15 +706,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 +758,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/services/MappingSkillLookup.ts b/src/services/MappingSkillLookup.ts new file mode 100644 index 0000000..7db9fbb --- /dev/null +++ b/src/services/MappingSkillLookup.ts @@ -0,0 +1,107 @@ +/** + * Mapping Skill Lookup + * + * Searches the `source-to-logic-apps-mapping` skill for the rows and rules that mention + * given components, so agents can look up a few mappings instead of loading the whole + * skill (100+ KB for BizTalk) into every analysis, planning and conversion run. + * + * @module services/MappingSkillLookup + */ + +export interface MappingSkillMatch { + /** Heading of the section the match belongs to */ + readonly section: string; + /** Header row of the table the match belongs to, if any */ + readonly columns?: string; + /** Matching table row or rule line */ + readonly text: string; +} + +interface ScoredMatch extends MappingSkillMatch { + readonly score: number; + readonly position: number; +} + +const MAX_TEXT_LENGTH = 600; + +/** Lower-case search terms: comma/semicolon-separated phrases, or words of a plain query. */ +export function mappingSearchTerms(query: string): string[] { + const phrases = query.split(/[,;\n]+/).map((term) => term.trim().toLowerCase()); + const terms = phrases.length > 1 ? phrases : query.toLowerCase().split(/\s+/); + return [...new Set(terms.map((term) => term.trim()).filter((term) => term.length >= 2))]; +} + +/** + * Find the table rows and rule lines of a mapping skill that mention the query terms. + * Rows matching more terms rank first; ties keep document order. + */ +export function searchMappingSkill( + markdown: string, + query: string, + limit = 25 +): MappingSkillMatch[] { + const terms = mappingSearchTerms(query); + if (terms.length === 0) { + return []; + } + + const matches: ScoredMatch[] = []; + let section = ''; + let columns: string | undefined; + let inFrontMatter = false; + const lines = markdown.split(/\r?\n/); + lines.forEach((line, position) => { + const trimmed = line.trim(); + if (position === 0 && trimmed === '---') { + inFrontMatter = true; + return; + } + if (inFrontMatter) { + inFrontMatter = trimmed !== '---'; + return; + } + const heading = /^#{1,6}\s+(.*)$/.exec(trimmed); + if (heading) { + section = heading[1].trim(); + columns = undefined; + return; + } + const isTableLine = trimmed.startsWith('|'); + if (!isTableLine) { + columns = undefined; + } else if (/^\|[\s:|-]+\|?$/.test(trimmed)) { + return; // separator row + } else if (columns === undefined) { + columns = trimmed; + return; // header row + } + if (!trimmed || trimmed.startsWith('\s*$/; + +function sha256(text: string): string { + return createHash('sha256').update(text.replace(/\r\n/g, '\n'), 'utf8').digest('hex'); +} + +function normalizeEnd(text: string): string { + return `${text.replace(/\s+$/, '')}\n`; +} + +/** Append a team's `CUSTOM.md` rules to a managed skill. */ +export function composeSkill( + base: string, + custom: string | undefined, + skillFolder: string +): string { + const rules = custom?.trim(); + if (!rules) { + return base; + } + return ( + `${normalizeEnd(base)}\n---\n\n## Customer Overrides\n\n` + + `> Maintained in \`.github/skills/${skillFolder}/${CUSTOM_SKILL_FILE}\`. ` + + 'When these rules conflict with the rules above, these rules win.\n\n' + + `${rules}\n` + ); +} + +/** Stamp a managed skill with a hash of its content. */ +export function withContentHash(content: string): string { + const body = normalizeEnd(content); + return `${body}\n`; +} + +/** True when a skill written by the extension was edited afterwards. */ +export function isEditedManagedSkill(existing: string): boolean { + const match = HASH_MARKER.exec(existing); + if (!match) { + // Written by an older version without a hash: edits cannot be detected. + return false; + } + return sha256(normalizeEnd(existing.slice(0, match.index))) !== match[1]; +} + +/** True when two skill files have the same content, ignoring line endings. */ +export function sameSkillContent(a: string, b: string): boolean { + return a.replace(/\r\n/g, '\n') === b.replace(/\r\n/g, '\n'); +} diff --git a/src/services/reports/PlanningRequirementsMarkdown.ts b/src/services/reports/PlanningRequirementsMarkdown.ts new file mode 100644 index 0000000..964106e --- /dev/null +++ b/src/services/reports/PlanningRequirementsMarkdown.ts @@ -0,0 +1,490 @@ +/** + * Planning Requirements Markdown + * + * Renders a finalized migration plan as a `requirements.md` document that + * skill-based build pipelines can consume. Pure and deterministic: no VS Code + * or file-system access, so the same plan always yields the same Markdown. + */ + +import type { + FlowPlanningResult, + PlannedWorkflow, +} from '../../stages/planning/PlanningCacheService'; +import { + PlanningBrief, + PlanningDecision, + selectedChoiceLabel, +} from '../../stages/planning/PlanningDecisions'; + +type ArtifactDisposition = NonNullable[number]; + +const DESTINATIONS: Readonly> = { + 'integration-account': { label: 'Integration Account', phrase: 'the Integration Account' }, + 'logic-app-artifact-folder': { + label: 'Logic App artifact folder', + phrase: 'the Logic App artifact folder', + }, + 'azure-function': { label: 'Azure Function', phrase: 'an Azure Function' }, + 'not-applicable': { label: 'Not applicable', phrase: '' }, +}; + +/** + * Render a finalized plan as `requirements.md`. Sections without content are + * omitted, and the acceptance criteria are derived only from plan content. + */ +export function renderPlanningRequirementsMarkdown(plan: FlowPlanningResult): string { + const workflows = items(plan.workflows); + const title = inline(plan.flowName) || inline(plan.flowId) || 'Migration plan'; + const criteria = acceptanceCriteria(plan); + + const blocks = [ + `# ${heading(`${title} — Migration Requirements`)}`, + '> Exported from the finalized Logic Apps migration plan.', + bullets([ + labelled('Flow ID', code(plan.flowId)), + labelled('Plan version', code(plan.planId) || 'Legacy'), + labelled('Plan generated', inline(plan.generatedAt)), + ]), + ...section('Summary', [text(plan.summary), text(plan.explanation)]), + ...section('Planning Decisions', [ + table( + ['Decision', 'Selected option', 'Source', 'Why it matters'], + items(plan.preferences?.decisions).map((decision) => [ + decision.question, + selectedOption(decision), + decision.source, + decision.whyItMatters, + ]) + ), + ]), + ...section('Planning Brief', briefBlocks(plan.brief)), + ...section('Modernization Opportunities', [ + table( + [ + 'Component', + 'Current approach', + 'Proposed approach', + 'Disposition', + 'Reason', + 'Evidence', + ], + items(plan.brief?.opportunities).map((opportunity) => [ + opportunity.component, + opportunity.currentApproach, + opportunity.proposedApproach, + opportunity.disposition, + opportunity.reason, + opportunity.evidence, + ]) + ), + ]), + ...section('Target Architecture', [fenced('mermaid', plan.mermaid)]), + ...section( + 'Planned Workflows', + workflows.length > 0 + ? [ + `The migration produces ${count(workflows.length, 'Logic Apps Standard workflow')}.`, + ...workflows.flatMap(workflowBlocks), + ] + : [] + ), + ...section('Connector Mappings', [ + table( + ['Source connector', 'Target connector', 'Native', 'Notes'], + items(plan.connectorMappings).map((mapping) => [ + mapping.source, + mapping.target, + yesNo(mapping.isNative), + mapping.notes, + ]) + ), + ]), + ...section('Action Mappings', [ + table( + ['Workflow', 'Source action', 'Target action', 'Notes'], + items(plan.actionMappings).map((mapping) => [ + mapping.workflowName, + mapping.source, + mapping.target, + mapping.notes, + ]) + ), + ]), + ...section('Artifact Dispositions', [ + table( + ['Artifact', 'Type', 'Conversion', 'Destination', 'Upload path', 'Notes'], + items(plan.artifactDispositions).map((disposition) => [ + disposition.artifactName, + disposition.artifactType, + conversionCell(disposition), + DESTINATIONS[disposition.uploadDestination]?.label ?? + disposition.uploadDestination, + disposition.uploadPath, + [text(disposition.conversionNotes), text(disposition.uploadNotes)] + .filter(Boolean) + .join('\n'), + ]) + ), + ]), + ...section('Required Azure Components', [ + table( + ['Component', 'Type', 'Reason', 'Configuration notes'], + items(plan.azureComponents).map((component) => [ + component.name, + component.type, + component.reason, + component.configNotes, + ]) + ), + ]), + ...section('Gap Analysis', [ + table( + ['Component', 'Gap', 'Severity', 'Recommendation'], + items(plan.gaps).map((gap) => [ + gap.component, + gap.gap, + gap.severity, + gap.recommendation, + ]) + ), + ]), + ...section('Integration Patterns', [ + table( + ['Pattern', 'Complexity', 'Source approach', 'Logic Apps approach'], + items(plan.patterns).map((pattern) => [ + pattern.name, + pattern.complexity, + pattern.sourceApproach, + pattern.logicAppsApproach, + ]) + ), + ]), + ...section('Effort Estimate', effortBlocks(plan.effortEstimate)), + ...section( + 'Acceptance Criteria', + criteria.length > 0 + ? ['Each criterion is derived from the plan content above.', checklist(criteria)] + : [] + ), + ]; + + return `${blocks.filter((block) => block.length > 0).join('\n\n')}\n`; +} + +// ─── Section builders ─── + +function briefBlocks(brief: PlanningBrief | undefined): string[] { + if (!brief) { + return []; + } + return [ + bullets([ + labelled('Scenario', inline(brief.scenarioName)), + labelled('Indicative timeline', inline(brief.estimatedTimeline)), + ]), + ...section('Assumptions', [bullets(items(brief.assumptions).map(inline))], 3), + ...section('Tradeoffs', [bullets(items(brief.tradeoffs).map(inline))], 3), + ]; +} + +function workflowBlocks(workflow: PlannedWorkflow, index: number): string[] { + const actions = items(workflow.actions).map(inline).filter(Boolean); + const sources = items(workflow.sourceArtifactIds).map(code).filter(Boolean); + const diagram = fenced('mermaid', workflow.mermaid); + return [ + `### ${heading(workflowName(workflow, index))}`, + text(workflow.description), + bullets([ + labelled('Trigger', inline(workflow.triggerType)), + labelled('Source artifacts', sources.join(', ')), + ]), + actions.length > 0 ? `**Actions:**\n\n${numbered(actions)}` : '', + diagram ? `**Workflow diagram:**\n\n${diagram}` : '', + ]; +} + +function effortBlocks(estimate: FlowPlanningResult['effortEstimate']): string[] { + if (!estimate) { + return []; + } + const breakdown = estimate.breakdown; + const phases: [string, unknown][] = breakdown + ? [ + ['Analysis', breakdown.analysis], + ['Conversion', breakdown.conversion], + ['Testing', breakdown.testing], + ['Deployment', breakdown.deployment], + ] + : []; + return [ + bullets([ + labelled('Total estimated hours', text(estimate.totalHours)), + labelled('Confidence', inline(estimate.confidence)), + ]), + table( + ['Phase', 'Hours'], + phases.filter(([, hours]) => text(hours)) + ), + ]; +} + +function acceptanceCriteria(plan: FlowPlanningResult): string[] { + const criteria: string[] = []; + + for (const decision of items(plan.preferences?.decisions)) { + const question = inline(decision.question); + const choice = inline(selectedChoiceLabel(decision)); + if (question && choice) { + criteria.push(`Implements the selected option for "${question}": ${choice}.`); + } + } + + items(plan.workflows).forEach((workflow, index) => { + const trigger = inline(workflow.triggerType); + const actionCount = items(workflow.actions).map(inline).filter(Boolean).length; + const sources = items(workflow.sourceArtifactIds).map(code).filter(Boolean); + const clauses: string[] = []; + if (trigger) { + clauses.push(`is triggered by "${trigger}"`); + } + if (actionCount > 0) { + clauses.push(`implements its ${count(actionCount, 'planned action')}`); + } + if (sources.length > 0) { + clauses.push( + `covers source ${sources.length === 1 ? 'artifact' : 'artifacts'} ${sources.join(', ')}` + ); + } + criteria.push( + `Workflow ${code(workflowName(workflow, index))} ${ + clauses.length > 0 ? sentenceList(clauses) : 'is implemented as planned' + }.` + ); + }); + + if (items(plan.connectorMappings).length > 0) { + criteria.push( + 'Each source connector listed in Connector Mappings is replaced by its target connector.' + ); + } + if (items(plan.actionMappings).length > 0) { + criteria.push( + 'Each source action listed in Action Mappings is implemented with its target action.' + ); + } + + for (const opportunity of items(plan.brief?.opportunities)) { + const component = inline(opportunity.component); + const proposed = inline(opportunity.proposedApproach); + const current = inline(opportunity.currentApproach); + if (component && opportunity.disposition === 'applied' && proposed) { + criteria.push(`${component} applies the planned modernization: ${proposed}.`); + } else if (component && opportunity.disposition === 'retained' && current) { + criteria.push(`${component} retains its current approach: ${current}.`); + } + } + + const components = items(plan.azureComponents) + .map((component) => inline(component.name)) + .filter(Boolean); + if (components.length > 0) { + criteria.push( + `Required Azure components are available to the workflows: ${components.join(', ')}.` + ); + } + + for (const disposition of items(plan.artifactDispositions)) { + const criterion = dispositionCriterion(disposition); + if (criterion) { + criteria.push(criterion); + } + } + + for (const gap of items(plan.gaps)) { + const severity = inline(gap.severity); + const subject = `Gap in ${inline(gap.component) || 'an unnamed component'}${ + severity ? ` (${severity} severity)` : '' + }`; + const recommendation = inline(gap.recommendation); + const description = inline(gap.gap); + if (recommendation) { + criteria.push( + `${subject}: the recommendation "${recommendation}" is implemented or tracked as an open item.` + ); + } else if (description) { + criteria.push(`${subject}: "${description}" is resolved or tracked as an open item.`); + } + } + + return criteria; +} + +function dispositionCriterion(disposition: ArtifactDisposition): string { + const name = code(disposition.artifactName); + if (!name) { + return ''; + } + const clauses: string[] = []; + if (disposition.conversionRequired) { + const range = conversionRange(disposition); + clauses.push(range ? `converted ${range}` : 'converted'); + } + const destination = + DESTINATIONS[disposition.uploadDestination]?.phrase ?? + inline(disposition.uploadDestination); + if (destination) { + const uploadPath = code(disposition.uploadPath); + clauses.push(`delivered to ${destination}${uploadPath ? ` at ${uploadPath}` : ''}`); + } + if (clauses.length === 0) { + return ''; + } + const type = inline(disposition.artifactType); + return `${name}${type ? ` (${type})` : ''} is ${clauses.join(' and ')}.`; +} + +function conversionCell(disposition: ArtifactDisposition): string { + if (!disposition.conversionRequired) { + return 'Not required'; + } + const from = inline(disposition.conversionFrom); + const to = inline(disposition.conversionTo); + return from && to ? `${from} → ${to}` : `Required ${conversionRange(disposition)}`.trim(); +} + +function conversionRange(disposition: ArtifactDisposition): string { + const from = inline(disposition.conversionFrom); + const to = inline(disposition.conversionTo); + return [from && `from ${from}`, to && `to ${to}`].filter(Boolean).join(' '); +} + +function selectedOption(decision: PlanningDecision): string { + const option = decision.options.find((choice) => choice.id === decision.selectedOptionId); + return [selectedChoiceLabel(decision), option?.description] + .map(inline) + .filter(Boolean) + .join(' — '); +} + +function workflowName(workflow: PlannedWorkflow, index: number): string { + return inline(workflow.name) || `Workflow ${index + 1}`; +} + +// ─── Markdown primitives ─── + +function section(title: string, blocks: readonly string[], level = 2): string[] { + const content = blocks.filter((block) => block.length > 0); + return content.length > 0 ? [`${'#'.repeat(level)} ${title}`, ...content] : []; +} + +function table(headers: readonly string[], rows: readonly (readonly unknown[])[]): string { + if (rows.length === 0) { + return ''; + } + return [ + `| ${headers.join(' | ')} |`, + `| ${headers.map(() => '---').join(' | ')} |`, + ...rows.map((row) => `| ${row.map(cell).join(' | ')} |`), + ].join('\n'); +} + +/** Table cell: escape backslashes and pipes, and keep line breaks as `
`. */ +function cell(value: unknown): string { + const content = text(value) + .split('\n') + .map((line) => line.trim()) + .join('
') + .replace(/\\/g, '\\\\') + .replace(/\|/g, '\\|'); + return content || '—'; +} + +function bullets(lines: readonly string[]): string { + return lines + .filter((line) => line.length > 0) + .map((line) => `- ${line}`) + .join('\n'); +} + +function numbered(lines: readonly string[]): string { + return lines + .filter((line) => line.length > 0) + .map((line, index) => `${index + 1}. ${line}`) + .join('\n'); +} + +function checklist(lines: readonly string[]): string { + return lines + .filter((line) => line.length > 0) + .map((line) => `- [ ] ${line}`) + .join('\n'); +} + +function labelled(label: string, value: string): string { + return value ? `**${label}:** ${value}` : ''; +} + +/** Single-line heading text; a trailing `#` run is escaped so it is not read as a closing sequence. */ +function heading(value: string): string { + return inline(value).replace(/(^|\s)(#+)$/, '$1\\$2'); +} + +/** Inline code span whose fence is longer than any backtick run in the value. */ +function code(value: unknown): string { + const content = inline(value); + if (!content) { + return ''; + } + const fence = '`'.repeat(longestBacktickRun(content) + 1); + const padding = content.startsWith('`') || content.endsWith('`') ? ' ' : ''; + return `${fence}${padding}${content}${padding}${fence}`; +} + +function fenced(language: string, value: unknown): string { + const body = text(value); + if (!body) { + return ''; + } + const fence = '`'.repeat(Math.max(3, longestBacktickRun(body) + 1)); + return `${fence}${language}\n${body}\n${fence}`; +} + +function longestBacktickRun(value: string): number { + return Math.max(0, ...(value.match(/`+/g) ?? []).map((run) => run.length)); +} + +function sentenceList(parts: readonly string[]): string { + return parts.length <= 2 + ? parts.join(' and ') + : `${parts.slice(0, -1).join(', ')}, and ${parts[parts.length - 1]}`; +} + +function count(amount: number, noun: string): string { + return `${amount} ${noun}${amount === 1 ? '' : 's'}`; +} + +function yesNo(value: unknown): string { + return value === true ? 'Yes' : value === false ? 'No' : ''; +} + +// ─── Value normalization (plans are LLM-authored JSON; never print `undefined`) ─── + +function items(value: readonly T[] | undefined): readonly T[] { + return Array.isArray(value) ? value : []; +} + +/** Trimmed text with normalized line endings; empty for missing or non-scalar values. */ +function text(value: unknown): string { + if (typeof value === 'string') { + return value.replace(/\r\n?/g, '\n').trim(); + } + if ((typeof value === 'number' && Number.isFinite(value)) || typeof value === 'boolean') { + return String(value); + } + return ''; +} + +/** Text collapsed onto a single line. */ +function inline(value: unknown): string { + return text(value).replace(/\s+/g, ' '); +} diff --git a/src/stages/conversion/Traceability.ts b/src/stages/conversion/Traceability.ts new file mode 100644 index 0000000..c988795 --- /dev/null +++ b/src/stages/conversion/Traceability.ts @@ -0,0 +1,172 @@ +/** + * Conversion Traceability + * + * Links source artifacts to the conversion tasks that implement them and the files those + * tasks generated, so users can see which generated code belongs to which source artifact. + * + * @module stages/conversion/Traceability + */ + +import * as path from 'path'; +import type { ConversionTaskPlan } from './types'; + +/** Name, type and location of a source artifact. */ +export interface TraceableArtifact { + readonly id: string; + readonly name: string; + readonly type: string; + readonly sourcePath?: string; +} + +/** Artifact types that are converted into Logic Apps, function or test assets. */ +const CONVERTIBLE_TYPES: ReadonlySet = new Set([ + 'orchestration', + 'flow', + 'process', + 'workflow', + 'map', + 'schema', + 'pipeline', + 'custom-code', + 'dataweave', + 'esql', + 'policy', + 'ruleset', +]); +const PROJECT_EXTENSIONS: ReadonlySet = new Set(['.btproj', '.csproj', '.vbproj', '.sln']); + +/** Folder name used for a flow's generated project under `out/`. */ +export function toOutputProjectName(flowName: string): string { + return flowName + .replace(/[^a-zA-Z0-9_-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-|-$/g, ''); +} + +function isConvertible(artifact: TraceableArtifact): boolean { + return ( + CONVERTIBLE_TYPES.has(artifact.type) && + !PROJECT_EXTENSIONS.has(path.extname(artifact.sourcePath ?? '').toLowerCase()) + ); +} + +export interface TaskArtifactCheck { + /** Task artifact references rewritten to artifact IDs (names resolved when unambiguous). */ + readonly tasks: { id: string; artifactIds?: string[] }[]; + /** References that match no artifact ID or unique artifact name. */ + readonly unknownReferences: { taskId: string; reference: string }[]; + /** Convertible flow artifacts that no task lists. */ + readonly uncoveredArtifacts: TraceableArtifact[]; +} + +/** + * Resolve the artifacts each task implements and find flow artifacts no task covers. + */ +export function checkTaskArtifacts( + tasks: readonly { id: string; artifactIds?: readonly string[] }[], + flowArtifacts: readonly TraceableArtifact[], + allArtifacts: readonly TraceableArtifact[] +): TaskArtifactCheck { + const ids = new Set(allArtifacts.map((artifact) => artifact.id)); + const byName = new Map(); + for (const artifact of [...flowArtifacts, ...allArtifacts]) { + const key = artifact.name.toLowerCase(); + const list = byName.get(key) ?? []; + if (!list.some((existing) => existing.id === artifact.id)) { + list.push(artifact); + } + byName.set(key, list); + } + const flowIds = new Set(flowArtifacts.map((artifact) => artifact.id)); + + const unknownReferences: { taskId: string; reference: string }[] = []; + const resolvedTasks = tasks.map((task) => { + if (!task.artifactIds) { + return { id: task.id }; + } + const resolved: string[] = []; + for (const reference of task.artifactIds) { + if (ids.has(reference)) { + resolved.push(reference); + continue; + } + const matches = byName.get(reference.toLowerCase()) ?? []; + const inFlow = matches.filter((artifact) => flowIds.has(artifact.id)); + const match = + inFlow.length === 1 ? inFlow[0] : matches.length === 1 ? matches[0] : undefined; + if (match) { + resolved.push(match.id); + } else { + unknownReferences.push({ taskId: task.id, reference }); + } + } + return { id: task.id, artifactIds: [...new Set(resolved)] }; + }); + + const covered = new Set(resolvedTasks.flatMap((task) => task.artifactIds ?? [])); + const uncoveredArtifacts = flowArtifacts.filter( + (artifact) => isConvertible(artifact) && !covered.has(artifact.id) + ); + return { tasks: resolvedTasks, unknownReferences, uncoveredArtifacts }; +} + +function cell(value: string | undefined): string { + return ( + (value ?? '').replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\r?\n/g, '
') || '—' + ); +} + +/** + * Markdown traceability matrix: source artifact → tasks → generated files. + */ +export function renderTraceabilityMarkdown( + plan: ConversionTaskPlan, + lookup: (artifactId: string) => TraceableArtifact | undefined +): string { + const tasks = [...plan.tasks].sort((a, b) => a.order - b.order); + const tasksByArtifact = new Map(); + for (const task of tasks) { + for (const artifactId of task.artifactIds ?? []) { + tasksByArtifact.set(artifactId, [...(tasksByArtifact.get(artifactId) ?? []), task]); + } + } + const artifactLabel = (id: string) => lookup(id)?.name ?? id; + + const lines = [ + `# Traceability — ${plan.flowName}`, + '', + 'Which conversion task implements each source artifact, and which files it generated.', + '', + '## Source artifacts', + '', + '| Source artifact | Type | Source path | Tasks | Generated files |', + '| --- | --- | --- | --- | --- |', + ]; + const artifactIds = [...tasksByArtifact.keys()].sort((a, b) => + artifactLabel(a).localeCompare(artifactLabel(b)) + ); + for (const id of artifactIds) { + const artifact = lookup(id); + const artifactTasks = tasksByArtifact.get(id) ?? []; + const files = [ + ...new Set(artifactTasks.flatMap((task) => task.output?.generatedFiles ?? [])), + ]; + lines.push( + `| ${cell(artifact?.name ?? id)} | ${cell(artifact?.type)} | ${cell(artifact?.sourcePath)} | ${cell(artifactTasks.map((task) => `${task.order}. ${task.name}`).join('
'))} | ${cell(files.join('
'))} |` + ); + } + + lines.push( + '', + '## Tasks', + '', + '| # | Task | Status | Source artifacts | Generated files |', + '| --- | --- | --- | --- | --- |' + ); + for (const task of tasks) { + lines.push( + `| ${task.order} | ${cell(task.name)} | ${cell(task.status)} | ${cell((task.artifactIds ?? []).map(artifactLabel).join(', '))} | ${cell((task.output?.generatedFiles ?? []).join('
'))} |` + ); + } + return `${lines.join('\n')}\n`; +} 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..dd4311d --- /dev/null +++ b/src/stages/discovery/FlowGroupDetector.ts @@ -0,0 +1,1040 @@ +/** + * 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 { + // BizTalk projects record Windows separators; normalize them on every OS + return path + .resolve(filePath.replace(/[\\/]+/g, path.sep)) + .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: (reference.split(/[\\/]/).pop() ?? 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'); + // Stable identity: the entry orchestration/flow, or the route's binding and port + const identity = primary ? primary.id : cluster.key; + return { cluster, roots, primary, baseName, identity }; + }); + const slugCounts = new Map(); + for (const candidate of candidates) { + const base = slug(candidate.baseName); + slugCounts.set(base, (slugCounts.get(base) ?? 0) + 1); + } + + const groups = candidates.map(({ cluster, roots, primary, baseName, identity }) => { + // Flows sharing a name are all suffixed from their own identity, so re-detection + // can never hand one flow's ID (and saved progress) to another flow. + const base = slug(baseName); + const id = + (slugCounts.get(base) ?? 0) > 1 + ? `flow-${base}-${shortHash(identity)}` + : `flow-${base}`; + + 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/stages/discovery/FlowGroupInventory.ts b/src/stages/discovery/FlowGroupInventory.ts new file mode 100644 index 0000000..0dd41b1 --- /dev/null +++ b/src/stages/discovery/FlowGroupInventory.ts @@ -0,0 +1,211 @@ +/** + * 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; +} + +/** + * Small flows without custom code can skip decompilation and broad reference lookups. + * Project files are containers, not code to decompile. + */ +export function isSimpleFlow( + artifacts: readonly (InventoryArtifactInfo | undefined)[], + maxArtifacts = 6 +): boolean { + if (artifacts.length === 0 || artifacts.length > maxArtifacts) { + return false; + } + return artifacts.every( + (artifact) => + !!artifact && + (artifact.type !== 'custom-code' || + /\.(btproj|csproj|vbproj|sln)$/i.test(artifact.sourcePath ?? '')) + ); +} + +/** 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(/\|/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/stages/planning/PlanningDecisionService.ts b/src/stages/planning/PlanningDecisionService.ts index bd8d4bf..8b962e3 100644 --- a/src/stages/planning/PlanningDecisionService.ts +++ b/src/stages/planning/PlanningDecisionService.ts @@ -1,8 +1,10 @@ import * as vscode from 'vscode'; import { randomUUID } from 'crypto'; import { UserPrompts } from '../../constants/UserMessages'; +import { LoggingService } from '../../services/LoggingService'; import { PlanningFileService } from './PlanningFileService'; import { + configuredDefaultOption, DEPLOYMENT_QUESTION, PlanningDecision, PlanningPreferences, @@ -10,6 +12,9 @@ import { validatePlanningQuestion, } from './PlanningDecisions'; +const CONFIGURATION_SECTION = 'logicAppsMigrationAgent'; +const DEFAULT_CHOICES_SETTING = 'planning.defaultChoices'; + export class PlanningDecisionService { private static readonly resolving = new Set(); @@ -61,20 +66,23 @@ export class PlanningDecisionService { const pending = new Map( (preferences.pendingQuestions ?? []).map((question) => [question.id, question]) ); - const inspected = vscode.workspace - .getConfiguration('logicAppsMigrationAgent') - .inspect('deploymentModel'); + const configuration = vscode.workspace.getConfiguration(CONFIGURATION_SECTION); + const inspected = configuration.inspect('deploymentModel'); // An extension default is not an explicit customer hosting decision. const configuredTarget = inspected?.workspaceFolderValue ?? inspected?.workspaceValue ?? inspected?.globalValue; + const defaultChoices = configuration.get(DEFAULT_CHOICES_SETTING); + const configuredOption = (question: PlanningQuestion) => + question.id === DEPLOYMENT_QUESTION.id + ? configuredTarget + : configuredDefaultOption(question, defaultChoices); const shouldReconsider = (question: PlanningQuestion) => reconsider && (question.id !== DEPLOYMENT_QUESTION.id || questions.length === 0); const toResolve = [hostingQuestion, ...questions].filter((question) => { const existing = originalDecisions.get(question.id); const configurationChanged = - question.id === DEPLOYMENT_QUESTION.id && existing?.source === 'configuration' && - configuredTarget !== existing.selectedOptionId; + configuredOption(question) !== existing.selectedOptionId; return ( pending.has(question.id) || shouldReconsider(question) || @@ -124,11 +132,11 @@ export class PlanningDecisionService { let source: PlanningDecision['source'] = selectedOptionId ? 'user-request' : 'user'; if ( !selectedOptionId && - question.id === DEPLOYMENT_QUESTION.id && !shouldReconsider(question) && (!existing || existing.source === 'configuration') ) { - selectedOptionId = configuredTarget; + // Only a configured host can be unsupported; defaults name offered options. + selectedOptionId = configuredOption(question); if ( selectedOptionId && !question.options.some((option) => option.id === selectedOptionId) @@ -194,6 +202,20 @@ export class PlanningDecisionService { pending.delete(question.id); preferences.revision = randomUUID(); persist(); + if ( + source === 'user' && + question.id !== DEPLOYMENT_QUESTION.id && + configuredOption(question) !== selectedOptionId + ) { + // Offer reuse across flows without blocking the remaining prompts. + this.offerDefaultChoice(question, selectedOptionId).catch((error: unknown) => + LoggingService.getInstance().warn( + '[PlanningDecisions] Failed to save a workspace default choice', + error instanceof Error ? error : new Error(String(error)), + { questionId: question.id } + ) + ); + } if (hostChanged && pending.size > 0) { return preferences; } @@ -205,4 +227,26 @@ export class PlanningDecisionService { PlanningDecisionService.resolving.delete(flowId); } } + + private async offerDefaultChoice(question: PlanningQuestion, optionId: string): Promise { + const label = question.options.find((option) => option.id === optionId)?.label ?? optionId; + const action = await vscode.window.showInformationMessage( + UserPrompts.applyPlanningChoiceToAllFlows(question.question, label), + UserPrompts.BUTTON_APPLY_TO_ALL_FLOWS + ); + if (action !== UserPrompts.BUTTON_APPLY_TO_ALL_FLOWS) { + return; + } + // Read on click so defaults saved from other prompts meanwhile are kept; update only the + // workspace layer so user-level defaults are not copied into it. + const configuration = vscode.workspace.getConfiguration(CONFIGURATION_SECTION); + const saved = configuration.inspect(DEFAULT_CHOICES_SETTING)?.workspaceValue; + const defaults = + typeof saved === 'object' && saved !== null && !Array.isArray(saved) ? saved : {}; + await configuration.update( + DEFAULT_CHOICES_SETTING, + { ...defaults, [question.id]: optionId }, + vscode.ConfigurationTarget.Workspace + ); + } } diff --git a/src/stages/planning/PlanningDecisions.ts b/src/stages/planning/PlanningDecisions.ts index cc65a2d..2b91ced 100644 --- a/src/stages/planning/PlanningDecisions.ts +++ b/src/stages/planning/PlanningDecisions.ts @@ -71,6 +71,31 @@ export const DEPLOYMENT_QUESTION: PlanningQuestion = { ], }; +/** Stable IDs of standard planning questions; workspace default choices match them verbatim. */ +export const PLANNING_QUESTION_IDS = { + messaging: 'messaging', + modernization: 'modernization', + mapStrategy: 'map-strategy', + workflowTopology: 'workflow-topology', +} as const; + +/** + * Returns the workspace default answer (question ID → option ID) for a non-hosting question, + * only when that option is offered. Hosting comes from the deployment model setting instead. + */ +export function configuredDefaultOption( + question: PlanningQuestion, + defaults: unknown +): string | undefined { + if (!isRecord(defaults) || question.id === DEPLOYMENT_QUESTION.id) { + return undefined; + } + const optionId = defaults[question.id]; + return typeof optionId === 'string' && question.options.some((option) => option.id === optionId) + ? optionId + : undefined; +} + export function validatePlanningQuestion(value: unknown): asserts value is PlanningQuestion { if ( !isRecord(value) || diff --git a/src/test/unit/conversion-traceability.test.ts b/src/test/unit/conversion-traceability.test.ts new file mode 100644 index 0000000..ba86fd2 --- /dev/null +++ b/src/test/unit/conversion-traceability.test.ts @@ -0,0 +1,187 @@ +import * as assert from 'assert/strict'; +import { + checkTaskArtifacts, + renderTraceabilityMarkdown, + toOutputProjectName, + TraceableArtifact, +} from '../../stages/conversion/Traceability'; +import { ChatPrompts } from '../../constants/ChatPrompts'; +import { ConversionTaskPlan } from '../../stages/conversion/types'; + +const artifacts: TraceableArtifact[] = [ + { + id: 'orch-1', + name: 'InvoiceNotification', + type: 'orchestration', + sourcePath: 'Orch/Inv.odx', + }, + { id: 'map-1', name: 'InvoiceToNotification', type: 'map', sourcePath: 'Maps/E2N.btm' }, + { id: 'schema-1', name: 'Invoice', type: 'schema', sourcePath: 'Cdm/Invoice.xsd' }, + { + id: 'schema-2', + name: 'Notification', + type: 'schema', + sourcePath: 'Schemas/Notification.xsd', + }, + { + id: 'project-1', + name: 'Orchestrations', + type: 'custom-code', + sourcePath: 'Orch/Orchestrations.btproj', + }, + { + id: 'binding-1', + name: 'Contoso.Application', + type: 'binding', + sourcePath: 'Deploy/Bindings.xml', + }, + { + id: 'other-flow-schema', + name: 'Customer', + type: 'schema', + sourcePath: 'Schemas/Customer.xsd', + }, + { id: 'dup-a', name: 'Common', type: 'schema', sourcePath: 'A/Common.xsd' }, + { id: 'dup-b', name: 'Common', type: 'schema', sourcePath: 'B/Common.xsd' }, +]; +const flowArtifacts = artifacts.filter((a) => + ['orch-1', 'map-1', 'schema-1', 'schema-2', 'project-1', 'binding-1'].includes(a.id) +); + +describe('Conversion traceability', () => { + it('names the generated project folder like the conversion commands do', () => { + assert.equal(toOutputProjectName('Invoice Notification / v2'), 'Invoice-Notification-v2'); + assert.equal(toOutputProjectName('--Hello_World--'), 'Hello_World'); + }); + + it('resolves artifact names, rejects unknown references and reports uncovered artifacts', () => { + const result = checkTaskArtifacts( + [ + { id: 'convert-schemas', artifactIds: ['Invoice', 'schema-2'] }, + { id: 'generate-workflow', artifactIds: ['orch-1', 'NoSuchArtifact', 'Common'] }, + { id: 'scaffold-project' }, + ], + flowArtifacts, + artifacts + ); + assert.deepEqual(result.tasks, [ + { id: 'convert-schemas', artifactIds: ['schema-1', 'schema-2'] }, + { id: 'generate-workflow', artifactIds: ['orch-1'] }, + { id: 'scaffold-project' }, + ]); + assert.deepEqual(result.unknownReferences, [ + { taskId: 'generate-workflow', reference: 'NoSuchArtifact' }, + { taskId: 'generate-workflow', reference: 'Common' }, + ]); + // Projects and bindings need no conversion task; the map does. + assert.deepEqual( + result.uncoveredArtifacts.map((a) => a.id), + ['map-1'] + ); + }); + + it('renders source artifact → task → generated file traceability', () => { + const plan: ConversionTaskPlan = { + flowId: 'flow-invoicenotification', + flowName: 'Invoice Notification', + generatedAt: '2026-01-01T00:00:00.000Z', + summary: 'Convert', + tasks: [ + { + id: 'generate-workflow', + type: 'generate-workflow', + name: 'Generate | notification workflow', + description: 'Workflow', + dependsOn: ['convert-artifacts'], + status: 'completed', + order: 2, + artifactIds: ['orch-1'], + output: { + completedAt: '2026-01-01T00:00:00.000Z', + summary: 'done', + generatedFiles: ['out/Invoice-Notification/la/Notify/workflow.json'], + }, + }, + { + id: 'convert-artifacts', + type: 'convert-maps', + name: 'Convert map and schemas', + description: 'Maps', + dependsOn: [], + status: 'pending', + order: 1, + artifactIds: ['map-1', 'schema-1'], + }, + ], + }; + const byId = new Map(artifacts.map((a) => [a.id, a])); + const markdown = renderTraceabilityMarkdown(plan, (id) => byId.get(id)); + + assert.match(markdown, /^# Traceability — Invoice Notification\n/); + assert.match( + markdown, + /\| InvoiceNotification \| orchestration \| Orch\/Inv\.odx \| 2\. Generate \\\| notification workflow \| out\/Invoice-Notification\/la\/Notify\/workflow\.json \|/ + ); + assert.match( + markdown, + /\| Invoice \| schema \| Cdm\/Invoice\.xsd \| 1\. Convert map and schemas \| — \|/ + ); + assert.match( + markdown, + /## Tasks[\s\S]*\| 1 \| Convert map and schemas \| pending \| InvoiceToNotification, Invoice \| — \|[\s\S]*\| 2 \| Generate \\\| notification workflow \| completed \| InvoiceNotification \|/ + ); + }); + + it('escapes backslashes before pipes in table cells', () => { + const markdown = renderTraceabilityMarkdown( + { + flowId: 'f', + flowName: 'F', + generatedAt: '2026-01-01T00:00:00.000Z', + summary: '', + tasks: [ + { + id: 't', + type: 'convert-maps', + name: 'Convert', + description: '', + dependsOn: [], + status: 'pending', + order: 1, + artifactIds: ['a'], + }, + ], + }, + () => ({ id: 'a', name: 'Odd\\|Name', type: 'map', sourcePath: 'Maps\\A.btm' }) + ); + assert.ok(markdown.includes('| Odd\\\\\\|Name | map | Maps\\\\A.btm |')); + }); +}); + +describe('Conversion prompts', () => { + const base = { + flowName: 'Invoice Notification', + flowId: 'flow-invoicenotification', + azureResourceGroup: 'rg', + azureLocation: 'westeurope', + azureSubscriptionId: '', + outputProjectName: 'Invoice-Notification', + outputProjectRoot: 'out/Invoice-Notification', + outputLogicAppName: 'Invoice-Notification-logicapp', + outputLogicAppRoot: 'out/Invoice-Notification/Invoice-Notification-logicapp', + }; + + it('keeps Azure settings when provisioning is allowed', () => { + const prompt = ChatPrompts.conversionForFlow({ ...base, provisioningMode: 'provision' }); + assert.match(prompt, /AZURE SETTINGS: Resource Group="rg", Location="westeurope"/); + assert.match(prompt, /`automated-test-generation`/); + assert.ok(!prompt.includes('OFFLINE')); + }); + + it('forbids Azure provisioning in offline mode', () => { + const prompt = ChatPrompts.conversionForFlow({ ...base, provisioningMode: 'offline' }); + assert.match(prompt, /AZURE PROVISIONING: OFFLINE — do not sign in to Azure/); + assert.match(prompt, /Generate Bicep/); + assert.ok(!prompt.includes('AZURE SETTINGS:')); + }); +}); 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..0aa4a2f --- /dev/null +++ b/src/test/unit/flow-group-detector.test.ts @@ -0,0 +1,579 @@ +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'; +import { LLMFlowGenerator } from '../../services/LLMFlowGenerator'; + +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('keeps the IDs of same-named flows when their clusters change', () => { + const appA = artifact('c1111111', 'Process', 'orchestration', 'AppA/Process.odx'); + const appB = (calls?: string) => + artifact('c2222222', 'Process', 'orchestration', 'AppB/Process.odx', { + actions: calls + ? [ + { + type: 'call-workflow', + sourceMapping: { + biztalk: { + shapeType: 'CallOrchestration', + calledOrchestration: calls, + }, + }, + }, + ] + : [], + }); + const idOf = (groups: { id: string; artifactIds: string[] }[], artifactId: string) => + groups.find((group) => group.artifactIds.includes(artifactId))?.id; + + const before = detectFlowGroups([appA, appB()]).groups; + const after = detectFlowGroups([ + appA, + appB('Helper'), + artifact('c0000000', 'Helper', 'orchestration', 'AppB/Helper.odx'), + ]).groups; + + assert.notEqual(idOf(before, 'c1111111'), idOf(before, 'c2222222')); + assert.match(idOf(before, 'c1111111') ?? '', /^flow-process-[0-9a-f]{6}$/); + assert.equal(idOf(after, 'c1111111'), idOf(before, 'c1111111')); + assert.equal(idOf(after, 'c2222222'), idOf(before, 'c2222222')); + }); + + it('links maps only to schemas with the exact referenced name', () => { + const artifacts = [ + artifact('s-order', 'Order', 'schema', 'Schemas/Order.xsd', { + schemas: [{ id: 's1', name: 'Order', targetNamespace: 'urn:order' }], + }), + artifact('s-po', 'PurchaseOrder', 'schema', 'Schemas/PurchaseOrder.xsd', { + schemas: [{ id: 's2', name: 'PurchaseOrder', targetNamespace: 'urn:po' }], + }), + artifact('m-po', 'PurchaseOrderToInvoice', 'map', 'Maps/PO.btm', { + maps: [ + { + id: 'm', + name: 'PurchaseOrderToInvoice', + sourceSchema: 'Company.Schemas.PurchaseOrder', + }, + ], + }), + ]; + const edges = LLMFlowGenerator.getInstance() + .buildArtifactConnectionGraph(artifacts) + .connections.filter((c) => c.type === 'map-source-schema') + .map((c) => `${c.fromId}->${c.toId}`); + assert.deepEqual(edges, ['s-po->m-po']); + }); + + it('matches project references written with either path separator', () => { + const references = [ + `${appRoot}/Cdm/Cdm.btproj`, + [appRoot, 'Common', 'Common.btproj'].join('\\'), + ]; + const missing = findMissingProjectReferences([ + artifact( + 'project-orch', + 'Orchestrations', + 'custom-code', + 'Orch/Orchestrations.btproj', + { + extensions: { biztalk: { projectReferences: references } }, + } + ), + artifact('project-cdm', 'Cdm', 'custom-code', 'Cdm/Cdm.btproj'), + ]); + assert.deepEqual( + missing.map((m) => m.project), + ['Common'] + ); + }); + + 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/test/unit/flow-group-inventory.test.ts b/src/test/unit/flow-group-inventory.test.ts new file mode 100644 index 0000000..4ec27e0 --- /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/test/unit/planning-defaults.test.ts b/src/test/unit/planning-defaults.test.ts new file mode 100644 index 0000000..c4b7cfe --- /dev/null +++ b/src/test/unit/planning-defaults.test.ts @@ -0,0 +1,87 @@ +import * as assert from 'assert/strict'; +import { + configuredDefaultOption, + DEPLOYMENT_QUESTION, + PLANNING_QUESTION_IDS, + PlanningQuestion, +} from '../../stages/planning/PlanningDecisions'; + +const mapStrategyQuestion: PlanningQuestion = { + id: PLANNING_QUESTION_IDS.mapStrategy, + question: 'Where should maps run?', + whyItMatters: 'Map hosting affects deployment, scaling, and regression testing.', + options: [ + { + id: 'logic-app-xslt', + label: 'Logic App XSLT', + description: 'Transform XML with maps in Artifacts/Maps.', + }, + { + id: 'local-function', + label: 'Local function', + description: '.NET local function in the Logic App.', + }, + { + id: 'azure-function', + label: 'Azure Functions', + description: 'Separate .NET isolated Functions project called by workflows.', + }, + ], + recommendedOptionId: 'logic-app-xslt', +}; + +describe('Planning default choices', () => { + it('keeps the standard question IDs stable for workspace settings', () => { + assert.deepEqual(PLANNING_QUESTION_IDS, { + messaging: 'messaging', + modernization: 'modernization', + mapStrategy: 'map-strategy', + workflowTopology: 'workflow-topology', + }); + }); + + it('returns the configured option when the question offers it', () => { + const defaults = { + messaging: 'azure-service-bus', + 'map-strategy': 'azure-function', + 'workflow-topology': 'receiver-processor-sender', + }; + assert.equal(configuredDefaultOption(mapStrategyQuestion, defaults), 'azure-function'); + }); + + it('ignores unknown options and answers for other questions', () => { + assert.equal( + configuredDefaultOption(mapStrategyQuestion, { 'map-strategy': 'data-mapper' }), + undefined + ); + assert.equal( + configuredDefaultOption(mapStrategyQuestion, { messaging: 'azure-function' }), + undefined + ); + }); + + it('ignores configured values that are not strings', () => { + const values = [undefined, null, 1, true, ['azure-function'], { id: 'azure-function' }]; + for (const value of values) { + assert.equal( + configuredDefaultOption(mapStrategyQuestion, { 'map-strategy': value }), + undefined + ); + } + }); + + it('ignores defaults that are not a plain object', () => { + const listWithKey = Object.assign(['azure-function'], { 'map-strategy': 'azure-function' }); + for (const defaults of [undefined, null, 'azure-function', 42, listWithKey]) { + assert.equal(configuredDefaultOption(mapStrategyQuestion, defaults), undefined); + } + }); + + it('never answers hosting, which comes from the deployment model setting', () => { + assert.ok(DEPLOYMENT_QUESTION.options.some((option) => option.id === 'hybrid')); + assert.equal( + configuredDefaultOption(DEPLOYMENT_QUESTION, { [DEPLOYMENT_QUESTION.id]: 'hybrid' }), + undefined + ); + }); +}); diff --git a/src/test/unit/planning-requirements-markdown.test.ts b/src/test/unit/planning-requirements-markdown.test.ts new file mode 100644 index 0000000..63f1e2a --- /dev/null +++ b/src/test/unit/planning-requirements-markdown.test.ts @@ -0,0 +1,526 @@ +import * as assert from 'assert/strict'; +import * as fs from 'fs'; +import * as path from 'path'; +import type { FlowPlanningResult } from '../../stages/planning/PlanningCacheService'; +import { renderPlanningRequirementsMarkdown } from '../../services/reports/PlanningRequirementsMarkdown'; + +function fullPlan(): FlowPlanningResult { + return { + planId: 'plan-2026-01', + flowId: 'orders', + flowName: 'Orders', + generatedAt: '2026-01-02T03:04:05.000Z', + preferences: { + flowId: 'orders', + revision: 'rev-1', + status: 'ready', + updatedAt: '2026-01-01T00:00:00.000Z', + decisions: [ + { + id: 'deployment-target', + question: 'Where will these workflows run?', + whyItMatters: 'Hosting affects connector availability.', + options: [ + { + id: 'workflow-service-plan', + label: 'Azure-hosted Standard', + description: 'Workflow Service Plan.', + }, + { + id: 'hybrid', + label: 'Standard hybrid', + description: 'Your infrastructure via Azure Arc.', + }, + ], + selectedOptionId: 'hybrid', + source: 'user', + decidedAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'messaging', + question: 'Which broker should receive orders?', + whyItMatters: 'The queue owns delivery guarantees.', + options: [ + { + id: 'service-bus', + label: 'Service Bus', + description: 'Azure-managed broker.', + }, + { + id: 'rabbitmq', + label: 'RabbitMQ', + description: 'Customer-managed broker.', + }, + ], + selectedOptionId: 'service-bus', + source: 'user-request', + decidedAt: '2026-01-01T00:00:00.000Z', + }, + ], + }, + brief: { + scenarioName: 'Hybrid with Service Bus', + estimatedTimeline: '3-4 weeks', + assumptions: ['Customer provides hybrid infrastructure.'], + tradeoffs: ['Local ownership adds operational effort.'], + opportunities: [ + { + component: 'ParseOrder', + currentApproach: 'Custom XML parsing', + proposedApproach: 'Parse XML with Schema', + disposition: 'applied', + reason: 'Equivalent behavior verified.', + evidence: 'OrderParser.Parse and Order.xsd.', + }, + { + component: 'PricingRules', + currentApproach: 'C# rules library', + proposedApproach: 'Rules engine', + disposition: 'retained', + reason: 'Rewrite risk is too high.', + evidence: 'PricingRules.cs', + }, + { + component: 'AuditLog', + currentApproach: 'Custom log table', + proposedApproach: 'Application Insights', + disposition: 'deferred', + reason: 'Needs an operations review.', + evidence: 'AuditLogger.cs', + }, + ], + }, + mermaid: 'flowchart LR\n Receive --> Route', + explanation: 'Orders arrive over HTTP and are routed to fulfillment.', + workflows: [ + { + name: 'OrderIntake', + description: 'Receives and validates orders.', + triggerType: 'HTTP request', + actions: ['Parse order', 'Transform order', 'Send to queue'], + sourceArtifactIds: ['orch-orders', 'map-order'], + mermaid: 'flowchart TB\r\n Trigger --> Parse', + workflowDefinition: { + definition: { actions: { Marker: { type: 'definition-marker' } } }, + }, + }, + { + name: 'OrderFulfillment', + description: 'Fulfills queued orders.', + triggerType: 'Service Bus message', + actions: ['Ship order'], + sourceArtifactIds: ['send-port-fulfillment'], + }, + ], + azureComponents: [ + { + name: 'Azure Service Bus', + type: 'Messaging', + reason: 'Queue orders.', + configNotes: 'Standard tier', + }, + { name: 'Integration Account', type: 'B2B', reason: 'Host schemas and maps.' }, + ], + connectorMappings: [ + { + source: 'WCF-BasicHttp', + target: 'Request trigger', + isNative: true, + notes: 'Accepts JSON | XML\nbodies', + }, + ], + actionMappings: [ + { + source: 'ParseOrderShape', + target: 'Parse XML with schema', + workflowName: 'OrderIntake', + }, + { + source: 'SendShape', + target: 'Service Bus send', + workflowName: 'OrderFulfillment', + notes: 'Session enabled', + }, + ], + gaps: [ + { + component: 'Pipeline | Decoder', + gap: 'Line one\r\nLine two\nLine three', + severity: 'high', + recommendation: String.raw`Split on \| tokens in a local function`, + }, + ], + patterns: [ + { + name: 'Content-based routing', + sourceApproach: 'Filter expressions', + logicAppsApproach: 'Switch action', + complexity: 'medium', + }, + ], + effortEstimate: { + totalHours: 40, + breakdown: { analysis: 8, conversion: 16, testing: 10, deployment: 6 }, + confidence: 'medium', + }, + summary: 'Migrate order intake and fulfillment.', + artifactDispositions: [ + { + artifactName: 'POSchema', + artifactType: 'Schema', + conversionRequired: true, + conversionFrom: 'BizTalk XSD', + conversionTo: 'XSD', + conversionNotes: 'Remove BizTalk annotations', + uploadDestination: 'integration-account', + uploadPath: 'Artifacts/Schemas/POSchema.xsd', + }, + { + artifactName: 'OrderMap', + artifactType: 'Map', + conversionRequired: false, + uploadDestination: 'logic-app-artifact-folder', + uploadPath: 'Artifacts/Maps/OrderMap.xslt', + }, + { + artifactName: 'Bindings', + artifactType: 'Binding file', + conversionRequired: false, + uploadDestination: 'not-applicable', + uploadNotes: 'Replaced by connections.json', + }, + ], + }; +} + +function minimalPlan(): FlowPlanningResult { + return { + flowId: 'orders', + flowName: 'Orders', + generatedAt: '2026-01-02T03:04:05.000Z', + mermaid: '', + explanation: '', + workflows: [], + azureComponents: [], + connectorMappings: [], + actionMappings: [], + gaps: [], + patterns: [], + summary: 'Order migration', + }; +} + +function headings(markdown: string, level: number): string[] { + const prefix = `${'#'.repeat(level)} `; + return markdown + .split('\n') + .filter((line) => line.startsWith(prefix)) + .map((line) => line.slice(prefix.length)); +} + +/** Lines from a heading up to the next heading of the same or a higher level. */ +function sectionText(markdown: string, heading: string): string { + const level = heading.indexOf(' '); + const lines = markdown.split('\n'); + const start = lines.indexOf(heading); + assert.ok(start >= 0, `Missing heading: ${heading}`); + const end = lines.findIndex( + (line, index) => index > start && /^#{1,6} /.test(line) && line.indexOf(' ') <= level + ); + return lines.slice(start, end === -1 ? undefined : end).join('\n'); +} + +function tables(markdown: string): string[][] { + const result: string[][] = []; + let current: string[] = []; + for (const line of markdown.split('\n')) { + if (line.startsWith('|')) { + current.push(line); + } else if (current.length > 0) { + result.push(current); + current = []; + } + } + if (current.length > 0) { + result.push(current); + } + return result; +} + +/** Cells separated by unescaped pipes; backslash escape pairs never split a cell. */ +function cellCount(row: string): number { + return row.replace(/\\./g, '_').split('|').length - 2; +} + +describe('Planning requirements Markdown export', () => { + it('renders the title, plan metadata, and sections in requirements order', () => { + const markdown = renderPlanningRequirementsMarkdown(fullPlan()); + + assert.equal(markdown.split('\n')[0], '# Orders — Migration Requirements'); + assert.ok(markdown.includes('- **Flow ID:** `orders`')); + assert.ok(markdown.includes('- **Plan version:** `plan-2026-01`')); + assert.ok(markdown.includes('- **Plan generated:** 2026-01-02T03:04:05.000Z')); + assert.deepEqual(headings(markdown, 2), [ + 'Summary', + 'Planning Decisions', + 'Planning Brief', + 'Modernization Opportunities', + 'Target Architecture', + 'Planned Workflows', + 'Connector Mappings', + 'Action Mappings', + 'Artifact Dispositions', + 'Required Azure Components', + 'Gap Analysis', + 'Integration Patterns', + 'Effort Estimate', + 'Acceptance Criteria', + ]); + assert.deepEqual(headings(markdown, 3), [ + 'Assumptions', + 'Tradeoffs', + 'OrderIntake', + 'OrderFulfillment', + ]); + + const summary = sectionText(markdown, '## Summary'); + assert.ok(summary.includes('Migrate order intake and fulfillment.')); + assert.ok(summary.includes('Orders arrive over HTTP and are routed to fulfillment.')); + assert.ok( + markdown.includes( + '| Where will these workflows run? | Standard hybrid — Your infrastructure via Azure Arc. | user | Hosting affects connector availability. |' + ) + ); + assert.ok(markdown.includes('- **Scenario:** Hybrid with Service Bus')); + assert.ok(markdown.includes('- **Indicative timeline:** 3-4 weeks')); + assert.ok(markdown.includes('### Tradeoffs\n\n- Local ownership adds operational effort.')); + assert.ok( + markdown.includes( + '| ParseOrder | Custom XML parsing | Parse XML with Schema | applied | Equivalent behavior verified. | OrderParser.Parse and Order.xsd. |' + ) + ); + assert.ok( + markdown.includes('| OrderIntake | ParseOrderShape | Parse XML with schema | — |') + ); + assert.ok( + markdown.includes( + '| POSchema | Schema | BizTalk XSD → XSD | Integration Account | Artifacts/Schemas/POSchema.xsd | Remove BizTalk annotations |' + ) + ); + assert.ok( + markdown.includes( + '| Bindings | Binding file | Not required | Not applicable | — | Replaced by connections.json |' + ) + ); + assert.ok(markdown.includes('| Integration Account | B2B | Host schemas and maps. | — |')); + assert.ok( + markdown.includes( + '| Content-based routing | medium | Filter expressions | Switch action |' + ) + ); + assert.ok(markdown.includes('- **Total estimated hours:** 40\n- **Confidence:** medium')); + assert.ok(markdown.includes('| Conversion | 16 |')); + assert.ok(markdown.endsWith('\n') && !markdown.endsWith('\n\n')); + }); + + it('fences the target architecture and per-workflow diagrams as Mermaid', () => { + const markdown = renderPlanningRequirementsMarkdown(fullPlan()); + + assert.ok( + sectionText(markdown, '## Target Architecture').includes( + '```mermaid\nflowchart LR\n Receive --> Route\n```' + ) + ); + assert.ok( + sectionText(markdown, '### OrderIntake').includes( + '**Workflow diagram:**\n\n```mermaid\nflowchart TB\n Trigger --> Parse\n```' + ) + ); + assert.ok(!sectionText(markdown, '### OrderFulfillment').includes('```mermaid')); + assert.equal(markdown.match(/^```mermaid$/gm)?.length, 2); + assert.equal(markdown.match(/^```$/gm)?.length, 2); + }); + + it('renders one section per workflow with trigger, ordered actions, and source artifacts', () => { + const markdown = renderPlanningRequirementsMarkdown(fullPlan()); + const intake = sectionText(markdown, '### OrderIntake'); + + assert.ok(intake.includes('Receives and validates orders.')); + assert.ok(intake.includes('- **Trigger:** HTTP request')); + assert.ok(intake.includes('- **Source artifacts:** `orch-orders`, `map-order`')); + assert.ok( + intake.includes('**Actions:**\n\n1. Parse order\n2. Transform order\n3. Send to queue') + ); + assert.ok( + sectionText(markdown, '### OrderFulfillment').includes( + '- **Source artifacts:** `send-port-fulfillment`' + ) + ); + assert.ok(markdown.includes('The migration produces 2 Logic Apps Standard workflows.')); + assert.ok(!markdown.includes('definition-marker')); + assert.ok(!markdown.includes('workflowDefinition')); + }); + + it('escapes pipes and normalizes newlines inside table cells', () => { + const markdown = renderPlanningRequirementsMarkdown(fullPlan()); + + assert.ok( + markdown.includes( + String.raw`| Pipeline \| Decoder | Line one
Line two
Line three | high | Split on \\\| tokens in a local function |` + ) + ); + assert.ok( + markdown.includes( + String.raw`| WCF-BasicHttp | Request trigger | Yes | Accepts JSON \| XML
bodies |` + ) + ); + assert.ok(!markdown.includes('\r')); + const allTables = tables(markdown); + assert.equal(allTables.length, 9); + for (const table of allTables) { + assert.match(table[1], /^\|( --- \|)+$/); + for (const row of table) { + assert.equal(cellCount(row), cellCount(table[0]), row); + } + } + }); + + it('omits optional sections that have no content', () => { + const markdown = renderPlanningRequirementsMarkdown(minimalPlan()); + + assert.deepEqual(headings(markdown, 2), ['Summary']); + assert.ok(markdown.includes('Order migration')); + assert.ok(markdown.includes('- **Plan version:** Legacy')); + assert.equal(tables(markdown).length, 0); + + const withBrief = renderPlanningRequirementsMarkdown({ + ...minimalPlan(), + mermaid: 'flowchart LR\n A --> B', + brief: { + scenarioName: 'Lift and shift', + estimatedTimeline: '2 weeks', + assumptions: [], + tradeoffs: [], + opportunities: [], + }, + workflows: [ + { + name: 'OnlyWorkflow', + description: '', + triggerType: 'Recurrence', + actions: [], + sourceArtifactIds: [], + }, + ], + }); + assert.deepEqual(headings(withBrief, 2), [ + 'Summary', + 'Planning Brief', + 'Target Architecture', + 'Planned Workflows', + 'Acceptance Criteria', + ]); + assert.deepEqual(headings(withBrief, 3), ['OnlyWorkflow']); + const workflow = sectionText(withBrief, '### OnlyWorkflow'); + assert.ok(!workflow.includes('**Actions:**')); + assert.ok(!workflow.includes('Source artifacts')); + assert.ok(!workflow.includes('**Workflow diagram:**')); + assert.equal(withBrief.match(/```mermaid/g)?.length, 1); + for (const output of [markdown, withBrief]) { + assert.doesNotMatch(output, /^#{1,6} .*\n\n#{1,6} /m); + assert.doesNotMatch(output, /\n{3,}/); + } + }); + + it('never prints undefined for missing or legacy plan fields', () => { + const legacy = { + flowId: 'legacy-flow', + flowName: 'Legacy', + generatedAt: '2025-12-31T00:00:00.000Z', + mermaid: 'flowchart LR\n A --> B', + explanation: 'Legacy plan', + summary: 'Legacy summary', + workflows: [ + { + name: 'LegacyWorkflow', + description: 'Does work', + triggerType: 'Recurrence', + actions: ['Step'], + }, + ], + azureComponents: [{ name: 'Storage', type: 'Storage account', reason: 'Files' }], + connectorMappings: [{ source: 'FILE', target: 'File System', isNative: true }], + actionMappings: [{ source: 'Construct', target: 'Compose' }], + gaps: [{ component: 'Adapter', gap: 'No equivalent', severity: 'low' }], + effortEstimate: { totalHours: 8, confidence: 'low' }, + artifactDispositions: [ + { + artifactName: 'Map', + artifactType: 'Map', + conversionRequired: true, + uploadDestination: 'logic-app-artifact-folder', + }, + ], + } as unknown as FlowPlanningResult; + + const markdown = renderPlanningRequirementsMarkdown(legacy); + + assert.doesNotMatch(markdown, /undefined|null|NaN|\[object Object\]/); + assert.ok(markdown.includes('- **Plan version:** Legacy')); + assert.ok(markdown.includes('| — | Construct | Compose | — |')); + assert.ok( + markdown.includes('| Map | Map | Required | Logic App artifact folder | — | — |') + ); + assert.ok(!markdown.includes('## Integration Patterns')); + assert.ok(!markdown.includes('| Phase | Hours |')); + assert.ok( + markdown.includes( + '- [ ] Gap in Adapter (low severity): "No equivalent" is resolved or tracked as an open item.' + ) + ); + assert.ok( + markdown.includes( + '- [ ] `Map` (Map) is converted and delivered to the Logic App artifact folder.' + ) + ); + }); + + it('derives acceptance criteria only from plan content', () => { + const markdown = renderPlanningRequirementsMarkdown(fullPlan()); + const criteria = sectionText(markdown, '## Acceptance Criteria') + .split('\n') + .filter((line) => line.startsWith('- [ ] ')); + + assert.deepEqual(criteria, [ + '- [ ] Implements the selected option for "Where will these workflows run?": Standard hybrid.', + '- [ ] Implements the selected option for "Which broker should receive orders?": Service Bus.', + '- [ ] Workflow `OrderIntake` is triggered by "HTTP request", implements its 3 planned actions, and covers source artifacts `orch-orders`, `map-order`.', + '- [ ] Workflow `OrderFulfillment` is triggered by "Service Bus message", implements its 1 planned action, and covers source artifact `send-port-fulfillment`.', + '- [ ] Each source connector listed in Connector Mappings is replaced by its target connector.', + '- [ ] Each source action listed in Action Mappings is implemented with its target action.', + '- [ ] ParseOrder applies the planned modernization: Parse XML with Schema.', + '- [ ] PricingRules retains its current approach: C# rules library.', + '- [ ] Required Azure components are available to the workflows: Azure Service Bus, Integration Account.', + '- [ ] `POSchema` (Schema) is converted from BizTalk XSD to XSD and delivered to the Integration Account at `Artifacts/Schemas/POSchema.xsd`.', + '- [ ] `OrderMap` (Map) is delivered to the Logic App artifact folder at `Artifacts/Maps/OrderMap.xslt`.', + String.raw`- [ ] Gap in Pipeline | Decoder (high severity): the recommendation "Split on \| tokens in a local function" is implemented or tracked as an open item.`, + ]); + assert.ok(!criteria.some((line) => line.includes('AuditLog') || line.includes('Bindings'))); + assert.equal( + renderPlanningRequirementsMarkdown(fullPlan()), + markdown, + 'rendering must be deterministic' + ); + }); + + it('keeps the renderer free of VS Code dependencies', () => { + const source = fs.readFileSync( + path.resolve( + __dirname, + '../../../src/services/reports/PlanningRequirementsMarkdown.ts' + ), + 'utf8' + ); + assert.doesNotMatch(source, /from 'vscode'|require\('vscode'\)|from 'fs'/); + }); +}); diff --git a/src/test/unit/skills-lookup.test.ts b/src/test/unit/skills-lookup.test.ts new file mode 100644 index 0000000..b9a535d --- /dev/null +++ b/src/test/unit/skills-lookup.test.ts @@ -0,0 +1,146 @@ +import * as assert from 'assert/strict'; +import * as fs from 'fs'; +import * as path from 'path'; +import { + composeSkill, + isEditedManagedSkill, + sameSkillContent, + withContentHash, +} from '../../services/SkillOverlay'; +import { mappingSearchTerms, searchMappingSkill } from '../../services/MappingSkillLookup'; +import { isSimpleFlow } from '../../stages/discovery/FlowGroupInventory'; +import { ChatPrompts } from '../../constants/ChatPrompts'; + +const base = + '---\nname: workflow-json-generation-rules\n---\n\n# Skill\n\n- Rule A\n'; + +describe('Customer skill overrides', () => { + it('appends CUSTOM.md rules as an authoritative section', () => { + const composed = composeSkill( + base, + '\n- Always publish to topic `contoso-out`.\n', + 'workflow-json-generation-rules' + ); + assert.ok(composed.startsWith(base.trimEnd())); + assert.match( + composed, + /## Customer Overrides\n\n> Maintained in `\.github\/skills\/workflow-json-generation-rules\/CUSTOM\.md`\. When these rules conflict with the rules above, these rules win\.\n\n- Always publish to topic `contoso-out`\.\n$/ + ); + assert.equal(composeSkill(base, ' ', 'x'), base); + assert.equal(composeSkill(base, undefined, 'x'), base); + }); + + it('detects edits to extension-written skills but not to legacy files', () => { + const managed = withContentHash(base); + assert.equal(isEditedManagedSkill(managed), false); + assert.equal(isEditedManagedSkill(managed.replace(/\n/g, '\r\n')), false); + assert.equal( + isEditedManagedSkill(managed.replace('- Rule A', '- Rule A (changed by team)')), + true + ); + assert.equal(isEditedManagedSkill(base), false); + assert.ok(sameSkillContent(managed, managed.replace(/\n/g, '\r\n'))); + assert.ok(!sameSkillContent(managed, base)); + }); +}); + +describe('Mapping skill lookup', () => { + const skill = [ + '---', + 'name: source-to-logic-apps-mapping', + 'description: FILE and SQL mappings', + '---', + '# BizTalk to Logic Apps', + '## Adapter Mappings', + '', + '| BizTalk Component | Logic Apps Equivalent | Native? |', + '| ---------------- | --------------------- | ------- |', + '| FILE adapter (receive) | File System trigger | Yes |', + '| WCF-SQL adapter | SQL Server built-in connector | Yes |', + '| SB-Messaging | Service Bus built-in connector | Yes |', + '', + '## Pipeline Components', + '', + '| Component | Equivalent |', + '|---|---|', + '| XML Disassembler | XmlParse with schema |', + '', + '- Use the File System connector only on Standard; FILE paths must be mounted.', + ].join('\n'); + + it('splits comma-separated phrases or plain words into terms', () => { + assert.deepEqual(mappingSearchTerms('FILE adapter, WCF-SQL'), ['file adapter', 'wcf-sql']); + assert.deepEqual(mappingSearchTerms('SB-Messaging send'), ['sb-messaging', 'send']); + assert.deepEqual(mappingSearchTerms(' , x '), []); + }); + + it('returns matching rows with their section and columns, table rows first', () => { + const matches = searchMappingSkill(skill, 'file, xml disassembler'); + assert.deepEqual(matches, [ + { + section: 'Adapter Mappings', + columns: '| BizTalk Component | Logic Apps Equivalent | Native? |', + text: '| FILE adapter (receive) | File System trigger | Yes |', + }, + { + section: 'Pipeline Components', + columns: '| Component | Equivalent |', + text: '| XML Disassembler | XmlParse with schema |', + }, + { + section: 'Pipeline Components', + text: '- Use the File System connector only on Standard; FILE paths must be mounted.', + }, + ]); + assert.deepEqual(searchMappingSkill(skill, 'description'), []); + assert.equal(searchMappingSkill(skill, 'connector', 1).length, 1); + }); + + it('finds adapter rows in the bundled BizTalk mapping skill', () => { + const bundled = fs.readFileSync( + path.resolve( + __dirname, + '../../../resources/skills/source-to-logic-apps-mapping/biztalk/SKILL.md' + ), + 'utf-8' + ); + const matches = searchMappingSkill(bundled, 'WCF-SQL, SB-Messaging', 10); + assert.ok(matches.length > 0); + assert.ok(matches.every((m) => /wcf-sql|sb-messaging/i.test(m.text))); + assert.ok(JSON.stringify(matches).length < bundled.length / 5); + }); +}); + +describe('Fast path for small flows', () => { + it('applies only to small flows without custom code', () => { + const orchestration = { name: 'Orch', type: 'orchestration', sourcePath: 'O.odx' }; + const project = { name: 'Orchestrations', type: 'custom-code', sourcePath: 'O/O.btproj' }; + const helper = { name: 'Helper', type: 'custom-code', sourcePath: 'Lib/Helper.cs' }; + assert.equal(isSimpleFlow([orchestration, project]), true); + assert.equal(isSimpleFlow([orchestration, helper]), false); + assert.equal(isSimpleFlow([orchestration, undefined]), false); + assert.equal(isSimpleFlow([]), false); + assert.equal(isSimpleFlow(Array(7).fill(orchestration)), false); + }); + + it('adds the fast path and mapping lookup guidance to analysis and planning prompts', () => { + const analysis = ChatPrompts.flowAnalysis({ + flowName: 'A', + flowId: 'flow-a', + simpleFlow: true, + }); + assert.match(analysis, /FAST PATH: this flow is small and has no custom code/); + assert.match(analysis, /migration_lookupMapping/); + assert.match(analysis, /customer-standards\/SKILL\.md/); + assert.ok( + !ChatPrompts.flowAnalysis({ flowName: 'A', flowId: 'flow-a' }).includes('FAST PATH') + ); + const plan = ChatPrompts.planForFlow({ + flowName: 'A', + flowId: 'flow-a', + artifactList: 'Artifacts: none', + simpleFlow: true, + }); + assert.match(plan, /FAST PATH/); + }); +}); diff --git a/src/views/conversion/ConversionWebviewPanel.ts b/src/views/conversion/ConversionWebviewPanel.ts index ed51813..10bdf47 100644 --- a/src/views/conversion/ConversionWebviewPanel.ts +++ b/src/views/conversion/ConversionWebviewPanel.ts @@ -14,6 +14,7 @@ import * as path from 'path'; import { LoggingService } from '../../services/LoggingService'; import { ConversionService } from '../../stages/conversion/ConversionService'; import { ConversionFileService } from '../../stages/conversion/ConversionFileService'; +import { InventoryService } from '../../stages/discovery/InventoryService'; import { ConversionFlow, ConversionFlowStatus, @@ -768,6 +769,11 @@ export class ConversionWebviewPanel implements vscode.Disposable { color: var(--vscode-descriptionForeground); margin-bottom: 6px; } + .task-sources { + font-size: 11px; + color: var(--vscode-descriptionForeground); + margin-bottom: 6px; + } .task-meta { font-size: 11px; color: var(--vscode-descriptionForeground); @@ -1128,6 +1134,7 @@ export class ConversionWebviewPanel implements vscode.Disposable {
${taskActionHtml}
${this.escapeHtml(task.description)}
+ ${this.getTaskSourcesHtml(task.artifactIds)}
Type: ${this.escapeHtml(task.type)} ${dependsOnHtml} @@ -1180,6 +1187,21 @@ export class ConversionWebviewPanel implements vscode.Disposable {
`; } + /** + * Source artifacts a task converts or implements, by name. + */ + private getTaskSourcesHtml(artifactIds: readonly string[] | undefined): string { + if (!artifactIds || artifactIds.length === 0) { + return ''; + } + const inventory = InventoryService.getInstance(); + const names = artifactIds.map((id) => { + const item = inventory.getItem(id); + return item ? `${item.name} (${item.category})` : id; + }); + return `
Source: ${this.escapeHtml(names.join(', '))}
`; + } + /** * Render output details for a completed task. */ diff --git a/src/views/discovery/SourceFlowVisualizer.ts b/src/views/discovery/SourceFlowVisualizer.ts index 2dcad80..1d5e9a2 100644 --- a/src/views/discovery/SourceFlowVisualizer.ts +++ b/src/views/discovery/SourceFlowVisualizer.ts @@ -19,6 +19,12 @@ 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, + isSimpleFlow, +} from '../../stages/discovery/FlowGroupInventory'; import { GeneratedFlowResult, FlowGroupsResult } from '../../services/LLMFlowGenerator'; import { UserPrompts } from '../../constants/UserMessages'; import { ChatPrompts } from '../../constants/ChatPrompts'; @@ -106,7 +112,32 @@ export class SourceFlowVisualizer implements vscode.Disposable { * Uses the multi-step discovery tools (storeMeta, storeComponents, storeMessageFlow, etc.) */ public static buildFlowAnalysisPrompt(flowName: string, flowId: string): string { - return ChatPrompts.flowAnalysis({ flowName, flowId }); + return ChatPrompts.flowAnalysis({ + flowName, + flowId, + simpleFlow: SourceFlowVisualizer.isSimpleFlowGroup(flowId), + }); + } + + /** + * True when the flow is small and has no custom code (fast analysis and planning). + */ + public static isSimpleFlowGroup(flowId: string): boolean { + const group = SourceFlowVisualizer.getStaticCachedFlowGroups()?.groups.find( + (g) => g.id === flowId + ); + if (!group) { + return false; + } + const inventory = InventoryService.getInstance(); + return isSimpleFlow( + group.artifactIds.map((id) => { + const item = inventory.getItem(id); + return item + ? { name: item.name, type: item.category, sourcePath: item.sourcePath } + : undefined; + }) + ); } /** @@ -204,6 +235,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 @@ -244,6 +295,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); @@ -357,17 +425,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}
    @@ -628,24 +731,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}