Skip to content

feat: add command workflow execute#9

Merged
UlisesGascon merged 11 commits intomainfrom
feat/workflow-run
Jun 21, 2025
Merged

feat: add command workflow execute#9
UlisesGascon merged 11 commits intomainfrom
feat/workflow-run

Conversation

@UlisesGascon
Copy link
Member

@UlisesGascon UlisesGascon commented Jun 21, 2025

Related #1
Related #OpenPathfinder/visionBoard#249 (no merge before this)

Summary by CodeRabbit

  • New Features

    • Added the ability to execute compliance workflows via a new CLI subcommand, supporting data input directly or from a file.
    • Workflows can now require and validate additional data against a JSON schema before execution.
    • Only enabled workflows are listed and executable in the CLI.
  • Improvements

    • Enhanced workflow execution output with detailed status, timing, and result messages.
  • Bug Fixes

    • Disabled workflows are now excluded from workflow listings.
  • Tests

    • Added comprehensive tests for workflow execution, including success, failure, and error scenarios.
  • Chores

    • Added dependencies for JSON schema validation.

@UlisesGascon UlisesGascon self-assigned this Jun 21, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jun 21, 2025

Walkthrough

The changes introduce workflow execution functionality to the CLI, including schema-based data validation using Ajv. New types and API methods support workflow runs, with enhanced test coverage for execution scenarios and error handling. The CLI now allows users to execute workflows with optional data, ensuring only enabled workflows are listed and executed.

Changes

File(s) Change Summary
package.json Added dependencies: ajv@8.17.1, ajv-formats@3.0.1.
src/types.ts Added APIWorkflowRunItem and WorkflowOperationItem interfaces; extended APIWorkflowItem.
src/api-client.ts Added runWorkflow function to initiate workflow execution via API.
src/utils.ts Added validateData function using Ajv for JSON schema validation.
src/cli-commands.ts Filtered out disabled workflows in printWorkflows; added executeWorkflow for workflow execution.
src/index.ts Added workflow execute subcommand with data input, validation, and execution logic.
src/tests/fixtures.ts Added mock workflow run response and extended workflow fixture properties.
src/tests/cli-commands.test.ts Added tests for workflow execution, error handling, and filtering of disabled workflows.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant APIClient
    participant Utils

    User->>CLI: workflow execute --workflow <name> [--data | --file]
    CLI->>APIClient: getAllWorkflows()
    APIClient-->>CLI: List of workflows
    CLI->>CLI: Find and validate workflow (enabled, exists)
    CLI->>Utils: validateData(data, schema)
    Utils-->>CLI: Validation result
    alt Validation success
        CLI->>APIClient: runWorkflow(workflowId, data)
        APIClient-->>CLI: Workflow run result
        CLI->>User: Output execution result
    else Validation failure
        CLI->>User: Output validation errors
    end
Loading

Poem

A hop, a skip, a schema check—
Now workflows run with just one spec!
Enabled only, the list is neat,
With Ajv’s help, the checks complete.
From test to run, the code’s in sync,
This bunny’s proud—let’s raise a drink!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f526d89 and 87e783a.

📒 Files selected for processing (3)
  • src/__tests__/cli-commands.test.ts (3 hunks)
  • src/cli-commands.ts (3 hunks)
  • src/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/cli-commands.ts
  • src/index.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/__tests__/cli-commands.test.ts (3)
src/cli-commands.ts (2)
  • printWorkflows (114-141)
  • executeWorkflow (143-167)
src/types.ts (2)
  • APIWorkflowRunItem (169-175)
  • APIErrorResponse (190-196)
src/__tests__/fixtures.ts (1)
  • mockAPIWorkflowRunResponse (134-140)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test on macOS-latest with Node 24.x
  • GitHub Check: Test on windows-latest with Node 22.x
  • GitHub Check: Test on ubuntu-latest with Node 24.x
  • GitHub Check: Test on macOS-latest with Node 20.x
  • GitHub Check: Test on windows-latest with Node 20.x
  • GitHub Check: Test on macOS-latest with Node 22.x
  • GitHub Check: Test on windows-latest with Node 24.x
  • GitHub Check: Test on ubuntu-latest with Node 22.x
  • GitHub Check: Test on ubuntu-latest with Node 20.x
