workflows

package
v0.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2026 License: GPL-3.0 Imports: 18 Imported by: 0

README

Temporal Workflows

This package contains Temporal workflow definitions for contextd automation tasks.

Plugin Update Validation Workflow

Automated workflow that validates Claude plugin updates in pull requests.

Overview

The PluginUpdateValidationWorkflow monitors pull requests for code changes that require corresponding plugin updates. When code is modified that affects MCP tools, services, or configuration, the workflow:

  1. Detects the changes
  2. Checks if the .claude-plugin/ directory was updated
  3. Validates plugin schemas if modified
  4. Posts reminder or success comments to the PR
Architecture
GitHub PR Event
      ↓
GitHub Webhook Server (cmd/github-webhook)
      ↓
Temporal Workflow Engine
      ↓
Plugin Validation Workflow
      ├── FetchPRFilesActivity (GitHub API)
      ├── CategorizeFilesActivity (regex patterns)
      ├── ValidatePluginSchemasActivity (JSON validation)
      └── PostCommentActivity (GitHub API)
Components
Component Purpose Location
Workflow Orchestrates validation steps plugin_validation.go
Activities GitHub API interactions, validation plugin_validation_activities.go
Worker Executes workflows and activities cmd/plugin-validator/main.go
Webhook Server Receives GitHub events cmd/github-webhook/main.go
Running the Stack
Prerequisites
  • Docker and Docker Compose
  • GitHub personal access token (for API access)
  • GitHub webhook secret (for webhook validation)
Local Development
# Set environment variables
export GITHUB_TOKEN=ghp_your_token_here
export GITHUB_WEBHOOK_SECRET=your_secret_here

# Start the full stack
docker-compose -f deploy/docker-compose.temporal.yml up

# Access Temporal Web UI
open http://localhost:8080

The stack includes:

  • PostgreSQL (Temporal state store) on port 5432
  • Temporal Server (gRPC) on port 7233
  • Temporal Web UI on port 8080
  • GitHub Webhook Server on port 3000
  • Plugin Validator Worker (background)
GitHub Webhook Configuration
  1. Go to your repository Settings > Webhooks
  2. Add webhook:
    • Payload URL: https://your-domain.com/webhook
    • Content type: application/json
    • Secret: Your webhook secret
    • Events: Pull requests (opened, synchronize, reopened)
File Categorization

The workflow categorizes changed files into two categories:

Code Files (require plugin update)
  • internal/mcp/tools.go - MCP tool definitions
  • internal/mcp/handlers/*.go - MCP tool handlers
  • internal/*/service.go - Service implementations
  • internal/config/{types,config}.go - Configuration types
Plugin Files
  • .claude-plugin/**/* - All plugin files
Validation Behavior
Scenario Action
Code changed, plugin NOT updated Post reminder comment
Code changed, plugin updated, schemas valid Post success comment
Code changed, plugin updated, schemas invalid Post error details
Only docs/tests changed No action
Testing
# Run workflow tests
go test ./internal/workflows/... -v

# Test specific workflow
go test ./internal/workflows/... -run TestPluginUpdateValidationWorkflow -v

# Test activity categorization
go test ./internal/workflows/... -run TestCategorizeFilesActivity -v
Environment Variables
Variable Required Description
GITHUB_TOKEN Yes GitHub personal access token for API access
GITHUB_WEBHOOK_SECRET Yes Secret for validating webhook signatures
TEMPORAL_HOST No Temporal server address (default: localhost:7233)
PORT No Webhook server port (default: 3000)
Monitoring
  • Temporal Web UI: http://localhost:8080 - View workflow executions, activity status, and errors
  • Workflow Logs: Check worker container logs for detailed execution traces
  • GitHub Comments: Workflow posts comments to PRs with validation results
Extending

To add new file patterns to detect:

  1. Edit CategorizeFilesActivity in plugin_validation_activities.go
  2. Add regex pattern to codePatterns slice
  3. Update tests in plugin_validation_test.go

To customize comments:

  1. Edit buildReminderComment() or buildSuccessComment() functions
  2. Update comment templates with your messaging
  • Issue #56: Claude plugin update validation automation
  • CLAUDE.md: Priority #3 - Update Claude Plugin on Changes
  • PR Template: .github/pull_request_template.md

Version Validation Workflow

Automated workflow that ensures VERSION file consistency across the codebase.

Overview

The VersionValidationWorkflow validates that the VERSION file matches the version in .claude-plugin/plugin.json for all pull requests. This prevents version mismatches that could cause confusion about which version is deployed.

When versions don't match, the workflow:

  1. Detects the mismatch
  2. Posts a detailed comment explaining the issue
  3. Provides exact commands to fix the problem
  4. Auto-updates the comment if versions are later synced
Architecture
GitHub PR Event (VERSION or plugin.json changed)
      ↓
GitHub Webhook Server
      ↓
Temporal Workflow Engine
      ↓
Version Validation Workflow
      ├── FetchFileContentActivity (VERSION)
      ├── FetchFileContentActivity (plugin.json)
      ├── Compare versions
      └── PostVersionMismatchCommentActivity (if needed)
Components
Component Purpose Location
Workflow Orchestrates version validation version_validation.go
Activities Fetches files, posts comments version_validation_activities.go
Tests Comprehensive test coverage version_validation_test.go
Validation Logic

Version matching:

  • Fetches VERSION file content from PR HEAD
  • Fetches .claude-plugin/plugin.json from PR HEAD
  • Parses JSON to extract version field
  • Compares versions (after trimming whitespace)
  • Posts comment only if versions don't match

Supported version formats:

  • Standard semantic versions: 1.2.3
  • Pre-release versions: 1.0.0-rc.1
  • Build metadata: 1.0.0+build.123
  • Complex versions: 2.0.0-beta.1+exp.sha.5114f85
Comment Behavior
Scenario Action
Versions match No comment posted
Versions don't match (first time) Post new mismatch comment
Versions don't match (updated PR) Update existing mismatch comment
Versions fixed after comment Comment remains (manual removal or future enhancement)
Testing
# Run workflow tests
go test ./internal/workflows/... -run TestVersionValidationWorkflow -v

# Run all version validation tests
go test ./internal/workflows/... -run Version -v

# Test the sync script itself
./scripts/sync-version_test.sh
Configuration

The workflow is triggered automatically by the webhook server when:

  • Pull request is opened
  • Pull request is synchronized (new commits pushed)
  • Pull request is reopened

No manual configuration required beyond standard webhook setup.

  • scripts/sync-version.sh - Script to sync versions across files
  • scripts/sync-version_test.sh - Test suite for sync script
  • docs/VERSIONING.md - Complete version management documentation
  • VERSION - Single source of truth for version

Documentation

Overview

Package workflows provides Temporal workflow definitions for contextd automation.

Package workflows provides Temporal workflow definitions for contextd automation.

This file contains shared types used across multiple workflows and activities.

Package workflows provides Temporal workflow definitions for contextd automation.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidInput indicates workflow input validation failed.
	ErrInvalidInput = errors.New("invalid workflow input")

	// ErrEmptyField indicates a required field is empty.
	ErrEmptyField = errors.New("required field is empty")

	// ErrInvalidGitHubIdentifier indicates an invalid GitHub owner/repo name.
	ErrInvalidGitHubIdentifier = errors.New("invalid GitHub identifier")

	// ErrInvalidPRNumber indicates an invalid PR number.
	ErrInvalidPRNumber = errors.New("invalid PR number")

	// ErrPathTraversal indicates a path contains traversal attempts.
	ErrPathTraversal = errors.New("path traversal detected")

	// ErrMissingToken indicates GitHubToken is missing.
	ErrMissingToken = errors.New("GitHub token is required")
)

Validation errors

Functions

func FetchFileContentActivity

func FetchFileContentActivity(ctx context.Context, input FetchFileContentInput) (string, error)

FetchFileContentActivity fetches the content of a single file from GitHub.

func FormatErrorForResult added in v0.3.2

func FormatErrorForResult(operation string, err error) string

FormatErrorForResult formats an error for inclusion in workflow result.Errors slice. This creates a human-readable error message for end users.

func NewGitHubClient

func NewGitHubClient(ctx context.Context, token config.Secret) (*github.Client, error)

NewGitHubClient creates a GitHub client with proper authentication.

func RemoveVersionMismatchCommentActivity

func RemoveVersionMismatchCommentActivity(ctx context.Context, input PostVersionCommentInput) error

RemoveVersionMismatchCommentActivity removes the version mismatch comment if it exists. This is called when versions match to clean up any previous mismatch comments.

func WrapActivityError added in v0.3.2

func WrapActivityError(operation string, err error) error

WrapActivityError wraps an activity error with operation context. Use this when an activity fails to provide consistent error messages.

Types

type CategorizeFilesInput

type CategorizeFilesInput struct {
	Files []FileChange // List of files to categorize
}

CategorizeFilesInput defines parameters for file categorization.

type CategorizedFiles

type CategorizedFiles struct {
	CodeFiles   []string // Files that affect plugin behavior
	PluginFiles []string // Files in .claude-plugin/
	OtherFiles  []string // Other files (tests, docs, etc.)
}

CategorizedFiles contains files categorized by type.

func CategorizeFilesActivity

func CategorizeFilesActivity(ctx context.Context, input CategorizeFilesInput) (*CategorizedFiles, error)

CategorizeFilesActivity categorizes files by whether they affect the plugin.

Error Handling:

  • This activity performs pure logic and doesn't fail under normal circumstances
  • No external dependencies, so no network or I/O errors

type DocumentationValidationInput

type DocumentationValidationInput struct {
	Owner       string   // Repository owner
	Repo        string   // Repository name
	PRNumber    int      // Pull request number
	HeadSHA     string   // Commit SHA
	CodeFiles   []string // List of code files changed
	PluginFiles []string // List of plugin files changed
}

DocumentationValidationInput defines parameters for ValidateDocumentationActivity.

type DocumentationValidationResult

type DocumentationValidationResult struct {
	Valid          bool              `json:"valid"`                    // Whether documentation is valid
	Summary        string            `json:"summary"`                  // Summary of validation
	FilesReviewed  int               `json:"files_reviewed,omitempty"` // Number of files reviewed
	CriticalIssues []ValidationIssue `json:"critical_issues"`          // Critical issues found
	HighIssues     []ValidationIssue `json:"high_issues"`              // High priority issues
	MediumIssues   []ValidationIssue `json:"medium_issues"`            // Medium priority issues
	LowIssues      []ValidationIssue `json:"low_issues"`               // Low priority issues
}

DocumentationValidationResult represents validation findings.

func ValidateDocumentationActivity

func ValidateDocumentationActivity(ctx context.Context, input DocumentationValidationInput) (*DocumentationValidationResult, error)

ValidateDocumentationActivity validates that plugin docs match code changes. TODO: Implement Claude API integration

type ErrorSeverity added in v0.3.2

type ErrorSeverity string

Error severity levels for workflow errors

const (
	// ErrorSeverityCritical indicates the workflow must fail
	ErrorSeverityCritical ErrorSeverity = "critical"
	// ErrorSeverityHigh indicates a major issue but workflow can continue
	ErrorSeverityHigh ErrorSeverity = "high"
	// ErrorSeverityLow indicates a minor issue that doesn't affect main functionality
	ErrorSeverityLow ErrorSeverity = "low"
)

type FetchFileContentInput

type FetchFileContentInput struct {
	Owner       string        // Repository owner
	Repo        string        // Repository name
	Path        string        // File path (restricted to allowed paths)
	Ref         string        // Commit SHA or branch name
	GitHubToken config.Secret // GitHub API token
}

FetchFileContentInput defines parameters for fetching file content from GitHub.

func (*FetchFileContentInput) ValidateComprehensive added in v0.3.2

func (i *FetchFileContentInput) ValidateComprehensive() error

ValidateComprehensive performs comprehensive validation with GitHub identifier patterns, path traversal checks, and other security validations.

type FetchPRFilesInput

type FetchPRFilesInput struct {
	Owner       string        // Repository owner
	Repo        string        // Repository name
	PRNumber    int           // Pull request number
	GitHubToken config.Secret // GitHub API token
}

FetchPRFilesInput defines parameters for fetching PR file changes.

func (*FetchPRFilesInput) ValidateComprehensive added in v0.3.2

func (i *FetchPRFilesInput) ValidateComprehensive() error

ValidateComprehensive performs comprehensive validation with GitHub identifier patterns, path traversal checks, and other security validations.

type FileChange

type FileChange struct {
	Path      string // File path relative to repository root
	Status    string // "added", "modified", "removed", "renamed"
	Additions int    // Number of lines added
	Deletions int    // Number of lines deleted
}

FileChange represents a changed file in a pull request.

func FetchPRFilesActivity

func FetchPRFilesActivity(ctx context.Context, input FetchPRFilesInput) ([]FileChange, error)

FetchPRFilesActivity fetches the list of files changed in a PR.

Error Handling:

  • Returns error if GitHub client creation fails
  • Returns error if listing PR files fails (404, network errors, etc.)

type GitHubClientConfig

type GitHubClientConfig struct {
	Token config.Secret // GitHub API token
}

GitHubClientConfig holds GitHub client configuration.

type PluginUpdateValidationConfig

type PluginUpdateValidationConfig struct {
	Owner              string        // GitHub repository owner
	Repo               string        // GitHub repository name
	PRNumber           int           // Pull request number
	BaseBranch         string        // Base branch (usually "main")
	HeadBranch         string        // PR branch
	HeadSHA            string        // PR commit SHA
	GitHubToken        config.Secret // GitHub API token for activities
	UseAgentValidation bool          // Whether to use AI agent for documentation validation
}

PluginUpdateValidationConfig configures the plugin validation workflow.

func (*PluginUpdateValidationConfig) ValidateComprehensive added in v0.3.2

func (c *PluginUpdateValidationConfig) ValidateComprehensive() error

ValidateComprehensive performs comprehensive validation with GitHub identifier patterns, path traversal checks, and other security validations.

type PluginUpdateValidationResult

type PluginUpdateValidationResult struct {
	CodeFilesChanged   []string                       // Files that affect plugin behavior
	PluginFilesChanged []string                       // Files in .claude-plugin/
	NeedsUpdate        bool                           // Whether plugin needs updating
	SchemaValid        bool                           // Whether schemas are valid JSON
	AgentValidation    *DocumentationValidationResult // Agent validation results (if enabled)
	AgentValidationRan bool                           // Whether agent validation was executed
	CommentPosted      bool                           // Whether we posted a comment
	CommentURL         string                         // URL of posted comment
	Errors             []string                       // Any errors encountered
}

PluginUpdateValidationResult contains validation results.

func PluginUpdateValidationWorkflow

func PluginUpdateValidationWorkflow(ctx workflow.Context, config PluginUpdateValidationConfig) (*PluginUpdateValidationResult, error)

PluginUpdateValidationWorkflow validates plugin updates in a PR.

This workflow: 1. Fetches PR file changes from GitHub 2. Detects if code changes require plugin updates 3. Validates plugin schemas if modified 4. Posts reminder comments if needed 5. Posts success message if plugin updated correctly

type PostCommentInput

type PostCommentInput struct {
	Owner           string                         // Repository owner
	Repo            string                         // Repository name
	PRNumber        int                            // Pull request number
	CodeFiles       []string                       // List of code files changed
	PluginFiles     []string                       // List of plugin files changed
	GitHubToken     config.Secret                  // GitHub API token
	AgentValidation *DocumentationValidationResult // Optional agent validation results
}

PostCommentInput defines parameters for posting comments.

type PostCommentResult

type PostCommentResult struct {
	URL string // URL of the posted or updated comment
}

PostCommentResult represents the result of posting a GitHub comment.

func PostReminderCommentActivity

func PostReminderCommentActivity(ctx context.Context, input PostCommentInput) (*PostCommentResult, error)

PostReminderCommentActivity posts a reminder comment to the PR.

func PostSuccessCommentActivity

func PostSuccessCommentActivity(ctx context.Context, input PostCommentInput) (*PostCommentResult, error)

PostSuccessCommentActivity posts a success message to the PR.

func PostVersionMismatchCommentActivity

func PostVersionMismatchCommentActivity(ctx context.Context, input PostVersionCommentInput) (*PostCommentResult, error)

PostVersionMismatchCommentActivity posts a version mismatch comment to the PR.

type PostVersionCommentInput

type PostVersionCommentInput struct {
	Owner         string        // Repository owner
	Repo          string        // Repository name
	PRNumber      int           // Pull request number
	VersionFile   string        // Version from VERSION file
	PluginVersion string        // Version from plugin.json
	GitHubToken   config.Secret // GitHub API token
}

PostVersionCommentInput defines parameters for posting version-related comments.

func (*PostVersionCommentInput) ValidateComprehensive added in v0.3.2

func (i *PostVersionCommentInput) ValidateComprehensive() error

ValidateComprehensive performs comprehensive validation with GitHub identifier patterns, path traversal checks, and other security validations.

type RetryConfig added in v0.3.2

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts.
	// Default: 3
	MaxRetries int

	// InitialBackoff is the initial backoff duration.
	// Default: 1 second
	InitialBackoff time.Duration

	// MaxBackoff is the maximum backoff duration.
	// Default: 30 seconds
	MaxBackoff time.Duration

	// BackoffMultiplier is the multiplier for exponential backoff.
	// Default: 2
	BackoffMultiplier float64
}

RetryConfig configures retry behavior for GitHub API calls.

func DefaultRetryConfig added in v0.3.2

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns the default retry configuration for GitHub API calls.

func (*RetryConfig) ApplyDefaults added in v0.3.2

func (c *RetryConfig) ApplyDefaults()

ApplyDefaults sets default values for unset fields.

type SchemaValidationResult

type SchemaValidationResult struct {
	Valid  bool     // Whether the schema is valid
	Errors []string // Validation errors, if any
}

SchemaValidationResult represents schema validation results.

func ValidatePluginSchemasActivity

func ValidatePluginSchemasActivity(ctx context.Context, input ValidateSchemasInput) (*SchemaValidationResult, error)

ValidatePluginSchemasActivity validates JSON schemas in plugin files.

Error Handling:

  • Returns error if GitHub client creation fails
  • Returns error if file fetch fails
  • Returns error if file content decoding fails
  • Returns result with Valid=false for invalid JSON (doesn't error)

type ValidateSchemasInput

type ValidateSchemasInput struct {
	Owner       string        // Repository owner
	Repo        string        // Repository name
	HeadSHA     string        // Commit SHA to validate
	FilePath    string        // Path to schema file
	GitHubToken config.Secret // GitHub API token
}

ValidateSchemasInput defines parameters for schema validation.

type ValidationIssue

type ValidationIssue struct {
	File     string `json:"file"`                // File path
	Line     int    `json:"line,omitempty"`      // Line number (if applicable)
	Severity string `json:"severity,omitempty"`  // Issue severity
	Issue    string `json:"issue"`               // Description of the issue
	Current  string `json:"current,omitempty"`   // Current value/state
	ShouldBe string `json:"should_be,omitempty"` // Expected value/state
	Fix      string `json:"fix"`                 // How to fix the issue
	Impact   string `json:"impact,omitempty"`    // Impact description
}

ValidationIssue represents a single validation finding.

type VersionValidationConfig

type VersionValidationConfig struct {
	Owner       string        // GitHub repository owner
	Repo        string        // GitHub repository name
	PRNumber    int           // Pull request number
	HeadSHA     string        // PR commit SHA
	GitHubToken config.Secret // GitHub API token for activities
}

VersionValidationConfig configures the version validation workflow.

func (*VersionValidationConfig) Validate added in v0.3.2

func (c *VersionValidationConfig) Validate() error

Validate checks that all required fields are set.

func (*VersionValidationConfig) ValidateComprehensive added in v0.3.2

func (c *VersionValidationConfig) ValidateComprehensive() error

ValidateComprehensive performs comprehensive validation with GitHub identifier patterns, path traversal checks, and other security validations.

type VersionValidationResult

type VersionValidationResult struct {
	VersionMatches bool     // Whether VERSION file matches plugin.json
	VersionFile    string   // Version from VERSION file
	PluginVersion  string   // Version from plugin.json
	CommentPosted  bool     // Whether we posted a comment
	CommentURL     string   // URL of posted comment
	Errors         []string // Any errors encountered
}

VersionValidationResult contains validation results.

func VersionValidationWorkflow

func VersionValidationWorkflow(ctx workflow.Context, config VersionValidationConfig) (*VersionValidationResult, error)

VersionValidationWorkflow validates that VERSION file matches plugin.json.

This workflow: 0. Validates input configuration 1. Fetches VERSION file content from PR 2. Fetches plugin.json and extracts version 3. Validates both versions are valid semantic versions 4. Compares versions 5. Posts comment if versions don't match

type WorkflowError added in v0.3.2

type WorkflowError struct {
	Operation string        // The operation that failed (e.g., "fetch_version_file", "validate_schema")
	Severity  ErrorSeverity // How severe the error is
	Err       error         // The underlying error
	Context   string        // Additional context about the error
}

WorkflowError represents a structured error in a workflow

func NewWorkflowError added in v0.3.2

func NewWorkflowError(operation string, severity ErrorSeverity, err error, context string) *WorkflowError

NewWorkflowError creates a new workflow error with context

func (*WorkflowError) Error added in v0.3.2

func (e *WorkflowError) Error() string

Error implements the error interface

func (*WorkflowError) Unwrap added in v0.3.2

func (e *WorkflowError) Unwrap() error

Unwrap allows errors.Is and errors.As to work with WorkflowError

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL