circuit_breaker-wf 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +4 -0
  3. data/CHANGELOG.md +52 -0
  4. data/Gemfile +10 -0
  5. data/Gemfile.lock +116 -0
  6. data/LICENSE +21 -0
  7. data/README.md +324 -0
  8. data/examples/document/README.md +150 -0
  9. data/examples/document/document_assistant.rb +535 -0
  10. data/examples/document/document_rules.rb +60 -0
  11. data/examples/document/document_token.rb +83 -0
  12. data/examples/document/document_workflow.rb +114 -0
  13. data/examples/document/mock_executor.rb +80 -0
  14. data/lib/circuit_breaker/executors/README.md +664 -0
  15. data/lib/circuit_breaker/executors/agent_executor.rb +187 -0
  16. data/lib/circuit_breaker/executors/assistant_executor.rb +245 -0
  17. data/lib/circuit_breaker/executors/base_executor.rb +56 -0
  18. data/lib/circuit_breaker/executors/docker_executor.rb +56 -0
  19. data/lib/circuit_breaker/executors/dsl.rb +97 -0
  20. data/lib/circuit_breaker/executors/llm/memory.rb +82 -0
  21. data/lib/circuit_breaker/executors/llm/tools.rb +94 -0
  22. data/lib/circuit_breaker/executors/nats_executor.rb +230 -0
  23. data/lib/circuit_breaker/executors/serverless_executor.rb +25 -0
  24. data/lib/circuit_breaker/executors/step_executor.rb +47 -0
  25. data/lib/circuit_breaker/history.rb +81 -0
  26. data/lib/circuit_breaker/rules.rb +251 -0
  27. data/lib/circuit_breaker/templates/mermaid.html.erb +51 -0
  28. data/lib/circuit_breaker/templates/plantuml.html.erb +55 -0
  29. data/lib/circuit_breaker/token.rb +486 -0
  30. data/lib/circuit_breaker/visualizer.rb +173 -0
  31. data/lib/circuit_breaker/workflow_dsl.rb +359 -0
  32. data/lib/circuit_breaker.rb +236 -0
  33. data/workflow-editor/.gitignore +24 -0
  34. data/workflow-editor/README.md +106 -0
  35. data/workflow-editor/eslint.config.js +28 -0
  36. data/workflow-editor/index.html +13 -0
  37. data/workflow-editor/package-lock.json +6864 -0
  38. data/workflow-editor/package.json +50 -0
  39. data/workflow-editor/postcss.config.js +6 -0
  40. data/workflow-editor/public/vite.svg +1 -0
  41. data/workflow-editor/src/App.css +42 -0
  42. data/workflow-editor/src/App.tsx +365 -0
  43. data/workflow-editor/src/assets/react.svg +1 -0
  44. data/workflow-editor/src/components/AddNodeButton.tsx +68 -0
  45. data/workflow-editor/src/components/EdgeDetails.tsx +175 -0
  46. data/workflow-editor/src/components/NodeDetails.tsx +177 -0
  47. data/workflow-editor/src/components/ResizablePanel.tsx +74 -0
  48. data/workflow-editor/src/components/SaveButton.tsx +45 -0
  49. data/workflow-editor/src/config/change_workflow.yaml +59 -0
  50. data/workflow-editor/src/config/constants.ts +11 -0
  51. data/workflow-editor/src/config/flowConfig.ts +189 -0
  52. data/workflow-editor/src/config/uiConfig.ts +77 -0
  53. data/workflow-editor/src/config/workflow.yaml +58 -0
  54. data/workflow-editor/src/hooks/useKeyPress.ts +29 -0
  55. data/workflow-editor/src/index.css +34 -0
  56. data/workflow-editor/src/main.tsx +10 -0
  57. data/workflow-editor/src/server/saveWorkflow.ts +81 -0
  58. data/workflow-editor/src/utils/saveWorkflow.ts +92 -0
  59. data/workflow-editor/src/utils/workflowLoader.ts +26 -0
  60. data/workflow-editor/src/utils/workflowTransformer.ts +91 -0
  61. data/workflow-editor/src/vite-env.d.ts +1 -0
  62. data/workflow-editor/src/yaml.d.ts +4 -0
  63. data/workflow-editor/tailwind.config.js +15 -0
  64. data/workflow-editor/tsconfig.app.json +26 -0
  65. data/workflow-editor/tsconfig.json +7 -0
  66. data/workflow-editor/tsconfig.node.json +24 -0
  67. data/workflow-editor/vite.config.ts +8 -0
  68. metadata +267 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 86400e938a443a0b3bd0c4b33a5be3da852e0b501a2ea86e19806c554d1f18f8
4
+ data.tar.gz: 7d9e3ca03f1df4a5c16f80986d60543b82457357e54f088fbfa8dfbb176b774c
5
+ SHA512:
6
+ metadata.gz: b9bf4f347b32d5079da2a196f3df088f3e7caed14899b63901c3a93a3fd67c4a3cc86951f795a420868855ebf687e0e88302cffdea277258d66dec90b2155df1
7
+ data.tar.gz: a782c8a67155cc6f468ede3a9638e40e4ecf0b23356fa942fc794f50186cc06d1df8fc33d3f470692b4079bc40b33b8961728d791987260875863873ac5768e3
data/.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ .idea
2
+ **.iml
3
+ bin
4
+ .DS_Store
data/CHANGELOG.md ADDED
@@ -0,0 +1,52 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2024-12-11
9
+
10
+ ### Added
11
+ - Initial implementation of Petri Net workflow system
12
+ - Core components:
13
+ - `Token` class for representing workflow state markers
14
+ - `Place` class for representing workflow states
15
+ - `Arc` class for connecting places and transitions
16
+ - `Transition` class for state change logic
17
+ - `PetriNet` class for overall workflow management
18
+ - Thread-safe token operations with mutex protection
19
+ - Support for weighted arcs
20
+ - Guard conditions on transitions
21
+ - Token data preservation during transitions
22
+ - JSON serialization for workflow state
23
+ - Example workflow demonstrating approval process
24
+ - Basic project documentation:
25
+ - README with usage examples and comparisons to Argo Workflows
26
+ - MIT License
27
+ - This CHANGELOG
28
+
29
+ ### Technical Details
30
+ - Proper handling of token flow between places and transitions
31
+ - Atomic transition firing with all-or-nothing semantics
32
+ - Step-by-step execution with `step` method
33
+ - Full workflow execution with `run_to_completion`
34
+ - State inspection through `marking` method
35
+ - Thread-safe operations in `Place` and `Transition` classes
36
+
37
+ ## [Unreleased]
38
+
39
+ ### Planned
40
+ - Visualization support for workflow graphs
41
+ - Persistence layer for workflow state
42
+ - Support for timed transitions
43
+ - Advanced synchronization patterns
44
+ - Integration with external systems
45
+ - Web-based workflow designer
46
+ - Performance optimizations for large workflows
47
+ - Additional example workflows
48
+ - Testing framework and test suite
49
+ - CI/CD pipeline setup
50
+ - Documentation website
51
+ - API documentation
52
+ - Contributing guidelines
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in circuit_breaker.gemspec
4
+ gemspec
5
+
6
+ group :development do
7
+ gem "rake", "~> 13.0"
8
+ gem "rspec", "~> 3.0"
9
+ gem "rubocop", "~> 1.21"
10
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,116 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ circuit_breaker (0.1.0)
5
+ async
6
+ concurrent-ruby (~> 1.2)
7
+ json (~> 2.6)
8
+ json-schema
9
+ nats-pure (~> 2.4)
10
+ nokogiri
11
+ redcarpet
12
+
13
+ GEM
14
+ remote: https://rubygems.org/
15
+ specs:
16
+ addressable (2.8.7)
17
+ public_suffix (>= 2.0.2, < 7.0)
18
+ ast (2.4.2)
19
+ async (2.21.1)
20
+ console (~> 1.29)
21
+ fiber-annotation
22
+ io-event (~> 1.6, >= 1.6.5)
23
+ bigdecimal (3.1.9)
24
+ concurrent-ruby (1.3.5)
25
+ console (1.29.2)
26
+ fiber-annotation
27
+ fiber-local (~> 1.1)
28
+ json
29
+ diff-lcs (1.5.1)
30
+ fiber-annotation (0.2.0)
31
+ fiber-local (1.1.0)
32
+ fiber-storage
33
+ fiber-storage (1.0.0)
34
+ io-event (1.7.5)
35
+ json (2.9.1)
36
+ json-schema (5.1.1)
37
+ addressable (~> 2.8)
38
+ bigdecimal (~> 3.1)
39
+ language_server-protocol (3.17.0.3)
40
+ nats-pure (2.4.0)
41
+ concurrent-ruby (~> 1.0)
42
+ nokogiri (1.18.1-aarch64-linux-gnu)
43
+ racc (~> 1.4)
44
+ nokogiri (1.18.1-aarch64-linux-musl)
45
+ racc (~> 1.4)
46
+ nokogiri (1.18.1-arm-linux-gnu)
47
+ racc (~> 1.4)
48
+ nokogiri (1.18.1-arm-linux-musl)
49
+ racc (~> 1.4)
50
+ nokogiri (1.18.1-arm64-darwin)
51
+ racc (~> 1.4)
52
+ nokogiri (1.18.1-x86_64-darwin)
53
+ racc (~> 1.4)
54
+ nokogiri (1.18.1-x86_64-linux-gnu)
55
+ racc (~> 1.4)
56
+ nokogiri (1.18.1-x86_64-linux-musl)
57
+ racc (~> 1.4)
58
+ parallel (1.26.3)
59
+ parser (3.3.6.0)
60
+ ast (~> 2.4.1)
61
+ racc
62
+ public_suffix (6.0.1)
63
+ racc (1.8.1)
64
+ rainbow (3.1.1)
65
+ rake (13.2.1)
66
+ redcarpet (3.6.0)
67
+ regexp_parser (2.10.0)
68
+ rspec (3.13.0)
69
+ rspec-core (~> 3.13.0)
70
+ rspec-expectations (~> 3.13.0)
71
+ rspec-mocks (~> 3.13.0)
72
+ rspec-core (3.13.2)
73
+ rspec-support (~> 3.13.0)
74
+ rspec-expectations (3.13.3)
75
+ diff-lcs (>= 1.2.0, < 2.0)
76
+ rspec-support (~> 3.13.0)
77
+ rspec-mocks (3.13.2)
78
+ diff-lcs (>= 1.2.0, < 2.0)
79
+ rspec-support (~> 3.13.0)
80
+ rspec-support (3.13.2)
81
+ rubocop (1.70.0)
82
+ json (~> 2.3)
83
+ language_server-protocol (>= 3.17.0)
84
+ parallel (~> 1.10)
85
+ parser (>= 3.3.0.2)
86
+ rainbow (>= 2.2.2, < 4.0)
87
+ regexp_parser (>= 2.9.3, < 3.0)
88
+ rubocop-ast (>= 1.36.2, < 2.0)
89
+ ruby-progressbar (~> 1.7)
90
+ unicode-display_width (>= 2.4.0, < 4.0)
91
+ rubocop-ast (1.37.0)
92
+ parser (>= 3.3.1.0)
93
+ ruby-progressbar (1.13.0)
94
+ unicode-display_width (3.1.4)
95
+ unicode-emoji (~> 4.0, >= 4.0.4)
96
+ unicode-emoji (4.0.4)
97
+
98
+ PLATFORMS
99
+ aarch64-linux-gnu
100
+ aarch64-linux-musl
101
+ arm-linux-gnu
102
+ arm-linux-musl
103
+ arm64-darwin
104
+ x86_64-darwin
105
+ x86_64-linux-gnu
106
+ x86_64-linux-musl
107
+
108
+ DEPENDENCIES
109
+ bundler (~> 2.0)
110
+ circuit_breaker!
111
+ rake (~> 13.0)
112
+ rspec (~> 3.0)
113
+ rubocop (~> 1.21)
114
+
115
+ BUNDLED WITH
116
+ 2.5.11
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Petri Workflows Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,324 @@
1
+ # Circuit Breaker
2
+
3
+ Circuit Breaker is a powerful Ruby library that provides a declarative DSL for building AI-powered workflows and assistants. It seamlessly integrates with various LLM providers and offers robust tools for document analysis, workflow management, and autonomous agents.
4
+
5
+ ## Features
6
+
7
+ ### 1. Declarative Workflow DSL
8
+ - State-based workflow engine with intuitive syntax
9
+ - Policy-based transitions with rule chains
10
+ - Unified rules system for validation and transitions
11
+ - Comprehensive history tracking
12
+ - Event handling and state management
13
+
14
+ ### 2. Rules System
15
+ - Unified DSL for defining rules and validations
16
+ - Support for complex rule chains and conditions
17
+ - Built-in helpers for common validations
18
+ - Rule composition with AND/OR logic
19
+ - Clear error reporting and handling
20
+
21
+ ### 3. AI Integration
22
+ - Multiple LLM providers (OpenAI, Ollama)
23
+ - Automatic model detection
24
+ - Tool integration framework
25
+ - Memory management
26
+ - Error handling with retries
27
+
28
+ ### 4. Document Analysis
29
+ - Content quality assessment
30
+ - Sentiment and tone analysis
31
+ - Context detection
32
+ - Improvement suggestions
33
+ - Structure evaluation
34
+
35
+ ### 5. Executors
36
+ - AssistantExecutor for AI-powered tools
37
+ - AgentExecutor for autonomous tasks
38
+ - Custom executor support
39
+ - Chainable tool pipelines
40
+
41
+ ## Installation
42
+
43
+ Add this line to your application's Gemfile:
44
+
45
+ ```ruby
46
+ gem 'circuit_breaker'
47
+ ```
48
+
49
+ And then execute:
50
+ ```bash
51
+ $ bundle install
52
+ ```
53
+
54
+ Or install it yourself as:
55
+ ```bash
56
+ $ gem install circuit_breaker
57
+ ```
58
+
59
+ ## Usage
60
+
61
+ ### Action-Rule Data Flow
62
+
63
+ Circuit Breaker provides a powerful mechanism for passing data between actions and rules during workflow transitions. Here's how it works:
64
+
65
+ 1. **Actions with Named Results**
66
+ ```ruby
67
+ flow :draft >> :pending_review, :submit do
68
+ actions do
69
+ # Execute action and store result with key :clarity
70
+ execute analyzer, :analyze_clarity, :clarity
71
+ end
72
+ policy all: [:valid_clarity]
73
+ end
74
+ ```
75
+
76
+ 2. **Accessing Results in Rules**
77
+ ```ruby
78
+ CircuitBreaker::Rules::DSL.define do
79
+ rule :valid_clarity do |token|
80
+ # Retrieve stored result using the same key
81
+ clarity = context.get_result(:clarity)
82
+ clarity && clarity[:score] >= 70
83
+ end
84
+ end
85
+ ```
86
+
87
+ 3. **Data Flow Process**
88
+ - Actions are executed first during a transition
89
+ - Results are stored in an action context using the specified key
90
+ - Rules can access these results through the same key
91
+ - This enables rules to validate based on action outputs
92
+
93
+ This pattern allows for:
94
+ - Clean separation between action execution and rule validation
95
+ - Reusable actions with different validation rules
96
+ - Complex rule chains based on multiple action results
97
+ - Clear data flow tracking during transitions
98
+
99
+ ### Creating a Workflow
100
+
101
+ ```ruby
102
+ # Define rules
103
+ rules = CircuitBreaker::Rules::DSL.define do
104
+ rule :valid_reviewer do |token|
105
+ token.reviewer_id.present?
106
+ end
107
+
108
+ rule :valid_review do |token|
109
+ token.reviewer_comments.present?
110
+ end
111
+ end
112
+
113
+ # Define workflow
114
+ workflow = CircuitBreaker::WorkflowDSL.define(rules: rules) do
115
+ # Define states
116
+ states :draft, :pending_review, :reviewed, :approved, :rejected
117
+
118
+ # Define transitions with rules
119
+ flow(:draft >> :pending_review)
120
+ .transition(:submit)
121
+ .policy(rules: { all: [:valid_reviewer] })
122
+
123
+ flow(:pending_review >> :reviewed)
124
+ .transition(:review)
125
+ .policy(
126
+ rules: {
127
+ all: [:valid_review],
128
+ any: [:is_high_priority, :is_urgent]
129
+ }
130
+ )
131
+ end
132
+
133
+ # Create and add token
134
+ token = CircuitBreaker::Token.new
135
+ workflow.add_token(token)
136
+
137
+ # Fire transitions
138
+ workflow.fire_transition(:submit, token)
139
+ ```
140
+
141
+ ### History Tracking
142
+
143
+ The workflow automatically tracks all transitions:
144
+
145
+ ```ruby
146
+ token.history.each do |event|
147
+ puts "#{event[:timestamp]}: #{event[:transition]} from #{event[:from]} to #{event[:to]}"
148
+ end
149
+ ```
150
+
151
+ ## Architecture
152
+
153
+ Circuit Breaker uses a hybrid architecture combining:
154
+
155
+ 1. **Workflow Engine**: Based on Petri nets for formal verification
156
+ 2. **Rules Engine**: Unified system for validations and transitions
157
+ 3. **AI Integration**: Pluggable LLM providers for analysis
158
+ 4. **Event System**: Comprehensive tracking and auditing
159
+
160
+ While basic Petri nets are not Turing complete, our implementation is closer to Colored Petri Nets (CPNs) or High-level Petri Nets. The system balances theoretical power with practical utility, providing:
161
+ - Sufficient expressiveness for real-world business processes
162
+ - Analyzability for critical property verification
163
+ - Maintainable and understandable structure through the workflow DSL
164
+
165
+ ## Components
166
+
167
+ ### 1. Workflow Engine
168
+
169
+ The workflow engine provides:
170
+ - State management
171
+ - Transition validation
172
+ - Rule enforcement
173
+ - Event tracking
174
+ - History management
175
+
176
+ Example:
177
+ ```ruby
178
+ # Define rules
179
+ rule :has_reviewer,
180
+ desc: "Document must have a reviewer assigned",
181
+ &requires(:reviewer_id)
182
+
183
+ # Define validations
184
+ validator :title,
185
+ desc: "Document title is required",
186
+ &must_be_present(:title)
187
+
188
+ # Create workflow instance
189
+ workflow = DocumentWorkflow.new(document)
190
+ workflow.submit # Transition to pending_review
191
+ ```
192
+
193
+ ### 2. AI Executors
194
+
195
+ Two main executor types:
196
+
197
+ 1. AssistantExecutor
198
+ - Tool-based execution
199
+ - Context management
200
+ - Memory persistence
201
+ - Error handling
202
+
203
+ 2. AgentExecutor
204
+ - Autonomous task execution
205
+ - Tool discovery
206
+ - Planning capabilities
207
+ - Progress tracking
208
+
209
+ ### 3. Tool Framework
210
+
211
+ Tools can be:
212
+ - Basic tools with direct execution
213
+ - Chainable tools for complex pipelines
214
+ - Stateful tools with context
215
+ - Fallback-enabled tools
216
+
217
+ Example chainable tool:
218
+ ```ruby
219
+ class ChainableTool < CircuitBreaker::Executors::LLM::ChainableTool
220
+ def initialize
221
+ super(
222
+ name: 'chainable_tool',
223
+ description: 'Part of processing pipeline',
224
+ input_schema: { type: 'string' },
225
+ output_schema: { type: 'object' }
226
+ )
227
+ end
228
+
229
+ def execute(input, context)
230
+ result = process(input)
231
+ next_tool = context.available_tools.find { |t| t.can_handle?(result) }
232
+ context.chain(next_tool) if next_tool
233
+ end
234
+ end
235
+ ```
236
+
237
+ ## Examples
238
+
239
+ See the `examples` directory for complete examples:
240
+
241
+ 1. Document Workflow
242
+ - Complete document management system
243
+ - AI-powered analysis
244
+ - Review process automation
245
+ - State tracking
246
+
247
+ 2. Research Assistant
248
+ - Autonomous research agent
249
+ - Source gathering
250
+ - Summary generation
251
+ - Citation management
252
+
253
+ ## Configuration
254
+
255
+ ### 1. LLM Providers
256
+
257
+ ```ruby
258
+ # Configure Ollama
259
+ CircuitBreaker.configure do |config|
260
+ config.ollama_base_url = 'http://localhost:11434'
261
+ config.default_model = 'qwen2.5-coder'
262
+ end
263
+
264
+ # Configure OpenAI
265
+ CircuitBreaker.configure do |config|
266
+ config.openai_api_key = ENV['OPENAI_API_KEY']
267
+ config.default_model = 'gpt-4'
268
+ end
269
+ ```
270
+
271
+ ### 2. Memory Settings
272
+
273
+ ```ruby
274
+ CircuitBreaker.configure do |config|
275
+ config.max_memory_tokens = 4000
276
+ config.memory_window_size = 10
277
+ end
278
+ ```
279
+
280
+ ### 3. Tool Settings
281
+
282
+ ```ruby
283
+ CircuitBreaker.configure do |config|
284
+ config.default_tools = [
285
+ ContentAnalysisTool,
286
+ SentimentAnalysisTool,
287
+ ImprovementTool
288
+ ]
289
+ config.tool_timeout = 30 # seconds
290
+ end
291
+ ```
292
+
293
+ ## Best Practices
294
+
295
+ 1. Workflow Design
296
+ - Keep states and transitions clear
297
+ - Use descriptive rule names
298
+ - Implement proper validation
299
+ - Track state changes
300
+
301
+ 2. AI Integration
302
+ - Choose appropriate models
303
+ - Handle errors gracefully
304
+ - Implement retries
305
+ - Monitor performance
306
+
307
+ 3. Tool Development
308
+ - Keep tools focused
309
+ - Provide clear descriptions
310
+ - Include fallback behavior
311
+ - Handle errors appropriately
312
+
313
+ ## Contributing
314
+
315
+ 1. Fork the repository
316
+ 2. Create your feature branch
317
+ 3. Add tests for new features
318
+ 4. Submit a pull request
319
+
320
+ Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.
321
+
322
+ ## License
323
+
324
+ This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
@@ -0,0 +1,150 @@
1
+ # Document Workflow Examples
2
+
3
+ This directory contains examples demonstrating how to use the Circuit Breaker library to implement a document workflow system with AI-powered analysis. The examples showcase a declarative DSL for defining workflows, rules, validations, and AI-powered document analysis.
4
+
5
+ ## Overview
6
+
7
+ The document workflow system implements a document review and approval process with the following states:
8
+ - `draft`: Initial state for new documents
9
+ - `pending_review`: Document submitted for review
10
+ - `reviewed`: Review completed with comments
11
+ - `approved`: Document approved by manager
12
+ - `rejected`: Document rejected with reasons
13
+
14
+ ## Features
15
+
16
+ ### 1. Unified Rules System
17
+ - Declarative rule definitions using DSL
18
+ - Complex rule chains with AND/OR logic
19
+ - Built-in validation helpers
20
+ - Clear error reporting
21
+ - Rule reusability across transitions
22
+
23
+ ### 2. Workflow Management
24
+ - Intuitive state transition syntax (`from >> to`)
25
+ - Policy-based transitions with rule chains
26
+ - Comprehensive history tracking
27
+ - Event handling and state management
28
+ - Automatic validation during transitions
29
+
30
+ ### 3. Document Rules
31
+ - Document validation rules:
32
+ - `valid_reviewer`: Ensures reviewer is assigned
33
+ - `valid_review`: Validates review comments
34
+ - `valid_approver`: Checks approver assignment
35
+ - `is_admin_approver`: Verifies approver permissions
36
+ - `valid_word_count`: Checks document length
37
+ - `valid_external_url`: Validates external references
38
+
39
+ ### 4. AI-Powered Document Analysis
40
+ - Content quality and structure assessment
41
+ - Sentiment and tone analysis
42
+ - Automatic context detection
43
+ - Improvement suggestions
44
+ - Word count validation
45
+
46
+ ## Example Usage
47
+
48
+ ### 1. Define Document Rules
49
+
50
+ ```ruby
51
+ rules = DocumentRules.define do
52
+ rule :valid_reviewer do |token|
53
+ token.reviewer_id.present?
54
+ end
55
+
56
+ rule :valid_review do |token|
57
+ token.reviewer_comments.present?
58
+ end
59
+
60
+ rule :is_admin_approver do |token|
61
+ token.approver_id&.start_with?('admin_')
62
+ end
63
+ end
64
+ ```
65
+
66
+ ### 2. Create Workflow
67
+
68
+ ```ruby
69
+ workflow = CircuitBreaker::WorkflowDSL.define(rules: rules) do
70
+ states :draft, :pending_review, :reviewed, :approved, :rejected
71
+
72
+ flow(:draft >> :pending_review)
73
+ .transition(:submit)
74
+ .policy(rules: { all: [:valid_reviewer] })
75
+
76
+ flow(:pending_review >> :reviewed)
77
+ .transition(:review)
78
+ .policy(
79
+ rules: {
80
+ all: [:valid_review],
81
+ any: [:is_high_priority, :is_urgent]
82
+ }
83
+ )
84
+
85
+ flow(:reviewed >> :approved)
86
+ .transition(:approve)
87
+ .policy(
88
+ rules: {
89
+ all: [:valid_approver, :valid_review, :is_admin_approver],
90
+ any: [:valid_external_url, :valid_word_count]
91
+ }
92
+ )
93
+ end
94
+ ```
95
+
96
+ ### 3. Process Document
97
+
98
+ ```ruby
99
+ # Create document
100
+ token = Examples::DocumentToken.new(
101
+ title: "Project Proposal",
102
+ content: "Detailed project proposal...",
103
+ priority: "high",
104
+ author_id: "charlie789"
105
+ )
106
+
107
+ # Add to workflow
108
+ workflow.add_token(token)
109
+
110
+ # Submit document
111
+ token.reviewer_id = "bob456"
112
+ workflow.fire_transition(:submit, token)
113
+
114
+ # Review document
115
+ token.reviewer_comments = "Detailed review comments..."
116
+ workflow.fire_transition(:review, token)
117
+
118
+ # Approve document
119
+ token.approver_id = "admin_eve789"
120
+ workflow.fire_transition(:approve, token)
121
+
122
+ # View history
123
+ token.history.each do |event|
124
+ puts "#{event[:timestamp]}: #{event[:transition]} from #{event[:from]} to #{event[:to]}"
125
+ end
126
+ ```
127
+
128
+ ## Files
129
+
130
+ - `document_token.rb`: Token class for documents
131
+ - `document_rules.rb`: Rule definitions for document workflow
132
+ - `document_workflow.rb`: Main workflow implementation
133
+ - `document_assistant.rb`: AI-powered document analysis
134
+
135
+ ## Requirements
136
+
137
+ 1. Ruby 2.7 or higher
138
+ 2. Ollama installed and running locally (for AI-powered document analysis)
139
+
140
+ ## Running the Example
141
+
142
+ ```bash
143
+ ruby document_workflow.rb
144
+ ```
145
+
146
+ This will execute the example workflow, showing:
147
+ 1. Workflow definition and states
148
+ 2. Document transitions through states
149
+ 3. Rule validations at each step
150
+ 4. Complete transition history