🔇 Additional comments (6)
src/__tests__/cli-commands.test.ts (6)

3-6: LGTM! Import additions are well-structured.

The new imports for executeWorkflow, APIWorkflowRunItem, and mockAPIWorkflowRunResponse are properly added to support the new test functionality.


435-459: Excellent test coverage for disabled workflow filtering.

This test correctly verifies that workflows with isEnabled: false are excluded from the output, which aligns perfectly with the filtering logic in the printWorkflows implementation.


508-536: Comprehensive test for successful workflow execution.

The test properly validates all aspects of successful execution including timing calculations, status reporting, and detailed output formatting. The expectation of "2.50 seconds" correctly matches the 2500ms difference between the mock timestamps.


538-556: Correct handling of unsuccessful workflow execution.

The test properly distinguishes between command execution success and workflow execution failure - the command itself succeeds (returns success: true) even when the workflow fails, which is the correct behavior for CLI command execution.


558-571: Solid API error handling test.

The test correctly verifies that API errors (404 workflow not found) are properly caught and result in command failure with appropriate error messaging.


573-587: Thorough network error handling coverage.

The test ensures network errors are gracefully handled and properly reported, maintaining consistent error messaging patterns with other CLI commands.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/utils.ts (1)

54-67: Improve error handling and type safety in validateData.

The function uses any types which reduces type safety, and the error mapping could be more robust.

Consider this improvement:

-export const validateData = (data: any, schema: any) => {
+export const validateData = (data: unknown, schema: object) => {
   const validate = ajv.compile(schema)
   const valid = validate(data)
   if (!valid) {
     return {
       success: false,
-      messages: validate.errors?.map((error: any) => error.message) || []
+      messages: validate.errors?.map((error) => `${error.instancePath || 'root'}: ${error.message}`) || ['Validation failed']
     }
   }
   return {
     success: true,
     messages: []
   }
 }

This provides better error context and improves type safety.

src/cli-commands.ts (1)

143-166: Enhance workflow execution output and error handling.

The function provides comprehensive execution details, but the duration display and success determination could be improved.

Consider these enhancements:

 export const executeWorkflow = async (workflowId: string, data: any): Promise<CommandResult> => {
   const messages: string[] = []
-  let success = true
   try {
     const results = await runWorkflow(workflowId, data)
     const startTime = new Date(results.started)
     const endTime = new Date(results.finished)
     const duration = endTime.getTime() - startTime.getTime()
+    const success = results.result.success

-    messages.push(`Workflow executed ${results.result.success ? 'successfully' : 'unsuccessfully'} in ${duration} ms`)
+    messages.push(`Workflow executed ${success ? 'successfully' : 'unsuccessfully'} in ${duration < 1000 ? duration + ' ms' : (duration / 1000).toFixed(2) + ' seconds'}`)
     messages.push(`- Status: ${results.status}`)
     messages.push(`- Started: ${startTime}`)
     messages.push(`- Finished: ${endTime}`)
     messages.push(`- Result: ${results.result.message}`)
+    
+    return {
+      messages,
+      success
+    }
   } catch (error) {
     messages.push(`❌ Failed to execute the workflow: ${error instanceof Error ? error.message : 'Unknown error'}`)
-    success = false
+    return {
+      messages,
+      success: false
+    }
   }
-
-  return {
-    messages,
-    success
-  }
 }

This bases success on the workflow result rather than just API call success and improves duration formatting.

src/index.ts (1)

47-47: TODO acknowledged for future refactoring.

The TODO comment indicates this validation logic should be moved to utils when the backend has workflows requiring additional data. This is acceptable for the current implementation.

Would you like me to create an issue to track this refactoring task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 30eed17 and f526d89.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • package.json (1 hunks)
  • src/__tests__/cli-commands.test.ts (3 hunks)
  • src/__tests__/fixtures.ts (2 hunks)
  • src/api-client.ts (2 hunks)
  • src/cli-commands.ts (3 hunks)
  • src/index.ts (2 hunks)
  • src/types.ts (1 hunks)
  • src/utils.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
src/__tests__/fixtures.ts (1)
src/types.ts (1)
  • APIWorkflowRunItem (169-175)
src/api-client.ts (1)
src/types.ts (1)
  • APIWorkflowRunItem (169-175)
src/index.ts (3)
src/api-client.ts (1)
  • getAllWorkflows (74-81)
src/utils.ts (2)
  • validateData (54-67)
  • handleCommandResult (45-52)
src/cli-commands.ts (1)
  • executeWorkflow (143-166)
src/cli-commands.ts (2)
src/types.ts (1)
  • CommandResult (205-208)
src/api-client.ts (1)
  • runWorkflow (83-94)
src/__tests__/cli-commands.test.ts (3)
src/cli-commands.ts (2)
  • printWorkflows (114-141)
  • executeWorkflow (143-166)
src/types.ts (2)
  • APIWorkflowRunItem (169-175)
  • APIErrorResponse (190-196)
src/__tests__/fixtures.ts (1)
  • mockAPIWorkflowRunResponse (134-140)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Test on windows-latest with Node 20.x
  • GitHub Check: Test on windows-latest with Node 22.x
  • GitHub Check: Test on windows-latest with Node 24.x
  • GitHub Check: Test on ubuntu-latest with Node 24.x
  • GitHub Check: Test on macOS-latest with Node 24.x
  • GitHub Check: Test on ubuntu-latest with Node 20.x
  • GitHub Check: Test on ubuntu-latest with Node 22.x
🔇 Additional comments (6)
package.json (1)

42-43: The initial audit failed due to a missing lockfile. Let’s generate one and re-run the security check:

#!/bin/bash
# Create a minimal lockfile and re-run npm audit for ajv dependencies
npm i --package-lock-only
npm audit --audit-level=moderate --json | \
  jq '.vulnerabilities | to_entries[] | select(.key == "ajv" or .key == "ajv-formats")'
src/api-client.ts (1)

83-94: Well-implemented async workflow execution.

The function correctly handles asynchronous workflow execution with appropriate status code expectation (202 Accepted) and follows the established error handling pattern.

Minor suggestion for payload construction:

-  const payload = data ? { data } : {}
+  const payload = data !== undefined ? { data } : {}

This handles the case where data is explicitly null or false, which might be valid workflow inputs.

src/__tests__/fixtures.ts (1)

127-140: Well-structured test fixtures for workflow execution.

The fixture updates properly support the new workflow execution functionality with realistic mock data. The timestamps and result structure align with the expected APIWorkflowRunItem interface.

src/cli-commands.ts (1)

128-131: Good UX improvement filtering enabled workflows.

Filtering out disabled workflows in the CLI output improves user experience by showing only actionable options.

src/types.ts (1)

144-175: LGTM! Well-structured type definitions for workflow execution.

The new interfaces and type extensions properly support the workflow execution feature. Good practice adding the TODO comment for future refactoring of WorkflowOperationItem.

src/__tests__/cli-commands.test.ts (1)

435-588: Excellent test coverage for the new workflow execution functionality!

The tests comprehensively cover:

  • Filtering of disabled workflows
  • Successful and unsuccessful workflow execution
  • Proper error handling for API and network errors
  • Detailed assertions on response messages and timing calculations

The test implementation follows the existing patterns and provides good coverage for the new feature.

@UlisesGascon UlisesGascon merged commit e8dc599 into main Jun 21, 2025
10 checks passed
@UlisesGascon UlisesGascon deleted the feat/workflow-run branch June 21, 2025 10:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant