crca 1.4.0__py3-none-any.whl

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 (501) hide show
  1. .github/ISSUE_TEMPLATE/bug_report.md +65 -0
  2. .github/ISSUE_TEMPLATE/feature_request.md +41 -0
  3. .github/PULL_REQUEST_TEMPLATE.md +20 -0
  4. .github/workflows/publish-manual.yml +61 -0
  5. .github/workflows/publish.yml +64 -0
  6. .gitignore +214 -0
  7. CRCA.py +4156 -0
  8. LICENSE +201 -0
  9. MANIFEST.in +43 -0
  10. PKG-INFO +5035 -0
  11. README.md +4959 -0
  12. __init__.py +17 -0
  13. branches/CRCA-Q.py +2728 -0
  14. branches/crca_cg/corposwarm.py +9065 -0
  15. branches/crca_cg/fix_rancher_docker_creds.ps1 +155 -0
  16. branches/crca_cg/package.json +5 -0
  17. branches/crca_cg/test_bolt_integration.py +446 -0
  18. branches/crca_cg/test_corposwarm_comprehensive.py +773 -0
  19. branches/crca_cg/test_new_features.py +163 -0
  20. branches/crca_sd/__init__.py +149 -0
  21. branches/crca_sd/crca_sd_core.py +770 -0
  22. branches/crca_sd/crca_sd_governance.py +1325 -0
  23. branches/crca_sd/crca_sd_mpc.py +1130 -0
  24. branches/crca_sd/crca_sd_realtime.py +1844 -0
  25. branches/crca_sd/crca_sd_tui.py +1133 -0
  26. crca-1.4.0.dist-info/METADATA +5035 -0
  27. crca-1.4.0.dist-info/RECORD +501 -0
  28. crca-1.4.0.dist-info/WHEEL +4 -0
  29. crca-1.4.0.dist-info/licenses/LICENSE +201 -0
  30. docs/CRCA-Q.md +2333 -0
  31. examples/config.yaml.example +25 -0
  32. examples/crca_sd_example.py +513 -0
  33. examples/data_broker_example.py +294 -0
  34. examples/logistics_corporation.py +861 -0
  35. examples/palantir_example.py +299 -0
  36. examples/policy_bench.py +934 -0
  37. examples/pridnestrovia-sd.py +705 -0
  38. examples/pridnestrovia_realtime.py +1902 -0
  39. prompts/__init__.py +10 -0
  40. prompts/default_crca.py +101 -0
  41. pyproject.toml +151 -0
  42. requirements.txt +76 -0
  43. schemas/__init__.py +43 -0
  44. schemas/mcpSchemas.py +51 -0
  45. schemas/policy.py +458 -0
  46. templates/__init__.py +38 -0
  47. templates/base_specialized_agent.py +195 -0
  48. templates/drift_detection.py +325 -0
  49. templates/examples/causal_agent_template.py +309 -0
  50. templates/examples/drag_drop_example.py +213 -0
  51. templates/examples/logistics_agent_template.py +207 -0
  52. templates/examples/trading_agent_template.py +206 -0
  53. templates/feature_mixins.py +253 -0
  54. templates/graph_management.py +442 -0
  55. templates/llm_integration.py +194 -0
  56. templates/module_registry.py +276 -0
  57. templates/mpc_planner.py +280 -0
  58. templates/policy_loop.py +1168 -0
  59. templates/prediction_framework.py +448 -0
  60. templates/statistical_methods.py +778 -0
  61. tests/sanity.yml +31 -0
  62. tests/sanity_check +406 -0
  63. tests/test_core.py +47 -0
  64. tests/test_crca_excel.py +166 -0
  65. tests/test_crca_sd.py +780 -0
  66. tests/test_data_broker.py +424 -0
  67. tests/test_palantir.py +349 -0
  68. tools/__init__.py +38 -0
  69. tools/actuators.py +437 -0
  70. tools/bolt.diy/Dockerfile +103 -0
  71. tools/bolt.diy/app/components/@settings/core/AvatarDropdown.tsx +175 -0
  72. tools/bolt.diy/app/components/@settings/core/ControlPanel.tsx +345 -0
  73. tools/bolt.diy/app/components/@settings/core/constants.tsx +108 -0
  74. tools/bolt.diy/app/components/@settings/core/types.ts +114 -0
  75. tools/bolt.diy/app/components/@settings/index.ts +12 -0
  76. tools/bolt.diy/app/components/@settings/shared/components/TabTile.tsx +151 -0
  77. tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionForm.tsx +193 -0
  78. tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionTestIndicator.tsx +60 -0
  79. tools/bolt.diy/app/components/@settings/shared/service-integration/ErrorState.tsx +102 -0
  80. tools/bolt.diy/app/components/@settings/shared/service-integration/LoadingState.tsx +94 -0
  81. tools/bolt.diy/app/components/@settings/shared/service-integration/ServiceHeader.tsx +72 -0
  82. tools/bolt.diy/app/components/@settings/shared/service-integration/index.ts +6 -0
  83. tools/bolt.diy/app/components/@settings/tabs/data/DataTab.tsx +721 -0
  84. tools/bolt.diy/app/components/@settings/tabs/data/DataVisualization.tsx +384 -0
  85. tools/bolt.diy/app/components/@settings/tabs/event-logs/EventLogsTab.tsx +1013 -0
  86. tools/bolt.diy/app/components/@settings/tabs/features/FeaturesTab.tsx +295 -0
  87. tools/bolt.diy/app/components/@settings/tabs/github/GitHubTab.tsx +281 -0
  88. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubAuthDialog.tsx +173 -0
  89. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubCacheManager.tsx +367 -0
  90. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubConnection.tsx +233 -0
  91. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubErrorBoundary.tsx +105 -0
  92. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubProgressiveLoader.tsx +266 -0
  93. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositoryCard.tsx +121 -0
  94. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositorySelector.tsx +312 -0
  95. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubStats.tsx +291 -0
  96. tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubUserProfile.tsx +46 -0
  97. tools/bolt.diy/app/components/@settings/tabs/github/components/shared/GitHubStateIndicators.tsx +264 -0
  98. tools/bolt.diy/app/components/@settings/tabs/github/components/shared/RepositoryCard.tsx +361 -0
  99. tools/bolt.diy/app/components/@settings/tabs/github/components/shared/index.ts +11 -0
  100. tools/bolt.diy/app/components/@settings/tabs/gitlab/GitLabTab.tsx +305 -0
  101. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabAuthDialog.tsx +186 -0
  102. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabConnection.tsx +253 -0
  103. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabRepositorySelector.tsx +358 -0
  104. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryCard.tsx +79 -0
  105. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryList.tsx +142 -0
  106. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/StatsDisplay.tsx +91 -0
  107. tools/bolt.diy/app/components/@settings/tabs/gitlab/components/index.ts +4 -0
  108. tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerList.tsx +99 -0
  109. tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerListItem.tsx +70 -0
  110. tools/bolt.diy/app/components/@settings/tabs/mcp/McpStatusBadge.tsx +37 -0
  111. tools/bolt.diy/app/components/@settings/tabs/mcp/McpTab.tsx +239 -0
  112. tools/bolt.diy/app/components/@settings/tabs/netlify/NetlifyTab.tsx +1393 -0
  113. tools/bolt.diy/app/components/@settings/tabs/netlify/components/NetlifyConnection.tsx +990 -0
  114. tools/bolt.diy/app/components/@settings/tabs/netlify/components/index.ts +1 -0
  115. tools/bolt.diy/app/components/@settings/tabs/notifications/NotificationsTab.tsx +300 -0
  116. tools/bolt.diy/app/components/@settings/tabs/profile/ProfileTab.tsx +181 -0
  117. tools/bolt.diy/app/components/@settings/tabs/providers/cloud/CloudProvidersTab.tsx +308 -0
  118. tools/bolt.diy/app/components/@settings/tabs/providers/local/ErrorBoundary.tsx +68 -0
  119. tools/bolt.diy/app/components/@settings/tabs/providers/local/HealthStatusBadge.tsx +64 -0
  120. tools/bolt.diy/app/components/@settings/tabs/providers/local/LoadingSkeleton.tsx +107 -0
  121. tools/bolt.diy/app/components/@settings/tabs/providers/local/LocalProvidersTab.tsx +556 -0
  122. tools/bolt.diy/app/components/@settings/tabs/providers/local/ModelCard.tsx +106 -0
  123. tools/bolt.diy/app/components/@settings/tabs/providers/local/ProviderCard.tsx +120 -0
  124. tools/bolt.diy/app/components/@settings/tabs/providers/local/SetupGuide.tsx +671 -0
  125. tools/bolt.diy/app/components/@settings/tabs/providers/local/StatusDashboard.tsx +91 -0
  126. tools/bolt.diy/app/components/@settings/tabs/providers/local/types.ts +44 -0
  127. tools/bolt.diy/app/components/@settings/tabs/settings/SettingsTab.tsx +215 -0
  128. tools/bolt.diy/app/components/@settings/tabs/supabase/SupabaseTab.tsx +1089 -0
  129. tools/bolt.diy/app/components/@settings/tabs/vercel/VercelTab.tsx +909 -0
  130. tools/bolt.diy/app/components/@settings/tabs/vercel/components/VercelConnection.tsx +368 -0
  131. tools/bolt.diy/app/components/@settings/tabs/vercel/components/index.ts +1 -0
  132. tools/bolt.diy/app/components/@settings/utils/tab-helpers.ts +54 -0
  133. tools/bolt.diy/app/components/chat/APIKeyManager.tsx +169 -0
  134. tools/bolt.diy/app/components/chat/Artifact.tsx +296 -0
  135. tools/bolt.diy/app/components/chat/AssistantMessage.tsx +192 -0
  136. tools/bolt.diy/app/components/chat/BaseChat.module.scss +47 -0
  137. tools/bolt.diy/app/components/chat/BaseChat.tsx +522 -0
  138. tools/bolt.diy/app/components/chat/Chat.client.tsx +670 -0
  139. tools/bolt.diy/app/components/chat/ChatAlert.tsx +108 -0
  140. tools/bolt.diy/app/components/chat/ChatBox.tsx +334 -0
  141. tools/bolt.diy/app/components/chat/CodeBlock.module.scss +10 -0
  142. tools/bolt.diy/app/components/chat/CodeBlock.tsx +85 -0
  143. tools/bolt.diy/app/components/chat/DicussMode.tsx +17 -0
  144. tools/bolt.diy/app/components/chat/ExamplePrompts.tsx +37 -0
  145. tools/bolt.diy/app/components/chat/FilePreview.tsx +38 -0
  146. tools/bolt.diy/app/components/chat/GitCloneButton.tsx +327 -0
  147. tools/bolt.diy/app/components/chat/ImportFolderButton.tsx +141 -0
  148. tools/bolt.diy/app/components/chat/LLMApiAlert.tsx +109 -0
  149. tools/bolt.diy/app/components/chat/MCPTools.tsx +129 -0
  150. tools/bolt.diy/app/components/chat/Markdown.module.scss +171 -0
  151. tools/bolt.diy/app/components/chat/Markdown.spec.ts +48 -0
  152. tools/bolt.diy/app/components/chat/Markdown.tsx +252 -0
  153. tools/bolt.diy/app/components/chat/Messages.client.tsx +102 -0
  154. tools/bolt.diy/app/components/chat/ModelSelector.tsx +797 -0
  155. tools/bolt.diy/app/components/chat/NetlifyDeploymentLink.client.tsx +51 -0
  156. tools/bolt.diy/app/components/chat/ProgressCompilation.tsx +110 -0
  157. tools/bolt.diy/app/components/chat/ScreenshotStateManager.tsx +33 -0
  158. tools/bolt.diy/app/components/chat/SendButton.client.tsx +39 -0
  159. tools/bolt.diy/app/components/chat/SpeechRecognition.tsx +28 -0
  160. tools/bolt.diy/app/components/chat/StarterTemplates.tsx +38 -0
  161. tools/bolt.diy/app/components/chat/SupabaseAlert.tsx +199 -0
  162. tools/bolt.diy/app/components/chat/SupabaseConnection.tsx +339 -0
  163. tools/bolt.diy/app/components/chat/ThoughtBox.tsx +43 -0
  164. tools/bolt.diy/app/components/chat/ToolInvocations.tsx +409 -0
  165. tools/bolt.diy/app/components/chat/UserMessage.tsx +101 -0
  166. tools/bolt.diy/app/components/chat/VercelDeploymentLink.client.tsx +158 -0
  167. tools/bolt.diy/app/components/chat/chatExportAndImport/ExportChatButton.tsx +49 -0
  168. tools/bolt.diy/app/components/chat/chatExportAndImport/ImportButtons.tsx +96 -0
  169. tools/bolt.diy/app/components/deploy/DeployAlert.tsx +197 -0
  170. tools/bolt.diy/app/components/deploy/DeployButton.tsx +277 -0
  171. tools/bolt.diy/app/components/deploy/GitHubDeploy.client.tsx +171 -0
  172. tools/bolt.diy/app/components/deploy/GitHubDeploymentDialog.tsx +1041 -0
  173. tools/bolt.diy/app/components/deploy/GitLabDeploy.client.tsx +171 -0
  174. tools/bolt.diy/app/components/deploy/GitLabDeploymentDialog.tsx +764 -0
  175. tools/bolt.diy/app/components/deploy/NetlifyDeploy.client.tsx +246 -0
  176. tools/bolt.diy/app/components/deploy/VercelDeploy.client.tsx +235 -0
  177. tools/bolt.diy/app/components/editor/codemirror/BinaryContent.tsx +7 -0
  178. tools/bolt.diy/app/components/editor/codemirror/CodeMirrorEditor.tsx +555 -0
  179. tools/bolt.diy/app/components/editor/codemirror/EnvMasking.ts +80 -0
  180. tools/bolt.diy/app/components/editor/codemirror/cm-theme.ts +192 -0
  181. tools/bolt.diy/app/components/editor/codemirror/indent.ts +68 -0
  182. tools/bolt.diy/app/components/editor/codemirror/languages.ts +112 -0
  183. tools/bolt.diy/app/components/git/GitUrlImport.client.tsx +147 -0
  184. tools/bolt.diy/app/components/header/Header.tsx +42 -0
  185. tools/bolt.diy/app/components/header/HeaderActionButtons.client.tsx +54 -0
  186. tools/bolt.diy/app/components/mandate/MandateSubmission.tsx +167 -0
  187. tools/bolt.diy/app/components/observability/DeploymentStatus.tsx +168 -0
  188. tools/bolt.diy/app/components/observability/EventTimeline.tsx +119 -0
  189. tools/bolt.diy/app/components/observability/FileDiffViewer.tsx +121 -0
  190. tools/bolt.diy/app/components/observability/GovernanceStatus.tsx +197 -0
  191. tools/bolt.diy/app/components/observability/GovernorMetrics.tsx +246 -0
  192. tools/bolt.diy/app/components/observability/LogStream.tsx +244 -0
  193. tools/bolt.diy/app/components/observability/MandateDetails.tsx +201 -0
  194. tools/bolt.diy/app/components/observability/ObservabilityDashboard.tsx +200 -0
  195. tools/bolt.diy/app/components/sidebar/HistoryItem.tsx +187 -0
  196. tools/bolt.diy/app/components/sidebar/Menu.client.tsx +536 -0
  197. tools/bolt.diy/app/components/sidebar/date-binning.ts +59 -0
  198. tools/bolt.diy/app/components/txt +1 -0
  199. tools/bolt.diy/app/components/ui/BackgroundRays/index.tsx +18 -0
  200. tools/bolt.diy/app/components/ui/BackgroundRays/styles.module.scss +246 -0
  201. tools/bolt.diy/app/components/ui/Badge.tsx +53 -0
  202. tools/bolt.diy/app/components/ui/BranchSelector.tsx +270 -0
  203. tools/bolt.diy/app/components/ui/Breadcrumbs.tsx +101 -0
  204. tools/bolt.diy/app/components/ui/Button.tsx +46 -0
  205. tools/bolt.diy/app/components/ui/Card.tsx +55 -0
  206. tools/bolt.diy/app/components/ui/Checkbox.tsx +32 -0
  207. tools/bolt.diy/app/components/ui/CloseButton.tsx +49 -0
  208. tools/bolt.diy/app/components/ui/CodeBlock.tsx +103 -0
  209. tools/bolt.diy/app/components/ui/Collapsible.tsx +9 -0
  210. tools/bolt.diy/app/components/ui/ColorSchemeDialog.tsx +378 -0
  211. tools/bolt.diy/app/components/ui/Dialog.tsx +449 -0
  212. tools/bolt.diy/app/components/ui/Dropdown.tsx +63 -0
  213. tools/bolt.diy/app/components/ui/EmptyState.tsx +154 -0
  214. tools/bolt.diy/app/components/ui/FileIcon.tsx +346 -0
  215. tools/bolt.diy/app/components/ui/FilterChip.tsx +92 -0
  216. tools/bolt.diy/app/components/ui/GlowingEffect.tsx +192 -0
  217. tools/bolt.diy/app/components/ui/GradientCard.tsx +100 -0
  218. tools/bolt.diy/app/components/ui/IconButton.tsx +84 -0
  219. tools/bolt.diy/app/components/ui/Input.tsx +22 -0
  220. tools/bolt.diy/app/components/ui/Label.tsx +20 -0
  221. tools/bolt.diy/app/components/ui/LoadingDots.tsx +27 -0
  222. tools/bolt.diy/app/components/ui/LoadingOverlay.tsx +32 -0
  223. tools/bolt.diy/app/components/ui/PanelHeader.tsx +20 -0
  224. tools/bolt.diy/app/components/ui/PanelHeaderButton.tsx +36 -0
  225. tools/bolt.diy/app/components/ui/Popover.tsx +29 -0
  226. tools/bolt.diy/app/components/ui/Progress.tsx +22 -0
  227. tools/bolt.diy/app/components/ui/RepositoryStats.tsx +87 -0
  228. tools/bolt.diy/app/components/ui/ScrollArea.tsx +41 -0
  229. tools/bolt.diy/app/components/ui/SearchInput.tsx +80 -0
  230. tools/bolt.diy/app/components/ui/SearchResultItem.tsx +134 -0
  231. tools/bolt.diy/app/components/ui/Separator.tsx +22 -0
  232. tools/bolt.diy/app/components/ui/SettingsButton.tsx +35 -0
  233. tools/bolt.diy/app/components/ui/Slider.tsx +73 -0
  234. tools/bolt.diy/app/components/ui/StatusIndicator.tsx +90 -0
  235. tools/bolt.diy/app/components/ui/Switch.tsx +37 -0
  236. tools/bolt.diy/app/components/ui/Tabs.tsx +52 -0
  237. tools/bolt.diy/app/components/ui/TabsWithSlider.tsx +112 -0
  238. tools/bolt.diy/app/components/ui/ThemeSwitch.tsx +29 -0
  239. tools/bolt.diy/app/components/ui/Tooltip.tsx +122 -0
  240. tools/bolt.diy/app/components/ui/index.ts +38 -0
  241. tools/bolt.diy/app/components/ui/use-toast.ts +66 -0
  242. tools/bolt.diy/app/components/workbench/DiffView.tsx +796 -0
  243. tools/bolt.diy/app/components/workbench/EditorPanel.tsx +174 -0
  244. tools/bolt.diy/app/components/workbench/ExpoQrModal.tsx +55 -0
  245. tools/bolt.diy/app/components/workbench/FileBreadcrumb.tsx +150 -0
  246. tools/bolt.diy/app/components/workbench/FileTree.tsx +565 -0
  247. tools/bolt.diy/app/components/workbench/Inspector.tsx +126 -0
  248. tools/bolt.diy/app/components/workbench/InspectorPanel.tsx +146 -0
  249. tools/bolt.diy/app/components/workbench/LockManager.tsx +262 -0
  250. tools/bolt.diy/app/components/workbench/PortDropdown.tsx +91 -0
  251. tools/bolt.diy/app/components/workbench/Preview.tsx +1049 -0
  252. tools/bolt.diy/app/components/workbench/ScreenshotSelector.tsx +293 -0
  253. tools/bolt.diy/app/components/workbench/Search.tsx +257 -0
  254. tools/bolt.diy/app/components/workbench/Workbench.client.tsx +506 -0
  255. tools/bolt.diy/app/components/workbench/terminal/Terminal.tsx +131 -0
  256. tools/bolt.diy/app/components/workbench/terminal/TerminalManager.tsx +68 -0
  257. tools/bolt.diy/app/components/workbench/terminal/TerminalTabs.tsx +277 -0
  258. tools/bolt.diy/app/components/workbench/terminal/theme.ts +36 -0
  259. tools/bolt.diy/app/components/workflow/WorkflowPhase.tsx +109 -0
  260. tools/bolt.diy/app/components/workflow/WorkflowStatus.tsx +60 -0
  261. tools/bolt.diy/app/components/workflow/WorkflowTimeline.tsx +150 -0
  262. tools/bolt.diy/app/entry.client.tsx +7 -0
  263. tools/bolt.diy/app/entry.server.tsx +80 -0
  264. tools/bolt.diy/app/root.tsx +156 -0
  265. tools/bolt.diy/app/routes/_index.tsx +175 -0
  266. tools/bolt.diy/app/routes/api.bug-report.ts +254 -0
  267. tools/bolt.diy/app/routes/api.chat.ts +463 -0
  268. tools/bolt.diy/app/routes/api.check-env-key.ts +41 -0
  269. tools/bolt.diy/app/routes/api.configured-providers.ts +110 -0
  270. tools/bolt.diy/app/routes/api.corporate-swarm-status.ts +55 -0
  271. tools/bolt.diy/app/routes/api.enhancer.ts +137 -0
  272. tools/bolt.diy/app/routes/api.export-api-keys.ts +44 -0
  273. tools/bolt.diy/app/routes/api.git-info.ts +69 -0
  274. tools/bolt.diy/app/routes/api.git-proxy.$.ts +178 -0
  275. tools/bolt.diy/app/routes/api.github-branches.ts +166 -0
  276. tools/bolt.diy/app/routes/api.github-deploy.ts +67 -0
  277. tools/bolt.diy/app/routes/api.github-stats.ts +198 -0
  278. tools/bolt.diy/app/routes/api.github-template.ts +242 -0
  279. tools/bolt.diy/app/routes/api.github-user.ts +287 -0
  280. tools/bolt.diy/app/routes/api.gitlab-branches.ts +143 -0
  281. tools/bolt.diy/app/routes/api.gitlab-deploy.ts +67 -0
  282. tools/bolt.diy/app/routes/api.gitlab-projects.ts +105 -0
  283. tools/bolt.diy/app/routes/api.health.ts +8 -0
  284. tools/bolt.diy/app/routes/api.llmcall.ts +298 -0
  285. tools/bolt.diy/app/routes/api.mandate.ts +351 -0
  286. tools/bolt.diy/app/routes/api.mcp-check.ts +16 -0
  287. tools/bolt.diy/app/routes/api.mcp-update-config.ts +23 -0
  288. tools/bolt.diy/app/routes/api.models.$provider.ts +2 -0
  289. tools/bolt.diy/app/routes/api.models.ts +90 -0
  290. tools/bolt.diy/app/routes/api.netlify-deploy.ts +240 -0
  291. tools/bolt.diy/app/routes/api.netlify-user.ts +142 -0
  292. tools/bolt.diy/app/routes/api.supabase-user.ts +199 -0
  293. tools/bolt.diy/app/routes/api.supabase.query.ts +92 -0
  294. tools/bolt.diy/app/routes/api.supabase.ts +56 -0
  295. tools/bolt.diy/app/routes/api.supabase.variables.ts +32 -0
  296. tools/bolt.diy/app/routes/api.system.diagnostics.ts +142 -0
  297. tools/bolt.diy/app/routes/api.system.disk-info.ts +311 -0
  298. tools/bolt.diy/app/routes/api.system.git-info.ts +332 -0
  299. tools/bolt.diy/app/routes/api.update.ts +21 -0
  300. tools/bolt.diy/app/routes/api.vercel-deploy.ts +497 -0
  301. tools/bolt.diy/app/routes/api.vercel-user.ts +161 -0
  302. tools/bolt.diy/app/routes/api.workflow-status.$proposalId.ts +309 -0
  303. tools/bolt.diy/app/routes/chat.$id.tsx +8 -0
  304. tools/bolt.diy/app/routes/execute.$mandateId.tsx +432 -0
  305. tools/bolt.diy/app/routes/git.tsx +25 -0
  306. tools/bolt.diy/app/routes/observability.$mandateId.tsx +50 -0
  307. tools/bolt.diy/app/routes/webcontainer.connect.$id.tsx +32 -0
  308. tools/bolt.diy/app/routes/webcontainer.preview.$id.tsx +97 -0
  309. tools/bolt.diy/app/routes/workflow.$proposalId.tsx +170 -0
  310. tools/bolt.diy/app/styles/animations.scss +49 -0
  311. tools/bolt.diy/app/styles/components/code.scss +9 -0
  312. tools/bolt.diy/app/styles/components/editor.scss +135 -0
  313. tools/bolt.diy/app/styles/components/resize-handle.scss +30 -0
  314. tools/bolt.diy/app/styles/components/terminal.scss +3 -0
  315. tools/bolt.diy/app/styles/components/toast.scss +23 -0
  316. tools/bolt.diy/app/styles/diff-view.css +72 -0
  317. tools/bolt.diy/app/styles/index.scss +73 -0
  318. tools/bolt.diy/app/styles/variables.scss +255 -0
  319. tools/bolt.diy/app/styles/z-index.scss +37 -0
  320. tools/bolt.diy/app/types/GitHub.ts +182 -0
  321. tools/bolt.diy/app/types/GitLab.ts +103 -0
  322. tools/bolt.diy/app/types/actions.ts +85 -0
  323. tools/bolt.diy/app/types/artifact.ts +5 -0
  324. tools/bolt.diy/app/types/context.ts +26 -0
  325. tools/bolt.diy/app/types/design-scheme.ts +93 -0
  326. tools/bolt.diy/app/types/global.d.ts +13 -0
  327. tools/bolt.diy/app/types/mandate.ts +333 -0
  328. tools/bolt.diy/app/types/model.ts +25 -0
  329. tools/bolt.diy/app/types/netlify.ts +94 -0
  330. tools/bolt.diy/app/types/supabase.ts +54 -0
  331. tools/bolt.diy/app/types/template.ts +8 -0
  332. tools/bolt.diy/app/types/terminal.ts +9 -0
  333. tools/bolt.diy/app/types/theme.ts +1 -0
  334. tools/bolt.diy/app/types/vercel.ts +67 -0
  335. tools/bolt.diy/app/utils/buffer.ts +29 -0
  336. tools/bolt.diy/app/utils/classNames.ts +65 -0
  337. tools/bolt.diy/app/utils/constants.ts +147 -0
  338. tools/bolt.diy/app/utils/debounce.ts +13 -0
  339. tools/bolt.diy/app/utils/debugLogger.ts +1284 -0
  340. tools/bolt.diy/app/utils/diff.spec.ts +11 -0
  341. tools/bolt.diy/app/utils/diff.ts +117 -0
  342. tools/bolt.diy/app/utils/easings.ts +3 -0
  343. tools/bolt.diy/app/utils/fileLocks.ts +96 -0
  344. tools/bolt.diy/app/utils/fileUtils.ts +121 -0
  345. tools/bolt.diy/app/utils/folderImport.ts +73 -0
  346. tools/bolt.diy/app/utils/formatSize.ts +12 -0
  347. tools/bolt.diy/app/utils/getLanguageFromExtension.ts +24 -0
  348. tools/bolt.diy/app/utils/githubStats.ts +9 -0
  349. tools/bolt.diy/app/utils/gitlabStats.ts +54 -0
  350. tools/bolt.diy/app/utils/logger.ts +162 -0
  351. tools/bolt.diy/app/utils/markdown.ts +155 -0
  352. tools/bolt.diy/app/utils/mobile.ts +4 -0
  353. tools/bolt.diy/app/utils/os.ts +4 -0
  354. tools/bolt.diy/app/utils/path.ts +19 -0
  355. tools/bolt.diy/app/utils/projectCommands.ts +197 -0
  356. tools/bolt.diy/app/utils/promises.ts +19 -0
  357. tools/bolt.diy/app/utils/react.ts +6 -0
  358. tools/bolt.diy/app/utils/sampler.ts +49 -0
  359. tools/bolt.diy/app/utils/selectStarterTemplate.ts +255 -0
  360. tools/bolt.diy/app/utils/shell.ts +384 -0
  361. tools/bolt.diy/app/utils/stacktrace.ts +27 -0
  362. tools/bolt.diy/app/utils/stripIndent.ts +23 -0
  363. tools/bolt.diy/app/utils/terminal.ts +11 -0
  364. tools/bolt.diy/app/utils/unreachable.ts +3 -0
  365. tools/bolt.diy/app/vite-env.d.ts +2 -0
  366. tools/bolt.diy/assets/entitlements.mac.plist +25 -0
  367. tools/bolt.diy/assets/icons/icon.icns +0 -0
  368. tools/bolt.diy/assets/icons/icon.ico +0 -0
  369. tools/bolt.diy/assets/icons/icon.png +0 -0
  370. tools/bolt.diy/bindings.js +78 -0
  371. tools/bolt.diy/bindings.sh +33 -0
  372. tools/bolt.diy/docker-compose.yaml +145 -0
  373. tools/bolt.diy/electron/main/index.ts +201 -0
  374. tools/bolt.diy/electron/main/tsconfig.json +30 -0
  375. tools/bolt.diy/electron/main/ui/menu.ts +29 -0
  376. tools/bolt.diy/electron/main/ui/window.ts +54 -0
  377. tools/bolt.diy/electron/main/utils/auto-update.ts +110 -0
  378. tools/bolt.diy/electron/main/utils/constants.ts +4 -0
  379. tools/bolt.diy/electron/main/utils/cookie.ts +40 -0
  380. tools/bolt.diy/electron/main/utils/reload.ts +35 -0
  381. tools/bolt.diy/electron/main/utils/serve.ts +71 -0
  382. tools/bolt.diy/electron/main/utils/store.ts +3 -0
  383. tools/bolt.diy/electron/main/utils/vite-server.ts +44 -0
  384. tools/bolt.diy/electron/main/vite.config.ts +44 -0
  385. tools/bolt.diy/electron/preload/index.ts +22 -0
  386. tools/bolt.diy/electron/preload/tsconfig.json +7 -0
  387. tools/bolt.diy/electron/preload/vite.config.ts +31 -0
  388. tools/bolt.diy/electron-builder.yml +64 -0
  389. tools/bolt.diy/electron-update.yml +4 -0
  390. tools/bolt.diy/eslint.config.mjs +57 -0
  391. tools/bolt.diy/functions/[[path]].ts +12 -0
  392. tools/bolt.diy/icons/angular.svg +1 -0
  393. tools/bolt.diy/icons/astro.svg +8 -0
  394. tools/bolt.diy/icons/chat.svg +1 -0
  395. tools/bolt.diy/icons/expo-brand.svg +1 -0
  396. tools/bolt.diy/icons/expo.svg +4 -0
  397. tools/bolt.diy/icons/logo-text.svg +1 -0
  398. tools/bolt.diy/icons/logo.svg +4 -0
  399. tools/bolt.diy/icons/mcp.svg +1 -0
  400. tools/bolt.diy/icons/nativescript.svg +1 -0
  401. tools/bolt.diy/icons/netlify.svg +10 -0
  402. tools/bolt.diy/icons/nextjs.svg +1 -0
  403. tools/bolt.diy/icons/nuxt.svg +1 -0
  404. tools/bolt.diy/icons/qwik.svg +1 -0
  405. tools/bolt.diy/icons/react.svg +1 -0
  406. tools/bolt.diy/icons/remix.svg +24 -0
  407. tools/bolt.diy/icons/remotion.svg +1 -0
  408. tools/bolt.diy/icons/shadcn.svg +21 -0
  409. tools/bolt.diy/icons/slidev.svg +60 -0
  410. tools/bolt.diy/icons/solidjs.svg +1 -0
  411. tools/bolt.diy/icons/stars.svg +1 -0
  412. tools/bolt.diy/icons/svelte.svg +1 -0
  413. tools/bolt.diy/icons/typescript.svg +1 -0
  414. tools/bolt.diy/icons/vite.svg +1 -0
  415. tools/bolt.diy/icons/vue.svg +1 -0
  416. tools/bolt.diy/load-context.ts +9 -0
  417. tools/bolt.diy/notarize.cjs +31 -0
  418. tools/bolt.diy/package.json +218 -0
  419. tools/bolt.diy/playwright.config.preview.ts +35 -0
  420. tools/bolt.diy/pre-start.cjs +26 -0
  421. tools/bolt.diy/public/apple-touch-icon-precomposed.png +0 -0
  422. tools/bolt.diy/public/apple-touch-icon.png +0 -0
  423. tools/bolt.diy/public/favicon.ico +0 -0
  424. tools/bolt.diy/public/favicon.svg +4 -0
  425. tools/bolt.diy/public/icons/AmazonBedrock.svg +1 -0
  426. tools/bolt.diy/public/icons/Anthropic.svg +4 -0
  427. tools/bolt.diy/public/icons/Cohere.svg +4 -0
  428. tools/bolt.diy/public/icons/Deepseek.svg +5 -0
  429. tools/bolt.diy/public/icons/Default.svg +4 -0
  430. tools/bolt.diy/public/icons/Google.svg +4 -0
  431. tools/bolt.diy/public/icons/Groq.svg +4 -0
  432. tools/bolt.diy/public/icons/HuggingFace.svg +4 -0
  433. tools/bolt.diy/public/icons/Hyperbolic.svg +3 -0
  434. tools/bolt.diy/public/icons/LMStudio.svg +5 -0
  435. tools/bolt.diy/public/icons/Mistral.svg +4 -0
  436. tools/bolt.diy/public/icons/Ollama.svg +4 -0
  437. tools/bolt.diy/public/icons/OpenAI.svg +4 -0
  438. tools/bolt.diy/public/icons/OpenAILike.svg +4 -0
  439. tools/bolt.diy/public/icons/OpenRouter.svg +4 -0
  440. tools/bolt.diy/public/icons/Perplexity.svg +4 -0
  441. tools/bolt.diy/public/icons/Together.svg +4 -0
  442. tools/bolt.diy/public/icons/xAI.svg +5 -0
  443. tools/bolt.diy/public/inspector-script.js +292 -0
  444. tools/bolt.diy/public/logo-dark-styled.png +0 -0
  445. tools/bolt.diy/public/logo-dark.png +0 -0
  446. tools/bolt.diy/public/logo-light-styled.png +0 -0
  447. tools/bolt.diy/public/logo-light.png +0 -0
  448. tools/bolt.diy/public/logo.svg +15 -0
  449. tools/bolt.diy/public/social_preview_index.jpg +0 -0
  450. tools/bolt.diy/scripts/clean.js +45 -0
  451. tools/bolt.diy/scripts/electron-dev.mjs +181 -0
  452. tools/bolt.diy/scripts/setup-env.sh +41 -0
  453. tools/bolt.diy/scripts/update-imports.sh +7 -0
  454. tools/bolt.diy/scripts/update.sh +52 -0
  455. tools/bolt.diy/services/execution-governor/Dockerfile +41 -0
  456. tools/bolt.diy/services/execution-governor/config.ts +42 -0
  457. tools/bolt.diy/services/execution-governor/index.ts +683 -0
  458. tools/bolt.diy/services/execution-governor/metrics.ts +141 -0
  459. tools/bolt.diy/services/execution-governor/package.json +31 -0
  460. tools/bolt.diy/services/execution-governor/priority-queue.ts +139 -0
  461. tools/bolt.diy/services/execution-governor/tsconfig.json +21 -0
  462. tools/bolt.diy/services/execution-governor/types.ts +145 -0
  463. tools/bolt.diy/services/headless-executor/Dockerfile +43 -0
  464. tools/bolt.diy/services/headless-executor/executor.ts +210 -0
  465. tools/bolt.diy/services/headless-executor/index.ts +323 -0
  466. tools/bolt.diy/services/headless-executor/package.json +27 -0
  467. tools/bolt.diy/services/headless-executor/tsconfig.json +21 -0
  468. tools/bolt.diy/services/headless-executor/types.ts +38 -0
  469. tools/bolt.diy/test-workflows.sh +240 -0
  470. tools/bolt.diy/tests/integration/corporate-swarm.test.ts +208 -0
  471. tools/bolt.diy/tests/mandates/budget-limited.json +34 -0
  472. tools/bolt.diy/tests/mandates/complex.json +53 -0
  473. tools/bolt.diy/tests/mandates/constraint-enforced.json +36 -0
  474. tools/bolt.diy/tests/mandates/simple.json +35 -0
  475. tools/bolt.diy/tsconfig.json +37 -0
  476. tools/bolt.diy/types/istextorbinary.d.ts +15 -0
  477. tools/bolt.diy/uno.config.ts +279 -0
  478. tools/bolt.diy/vite-electron.config.ts +76 -0
  479. tools/bolt.diy/vite.config.ts +112 -0
  480. tools/bolt.diy/worker-configuration.d.ts +22 -0
  481. tools/bolt.diy/wrangler.toml +6 -0
  482. tools/code_generator.py +461 -0
  483. tools/file_operations.py +465 -0
  484. tools/mandate_generator.py +337 -0
  485. tools/mcpClientUtils.py +1216 -0
  486. tools/sensors.py +285 -0
  487. utils/Agent_types.py +15 -0
  488. utils/AnyToStr.py +0 -0
  489. utils/HHCS.py +277 -0
  490. utils/__init__.py +30 -0
  491. utils/agent.py +3627 -0
  492. utils/aop.py +2948 -0
  493. utils/canonical.py +143 -0
  494. utils/conversation.py +1195 -0
  495. utils/doctrine_versioning +230 -0
  496. utils/formatter.py +474 -0
  497. utils/ledger.py +311 -0
  498. utils/out_types.py +16 -0
  499. utils/rollback.py +339 -0
  500. utils/router.py +929 -0
  501. utils/tui.py +1908 -0
PKG-INFO ADDED
@@ -0,0 +1,5035 @@
1
+ Metadata-Version: 2.4
2
+ Name: crca
3
+ Version: 1.4.0
4
+ Summary: CR-CA Lite — lightweight causal reasoning agent with advanced analysis suite (CR-CA)
5
+ Project-URL: Homepage, https://github.com/IlumCI/CR-CA
6
+ Project-URL: Repository, https://github.com/IlumCI/CR-CA
7
+ Project-URL: Documentation, https://github.com/IlumCI/CR-CA/blob/main/README.md
8
+ Project-URL: Issues, https://github.com/IlumCI/CR-CA/issues
9
+ Author-email: Ilum <a.leilionas@vk.com>
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: causal-reasoning,counterfactual-analysis,data-science,governance,llm,machine-learning,optimization,socioeconomic-dynamics,structural-causal-models,trading
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: ccxt>=4.0
28
+ Requires-Dist: dowhy>=0.8
29
+ Requires-Dist: geoip2>=4.7.0
30
+ Requires-Dist: lightgbm>=4.0
31
+ Requires-Dist: litellm>=0.1
32
+ Requires-Dist: loguru>=0.7
33
+ Requires-Dist: matplotlib>=3.5
34
+ Requires-Dist: mcp>=0.9.0
35
+ Requires-Dist: networkx>=3.0
36
+ Requires-Dist: numba>=0.58
37
+ Requires-Dist: numpy>=1.23
38
+ Requires-Dist: openai>=1.0.0
39
+ Requires-Dist: optuna>=3.0
40
+ Requires-Dist: pandas>=1.5
41
+ Requires-Dist: pillow>=10.0
42
+ Requires-Dist: praw>=7.0
43
+ Requires-Dist: psutil>=5.9.0
44
+ Requires-Dist: pycoingecko>=3.0
45
+ Requires-Dist: pydantic>=2.0
46
+ Requires-Dist: python-dateutil>=2.8
47
+ Requires-Dist: python-dotenv>=1.0
48
+ Requires-Dist: pytrends>=4.8.0
49
+ Requires-Dist: pyyaml>=6.0
50
+ Requires-Dist: redis>=5.0
51
+ Requires-Dist: reportlab>=4.0.0
52
+ Requires-Dist: requests>=2.28
53
+ Requires-Dist: rich>=13.0
54
+ Requires-Dist: rustworkx>=0.12.0
55
+ Requires-Dist: scikit-learn>=1.3
56
+ Requires-Dist: scipy>=1.10
57
+ Requires-Dist: seaborn>=0.11
58
+ Requires-Dist: shodan>=1.30.0
59
+ Requires-Dist: swarms
60
+ Requires-Dist: toml>=0.10.2
61
+ Requires-Dist: torch>=2.0.0
62
+ Requires-Dist: tqdm>=4.65.0
63
+ Requires-Dist: web3>=6.0
64
+ Requires-Dist: websockets>=11.0
65
+ Requires-Dist: xgboost>=2.0
66
+ Requires-Dist: yfinance>=0.2.0
67
+ Provides-Extra: dev
68
+ Requires-Dist: black>=23.0; extra == 'dev'
69
+ Requires-Dist: mypy>=1.0; extra == 'dev'
70
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
71
+ Requires-Dist: pytest>=7.0; extra == 'dev'
72
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
73
+ Provides-Extra: optimization
74
+ Requires-Dist: cvxpy>=1.4; extra == 'optimization'
75
+ Description-Content-Type: text/markdown
76
+
77
+ # CR-CA: Causal Reasoning and Counterfactual Analysis Framework
78
+
79
+ **Version**: v1.4.0
80
+ **Repository**: [https://github.com/IlumCI/CR-CA](https://github.com/IlumCI/CR-CA)
81
+ **License**: Apache-2.0
82
+
83
+ CR-CA is a comprehensive framework for causal reasoning and counterfactual analysis, combining structural causal models (SCMs) with large language model (LLM) integration. The framework enables sophisticated causal inference, automatic variable extraction from natural language, deterministic causal simulation, and comprehensive counterfactual scenario generation. Designed for both research and practical applications, CR-CA provides a modular architecture supporting specialized agents for quantitative trading, socioeconomic dynamics, and corporate governance.
84
+
85
+ ---
86
+
87
+ ## Quick Reference Tables
88
+
89
+ ### Feature Matrix
90
+
91
+ | Feature | Core CRCAAgent | CRCA-SD | CRCA-CG | CRCA-Q |
92
+ |---------|----------------|---------|---------|--------|
93
+ | Automatic Variable Extraction | ✓ | ✓ | ✓ | ✓ |
94
+ | LLM-Based Causal Analysis | ✓ | ✓ | ✓ | ✓ |
95
+ | Deterministic Simulation | ✓ | ✓ | - | ✓ |
96
+ | Counterfactual Generation | ✓ | ✓ | ✓ | ✓ |
97
+ | Batch Prediction | ✓ | - | - | ✓ |
98
+ | Async Operations | ✓ | - | - | ✓ |
99
+ | Optimization Methods | ✓ | ✓ | - | ✓ |
100
+ | Time-Series Analysis | ✓ | - | - | ✓ |
101
+ | Bayesian Inference | ✓ | - | - | ✓ |
102
+ | Data Source Integration | - | - | - | ✓ |
103
+
104
+ ### Module Overview
105
+
106
+ | Module | Purpose | Key Components |
107
+ |--------|---------|----------------|
108
+ | `CRCA.py` | Core causal reasoning agent | CRCAAgent, automatic extraction, dual-mode operation |
109
+ | `utils/` | Utility functions and extensions | Formatter, TUI, router, conversation management |
110
+ | `tools/` | External tool integration | MCP client utilities, protocol handling |
111
+ | `templates/` | Agent creation framework | Base agents, feature mixins, module registry |
112
+ | `schemas/` | Type definitions | MCP schemas, data structures |
113
+ | `crca_sd/` | Socioeconomic dynamics | MPC solver, governance, real-time monitoring |
114
+ | `crca_cg/` | Corporate governance | CorporateSwarm, ESG scoring, multi-agent orchestration |
115
+ | `branches/CRCA-Q.py` | Quantitative trading | QuantTradingAgent, causal signals, portfolio optimization |
116
+
117
+ ### Dependency Matrix
118
+
119
+ | Dependency | Core | Advanced Analysis | CRCA-SD | CRCA-CG | CRCA-Q |
120
+ |------------|------|-------------------|---------|---------|--------|
121
+ | numpy | ✓ | ✓ | ✓ | ✓ | ✓ |
122
+ | rustworkx | ✓ | ✓ | ✓ | ✓ | ✓ |
123
+ | swarms | ✓ | ✓ | ✓ | ✓ | ✓ |
124
+ | litellm | ✓ | ✓ | ✓ | ✓ | ✓ |
125
+ | pandas | - | ✓ | ✓ | ✓ | ✓ |
126
+ | scipy | - | ✓ | ✓ | - | ✓ |
127
+ | loguru | ✓ | ✓ | ✓ | ✓ | ✓ |
128
+ | pydantic | ✓ | ✓ | ✓ | ✓ | ✓ |
129
+ | mcp | ✓ | ✓ | - | - | - |
130
+ | openai | ✓ | ✓ | - | - | - |
131
+ | ccxt | - | - | - | - | ✓ |
132
+ | web3 | - | - | - | - | ✓ |
133
+ | curses | - | - | ✓ | - | - |
134
+
135
+ ---
136
+
137
+ ## Table of Contents
138
+
139
+ 1. [Installation & Setup](#installation--setup)
140
+ 2. [Core CRCAAgent](#core-crcaagent)
141
+ 3. [Automatic Variable Extraction](#automatic-variable-extraction)
142
+ 4. [Module Documentation](#module-documentation)
143
+ - [Utils Module](#utils-module)
144
+ - [Tools Module](#tools-module)
145
+ - [Templates Module](#templates-module)
146
+ - [Schemas Module](#schemas-module)
147
+ - [CRCA-SD Module](#crca-sd-module)
148
+ - [CRCA-CG Module](#crca-cg-module)
149
+ 5. [Policy Engine System](#policy-engine-system)
150
+ 6. [Branch Integrations](#branch-integrations)
151
+ - [CRCA-Q Integration](#crca-q-integration)
152
+ - [CRCA-SD Integration](#crca-sd-integration)
153
+ - [CRCA-CG Integration](#crca-cg-integration)
154
+ 7. [Usage Examples](#usage-examples)
155
+ 8. [Advanced Features](#advanced-features)
156
+ 9. [Testing](#testing)
157
+ 10. [CI/CD Workflows](#cicd-workflows)
158
+ 11. [Project Structure](#project-structure)
159
+ 12. [Architecture Diagrams](#architecture-diagrams)
160
+ 13. [Integration Examples](#integration-examples)
161
+ 14. [API Reference](#api-reference)
162
+ 15. [Architecture & Design](#architecture--design)
163
+ 16. [Research & Theory](#research--theory)
164
+ 17. [Configuration & Customization](#configuration--customization)
165
+ 18. [Troubleshooting](#troubleshooting)
166
+ 19. [Contributing](#contributing)
167
+ 20. [Changelog](#changelog)
168
+ 21. [References & Resources](#references--resources)
169
+ 22. [Bolt.diy Web Application (WIP)](#boltdiy-web-application-wip)
170
+
171
+ ---
172
+
173
+ ## Installation & Setup
174
+
175
+ ### Prerequisites
176
+
177
+ - Python 3.10 or higher
178
+ - pip package manager
179
+ - (Optional) Git for cloning the repository
180
+ - (Optional) Docker for containerized deployment
181
+
182
+ ### Quick Install
183
+
184
+ **Method 1: From PyPI (Recommended)**
185
+
186
+ ```bash
187
+ pip install crca
188
+ ```
189
+
190
+ **Method 2: From Source**
191
+
192
+ Clone the repository:
193
+
194
+ ```bash
195
+ git clone https://github.com/IlumCI/CR-CA.git
196
+ cd CR-CA
197
+ ```
198
+
199
+ Install dependencies:
200
+
201
+ ```bash
202
+ pip install -r requirements.txt
203
+ ```
204
+
205
+ **Method 3: Development Install**
206
+
207
+ For development with editable install:
208
+
209
+ ```bash
210
+ git clone https://github.com/IlumCI/CR-CA.git
211
+ cd CR-CA
212
+ pip install -e ".[dev]"
213
+ ```
214
+
215
+ ### Optional Dependencies
216
+
217
+ **For Policy Engine:**
218
+
219
+ ```bash
220
+ # Install policy engine dependencies
221
+ pip install cvxpy ruptures psutil
222
+
223
+ # Or install all optional dependencies
224
+ pip install crca[policy-engine]
225
+ ```
226
+
227
+ **For CRCA-SD:**
228
+
229
+ ```bash
230
+ # CRCA-SD dependencies are included in requirements.txt
231
+ # Additional dependencies may be needed for specific features
232
+ ```
233
+
234
+ **For CRCA-CG:**
235
+
236
+ ```bash
237
+ # Install TUI dependencies (optional)
238
+ pip install rich
239
+
240
+ # Or install all optional dependencies
241
+ pip install crca[tui]
242
+ ```
243
+
244
+ **For CRCA-Q:**
245
+
246
+ ```bash
247
+ # Install trading dependencies
248
+ pip install ccxt web3
249
+
250
+ # Or install all optional dependencies
251
+ pip install crca[trading]
252
+ ```
253
+
254
+ ### Environment Variables
255
+
256
+ Create a `.env` file in the project root with required API keys:
257
+
258
+ ```bash
259
+ # Required for LLM functionality
260
+ OPENAI_API_KEY=your_openai_api_key_here
261
+
262
+ # Optional: For CRCA-Q trading
263
+ KRAKEN_API_KEY=your_kraken_key_here
264
+ KRAKEN_API_SECRET=your_kraken_secret_here
265
+
266
+ # Optional: For alternative data sources
267
+ TWITTER_BEARER_TOKEN=your_twitter_token_here
268
+ ETHERSCAN_API_KEY=your_etherscan_key_here
269
+ THEGRAPH_API_KEY=your_thegraph_key_here
270
+
271
+ # Optional: For MCP servers
272
+ MCP_SERVER_URL=http://localhost:8000
273
+ MCP_API_KEY=your_mcp_api_key_here
274
+ ```
275
+
276
+ ### Docker Setup (Optional)
277
+
278
+ **Example: Dockerfile for Policy Engine**
279
+
280
+ ```dockerfile
281
+ FROM python:3.11-slim
282
+
283
+ WORKDIR /app
284
+
285
+ # Install system dependencies
286
+ RUN apt-get update && apt-get install -y \
287
+ gcc \
288
+ g++ \
289
+ && rm -rf /var/lib/apt/lists/*
290
+
291
+ # Copy requirements
292
+ COPY requirements.txt .
293
+ RUN pip install --no-cache-dir -r requirements.txt
294
+
295
+ # Install policy engine dependencies
296
+ RUN pip install cvxpy ruptures psutil
297
+
298
+ # Copy application
299
+ COPY . .
300
+
301
+ # Set environment variables
302
+ ENV PYTHONUNBUFFERED=1
303
+
304
+ # Run application
305
+ CMD ["python", "-m", "CRCA"]
306
+ ```
307
+
308
+ **Example: Docker Compose for Full Stack**
309
+
310
+ ```yaml
311
+ version: '3.8'
312
+
313
+ services:
314
+ crca:
315
+ build: .
316
+ environment:
317
+ - OPENAI_API_KEY=${OPENAI_API_KEY}
318
+ volumes:
319
+ - ./policy_ledger.db:/app/policy_ledger.db
320
+ - ./rollback.db:/app/rollback.db
321
+ ports:
322
+ - "8000:8000"
323
+ ```
324
+
325
+ ### Verification
326
+
327
+ **Example 1: Basic Verification**
328
+
329
+ ```python
330
+ from dotenv import load_dotenv
331
+ from CRCA import CRCAAgent
332
+
333
+ load_dotenv()
334
+
335
+ agent = CRCAAgent(
336
+ model_name="gpt-4o-mini",
337
+ causal_edges=[("funding", "failure"), ("engineers", "failure"), ("project", "failure")],
338
+ variables=["funding", "engineers", "project", "failure", "success"],
339
+ max_loops=3,
340
+ agent_max_loops=3,
341
+ use_crca_tools=True,
342
+ enable_batch_predict=True,
343
+ )
344
+
345
+ task = "Why do large software projects collapse despite adequate funding?"
346
+ result = agent.run(task)
347
+ print(result.get("causal_analysis", ""))
348
+ ```
349
+
350
+ **Example 2: Verify Policy Engine**
351
+
352
+ ```python
353
+ from schemas.policy import DoctrineV1, EpochConfig, MetricSpec, Objective, RiskBudget
354
+ from utils.ledger import Ledger
355
+
356
+ # Create minimal doctrine
357
+ doctrine = DoctrineV1(
358
+ epoch=EpochConfig(unit="hours", length=1.0),
359
+ metrics={"test": MetricSpec(extractor_key="test", unit="unit")},
360
+ objectives=[Objective(metric_name="test", direction="minimize", weight=1.0)],
361
+ invariants=[],
362
+ levers={},
363
+ risk_budget=RiskBudget()
364
+ )
365
+
366
+ # Test ledger
367
+ ledger = Ledger(db_path=":memory:")
368
+ print("Policy engine components verified!")
369
+ ```
370
+
371
+ **Example 3: Verify All Modules**
372
+
373
+ ```python
374
+ # Test core
375
+ from CRCA import CRCAAgent
376
+ agent = CRCAAgent(model_name="gpt-4o-mini")
377
+ print("✓ Core CRCA verified")
378
+
379
+ # Test CRCA-SD
380
+ try:
381
+ from crca_sd import StateVector
382
+ print("✓ CRCA-SD verified")
383
+ except ImportError:
384
+ print("✗ CRCA-SD not available")
385
+
386
+ # Test CRCA-CG
387
+ try:
388
+ from crca_cg.corposwarm import CorporateSwarm
389
+ print("✓ CRCA-CG verified")
390
+ except ImportError:
391
+ print("✗ CRCA-CG not available")
392
+
393
+ # Test Policy Engine
394
+ from schemas.policy import DoctrineV1
395
+ from utils.ledger import Ledger
396
+ print("✓ Policy Engine verified")
397
+ ```
398
+
399
+ ---
400
+
401
+ ## Core CRCAAgent
402
+
403
+ ### Introduction
404
+
405
+ CRCAAgent is the core component of the CR-CA framework, providing a lightweight causal reasoning engine with LLM integration. It implements structural causal models (SCMs) based on Judea Pearl's causal hierarchy, enabling both LLM-based causal analysis and deterministic causal simulation.
406
+
407
+ ### Key Features
408
+
409
+ - **Automatic Variable Extraction**: Extract variables and causal relationships directly from natural language tasks without manual declaration
410
+ - **LLM-Based Causal Reasoning**: Sophisticated multi-loop causal analysis using large language models
411
+ - **Deterministic Causal Simulation**: Fast, deterministic state evolution using linear/non-linear SCMs
412
+ - **Dual-Mode Operation**: Automatically selects LLM mode (task string) or deterministic mode (state dict)
413
+ - **Batch Prediction**: Efficient vectorized predictions for ensemble forecasting
414
+ - **Async/Await Support**: Non-blocking operations for concurrent analysis
415
+ - **Advanced Analysis Methods**: Optimization, time-series analysis, Bayesian inference, root cause analysis
416
+
417
+ ### Architecture
418
+
419
+ ```mermaid
420
+ flowchart TB
421
+ Input[Input: Task or State] --> ModeCheck{Mode Detection}
422
+
423
+ ModeCheck -->|String Task| LLMMode[LLM Mode]
424
+ ModeCheck -->|State Dict| DetMode[Deterministic Mode]
425
+
426
+ LLMMode --> EmptyCheck{Graph Empty?}
427
+ EmptyCheck -->|Yes| AutoExtract[Automatic Variable Extraction]
428
+ EmptyCheck -->|No| BuildPrompt[Build Causal Prompt]
429
+
430
+ AutoExtract --> LLMAnalysis[LLM Causal Analysis]
431
+ BuildPrompt --> LLMAnalysis
432
+ LLMAnalysis --> GenerateCF[Generate Counterfactuals]
433
+
434
+ DetMode --> Standardize[Standardize to z-space]
435
+ Standardize --> TopoSort[Topological Sort]
436
+ TopoSort --> Predict[SCM Evolution]
437
+ Predict --> DeStandardize[De-standardize]
438
+ DeStandardize --> GenerateCF
439
+
440
+ GenerateCF --> Output[Output: Analysis + Scenarios]
441
+
442
+ Graph[Causal Graph] --> LLMMode
443
+ Graph --> DetMode
444
+ ```
445
+
446
+ ### Automatic Variable Extraction
447
+
448
+ One of the most powerful features introduced in v1.3.0 is automatic variable extraction. When a task is provided without pre-declared variables, CRCAAgent automatically:
449
+
450
+ 1. **Analyzes the task** using LLM-based natural language understanding
451
+ 2. **Extracts relevant variables** from the task description
452
+ 3. **Identifies causal relationships** between variables
453
+ 4. **Builds the causal graph** automatically
454
+ 5. **Proceeds with causal analysis** using the extracted graph
455
+
456
+ This eliminates the need to manually declare variables and edges for most use cases, making the framework significantly more accessible.
457
+
458
+ **How it works:**
459
+
460
+ - When `run(task)` is called with a string task and the causal graph is empty, the agent triggers automatic extraction
461
+ - The LLM analyzes the task and generates structured JSON with variables and edges
462
+ - The extraction handler programmatically adds variables and relationships to the graph
463
+ - Subsequent analysis uses the automatically constructed graph
464
+
465
+ **Example:**
466
+
467
+ ```python
468
+ from CRCA import CRCAAgent
469
+
470
+ # No variables declared - automatic extraction will occur
471
+ agent = CRCAAgent(model_name="gpt-4o-mini")
472
+
473
+ # Task automatically triggers variable extraction
474
+ task = "Analyze how increasing product price affects demand and revenue"
475
+ result = agent.run(task=task)
476
+
477
+ # Variables and edges were automatically extracted and used
478
+ print(f"Extracted {len(agent.get_nodes())} variables")
479
+ print(f"Created {len(agent.get_edges())} causal relationships")
480
+ ```
481
+
482
+ ### Basic Usage
483
+
484
+ #### LLM-Based Causal Analysis (Automatic Extraction)
485
+
486
+ ```python
487
+ from CRCA import CRCAAgent
488
+
489
+ agent = CRCAAgent(
490
+ model_name="gpt-4o",
491
+ max_loops=3,
492
+ agent_max_loops=3
493
+ )
494
+
495
+ # Automatic variable extraction + causal analysis
496
+ task = "Why do software projects fail despite adequate funding?"
497
+ result = agent.run(task=task)
498
+
499
+ print(result["causal_analysis"])
500
+ for scenario in result["counterfactual_scenarios"][:3]:
501
+ print(f"{scenario.name}: {scenario.reasoning}")
502
+ ```
503
+
504
+ #### Deterministic Simulation (Traditional Approach)
505
+
506
+ ```python
507
+ from CRCA import CRCAAgent
508
+
509
+ agent = CRCAAgent(variables=["price", "demand", "inventory"])
510
+ agent.add_causal_relationship("price", "demand", strength=-0.5)
511
+ agent.add_causal_relationship("demand", "inventory", strength=-0.2)
512
+
513
+ state = {"price": 100.0, "demand": 1000.0, "inventory": 5000.0}
514
+ result = agent.run(initial_state=state, max_steps=2)
515
+
516
+ print(result["evolved_state"])
517
+ for scenario in result["counterfactual_scenarios"][:3]:
518
+ print(f"{scenario.name}: {scenario.probability:.2f}")
519
+ ```
520
+
521
+ #### Hybrid Approach (LLM Extraction + Deterministic Simulation)
522
+
523
+ ```python
524
+ from CRCA import CRCAAgent
525
+
526
+ agent = CRCAAgent(model_name="gpt-4o-mini")
527
+
528
+ # Step 1: Automatic extraction via LLM
529
+ task = "Analyze pricing strategy for a new product"
530
+ extraction_result = agent.run(task=task)
531
+
532
+ # Step 2: Use extracted graph for deterministic simulation
533
+ initial_state = {var: 0.0 for var in agent.get_nodes()}
534
+ simulation_result = agent.run(initial_state=initial_state, max_steps=5)
535
+
536
+ print(f"Simulated {len(simulation_result['counterfactual_scenarios'])} scenarios")
537
+ ```
538
+
539
+ ### Advanced Features
540
+
541
+ #### Batch Prediction
542
+
543
+ ```python
544
+ agent = CRCAAgent(
545
+ variables=["price", "demand"],
546
+ enable_batch_predict=True,
547
+ max_batch_size=32
548
+ )
549
+
550
+ factual_states = [{"price": 100.0, "demand": 1000.0} for _ in range(100)]
551
+ interventions_list = [{"price": 100.0 + i} for i in range(100)]
552
+
553
+ predictions = agent._predict_outcomes_batch(factual_states, interventions_list)
554
+ ```
555
+
556
+ #### Async Operations
557
+
558
+ ```python
559
+ import asyncio
560
+
561
+ async def analyze_async():
562
+ agent = CRCAAgent(variables=["x", "y"])
563
+ result = await agent.run_async(
564
+ initial_state={"x": 1.0, "y": 2.0},
565
+ max_steps=3
566
+ )
567
+ return result
568
+
569
+ result = asyncio.run(analyze_async())
570
+ ```
571
+
572
+ #### Optimization Methods
573
+
574
+ ```python
575
+ agent = CRCAAgent(variables=["price", "demand", "revenue"])
576
+ agent.add_causal_relationship("price", "demand", strength=-0.5)
577
+ agent.add_causal_relationship("price", "revenue", strength=1.0)
578
+ agent.add_causal_relationship("demand", "revenue", strength=0.8)
579
+
580
+ initial_state = {"price": 100.0, "demand": 1000.0, "revenue": 100000.0}
581
+
582
+ # Gradient-based optimization
583
+ opt_result = agent.gradient_based_intervention_optimization(
584
+ initial_state=initial_state,
585
+ target="revenue",
586
+ intervention_vars=["price"],
587
+ constraints={"price": (80.0, 120.0)}
588
+ )
589
+
590
+ print(f"Optimal price: {opt_result['optimal_intervention']['price']}")
591
+ print(f"Optimal revenue: {opt_result['optimal_target_value']}")
592
+ ```
593
+
594
+ ---
595
+
596
+ ## Module Documentation
597
+
598
+ ### Utils Module
599
+
600
+ The `utils/` module provides essential utilities and extensions for the CR-CA framework.
601
+
602
+ #### Formatter (`utils/formatter.py`)
603
+
604
+ Provides markdown output formatting and rich text rendering:
605
+
606
+ ```python
607
+ from utils.formatter import Formatter
608
+
609
+ formatter = Formatter(md=True)
610
+ formatter.print_markdown(analysis_text, title="Causal Analysis")
611
+ ```
612
+
613
+ #### Agent Types (`utils/Agent_types.py`)
614
+
615
+ Type definitions for agent-related structures.
616
+
617
+ #### Conversation (`utils/conversation.py`)
618
+
619
+ Manages conversation history and message handling for agent interactions.
620
+
621
+ #### Agent Extensions (`utils/agent.py`)
622
+
623
+ Extended agent functionality building on the Swarms Agent base class, including streaming output, error handling, and tool management.
624
+
625
+ #### TUI (`utils/tui.py`)
626
+
627
+ Terminal user interface components for interactive agent interactions, including CorporateSwarmTUI for multi-agent orchestration.
628
+
629
+ #### Router (`utils/router.py`)
630
+
631
+ Task routing and distribution system for multi-agent workflows. Supports multiple swarm architectures including sequential, concurrent, hierarchical, and collaborative patterns.
632
+
633
+ **Example 1: Sequential Workflow**
634
+
635
+ ```python
636
+ from utils.router import SwarmRouter, SwarmRouterConfig
637
+
638
+ # Create sequential workflow router
639
+ config = SwarmRouterConfig(
640
+ name="sequential-processor",
641
+ description="Process tasks sequentially",
642
+ swarm_type="SequentialWorkflow",
643
+ task="Process data pipeline: extract, transform, load"
644
+ )
645
+
646
+ router = SwarmRouter(config=config)
647
+ result = router.run()
648
+
649
+ print(f"Sequential workflow completed: {result}")
650
+ ```
651
+
652
+ **Example 2: Concurrent Workflow**
653
+
654
+ ```python
655
+ from utils.router import SwarmRouter, SwarmRouterConfig
656
+
657
+ # Create concurrent workflow for parallel processing
658
+ config = SwarmRouterConfig(
659
+ name="parallel-processor",
660
+ description="Process multiple tasks in parallel",
661
+ swarm_type="ConcurrentWorkflow",
662
+ task="Analyze multiple datasets concurrently"
663
+ )
664
+
665
+ router = SwarmRouter(config=config)
666
+ result = router.run()
667
+
668
+ print(f"Concurrent workflow completed: {result}")
669
+ ```
670
+
671
+ **Example 3: Hierarchical Swarm**
672
+
673
+ ```python
674
+ from utils.router import SwarmRouter, SwarmRouterConfig
675
+
676
+ # Create hierarchical swarm for complex task decomposition
677
+ config = SwarmRouterConfig(
678
+ name="hierarchical-manager",
679
+ description="Decompose complex tasks hierarchically",
680
+ swarm_type="HierarchicalSwarm",
681
+ task="Manage multi-level project with dependencies"
682
+ )
683
+
684
+ router = SwarmRouter(config=config)
685
+ result = router.run()
686
+
687
+ print(f"Hierarchical swarm completed: {result}")
688
+ ```
689
+
690
+ **Example 4: Collaborative Group Chat**
691
+
692
+ ```python
693
+ from utils.router import SwarmRouter, SwarmRouterConfig
694
+
695
+ # Create collaborative swarm for group discussion
696
+ config = SwarmRouterConfig(
697
+ name="collaborative-team",
698
+ description="Collaborative problem solving",
699
+ swarm_type="GroupChat",
700
+ multi_agent_collab_prompt=True,
701
+ task="Design a new feature through team discussion"
702
+ )
703
+
704
+ router = SwarmRouter(config=config)
705
+ result = router.run()
706
+
707
+ print(f"Collaborative discussion completed: {result}")
708
+ ```
709
+
710
+ **Example 5: Auto Swarm Selection**
711
+
712
+ ```python
713
+ from utils.router import SwarmRouter, SwarmRouterConfig
714
+
715
+ # Let router automatically select best swarm type
716
+ config = SwarmRouterConfig(
717
+ name="auto-router",
718
+ description="Automatic swarm selection",
719
+ swarm_type="auto", # Automatic selection
720
+ task="Complex task requiring intelligent routing"
721
+ )
722
+
723
+ router = SwarmRouter(config=config)
724
+ result = router.run()
725
+
726
+ print(f"Auto-selected swarm type: {router.selected_swarm_type}")
727
+ print(f"Result: {result}")
728
+ ```
729
+
730
+ #### HHCS (`utils/HHCS.py`)
731
+
732
+ Hybrid Hierarchical-Cluster Swarm implementation for intelligent task routing with hierarchical decision-making.
733
+
734
+ **Example 6: Basic HHCS Setup**
735
+
736
+ ```python
737
+ from utils.HHCS import HybridHierarchicalClusterSwarm
738
+ from swarms.structs.agent import Agent
739
+
740
+ # Create agents for different roles
741
+ analyst = Agent(agent_name="analyst", model_name="gpt-4o-mini")
742
+ researcher = Agent(agent_name="researcher", model_name="gpt-4o-mini")
743
+ writer = Agent(agent_name="writer", model_name="gpt-4o-mini")
744
+
745
+ # Create HHCS with agents
746
+ hhcs = HybridHierarchicalClusterSwarm(
747
+ agents=[analyst, researcher, writer],
748
+ task="Research and write a comprehensive report on causal inference"
749
+ )
750
+
751
+ # Run HHCS
752
+ result = hhcs.run()
753
+
754
+ print(f"HHCS completed: {result}")
755
+ ```
756
+
757
+ **Example 7: HHCS with Custom Router**
758
+
759
+ ```python
760
+ from utils.HHCS import HybridHierarchicalClusterSwarm
761
+ from swarms.structs.agent import Agent
762
+
763
+ # Create specialized agents
764
+ agents = [
765
+ Agent(agent_name="data_analyst", model_name="gpt-4o-mini"),
766
+ Agent(agent_name="domain_expert", model_name="gpt-4o-mini"),
767
+ Agent(agent_name="technical_writer", model_name="gpt-4o-mini")
768
+ ]
769
+
770
+ # Create HHCS with custom routing
771
+ hhcs = HybridHierarchicalClusterSwarm(
772
+ agents=agents,
773
+ task="Analyze market trends and create investment strategy"
774
+ )
775
+
776
+ result = hhcs.run()
777
+ print(f"Task routed to: {hhcs.selected_agent}")
778
+ print(f"Result: {result}")
779
+ ```
780
+
781
+ #### AOP (`utils/aop.py`)
782
+
783
+ Agent Orchestration Platform with task queue and MCP server deployment for multi-agent coordination.
784
+
785
+ **Example 8: Task Queue Management**
786
+
787
+ ```python
788
+ from utils.aop import TaskQueue, Task
789
+ from swarms.structs.agent import Agent
790
+
791
+ # Create agent
792
+ agent = Agent(agent_name="worker", model_name="gpt-4o-mini")
793
+
794
+ # Create task queue
795
+ queue = TaskQueue(
796
+ agent_name="worker",
797
+ agent=agent,
798
+ max_workers=3, # 3 parallel workers
799
+ max_queue_size=100
800
+ )
801
+
802
+ # Start workers
803
+ queue.start_workers()
804
+
805
+ # Add tasks
806
+ task1 = Task(task="Analyze dataset A", priority=10)
807
+ task2 = Task(task="Analyze dataset B", priority=5)
808
+ task3 = Task(task="Generate report", priority=8)
809
+
810
+ queue.add_task(task1)
811
+ queue.add_task(task2)
812
+ queue.add_task(task3)
813
+
814
+ # Get task status
815
+ task = queue.get_task(task1.task_id)
816
+ print(f"Task status: {task.status}")
817
+
818
+ # Get queue statistics
819
+ stats = queue.get_stats()
820
+ print(f"Total tasks: {stats.total_tasks}")
821
+ print(f"Completed: {stats.completed_tasks}")
822
+ print(f"Pending: {stats.pending_tasks}")
823
+
824
+ # Stop workers when done
825
+ queue.stop_workers()
826
+ ```
827
+
828
+ **Example 9: MCP Server Deployment**
829
+
830
+ ```python
831
+ from utils.aop import AOP, AgentToolConfig
832
+ from swarms.structs.agent import Agent
833
+
834
+ # Create agents
835
+ agent1 = Agent(agent_name="analyst", model_name="gpt-4o-mini")
836
+ agent2 = Agent(agent_name="researcher", model_name="gpt-4o-mini")
837
+
838
+ # Configure agent tools
839
+ configs = [
840
+ AgentToolConfig(
841
+ agent=agent1,
842
+ tool_name="analyze_data",
843
+ description="Analyze datasets and extract insights"
844
+ ),
845
+ AgentToolConfig(
846
+ agent=agent2,
847
+ tool_name="research_topic",
848
+ description="Research topics and gather information"
849
+ )
850
+ ]
851
+
852
+ # Create AOP and deploy as MCP server
853
+ aop = AOP(agent_configs=configs)
854
+
855
+ # Start MCP server
856
+ aop.start_mcp_server(port=8000)
857
+
858
+ print("MCP server started on port 8000")
859
+ print(f"Available tools: {aop.get_available_tools()}")
860
+ ```
861
+
862
+ **Example 10: AOP with Task Queue and MCP**
863
+
864
+ ```python
865
+ from utils.aop import AOP, TaskQueue, AgentToolConfig
866
+ from swarms.structs.agent import Agent
867
+
868
+ # Create agents
869
+ agents = [
870
+ Agent(agent_name="worker1", model_name="gpt-4o-mini"),
871
+ Agent(agent_name="worker2", model_name="gpt-4o-mini")
872
+ ]
873
+
874
+ # Configure AOP
875
+ configs = [
876
+ AgentToolConfig(agent=agents[0], tool_name="process_task"),
877
+ AgentToolConfig(agent=agents[1], tool_name="analyze_data")
878
+ ]
879
+
880
+ aop = AOP(agent_configs=configs)
881
+
882
+ # Deploy as MCP server
883
+ aop.start_mcp_server(port=8000)
884
+
885
+ # Create task queues for each agent
886
+ for agent in agents:
887
+ queue = TaskQueue(agent_name=agent.agent_name, agent=agent, max_workers=2)
888
+ queue.start_workers()
889
+
890
+ # Add tasks
891
+ queue.add_task(Task(task=f"Task for {agent.agent_name}", priority=5))
892
+ ```
893
+
894
+ #### Ledger (`utils/ledger.py`)
895
+
896
+ Event-sourced append-only SQLite ledger for audit trail. See Policy Engine examples above for detailed usage.
897
+
898
+ **Example 11: Ledger Event Recording**
899
+
900
+ ```python
901
+ from utils.ledger import Ledger
902
+ from schemas.policy import ObservationEvent, DecisionEvent
903
+
904
+ ledger = Ledger(db_path="audit_ledger.db")
905
+
906
+ # Record observation
907
+ obs = ObservationEvent(epoch=1, metrics={"cpu": 75.0, "memory": 60.0})
908
+ event_id = ledger.append(obs)
909
+
910
+ # Record decision
911
+ dec = DecisionEvent(
912
+ epoch=1,
913
+ interventions=[{"lever_id": "throttle", "params": {"value": 5}}],
914
+ rationale="CPU high, throttling",
915
+ decision_hash="abc123"
916
+ )
917
+ event_id = ledger.append(dec)
918
+
919
+ # Query events
920
+ events = ledger.get_events_by_epoch(epoch=1)
921
+ print(f"Found {len(events)} events in epoch 1")
922
+ ```
923
+
924
+ #### Rollback (`utils/rollback.py`)
925
+
926
+ Rollback system for intervention recovery. See Policy Engine examples above for detailed usage.
927
+
928
+ **Example 12: Checkpoint and Rollback**
929
+
930
+ ```python
931
+ from utils.rollback import RollbackManager
932
+
933
+ rollback = RollbackManager(db_path="rollback.db")
934
+
935
+ # Create checkpoint
936
+ checkpoint_id = rollback.create_checkpoint(epoch=1, state={"value": 100})
937
+
938
+ # Execute intervention
939
+ # ... intervention code ...
940
+
941
+ # Rollback if needed
942
+ rollback.rollback_n_steps(epoch=1, n_steps=1)
943
+ restored = rollback.restore_checkpoint(checkpoint_id)
944
+ ```
945
+
946
+ #### Canonical (`utils/canonical.py`)
947
+
948
+ Canonicalization utilities for deterministic hashing. See Policy Engine examples above for detailed usage.
949
+
950
+ **Example 13: Stable Hashing**
951
+
952
+ ```python
953
+ from utils.canonical import stable_hash
954
+
955
+ obj = {"a": 1, "b": 2, "c": 3}
956
+ hash_value = stable_hash(obj)
957
+ print(f"Stable hash: {hash_value}")
958
+ ```
959
+
960
+ #### AnyToStr (`utils/AnyToStr.py`)
961
+
962
+ Type conversion utilities for converting various types to strings.
963
+
964
+ **Example 14: Type Conversion**
965
+
966
+ ```python
967
+ from utils.AnyToStr import any_to_str
968
+
969
+ # Convert various types to string
970
+ result1 = any_to_str(123)
971
+ result2 = any_to_str([1, 2, 3])
972
+ result3 = any_to_str({"key": "value"})
973
+
974
+ print(f"Int to string: {result1}")
975
+ print(f"List to string: {result2}")
976
+ print(f"Dict to string: {result3}")
977
+ ```
978
+
979
+ #### Out Types (`utils/out_types.py`)
980
+
981
+ Output type definitions for history and conversation formatting.
982
+
983
+ **Example 15: Output Type Usage**
984
+
985
+ ```python
986
+ from utils.out_types import OutputType, HistoryOutputType
987
+
988
+ # Define output format
989
+ output_format: OutputType = "json" # or "dict", "string", "yaml", etc.
990
+
991
+ # Use in conversation formatting
992
+ from utils.conversation import Conversation
993
+
994
+ conv = Conversation()
995
+ history = conv.get_history(output_type=output_format)
996
+ ```
997
+
998
+ ### Tools Module
999
+
1000
+ #### MCP Client Utils (`tools/mcpClientUtils.py`)
1001
+
1002
+ Model Context Protocol (MCP) integration for connecting to MCP servers and executing tools:
1003
+
1004
+ - **Connection Management**: Establish and manage MCP server connections
1005
+ - **Tool Execution**: Execute tools via MCP protocol
1006
+ - **Protocol Handling**: Transform MCP tools to OpenAI-compatible format
1007
+ - **Error Handling**: Comprehensive error handling for MCP operations
1008
+
1009
+ **Example 1: Basic MCP Connection**
1010
+
1011
+ ```python
1012
+ from tools.mcpClientUtils import connect_to_mcp_server, execute_mcp_tool
1013
+
1014
+ # Connection configuration
1015
+ connection_config = {
1016
+ "server_url": "http://localhost:8000",
1017
+ "api_key": "your_api_key"
1018
+ }
1019
+
1020
+ # Connect to MCP server
1021
+ session = await connect_to_mcp_server(connection_config)
1022
+
1023
+ # Execute tool
1024
+ result = await execute_mcp_tool(
1025
+ session=session,
1026
+ tool_name="analyze_data",
1027
+ parameters={"dataset": "sales_data.csv"}
1028
+ )
1029
+
1030
+ print(f"Tool execution result: {result}")
1031
+ ```
1032
+
1033
+ **Example 2: Transform MCP Tools to OpenAI Format**
1034
+
1035
+ ```python
1036
+ from tools.mcpClientUtils import transform_mcp_tool_to_openai_tool
1037
+
1038
+ # MCP tool schema
1039
+ mcp_tool = {
1040
+ "name": "process_file",
1041
+ "description": "Process a file",
1042
+ "parameters": {
1043
+ "type": "object",
1044
+ "properties": {
1045
+ "file_path": {"type": "string"},
1046
+ "operation": {"type": "string"}
1047
+ }
1048
+ }
1049
+ }
1050
+
1051
+ # Transform to OpenAI format
1052
+ openai_tool = transform_mcp_tool_to_openai_tool(mcp_tool)
1053
+
1054
+ print(f"OpenAI tool format: {openai_tool}")
1055
+ ```
1056
+
1057
+ **Example 3: Error Handling in MCP Operations**
1058
+
1059
+ ```python
1060
+ from tools.mcpClientUtils import connect_to_mcp_server, execute_mcp_tool
1061
+ from loguru import logger
1062
+
1063
+ try:
1064
+ session = await connect_to_mcp_server(connection_config)
1065
+ result = await execute_mcp_tool(session, "tool_name", {})
1066
+ except ConnectionError as e:
1067
+ logger.error(f"MCP connection failed: {e}")
1068
+ except Exception as e:
1069
+ logger.error(f"Tool execution failed: {e}")
1070
+ ```
1071
+
1072
+ #### Actuators (`tools/actuators.py`)
1073
+
1074
+ Actuator interfaces for executing interventions on system controls, cloud resources, and services. See Policy Engine examples above for detailed usage.
1075
+
1076
+ **Example 4: System Control Actuator**
1077
+
1078
+ ```python
1079
+ from tools.actuators import SystemControlActuator
1080
+ from schemas.policy import InterventionSpec
1081
+
1082
+ actuator = SystemControlActuator(require_root=False)
1083
+
1084
+ # CPU throttling intervention
1085
+ intervention = InterventionSpec(
1086
+ lever_id="cpu_throttle",
1087
+ parameters={"nice_value": 10, "pid": 12345}
1088
+ )
1089
+
1090
+ result = actuator.execute([intervention])
1091
+ print(f"Intervention result: {result}")
1092
+ ```
1093
+
1094
+ **Example 5: Custom Actuator Implementation**
1095
+
1096
+ ```python
1097
+ from tools.actuators import BaseActuator
1098
+ from schemas.policy import InterventionSpec
1099
+ from typing import List, Dict, Any
1100
+
1101
+ class CloudResourceActuator(BaseActuator):
1102
+ """Actuator for cloud resource management."""
1103
+
1104
+ def execute(self, interventions: List[InterventionSpec]) -> Dict[str, Any]:
1105
+ """Execute cloud resource interventions."""
1106
+ results = []
1107
+
1108
+ for intervention in interventions:
1109
+ if intervention.lever_id == "scale_instance":
1110
+ instance_id = intervention.parameters["instance_id"]
1111
+ instance_type = intervention.parameters["instance_type"]
1112
+
1113
+ # Scale cloud instance (pseudo-code)
1114
+ result = self._scale_instance(instance_id, instance_type)
1115
+ results.append({"intervention": intervention.model_dump(), "result": result})
1116
+
1117
+ return {"executed": len(results), "results": results}
1118
+
1119
+ def _scale_instance(self, instance_id: str, instance_type: str) -> Dict[str, Any]:
1120
+ """Scale cloud instance."""
1121
+ # Implementation would call cloud API
1122
+ return {"status": "success", "instance_id": instance_id, "type": instance_type}
1123
+
1124
+ # Use custom actuator
1125
+ actuator = CloudResourceActuator()
1126
+ intervention = InterventionSpec(
1127
+ lever_id="scale_instance",
1128
+ parameters={"instance_id": "i-12345", "instance_type": "t3.large"}
1129
+ )
1130
+ result = actuator.execute([intervention])
1131
+ ```
1132
+
1133
+ #### Sensors (`tools/sensors.py`)
1134
+
1135
+ Sensor interfaces for reading system metrics, cloud resources, and custom metrics. See Policy Engine examples above for detailed usage.
1136
+
1137
+ **Example 6: System Metrics Sensor**
1138
+
1139
+ ```python
1140
+ from tools.sensors import SystemMetricsSensor
1141
+
1142
+ sensor = SystemMetricsSensor()
1143
+ snapshot = sensor.read()
1144
+
1145
+ print(f"CPU: {snapshot['cpu_percent']:.1f}%")
1146
+ print(f"Memory: {snapshot['memory_percent']:.1f}%")
1147
+ ```
1148
+
1149
+ **Example 7: Custom Sensor with Registry**
1150
+
1151
+ ```python
1152
+ from tools.sensors import BaseSensor, SensorRegistry
1153
+ from typing import Dict
1154
+
1155
+ class ApplicationMetricsSensor(BaseSensor):
1156
+ """Sensor for application-specific metrics."""
1157
+
1158
+ def read(self) -> Dict[str, float]:
1159
+ """Read application metrics."""
1160
+ # Read from application monitoring endpoint
1161
+ return {
1162
+ "request_rate": 150.0,
1163
+ "error_rate": 2.5,
1164
+ "response_time": 95.0
1165
+ }
1166
+
1167
+ # Register sensor
1168
+ registry = SensorRegistry()
1169
+ registry.register("app_metrics", ApplicationMetricsSensor())
1170
+
1171
+ # Use registered sensor
1172
+ sensor = registry.get_sensor("app_metrics")
1173
+ snapshot = sensor.read()
1174
+ ```
1175
+
1176
+ #### Code Generator (`tools/code_generator.py`)
1177
+
1178
+ Code generation tools with LLM and ML integration for generating, analyzing, and optimizing code.
1179
+
1180
+ **Example 8: Basic Code Generation**
1181
+
1182
+ ```python
1183
+ from tools.code_generator import LLMCodeGenerator
1184
+ from swarms.structs.agent import Agent
1185
+
1186
+ # Create agent for code generation
1187
+ agent = Agent(agent_name="code_gen", model_name="gpt-4o-mini")
1188
+
1189
+ # Initialize code generator
1190
+ generator = LLMCodeGenerator(agent=agent)
1191
+
1192
+ # Generate code from specification
1193
+ specification = "Create a Python function that calculates factorial recursively"
1194
+ code = generator.generate(
1195
+ specification=specification,
1196
+ language="python"
1197
+ )
1198
+
1199
+ print(f"Generated code:\n{code}")
1200
+
1201
+ # Validate generated code
1202
+ validation = generator.validate(code, language="python")
1203
+ print(f"Validation result: {validation}")
1204
+ ```
1205
+
1206
+ **Example 9: Language-Specific Code Generation**
1207
+
1208
+ ```python
1209
+ from tools.code_generator import LLMCodeGenerator
1210
+
1211
+ generator = LLMCodeGenerator(agent=agent)
1212
+
1213
+ # Generate JavaScript code
1214
+ js_code = generator.generate(
1215
+ specification="Create a React component for a todo list",
1216
+ language="javascript"
1217
+ )
1218
+
1219
+ # Generate Python code
1220
+ python_code = generator.generate(
1221
+ specification="Create a data processing pipeline",
1222
+ language="python"
1223
+ )
1224
+
1225
+ # Generate TypeScript code
1226
+ ts_code = generator.generate(
1227
+ specification="Create a type-safe API client",
1228
+ language="typescript"
1229
+ )
1230
+ ```
1231
+
1232
+ **Example 10: Code Optimization with ML**
1233
+
1234
+ ```python
1235
+ from tools.code_generator import MLCodeOptimizer
1236
+
1237
+ # Initialize ML-based optimizer
1238
+ optimizer = MLCodeOptimizer()
1239
+
1240
+ # Optimize code
1241
+ original_code = """
1242
+ def factorial(n):
1243
+ if n <= 1:
1244
+ return 1
1245
+ return n * factorial(n - 1)
1246
+ """
1247
+
1248
+ optimized_code = optimizer.optimize(
1249
+ code=original_code,
1250
+ language="python",
1251
+ optimization_target="performance"
1252
+ )
1253
+
1254
+ print(f"Optimized code:\n{optimized_code}")
1255
+ ```
1256
+
1257
+ #### Mandate Generator (`tools/mandate_generator.py`)
1258
+
1259
+ Convert CorporateProposal to bolt.diy execution mandate for autonomous code generation.
1260
+
1261
+ **Example 11: Proposal to Mandate Conversion**
1262
+
1263
+ ```python
1264
+ from tools.mandate_generator import proposal_to_mandate
1265
+ from crca_cg.corposwarm import CorporateProposal, ProposalType
1266
+
1267
+ # Create corporate proposal
1268
+ proposal = CorporateProposal(
1269
+ proposal_id="prop-001",
1270
+ title="Implement new feature",
1271
+ description="Add user authentication system",
1272
+ proposal_type=ProposalType.TECHNICAL,
1273
+ budget_impact=50000.0,
1274
+ risk_level=0.3
1275
+ )
1276
+
1277
+ # Convert to execution mandate
1278
+ mandate = proposal_to_mandate(
1279
+ proposal=proposal,
1280
+ mandate_id="mandate-001"
1281
+ )
1282
+
1283
+ print(f"Mandate ID: {mandate['mandate_id']}")
1284
+ print(f"Objectives: {mandate['objectives']}")
1285
+ print(f"Budget: {mandate['budget']}")
1286
+ print(f"Constraints: {mandate['constraints']}")
1287
+ ```
1288
+
1289
+ **Example 12: Complete Workflow with Mandate Generation**
1290
+
1291
+ ```python
1292
+ from tools.mandate_generator import proposal_to_mandate
1293
+ from crca_cg.corposwarm import CorporateSwarm, CorporateProposal
1294
+
1295
+ # Create corporate swarm
1296
+ swarm = CorporateSwarm()
1297
+
1298
+ # Create and submit proposal
1299
+ proposal = swarm.create_proposal(
1300
+ title="Build API gateway",
1301
+ description="Implement microservices API gateway",
1302
+ proposal_type=ProposalType.TECHNICAL
1303
+ )
1304
+
1305
+ # Vote on proposal
1306
+ vote_result = swarm.board.vote_on_proposal(proposal)
1307
+
1308
+ if vote_result.passed:
1309
+ # Convert approved proposal to mandate
1310
+ mandate = proposal_to_mandate(
1311
+ proposal=proposal,
1312
+ corporate_swarm=swarm
1313
+ )
1314
+
1315
+ # Execute mandate (would integrate with bolt.diy)
1316
+ print(f"Mandate created: {mandate['mandate_id']}")
1317
+ print(f"Ready for execution")
1318
+ ```
1319
+
1320
+ #### File Operations (`tools/file_operations.py`)
1321
+
1322
+ File manipulation tools with LLM integration for intelligent file operations.
1323
+
1324
+ **Example 13: Basic File Operations**
1325
+
1326
+ ```python
1327
+ from tools.file_operations import FileWriter, FileReader
1328
+
1329
+ # Write file
1330
+ writer = FileWriter()
1331
+ result = writer.execute(
1332
+ operation="write",
1333
+ file_path="output.txt",
1334
+ content="Hello, World!"
1335
+ )
1336
+
1337
+ # Read file
1338
+ reader = FileReader()
1339
+ result = reader.execute(
1340
+ operation="read",
1341
+ file_path="output.txt"
1342
+ )
1343
+
1344
+ print(f"File content: {result['content']}")
1345
+ ```
1346
+
1347
+ **Example 14: LLM-Powered File Operations**
1348
+
1349
+ ```python
1350
+ from tools.file_operations import LLMFileOperator
1351
+ from swarms.structs.agent import Agent
1352
+
1353
+ agent = Agent(agent_name="file_ops", model_name="gpt-4o-mini")
1354
+ operator = LLMFileOperator(agent=agent)
1355
+
1356
+ # Generate file content using LLM
1357
+ result = operator.generate_file(
1358
+ specification="Create a Python class for handling user authentication",
1359
+ file_path="auth.py",
1360
+ language="python"
1361
+ )
1362
+
1363
+ print(f"Generated file: {result['file_path']}")
1364
+ print(f"Content length: {len(result['content'])} characters")
1365
+ ```
1366
+
1367
+ **Example 15: File Analysis and Optimization**
1368
+
1369
+ ```python
1370
+ from tools.file_operations import FileAnalyzer
1371
+
1372
+ analyzer = FileAnalyzer()
1373
+
1374
+ # Analyze file
1375
+ analysis = analyzer.analyze_file(
1376
+ file_path="code.py",
1377
+ analysis_type="complexity" # or "performance", "security", etc.
1378
+ )
1379
+
1380
+ print(f"Complexity score: {analysis['complexity_score']}")
1381
+ print(f"Issues found: {analysis['issues']}")
1382
+ print(f"Suggestions: {analysis['suggestions']}")
1383
+ ```
1384
+
1385
+ ### Templates Module
1386
+
1387
+ The templates module provides a framework for creating specialized agents with drag-and-drop feature composition.
1388
+
1389
+ #### Base Specialized Agent (`templates/base_specialized_agent.py`)
1390
+
1391
+ Base class for creating domain-specific agents with common initialization patterns and memory management.
1392
+
1393
+ #### Feature Mixins (`templates/feature_mixins.py`)
1394
+
1395
+ Modular feature components that can be mixed into agent classes:
1396
+
1397
+ - **GraphFeatureMixin**: Graph operations (nodes, edges, topological sort)
1398
+ - **PredictionFeatureMixin**: Prediction methods and standardization
1399
+ - **StatisticsFeatureMixin**: Statistical analysis and data fitting
1400
+ - **LLMFeatureMixin**: LLM integration patterns
1401
+ - **FullFeatureMixin**: All features combined
1402
+
1403
+ **Usage:**
1404
+
1405
+ ```python
1406
+ from templates.base_specialized_agent import BaseSpecializedAgent
1407
+ from templates.feature_mixins import GraphFeatureMixin, PredictionFeatureMixin
1408
+
1409
+ class MyAgent(BaseSpecializedAgent, GraphFeatureMixin, PredictionFeatureMixin):
1410
+ def __init__(self, **kwargs):
1411
+ super().__init__(**kwargs)
1412
+ self.init_graph_feature(variables=["A", "B", "C"])
1413
+ self.init_prediction_feature(use_nonlinear=True)
1414
+ ```
1415
+
1416
+ #### Module Registry (`templates/module_registry.py`)
1417
+
1418
+ Feature composition system allowing dynamic agent creation:
1419
+
1420
+ ```python
1421
+ from templates.module_registry import compose_agent
1422
+
1423
+ agent = compose_agent(
1424
+ features=["graph", "prediction", "statistics"],
1425
+ variables=["x", "y", "z"]
1426
+ )
1427
+ ```
1428
+
1429
+ #### Graph Management (`templates/graph_management.py`)
1430
+
1431
+ Graph operations including path finding, cycle detection, and topological sorting.
1432
+
1433
+ **Example 1: Graph Operations**
1434
+
1435
+ ```python
1436
+ from templates.graph_management import GraphManager
1437
+
1438
+ # Create graph manager
1439
+ graph = GraphManager()
1440
+ graph.add_node("A")
1441
+ graph.add_node("B")
1442
+ graph.add_node("C")
1443
+ graph.add_edge("A", "B")
1444
+ graph.add_edge("B", "C")
1445
+
1446
+ # Topological sort
1447
+ topo_order = graph.topological_sort()
1448
+ print(f"Topological order: {topo_order}")
1449
+
1450
+ # Find paths
1451
+ paths = graph.find_paths("A", "C")
1452
+ print(f"Paths from A to C: {paths}")
1453
+
1454
+ # Check for cycles
1455
+ has_cycle = graph.has_cycle()
1456
+ print(f"Has cycle: {has_cycle}")
1457
+ ```
1458
+
1459
+ #### Prediction Framework (`templates/prediction_framework.py`)
1460
+
1461
+ Prediction methods, standardization, and counterfactual generation patterns.
1462
+
1463
+ **Example 2: Prediction with Standardization**
1464
+
1465
+ ```python
1466
+ from templates.prediction_framework import PredictionMixin
1467
+
1468
+ class MyAgent(PredictionMixin):
1469
+ def __init__(self):
1470
+ self.init_prediction_feature(use_nonlinear=True)
1471
+
1472
+ agent = MyAgent()
1473
+
1474
+ # Standardize state
1475
+ state = {"x": 100.0, "y": 200.0}
1476
+ standardized = agent.standardize_state(state)
1477
+
1478
+ # Predict outcome
1479
+ prediction = agent.predict_outcome(
1480
+ state=state,
1481
+ intervention={"x": 110.0}
1482
+ )
1483
+
1484
+ print(f"Predicted outcome: {prediction}")
1485
+ ```
1486
+
1487
+ #### Statistical Methods (`templates/statistical_methods.py`)
1488
+
1489
+ Statistical analysis including data fitting, uncertainty quantification, and time-series methods.
1490
+
1491
+ **Example 3: Statistical Analysis**
1492
+
1493
+ ```python
1494
+ from templates.statistical_methods import StatisticsMixin
1495
+ import numpy as np
1496
+
1497
+ class StatsAgent(StatisticsMixin):
1498
+ def __init__(self):
1499
+ self.init_statistics_feature()
1500
+
1501
+ agent = StatsAgent()
1502
+
1503
+ # Fit data to model
1504
+ data = np.array([[1, 2], [2, 4], [3, 6], [4, 8]])
1505
+ fitted_model = agent.fit_data(data, model_type="linear")
1506
+
1507
+ # Quantify uncertainty
1508
+ uncertainty = agent.quantify_uncertainty(data, fitted_model)
1509
+ print(f"Uncertainty: {uncertainty}")
1510
+ ```
1511
+
1512
+ #### LLM Integration (`templates/llm_integration.py`)
1513
+
1514
+ LLM integration patterns for schema definition, prompt building, and multi-loop reasoning.
1515
+
1516
+ **Example 4: LLM Integration**
1517
+
1518
+ ```python
1519
+ from templates.llm_integration import LLMFeatureMixin
1520
+
1521
+ class LLMAgent(LLMFeatureMixin):
1522
+ def __init__(self):
1523
+ self.init_llm_feature(model_name="gpt-4o-mini")
1524
+
1525
+ agent = LLMAgent()
1526
+
1527
+ # Build prompt
1528
+ prompt = agent.build_prompt(
1529
+ task="Analyze causal relationships",
1530
+ context={"variables": ["A", "B", "C"]}
1531
+ )
1532
+
1533
+ # Execute with multi-loop reasoning
1534
+ result = agent.execute_with_loops(
1535
+ prompt=prompt,
1536
+ max_loops=3
1537
+ )
1538
+ ```
1539
+
1540
+ #### Policy Loop Integration (`templates/policy_loop.py`)
1541
+
1542
+ Policy loop mixin for temporal policy execution. See Policy Engine examples above for detailed usage.
1543
+
1544
+ **Example 5: Policy Loop with Agent**
1545
+
1546
+ ```python
1547
+ from templates.policy_loop import PolicyLoopMixin
1548
+ from schemas.policy import DoctrineV1
1549
+ from utils.ledger import Ledger
1550
+
1551
+ class PolicyAgent(PolicyLoopMixin):
1552
+ def __init__(self, doctrine, ledger):
1553
+ super().__init__(doctrine, ledger, seed=42)
1554
+
1555
+ doctrine = DoctrineV1.from_json("doctrine.json")
1556
+ ledger = Ledger(db_path="ledger.db")
1557
+
1558
+ agent = PolicyAgent(doctrine, ledger)
1559
+ result = agent.run_epoch(epoch=1)
1560
+ ```
1561
+
1562
+ #### Drift Detection Integration (`templates/drift_detection.py`)
1563
+
1564
+ Drift detection for change-point detection. See Policy Engine examples above for detailed usage.
1565
+
1566
+ **Example 6: Drift Detection in Policy Loop**
1567
+
1568
+ ```python
1569
+ from templates.drift_detection import DriftDetector
1570
+ from templates.policy_loop import PolicyLoopMixin
1571
+
1572
+ class DriftAwarePolicyAgent(PolicyLoopMixin):
1573
+ def __init__(self, doctrine, ledger):
1574
+ super().__init__(doctrine, ledger)
1575
+ self.drift_detector = DriftDetector(algorithm="pelt")
1576
+
1577
+ def check_drift(self, metric_name: str, history: List[float]):
1578
+ """Check for drift in metric."""
1579
+ change_points, confidence = self.drift_detector.detect_changepoints(
1580
+ metric_name=metric_name,
1581
+ metric_history=history
1582
+ )
1583
+ return len(change_points) > 0
1584
+
1585
+ agent = DriftAwarePolicyAgent(doctrine, ledger)
1586
+
1587
+ # Check for drift
1588
+ has_drift = agent.check_drift("cpu_usage", [50, 55, 60, 65, 70, 75])
1589
+ if has_drift:
1590
+ print("WARNING: Drift detected!")
1591
+ ```
1592
+
1593
+ #### MPC Planner Integration (`templates/mpc_planner.py`)
1594
+
1595
+ MPC planner for multi-step optimization. See Policy Engine examples above for detailed usage.
1596
+
1597
+ **Example 7: MPC Planning in Policy Loop**
1598
+
1599
+ ```python
1600
+ from templates.mpc_planner import MPCPlanner
1601
+ from templates.policy_loop import PolicyLoopMixin
1602
+
1603
+ class MPCPolicyAgent(PolicyLoopMixin):
1604
+ def __init__(self, doctrine, ledger):
1605
+ super().__init__(doctrine, ledger)
1606
+ self.mpc_planner = MPCPlanner(doctrine, horizon=5)
1607
+ self.use_mpc = True
1608
+
1609
+ def plan_actions(self, epoch: int, state: Dict[str, float]):
1610
+ """Plan actions using MPC."""
1611
+ if self.use_mpc:
1612
+ interventions, score, rationale = self.mpc_planner.solve_mpc(...)
1613
+ return interventions
1614
+ else:
1615
+ return super().plan_actions(epoch, state)
1616
+
1617
+ agent = MPCPolicyAgent(doctrine, ledger)
1618
+ ```
1619
+
1620
+ #### Template Examples (`templates/examples/`)
1621
+
1622
+ Four example templates demonstrating different agent creation patterns.
1623
+
1624
+ **Example 8: Causal Agent Template**
1625
+
1626
+ ```python
1627
+ from templates.examples.causal_agent_template import create_causal_agent
1628
+
1629
+ # Create causal agent from template
1630
+ agent = create_causal_agent(
1631
+ variables=["price", "demand", "supply"],
1632
+ model_name="gpt-4o-mini"
1633
+ )
1634
+
1635
+ # Use agent
1636
+ result = agent.run("Analyze price-demand relationship")
1637
+ ```
1638
+
1639
+ **Example 9: Drag-Drop Feature Composition**
1640
+
1641
+ ```python
1642
+ from templates.examples.drag_drop_example import compose_agent_features
1643
+
1644
+ # Compose agent with selected features
1645
+ agent = compose_agent_features(
1646
+ features=["graph", "prediction", "statistics"],
1647
+ variables=["x", "y", "z"]
1648
+ )
1649
+
1650
+ # Agent now has graph, prediction, and statistics capabilities
1651
+ result = agent.analyze_with_features(data)
1652
+ ```
1653
+
1654
+ **Example 10: Logistics Agent Template**
1655
+
1656
+ ```python
1657
+ from templates.examples.logistics_agent_template import create_logistics_agent
1658
+
1659
+ # Create logistics-specific agent
1660
+ agent = create_logistics_agent(
1661
+ model_name="gpt-4o-mini",
1662
+ logistics_domain="supply_chain"
1663
+ )
1664
+
1665
+ # Use for logistics tasks
1666
+ result = agent.run("Optimize warehouse inventory levels")
1667
+ ```
1668
+
1669
+ **Example 11: Trading Agent Template**
1670
+
1671
+ ```python
1672
+ from templates.examples.trading_agent_template import create_trading_agent
1673
+
1674
+ # Create trading agent
1675
+ agent = create_trading_agent(
1676
+ model_name="gpt-4o-mini",
1677
+ trading_strategy="momentum"
1678
+ )
1679
+
1680
+ # Use for trading analysis
1681
+ result = agent.run("Analyze market signals for BTC")
1682
+ ```
1683
+
1684
+ **Example 12: Custom Agent from Templates**
1685
+
1686
+ ```python
1687
+ from templates.base_specialized_agent import BaseSpecializedAgent
1688
+ from templates.feature_mixins import (
1689
+ GraphFeatureMixin,
1690
+ PredictionFeatureMixin,
1691
+ StatisticsFeatureMixin,
1692
+ LLMFeatureMixin
1693
+ )
1694
+
1695
+ class CustomAgent(
1696
+ BaseSpecializedAgent,
1697
+ GraphFeatureMixin,
1698
+ PredictionFeatureMixin,
1699
+ StatisticsFeatureMixin,
1700
+ LLMFeatureMixin
1701
+ ):
1702
+ def __init__(self, **kwargs):
1703
+ super().__init__(**kwargs)
1704
+ # Initialize all features
1705
+ self.init_graph_feature(variables=["A", "B", "C"])
1706
+ self.init_prediction_feature(use_nonlinear=True)
1707
+ self.init_statistics_feature()
1708
+ self.init_llm_feature(model_name="gpt-4o-mini")
1709
+
1710
+ def _get_domain_schema(self):
1711
+ """Define domain-specific tools."""
1712
+ return {
1713
+ "type": "function",
1714
+ "function": {
1715
+ "name": "custom_domain_tool",
1716
+ "description": "Custom domain tool",
1717
+ "parameters": {
1718
+ "type": "object",
1719
+ "properties": {
1720
+ "param1": {"type": "string"},
1721
+ "param2": {"type": "number"}
1722
+ }
1723
+ }
1724
+ }
1725
+ }
1726
+
1727
+ # Use custom agent
1728
+ agent = CustomAgent(agent_name="custom_agent")
1729
+ result = agent.run("Custom domain task")
1730
+ ```
1731
+
1732
+ ### Schemas Module
1733
+
1734
+ #### MCP Schemas (`schemas/mcpSchemas.py`)
1735
+
1736
+ Type definitions and schemas for MCP (Model Context Protocol) connections, including connection configurations and tool schemas.
1737
+
1738
+ **Example 1: MCP Connection Schema**
1739
+
1740
+ ```python
1741
+ from schemas.mcpSchemas import MCPConnectionConfig, MCPToolSchema
1742
+
1743
+ # Define MCP connection
1744
+ connection = MCPConnectionConfig(
1745
+ server_url="http://localhost:8000",
1746
+ api_key="your_api_key",
1747
+ timeout=30
1748
+ )
1749
+
1750
+ # Define MCP tool schema
1751
+ tool = MCPToolSchema(
1752
+ name="analyze_data",
1753
+ description="Analyze dataset",
1754
+ parameters={
1755
+ "type": "object",
1756
+ "properties": {
1757
+ "dataset": {"type": "string"},
1758
+ "operation": {"type": "string"}
1759
+ }
1760
+ }
1761
+ )
1762
+ ```
1763
+
1764
+ #### Policy Schemas (`schemas/policy.py`)
1765
+
1766
+ Comprehensive policy schema definitions for the policy engine system.
1767
+
1768
+ **Example 2: Policy Schema Usage**
1769
+
1770
+ ```python
1771
+ from schemas.policy import (
1772
+ DoctrineV1, EpochConfig, MetricSpec, Objective,
1773
+ Invariant, LeverSpec, RiskBudget, CompiledPolicy
1774
+ )
1775
+
1776
+ # Create complete doctrine
1777
+ doctrine = DoctrineV1(
1778
+ epoch=EpochConfig(unit="hours", length=1.0),
1779
+ metrics={
1780
+ "cpu_usage": MetricSpec(extractor_key="cpu_percent", unit="percent")
1781
+ },
1782
+ objectives=[
1783
+ Objective(metric_name="cpu_usage", direction="minimize", weight=1.0)
1784
+ ],
1785
+ invariants=[
1786
+ Invariant(name="cpu_limit", condition="cpu_usage < 90.0")
1787
+ ],
1788
+ levers={
1789
+ "throttle": LeverSpec(lever_type="cpu_throttle", bounds={"nice_value": {"min": 0, "max": 19}})
1790
+ },
1791
+ risk_budget=RiskBudget(max_actions_per_epoch=5)
1792
+ )
1793
+
1794
+ # Compile policy
1795
+ compiled = CompiledPolicy.compile(doctrine)
1796
+ print(f"Policy hash: {compiled.policy_hash}")
1797
+ ```
1798
+
1799
+ **Example 3: Policy Schema Validation**
1800
+
1801
+ ```python
1802
+ from schemas.policy import DoctrineV1, EpochConfig
1803
+ from pydantic import ValidationError
1804
+
1805
+ try:
1806
+ # Invalid doctrine (missing required fields)
1807
+ doctrine = DoctrineV1(
1808
+ epoch=EpochConfig(unit="hours", length=1.0)
1809
+ # Missing metrics, objectives, etc.
1810
+ )
1811
+ except ValidationError as e:
1812
+ print(f"Validation error: {e}")
1813
+ print("Doctrine must include metrics, objectives, invariants, levers, and risk_budget")
1814
+ ```
1815
+
1816
+ **Example 4: Policy Schema Serialization**
1817
+
1818
+ ```python
1819
+ from schemas.policy import DoctrineV1
1820
+
1821
+ # Create doctrine
1822
+ doctrine = DoctrineV1(...)
1823
+
1824
+ # Serialize to JSON
1825
+ doctrine_json = doctrine.model_dump_json(indent=2)
1826
+ print(doctrine_json)
1827
+
1828
+ # Save to file
1829
+ doctrine.to_json("doctrine.json")
1830
+
1831
+ # Load from file
1832
+ loaded_doctrine = DoctrineV1.from_json("doctrine.json")
1833
+ assert loaded_doctrine.version == doctrine.version
1834
+ ```
1835
+
1836
+ ### CRCA-SD Module
1837
+
1838
+ CRCA-SD (Socioeconomic Dynamics & Logistics) provides a constrained, stochastic, multi-objective model-predictive control system for socioeconomic dynamics optimization.
1839
+
1840
+ #### Core Components
1841
+
1842
+ - **StateVector**: System state representation
1843
+ - **ControlVector**: Control inputs
1844
+ - **DynamicsModel**: System dynamics modeling
1845
+ - **ConstraintChecker**: Constraint validation
1846
+ - **ForwardSimulator**: Forward simulation engine
1847
+ - **MPCSolver**: Model Predictive Control solver
1848
+ - **ScenarioGenerator**: Scenario generation with CRCA integration
1849
+
1850
+ #### Governance System
1851
+
1852
+ - **Board**: Governance board structure
1853
+ - **Arbitration**: Dispute resolution
1854
+ - **GovernanceSystem**: Complete governance framework
1855
+
1856
+ #### Real-time Components
1857
+
1858
+ - **DataAcquisition**: Real-time data collection
1859
+ - **DataPipeline**: Data processing pipeline
1860
+ - **RealTimeMonitor**: Real-time monitoring
1861
+ - **PolicyExecutor**: Policy execution engine
1862
+
1863
+ #### CRCA Integration
1864
+
1865
+ CRCA-SD integrates CRCAAgent for causal scenario generation:
1866
+
1867
+ ```python
1868
+ from crca_sd import get_crca_agent
1869
+ from crca_sd.crca_sd_mpc import ScenarioGenerator
1870
+
1871
+ # Get CRCAAgent instance
1872
+ crca = get_crca_agent(variables=['Y', 'U', 'S', 'P', 'L', 'W', 'K', 'I'])
1873
+
1874
+ # Create scenario generator with CRCA
1875
+ gen = ScenarioGenerator(crca_agent=crca)
1876
+
1877
+ # Generate causal scenarios (not just random)
1878
+ scenarios = gen.generate_causal_scenarios(
1879
+ n_scenarios=10,
1880
+ horizon=12,
1881
+ current_state=state_vector,
1882
+ target_variables=['Y', 'U', 'S']
1883
+ )
1884
+ ```
1885
+
1886
+ **Usage Example:**
1887
+
1888
+ ```python
1889
+ from crca_sd import StateVector, ControlVector, DynamicsModel
1890
+ from crca_sd.crca_sd_mpc import MPCSolver
1891
+ from crca_sd import get_crca_agent
1892
+
1893
+ # Initialize CRCA agent for causal reasoning
1894
+ crca = get_crca_agent(
1895
+ variables=['GDP', 'unemployment', 'inflation'],
1896
+ model_name="gpt-4o-mini"
1897
+ )
1898
+
1899
+ # Create MPC solver with CRCA integration
1900
+ solver = MPCSolver(
1901
+ dynamics_model=dynamics_model,
1902
+ crca_agent=crca
1903
+ )
1904
+
1905
+ # Solve with causal scenario generation
1906
+ solution = solver.solve(
1907
+ initial_state=state_vector,
1908
+ horizon=12,
1909
+ use_causal_scenarios=True
1910
+ )
1911
+ ```
1912
+
1913
+ ### CRCA-CG Module
1914
+
1915
+ CRCA-CG (Corporate Governance) provides a multi-agent orchestration system for corporate governance with board oversight, executive leadership, ESG frameworks, and democratic decision-making.
1916
+
1917
+ #### Core Components
1918
+
1919
+ - **CorporateSwarm**: Main multi-agent orchestration system
1920
+ - **ESG Scoring**: Environmental, Social, and Governance metrics
1921
+ - **Risk Assessment**: Comprehensive risk analysis
1922
+ - **Stakeholder Engagement**: Stakeholder interaction management
1923
+ - **Regulatory Compliance**: Compliance monitoring
1924
+
1925
+ #### CRCA Integration
1926
+
1927
+ CorporateSwarm uses CRCAAgent for causal policy analysis:
1928
+
1929
+ ```python
1930
+ from crca_cg.corposwarm import CorporateSwarm
1931
+ from CRCA import CRCAAgent
1932
+
1933
+ # Initialize CRCA agent
1934
+ crca = CRCAAgent(
1935
+ variables=['revenue', 'costs', 'employee_satisfaction', 'market_share'],
1936
+ model_name="gpt-4o"
1937
+ )
1938
+
1939
+ # Create CorporateSwarm with CRCA
1940
+ swarm = CorporateSwarm(
1941
+ crca_agent=crca,
1942
+ enable_crca_q=True, # Enable CRCA-Q integration for Investment Committee
1943
+ enable_crca_sd=True # Enable CRCA-SD integration for enhanced voting
1944
+ )
1945
+
1946
+ # Use causal reasoning in governance decisions
1947
+ result = swarm.analyze_policy_impact(
1948
+ policy_description="Increase R&D spending by 20%",
1949
+ use_causal_analysis=True
1950
+ )
1951
+ ```
1952
+
1953
+ #### CRCA-Q Integration
1954
+
1955
+ CorporateSwarm can integrate CRCA-Q for Investment Committee decisions:
1956
+
1957
+ ```python
1958
+ from crca_cg.corposwarm import CorporateSwarm
1959
+
1960
+ swarm = CorporateSwarm(
1961
+ enable_crca_q=True,
1962
+ crca_q_config={
1963
+ 'account_size': 1000000,
1964
+ 'conservative_mode': True
1965
+ }
1966
+ )
1967
+
1968
+ # Investment Committee uses CRCA-Q for trading decisions
1969
+ investment_decision = swarm.investment_committee.recommend_allocation()
1970
+ ```
1971
+
1972
+ #### CRCA-SD Integration
1973
+
1974
+ Enhanced voting and governance using CRCA-SD:
1975
+
1976
+ ```python
1977
+ swarm = CorporateSwarm(
1978
+ enable_crca_sd=True,
1979
+ crca_sd_config={
1980
+ 'governance_model': 'democratic',
1981
+ 'voting_threshold': 0.6
1982
+ }
1983
+ )
1984
+
1985
+ # Enhanced voting with CRCA-SD governance
1986
+ vote_result = swarm.board.vote_on_proposal(
1987
+ proposal="Approve new product launch",
1988
+ use_enhanced_voting=True
1989
+ )
1990
+ ```
1991
+
1992
+ ---
1993
+
1994
+ ## Policy Engine System
1995
+
1996
+ The Policy Engine System provides a comprehensive temporal policy execution framework with online learning, multi-objective optimization, drift detection, and deterministic decision-making. It enables autonomous policy execution with audit trails, rollback capabilities, and causal scenario generation.
1997
+
1998
+ ### Overview
1999
+
2000
+ The Policy Engine implements a doctrine-based policy system where:
2001
+ - **Doctrine**: Defines the policy specification (metrics, objectives, invariants, levers, risk budget)
2002
+ - **Compiled Policy**: Normalized, compiled version with deterministic selectors
2003
+ - **Ledger**: Event-sourced append-only audit trail
2004
+ - **Policy Loop**: Temporal execution with observe → plan → act → update cycle
2005
+ - **Sensors**: Read system metrics and state
2006
+ - **Actuators**: Execute interventions on system controls
2007
+ - **Rollback**: Recovery system for failed interventions
2008
+ - **MPC Planner**: Model Predictive Control for multi-step optimization
2009
+ - **Drift Detection**: Change-point detection for regime shifts
2010
+
2011
+ ### Core Components
2012
+
2013
+ #### DoctrineV1: Policy Specification
2014
+
2015
+ A doctrine defines the complete policy plan with epochs, metrics, objectives, invariants, levers, and risk budget.
2016
+
2017
+ **Example 1: Basic Doctrine Creation**
2018
+
2019
+ ```python
2020
+ from schemas.policy import (
2021
+ DoctrineV1, EpochConfig, MetricSpec, Objective,
2022
+ Invariant, LeverSpec, RiskBudget
2023
+ )
2024
+
2025
+ # Define epoch configuration (1 hour epochs)
2026
+ epoch = EpochConfig(unit="hours", length=1.0, timezone="UTC")
2027
+
2028
+ # Define metrics to track
2029
+ metrics = {
2030
+ "cpu_usage": MetricSpec(
2031
+ extractor_key="cpu_percent",
2032
+ unit="percent",
2033
+ description="CPU utilization percentage"
2034
+ ),
2035
+ "memory_usage": MetricSpec(
2036
+ extractor_key="memory_percent",
2037
+ unit="percent",
2038
+ description="Memory utilization percentage"
2039
+ ),
2040
+ "request_latency": MetricSpec(
2041
+ extractor_key="latency_ms",
2042
+ unit="milliseconds",
2043
+ description="Request latency in milliseconds"
2044
+ )
2045
+ }
2046
+
2047
+ # Define objectives (multi-objective optimization)
2048
+ objectives = [
2049
+ Objective(
2050
+ metric_name="request_latency",
2051
+ direction="minimize",
2052
+ target_value=100.0, # Target: <100ms
2053
+ deadline_epoch=24, # Within 24 epochs
2054
+ weight=2.0 # Higher priority
2055
+ ),
2056
+ Objective(
2057
+ metric_name="cpu_usage",
2058
+ direction="minimize",
2059
+ target_value=70.0, # Target: <70%
2060
+ weight=1.0
2061
+ )
2062
+ ]
2063
+
2064
+ # Define invariants (hard constraints)
2065
+ invariants = [
2066
+ Invariant(
2067
+ name="memory_safety",
2068
+ condition="memory_usage < 90.0",
2069
+ description="Memory must never exceed 90%"
2070
+ ),
2071
+ Invariant(
2072
+ name="latency_sla",
2073
+ condition="request_latency < 500.0",
2074
+ description="Latency must never exceed 500ms SLA"
2075
+ )
2076
+ ]
2077
+
2078
+ # Define levers (allowed interventions)
2079
+ levers = {
2080
+ "cpu_throttle": LeverSpec(
2081
+ lever_type="cpu_throttle",
2082
+ bounds={"nice_value": {"min": 0, "max": 19}},
2083
+ cost_function="nice_value * 0.1",
2084
+ rollback_required=True,
2085
+ description="CPU throttling via nice values"
2086
+ ),
2087
+ "scale_replicas": LeverSpec(
2088
+ lever_type="scale_replicas",
2089
+ bounds={"replicas": {"min": 1, "max": 10}},
2090
+ cost_function="replicas * 10.0",
2091
+ rollback_required=True,
2092
+ description="Scale service replicas"
2093
+ )
2094
+ }
2095
+
2096
+ # Define risk budget
2097
+ risk_budget = RiskBudget(
2098
+ max_actions_per_epoch=5,
2099
+ max_risk_per_epoch=0.5,
2100
+ rollback_required=True
2101
+ )
2102
+
2103
+ # Create doctrine
2104
+ doctrine = DoctrineV1(
2105
+ epoch=epoch,
2106
+ metrics=metrics,
2107
+ objectives=objectives,
2108
+ invariants=invariants,
2109
+ levers=levers,
2110
+ risk_budget=risk_budget,
2111
+ version="1.0"
2112
+ )
2113
+
2114
+ # Save to file
2115
+ doctrine.to_json("policy_doctrine.json")
2116
+ ```
2117
+
2118
+ **Example 2: Loading Doctrine from JSON**
2119
+
2120
+ ```python
2121
+ from schemas.policy import DoctrineV1
2122
+
2123
+ # Load doctrine from JSON file
2124
+ doctrine = DoctrineV1.from_json("policy_doctrine.json")
2125
+
2126
+ print(f"Doctrine version: {doctrine.version}")
2127
+ print(f"Metrics: {list(doctrine.metrics.keys())}")
2128
+ print(f"Objectives: {len(doctrine.objectives)}")
2129
+ print(f"Levers: {list(doctrine.levers.keys())}")
2130
+ ```
2131
+
2132
+ **Example 3: Multi-Objective Policy with Deadlines**
2133
+
2134
+ ```python
2135
+ from schemas.policy import DoctrineV1, Objective, EpochConfig, MetricSpec, RiskBudget
2136
+
2137
+ # Complex multi-objective policy
2138
+ objectives = [
2139
+ # Primary objective: minimize latency (high weight, urgent deadline)
2140
+ Objective(
2141
+ metric_name="p95_latency",
2142
+ direction="minimize",
2143
+ target_value=200.0,
2144
+ deadline_epoch=12, # Must achieve within 12 hours
2145
+ weight=3.0
2146
+ ),
2147
+ # Secondary objective: minimize cost (medium weight, no deadline)
2148
+ Objective(
2149
+ metric_name="hourly_cost",
2150
+ direction="minimize",
2151
+ weight=1.5
2152
+ ),
2153
+ # Tertiary objective: maximize throughput (lower weight)
2154
+ Objective(
2155
+ metric_name="requests_per_second",
2156
+ direction="maximize",
2157
+ target_value=1000.0,
2158
+ weight=1.0
2159
+ )
2160
+ ]
2161
+
2162
+ doctrine = DoctrineV1(
2163
+ epoch=EpochConfig(unit="hours", length=1.0),
2164
+ metrics={
2165
+ "p95_latency": MetricSpec(extractor_key="p95_latency_ms", unit="ms"),
2166
+ "hourly_cost": MetricSpec(extractor_key="cost_usd", unit="USD"),
2167
+ "requests_per_second": MetricSpec(extractor_key="rps", unit="req/s")
2168
+ },
2169
+ objectives=objectives,
2170
+ invariants=[],
2171
+ levers={},
2172
+ risk_budget=RiskBudget()
2173
+ )
2174
+ ```
2175
+
2176
+ #### CompiledPolicy: Normalized Policy
2177
+
2178
+ The compiled policy normalizes weights, resolves IDs, and creates deterministic selectors.
2179
+
2180
+ **Example 4: Compiling a Doctrine**
2181
+
2182
+ ```python
2183
+ from schemas.policy import DoctrineV1, CompiledPolicy
2184
+
2185
+ # Create doctrine
2186
+ doctrine = DoctrineV1(...) # As defined above
2187
+
2188
+ # Compile to normalized policy
2189
+ compiled = CompiledPolicy.compile(doctrine)
2190
+
2191
+ print(f"Policy hash: {compiled.policy_hash}")
2192
+ print(f"Normalized weights: {compiled.normalized_weights}")
2193
+ print(f"Resolved metric IDs: {compiled.resolved_metric_ids}")
2194
+ print(f"Deadline epochs: {compiled.deadline_epochs}")
2195
+ ```
2196
+
2197
+ #### Ledger: Event-Sourced Audit Trail
2198
+
2199
+ The ledger provides an append-only event store for all policy decisions and outcomes.
2200
+
2201
+ **Example 5: Recording Events in Ledger**
2202
+
2203
+ ```python
2204
+ from utils.ledger import Ledger
2205
+ from schemas.policy import ObservationEvent, DecisionEvent, OutcomeEvent
2206
+
2207
+ # Initialize ledger
2208
+ ledger = Ledger(db_path="policy_ledger.db")
2209
+
2210
+ # Record observation event
2211
+ observation = ObservationEvent(
2212
+ epoch=1,
2213
+ metrics={"cpu_usage": 75.5, "memory_usage": 60.2, "latency_ms": 120.0}
2214
+ )
2215
+ event_id = ledger.append(observation)
2216
+ print(f"Recorded observation event: {event_id}")
2217
+
2218
+ # Record decision event
2219
+ decision = DecisionEvent(
2220
+ epoch=1,
2221
+ interventions=[
2222
+ {"lever_id": "cpu_throttle", "parameters": {"nice_value": 5}}
2223
+ ],
2224
+ rationale="CPU usage high, throttling to reduce load",
2225
+ decision_hash="abc123..."
2226
+ )
2227
+ event_id = ledger.append(decision)
2228
+ print(f"Recorded decision event: {event_id}")
2229
+
2230
+ # Record outcome event
2231
+ outcome = OutcomeEvent(
2232
+ epoch=1,
2233
+ metrics={"cpu_usage": 65.0, "memory_usage": 58.0, "latency_ms": 95.0},
2234
+ objectives_met={"request_latency": True, "cpu_usage": True}
2235
+ )
2236
+ event_id = ledger.append(outcome)
2237
+ print(f"Recorded outcome event: {event_id}")
2238
+ ```
2239
+
2240
+ **Example 6: Querying Ledger History**
2241
+
2242
+ ```python
2243
+ from utils.ledger import Ledger
2244
+
2245
+ ledger = Ledger(db_path="policy_ledger.db")
2246
+
2247
+ # Get all events for a specific epoch
2248
+ epoch_events = ledger.get_events_by_epoch(epoch=1)
2249
+ print(f"Found {len(epoch_events)} events in epoch 1")
2250
+
2251
+ # Get events in a window
2252
+ window_events = ledger.get_events_window(start_epoch=1, end_epoch=10)
2253
+ print(f"Found {len(window_events)} events in window [1, 10]")
2254
+
2255
+ # Get events by type
2256
+ observations = ledger.get_events_by_type("observation", start_epoch=1, end_epoch=24)
2257
+ print(f"Found {len(observations)} observation events")
2258
+
2259
+ # Replay events (for deterministic execution)
2260
+ replay_events = ledger.replay_events(start_epoch=1, end_epoch=10)
2261
+ for event in replay_events:
2262
+ print(f"Event {event['id']}: {event['type']} at epoch {event['epoch']}")
2263
+ ```
2264
+
2265
+ #### RollbackManager: Intervention Recovery
2266
+
2267
+ The rollback manager provides checkpoint creation and intervention recovery.
2268
+
2269
+ **Example 7: Creating Checkpoints and Rollback**
2270
+
2271
+ ```python
2272
+ from utils.rollback import RollbackManager
2273
+ from schemas.policy import InterventionSpec
2274
+
2275
+ # Initialize rollback manager
2276
+ rollback = RollbackManager(db_path="rollback.db", retention_days=7)
2277
+
2278
+ # Create checkpoint before intervention
2279
+ state = {
2280
+ "cpu_usage": 70.0,
2281
+ "memory_usage": 60.0,
2282
+ "replicas": 3
2283
+ }
2284
+ checkpoint_id = rollback.create_checkpoint(epoch=1, state=state)
2285
+ print(f"Created checkpoint: {checkpoint_id}")
2286
+
2287
+ # Record intervention
2288
+ intervention = InterventionSpec(
2289
+ lever_id="scale_replicas",
2290
+ parameters={"replicas": 5}
2291
+ )
2292
+ intervention_id = rollback.record_intervention(
2293
+ checkpoint_id=checkpoint_id,
2294
+ epoch=1,
2295
+ intervention=intervention,
2296
+ result={"status": "success", "new_replicas": 5}
2297
+ )
2298
+ print(f"Recorded intervention: {intervention_id}")
2299
+
2300
+ # If intervention fails, rollback
2301
+ if intervention_failed:
2302
+ rollback_result = rollback.rollback_n_steps(
2303
+ epoch=1,
2304
+ n_steps=1
2305
+ )
2306
+ print(f"Rolled back {rollback_result['n_rolled_back']} interventions")
2307
+
2308
+ # Restore checkpoint
2309
+ restored_state = rollback.restore_checkpoint(checkpoint_id)
2310
+ print(f"Restored state: {restored_state}")
2311
+ ```
2312
+
2313
+ **Example 8: Automatic Rollback on Failure**
2314
+
2315
+ ```python
2316
+ from utils.rollback import RollbackManager
2317
+
2318
+ rollback = RollbackManager()
2319
+
2320
+ # Create checkpoint
2321
+ checkpoint_id = rollback.create_checkpoint(epoch=1, state=current_state)
2322
+
2323
+ try:
2324
+ # Execute intervention
2325
+ result = execute_intervention(intervention)
2326
+ rollback.record_intervention(
2327
+ checkpoint_id=checkpoint_id,
2328
+ epoch=1,
2329
+ intervention=intervention,
2330
+ result=result
2331
+ )
2332
+ except Exception as e:
2333
+ # Automatic rollback on failure
2334
+ logger.error(f"Intervention failed: {e}")
2335
+ rollback.rollback_n_steps(epoch=1, n_steps=1)
2336
+ restored_state = rollback.restore_checkpoint(checkpoint_id)
2337
+ logger.info(f"Rolled back to checkpoint: {checkpoint_id}")
2338
+ ```
2339
+
2340
+ #### PolicyLoopMixin: Temporal Policy Execution
2341
+
2342
+ The policy loop mixin provides the observe → plan → act → update cycle with online learning.
2343
+
2344
+ **Example 9: Basic Policy Loop Execution**
2345
+
2346
+ ```python
2347
+ from templates.policy_loop import PolicyLoopMixin
2348
+ from schemas.policy import DoctrineV1
2349
+ from utils.ledger import Ledger
2350
+
2351
+ # Create doctrine and ledger
2352
+ doctrine = DoctrineV1.from_json("policy_doctrine.json")
2353
+ ledger = Ledger(db_path="policy_ledger.db")
2354
+
2355
+ # Create agent with policy loop mixin
2356
+ class PolicyAgent(PolicyLoopMixin):
2357
+ def __init__(self, doctrine, ledger):
2358
+ super().__init__(doctrine, ledger, seed=42)
2359
+
2360
+ agent = PolicyAgent(doctrine, ledger)
2361
+
2362
+ # Run single epoch
2363
+ result = agent.run_epoch(epoch=1)
2364
+
2365
+ print(f"Epoch {result['epoch']} completed")
2366
+ print(f"Interventions: {result['interventions']}")
2367
+ print(f"Objectives met: {result['objectives_met']}")
2368
+ print(f"Decision hash: {result['decision_hash']}")
2369
+ ```
2370
+
2371
+ **Example 10: Policy Loop with Online Learning**
2372
+
2373
+ ```python
2374
+ from templates.policy_loop import PolicyLoopMixin
2375
+ from schemas.policy import DoctrineV1
2376
+ from utils.ledger import Ledger
2377
+
2378
+ class LearningPolicyAgent(PolicyLoopMixin):
2379
+ def __init__(self, doctrine, ledger):
2380
+ super().__init__(doctrine, ledger, seed=42)
2381
+
2382
+ agent = LearningPolicyAgent(doctrine, ledger)
2383
+
2384
+ # Run multiple epochs with online learning
2385
+ for epoch in range(1, 25): # 24 hours
2386
+ result = agent.run_epoch(epoch=epoch)
2387
+
2388
+ # Online learning updates model after each epoch
2389
+ agent.update_models(epoch=epoch)
2390
+
2391
+ print(f"Epoch {epoch}: {result['objectives_met']}")
2392
+ print(f"Model updated with {len(result['metrics'])} observations")
2393
+ ```
2394
+
2395
+ #### MPCPlanner: Model Predictive Control
2396
+
2397
+ The MPC planner provides multi-step optimization with horizon-based prediction.
2398
+
2399
+ **Example 11: MPC Planning for Multi-Step Optimization**
2400
+
2401
+ ```python
2402
+ from templates.mpc_planner import MPCPlanner
2403
+ from schemas.policy import DoctrineV1
2404
+ import numpy as np
2405
+
2406
+ # Create doctrine
2407
+ doctrine = DoctrineV1(...)
2408
+
2409
+ # Initialize MPC planner with 5-step horizon
2410
+ planner = MPCPlanner(
2411
+ doctrine=doctrine,
2412
+ horizon=5, # Plan 5 steps ahead
2413
+ use_robust=False
2414
+ )
2415
+
2416
+ # Current state
2417
+ x_t = np.array([75.0, 60.0, 120.0]) # [cpu, memory, latency]
2418
+
2419
+ # State transition matrices (if available)
2420
+ A = np.array([[0.9, 0.0, 0.0], [0.0, 0.95, 0.0], [0.0, 0.0, 0.85]])
2421
+ B = np.array([[0.1, 0.0], [0.0, 0.05], [0.0, 0.15]])
2422
+
2423
+ # Solve MPC problem
2424
+ interventions, score, rationale = planner.solve_mpc(
2425
+ x_t=x_t,
2426
+ A=A,
2427
+ B=B,
2428
+ objectives=[{"metric_name": "latency_ms", "weight": 2.0, "direction": "minimize"}],
2429
+ constraints=[],
2430
+ lever_bounds={"cpu_throttle": {"nice_value": {"min": 0, "max": 19}}}
2431
+ )
2432
+
2433
+ print(f"MPC solution score: {score}")
2434
+ print(f"Interventions: {interventions}")
2435
+ print(f"Rationale: {rationale}")
2436
+ ```
2437
+
2438
+ **Example 12: Robust MPC with Uncertainty**
2439
+
2440
+ ```python
2441
+ from templates.mpc_planner import MPCPlanner
2442
+
2443
+ # Initialize robust MPC planner
2444
+ planner = MPCPlanner(
2445
+ doctrine=doctrine,
2446
+ horizon=5,
2447
+ use_robust=True, # Enable robust MPC
2448
+ uncertainty_set_size=0.1 # 10% uncertainty
2449
+ )
2450
+
2451
+ # Solve with uncertainty sets
2452
+ interventions, score, rationale = planner.solve_mpc(...)
2453
+ ```
2454
+
2455
+ #### DriftDetector: Change-Point Detection
2456
+
2457
+ The drift detector identifies regime shifts and change points in metrics.
2458
+
2459
+ **Example 13: Detecting Drift in Metrics**
2460
+
2461
+ ```python
2462
+ from templates.drift_detection import DriftDetector
2463
+
2464
+ # Initialize drift detector
2465
+ detector = DriftDetector(
2466
+ algorithm="pelt", # Optimal segmentation
2467
+ min_size=2,
2468
+ penalty=10.0,
2469
+ model="rbf"
2470
+ )
2471
+
2472
+ # Metric history (e.g., latency over time)
2473
+ latency_history = [95.0, 98.0, 102.0, 105.0, 110.0, 115.0, 120.0, 125.0, 130.0, 135.0]
2474
+
2475
+ # Detect change points
2476
+ change_points, confidence = detector.detect_changepoints(
2477
+ metric_name="latency",
2478
+ metric_history=latency_history,
2479
+ min_history=5
2480
+ )
2481
+
2482
+ print(f"Change points detected at indices: {change_points}")
2483
+ print(f"Confidence scores: {confidence}")
2484
+
2485
+ # Check if drift detected
2486
+ if len(change_points) > 0:
2487
+ print("WARNING: Drift detected in latency metric!")
2488
+ print(f"Regime change at epoch {change_points[0]}")
2489
+ ```
2490
+
2491
+ **Example 14: Multi-Metric Drift Detection**
2492
+
2493
+ ```python
2494
+ from templates.drift_detection import DriftDetector
2495
+
2496
+ detector = DriftDetector(algorithm="pelt")
2497
+
2498
+ # Monitor multiple metrics
2499
+ metrics_history = {
2500
+ "cpu_usage": [50.0, 52.0, 55.0, 60.0, 65.0, 70.0, 75.0],
2501
+ "memory_usage": [40.0, 42.0, 45.0, 50.0, 55.0, 60.0, 65.0],
2502
+ "latency": [100.0, 105.0, 110.0, 120.0, 130.0, 140.0, 150.0]
2503
+ }
2504
+
2505
+ # Detect drift in all metrics
2506
+ for metric_name, history in metrics_history.items():
2507
+ change_points, confidence = detector.detect_changepoints(
2508
+ metric_name=metric_name,
2509
+ metric_history=history
2510
+ )
2511
+
2512
+ if len(change_points) > 0:
2513
+ print(f"Drift detected in {metric_name} at epochs: {change_points}")
2514
+ ```
2515
+
2516
+ #### Sensors: Metric Collection
2517
+
2518
+ Sensors read system metrics and state snapshots.
2519
+
2520
+ **Example 15: System Metrics Sensor**
2521
+
2522
+ ```python
2523
+ from tools.sensors import SystemMetricsSensor
2524
+
2525
+ # Initialize system metrics sensor
2526
+ sensor = SystemMetricsSensor()
2527
+
2528
+ # Read current metrics
2529
+ snapshot = sensor.read()
2530
+
2531
+ print(f"CPU usage: {snapshot['cpu_percent']:.1f}%")
2532
+ print(f"Memory usage: {snapshot['memory_percent']:.1f}%")
2533
+ print(f"Memory available: {snapshot['memory_available_gb']:.2f} GB")
2534
+ print(f"Disk usage: {snapshot['disk_usage_percent']:.1f}%")
2535
+ print(f"Process count: {snapshot['process_count']:.0f}")
2536
+ ```
2537
+
2538
+ **Example 16: Custom Sensor Implementation**
2539
+
2540
+ ```python
2541
+ from tools.sensors import BaseSensor
2542
+ from typing import Dict
2543
+
2544
+ class CustomMetricsSensor(BaseSensor):
2545
+ """Custom sensor for application-specific metrics."""
2546
+
2547
+ def read(self) -> Dict[str, float]:
2548
+ """Read custom metrics."""
2549
+ # Example: Read from application API
2550
+ import requests
2551
+
2552
+ response = requests.get("http://app:8080/metrics")
2553
+ data = response.json()
2554
+
2555
+ return {
2556
+ "request_rate": data.get("requests_per_second", 0.0),
2557
+ "error_rate": data.get("errors_per_second", 0.0),
2558
+ "active_connections": float(data.get("active_connections", 0)),
2559
+ "queue_depth": float(data.get("queue_depth", 0))
2560
+ }
2561
+
2562
+ # Use custom sensor
2563
+ sensor = CustomMetricsSensor()
2564
+ snapshot = sensor.read()
2565
+ print(f"Request rate: {snapshot['request_rate']:.1f} req/s")
2566
+ ```
2567
+
2568
+ #### Actuators: Intervention Execution
2569
+
2570
+ Actuators execute interventions on system controls.
2571
+
2572
+ **Example 17: System Control Actuator**
2573
+
2574
+ ```python
2575
+ from tools.actuators import SystemControlActuator
2576
+ from schemas.policy import InterventionSpec
2577
+
2578
+ # Initialize actuator
2579
+ actuator = SystemControlActuator(require_root=False)
2580
+
2581
+ # Create intervention
2582
+ intervention = InterventionSpec(
2583
+ lever_id="cpu_throttle",
2584
+ parameters={"nice_value": 10, "pid": 12345}
2585
+ )
2586
+
2587
+ # Execute intervention
2588
+ result = actuator.execute([intervention])
2589
+
2590
+ print(f"Executed {result['executed']} interventions")
2591
+ for r in result['results']:
2592
+ print(f"Status: {r['result']['status']}")
2593
+ ```
2594
+
2595
+ **Example 18: Custom Actuator Implementation**
2596
+
2597
+ ```python
2598
+ from tools.actuators import BaseActuator
2599
+ from schemas.policy import InterventionSpec
2600
+ from typing import Dict, List, Any
2601
+
2602
+ class KubernetesActuator(BaseActuator):
2603
+ """Actuator for Kubernetes deployments."""
2604
+
2605
+ def execute(self, interventions: List[InterventionSpec]) -> Dict[str, Any]:
2606
+ """Execute Kubernetes interventions."""
2607
+ results = []
2608
+
2609
+ for intervention in interventions:
2610
+ if intervention.lever_id == "scale_replicas":
2611
+ replicas = intervention.parameters["replicas"]
2612
+ deployment = intervention.parameters["deployment"]
2613
+
2614
+ # Scale deployment (pseudo-code)
2615
+ # kubectl scale deployment {deployment} --replicas={replicas}
2616
+ result = self._scale_deployment(deployment, replicas)
2617
+
2618
+ results.append({
2619
+ "intervention": intervention.model_dump(),
2620
+ "result": result
2621
+ })
2622
+
2623
+ return {"executed": len(results), "results": results}
2624
+
2625
+ def _scale_deployment(self, deployment: str, replicas: int) -> Dict[str, Any]:
2626
+ """Scale Kubernetes deployment."""
2627
+ # Implementation would call kubectl or Kubernetes API
2628
+ return {"status": "success", "deployment": deployment, "replicas": replicas}
2629
+
2630
+ # Use custom actuator
2631
+ actuator = KubernetesActuator()
2632
+ intervention = InterventionSpec(
2633
+ lever_id="scale_replicas",
2634
+ parameters={"deployment": "web-app", "replicas": 5}
2635
+ )
2636
+ result = actuator.execute([intervention])
2637
+ ```
2638
+
2639
+ #### Canonical: Deterministic Hashing
2640
+
2641
+ The canonical module provides stable hashing for reproducible decisions.
2642
+
2643
+ **Example 19: Stable Hashing for Decision Artifacts**
2644
+
2645
+ ```python
2646
+ from utils.canonical import stable_hash, canonical_bytes
2647
+
2648
+ # Hash a decision artifact
2649
+ decision = {
2650
+ "epoch": 1,
2651
+ "interventions": [
2652
+ {"lever_id": "cpu_throttle", "parameters": {"nice_value": 5}}
2653
+ ],
2654
+ "metrics": {"cpu_usage": 75.5, "memory_usage": 60.2}
2655
+ }
2656
+
2657
+ # Compute stable hash (same input = same hash)
2658
+ hash1 = stable_hash(decision)
2659
+ hash2 = stable_hash(decision) # Identical input
2660
+
2661
+ assert hash1 == hash2
2662
+ print(f"Decision hash: {hash1}")
2663
+
2664
+ # Hash with quantized floats (for numeric stability)
2665
+ from utils.canonical import quantize_float
2666
+
2667
+ value = 75.5123456789
2668
+ quantized = quantize_float(value, mode="decimal", p=1e-6)
2669
+ print(f"Original: {value}, Quantized: {quantized}")
2670
+ ```
2671
+
2672
+ **Example 20: Canonical Bytes for Deterministic Serialization**
2673
+
2674
+ ```python
2675
+ from utils.canonical import canonical_bytes, stable_hash
2676
+
2677
+ # Convert object to canonical bytes
2678
+ obj = {
2679
+ "a": 1,
2680
+ "b": [2, 3, 4],
2681
+ "c": {"x": 10.5, "y": 20.3}
2682
+ }
2683
+
2684
+ canonical = canonical_bytes(obj)
2685
+ hash_value = stable_hash(obj)
2686
+
2687
+ print(f"Canonical bytes length: {len(canonical)}")
2688
+ print(f"Stable hash: {hash_value}")
2689
+
2690
+ # Same object in different order produces same hash
2691
+ obj2 = {"c": {"y": 20.3, "x": 10.5}, "a": 1, "b": [2, 3, 4]}
2692
+ hash2 = stable_hash(obj2)
2693
+
2694
+ assert hash_value == hash2 # Same hash despite different key order
2695
+ ```
2696
+
2697
+ ### Complete End-to-End Example
2698
+
2699
+ **Example 21: Full Policy Engine Workflow**
2700
+
2701
+ ```python
2702
+ from schemas.policy import DoctrineV1, EpochConfig, MetricSpec, Objective, RiskBudget
2703
+ from utils.ledger import Ledger
2704
+ from utils.rollback import RollbackManager
2705
+ from templates.policy_loop import PolicyLoopMixin
2706
+ from tools.sensors import SystemMetricsSensor
2707
+ from tools.actuators import SystemControlActuator
2708
+
2709
+ # Step 1: Create doctrine
2710
+ doctrine = DoctrineV1(
2711
+ epoch=EpochConfig(unit="hours", length=1.0),
2712
+ metrics={
2713
+ "cpu_usage": MetricSpec(extractor_key="cpu_percent", unit="percent"),
2714
+ "memory_usage": MetricSpec(extractor_key="memory_percent", unit="percent")
2715
+ },
2716
+ objectives=[
2717
+ Objective(metric_name="cpu_usage", direction="minimize", target_value=70.0, weight=1.0)
2718
+ ],
2719
+ invariants=[],
2720
+ levers={
2721
+ "cpu_throttle": LeverSpec(
2722
+ lever_type="cpu_throttle",
2723
+ bounds={"nice_value": {"min": 0, "max": 19}},
2724
+ rollback_required=True
2725
+ )
2726
+ },
2727
+ risk_budget=RiskBudget(max_actions_per_epoch=5)
2728
+ )
2729
+
2730
+ # Step 2: Initialize ledger and rollback
2731
+ ledger = Ledger(db_path="policy_ledger.db")
2732
+ rollback = RollbackManager(db_path="rollback.db")
2733
+
2734
+ # Step 3: Initialize sensors and actuators
2735
+ sensor = SystemMetricsSensor()
2736
+ actuator = SystemControlActuator()
2737
+
2738
+ # Step 4: Create policy agent
2739
+ class FullPolicyAgent(PolicyLoopMixin):
2740
+ def __init__(self, doctrine, ledger, sensor, actuator):
2741
+ super().__init__(doctrine, ledger, seed=42)
2742
+ self.sensor = sensor
2743
+ self.actuator = actuator
2744
+
2745
+ def observe(self, epoch: int):
2746
+ """Observe current state."""
2747
+ return self.sensor.read()
2748
+
2749
+ def act(self, interventions, epoch: int):
2750
+ """Execute interventions."""
2751
+ return self.actuator.execute(interventions)
2752
+
2753
+ agent = FullPolicyAgent(doctrine, ledger, sensor, actuator)
2754
+
2755
+ # Step 5: Run policy loop
2756
+ for epoch in range(1, 25):
2757
+ # Create checkpoint
2758
+ state = agent.observe(epoch)
2759
+ checkpoint_id = rollback.create_checkpoint(epoch, state)
2760
+
2761
+ try:
2762
+ # Run epoch
2763
+ result = agent.run_epoch(epoch=epoch)
2764
+
2765
+ # Record intervention
2766
+ for intervention in result['interventions']:
2767
+ rollback.record_intervention(
2768
+ checkpoint_id=checkpoint_id,
2769
+ epoch=epoch,
2770
+ intervention=intervention,
2771
+ result={"status": "success"}
2772
+ )
2773
+
2774
+ print(f"Epoch {epoch}: {result['objectives_met']}")
2775
+ except Exception as e:
2776
+ # Rollback on failure
2777
+ logger.error(f"Epoch {epoch} failed: {e}")
2778
+ rollback.rollback_n_steps(epoch, n_steps=1)
2779
+ ```
2780
+
2781
+ ---
2782
+
2783
+ ## Branch Integrations
2784
+
2785
+ ### CRCA-Q Integration
2786
+
2787
+ CRCA-Q (Quantitative Trading) is a single-file quantitative trading system integrating causal reasoning with traditional quantitative finance techniques.
2788
+
2789
+ #### Overview
2790
+
2791
+ CRCA-Q uses causal inference to understand why market movements occur, enabling more robust predictions that remain valid across different market regimes. Unlike correlation-based systems, it implements structural causal models for market analysis.
2792
+
2793
+ #### Key Features
2794
+
2795
+ - **Causal Signal Generation**: Signals based on causal relationships, not correlations
2796
+ - **Portfolio Optimization**: CVaR-based optimization with causal constraints
2797
+ - **Risk Management**: Causal risk modeling and stress testing
2798
+ - **Multi-Asset Support**: Automatic asset discovery and rotation
2799
+ - **Alternative Data Integration**: On-chain, social, news data sources
2800
+
2801
+ #### Integration with CRCAAgent
2802
+
2803
+ ```python
2804
+ from branches.CRCA_Q import QuantTradingAgent
2805
+ from CRCA import CRCAAgent
2806
+
2807
+ # QuantTradingAgent uses CRCAAgent internally for causal reasoning
2808
+ # It automatically creates and manages CRCAAgent instances
2809
+
2810
+ agent = QuantTradingAgent(
2811
+ account_size=10000,
2812
+ model_name="gpt-4o-mini",
2813
+ use_crca_agent_heavily=True,
2814
+ crca_max_loops=5
2815
+ )
2816
+
2817
+ # Run trading loop with causal reasoning
2818
+ result = agent.run(
2819
+ task="Analyze market and generate trading signals",
2820
+ use_causal_validation=True
2821
+ )
2822
+ ```
2823
+
2824
+ #### Usage in CorporateSwarm
2825
+
2826
+ CRCA-Q can be integrated into CorporateSwarm for Investment Committee decisions:
2827
+
2828
+ ```python
2829
+ from crca_cg.corposwarm import CorporateSwarm
2830
+
2831
+ swarm = CorporateSwarm(
2832
+ enable_crca_q=True,
2833
+ crca_q_config={
2834
+ 'account_size': 1000000,
2835
+ 'conservative_mode': True,
2836
+ 'use_crca_agent_heavily': True
2837
+ }
2838
+ )
2839
+
2840
+ # Investment Committee uses CRCA-Q
2841
+ allocation = swarm.investment_committee.recommend_allocation()
2842
+ ```
2843
+
2844
+ ### CRCA-SD Integration
2845
+
2846
+ CRCA-SD integrates CRCAAgent for causal scenario generation in model-predictive control systems.
2847
+
2848
+ #### Integration Pattern
2849
+
2850
+ ```python
2851
+ from crca_sd import get_crca_agent
2852
+ from crca_sd.crca_sd_mpc import ScenarioGenerator
2853
+
2854
+ # Get CRCAAgent instance (returns None if CRCA not available)
2855
+ crca = get_crca_agent(
2856
+ variables=['GDP', 'unemployment', 'inflation', 'stability'],
2857
+ model_name="gpt-4o-mini"
2858
+ )
2859
+
2860
+ if crca:
2861
+ # Create scenario generator with CRCA
2862
+ gen = ScenarioGenerator(crca_agent=crca)
2863
+
2864
+ # Generate causal scenarios instead of random noise
2865
+ scenarios = gen.generate_causal_scenarios(
2866
+ n_scenarios=10,
2867
+ horizon=12,
2868
+ current_state=state_vector,
2869
+ target_variables=['GDP', 'unemployment']
2870
+ )
2871
+ else:
2872
+ # Fallback to Gaussian scenarios
2873
+ scenarios = gen.generate_gaussian(n_scenarios=10, horizon=12)
2874
+ ```
2875
+
2876
+ #### Benefits
2877
+
2878
+ - **Causal Understanding**: Scenarios based on causal relationships
2879
+ - **Counterfactual Analysis**: Explores "what-if" scenarios
2880
+ - **Better Policy Optimization**: MPC uses causally-informed scenarios
2881
+
2882
+ ### CRCA-CG Integration
2883
+
2884
+ CorporateSwarm integrates both CRCAAgent and CRCA-SD for enhanced governance.
2885
+
2886
+ #### CRCAAgent Integration
2887
+
2888
+ ```python
2889
+ from crca_cg.corposwarm import CorporateSwarm
2890
+ from CRCA import CRCAAgent
2891
+
2892
+ # Initialize CRCA agent for causal policy analysis
2893
+ crca = CRCAAgent(
2894
+ variables=['revenue', 'costs', 'employee_satisfaction'],
2895
+ model_name="gpt-4o"
2896
+ )
2897
+
2898
+ swarm = CorporateSwarm(crca_agent=crca)
2899
+
2900
+ # Analyze policy impact using causal reasoning
2901
+ result = swarm.analyze_policy_impact(
2902
+ policy_description="Increase R&D spending by 20%",
2903
+ use_causal_analysis=True
2904
+ )
2905
+ ```
2906
+
2907
+ #### CRCA-SD Integration
2908
+
2909
+ Enhanced voting and governance:
2910
+
2911
+ ```python
2912
+ swarm = CorporateSwarm(
2913
+ enable_crca_sd=True,
2914
+ crca_sd_config={
2915
+ 'governance_model': 'democratic',
2916
+ 'voting_threshold': 0.6
2917
+ }
2918
+ )
2919
+
2920
+ # Enhanced voting with CRCA-SD governance system
2921
+ vote_result = swarm.board.vote_on_proposal(
2922
+ proposal="Approve new product launch",
2923
+ use_enhanced_voting=True
2924
+ )
2925
+ ```
2926
+
2927
+ ---
2928
+
2929
+ ## Usage Examples
2930
+
2931
+ ### Example 1: Automatic Variable Extraction
2932
+
2933
+ Demonstrates the automatic variable extraction feature:
2934
+
2935
+ ```python
2936
+ from CRCA import CRCAAgent
2937
+
2938
+ # No variables declared - automatic extraction
2939
+ agent = CRCAAgent(model_name="gpt-4o-mini")
2940
+
2941
+ # Task automatically triggers extraction and analysis
2942
+ task = "Analyze how increasing marketing budget affects sales and customer acquisition"
2943
+ result = agent.run(task=task)
2944
+
2945
+ # Variables were automatically extracted
2946
+ print(f"Variables: {agent.get_nodes()}")
2947
+ print(f"Edges: {agent.get_edges()}")
2948
+ print(f"Analysis: {result['causal_analysis'][:200]}...")
2949
+ ```
2950
+
2951
+ **Variation 1: Multiple Related Variables**
2952
+
2953
+ ```python
2954
+ from CRCA import CRCAAgent
2955
+
2956
+ agent = CRCAAgent(model_name="gpt-4o-mini")
2957
+
2958
+ # Complex task with multiple variables
2959
+ task = """
2960
+ Analyze the causal relationships between:
2961
+ - Product quality and customer satisfaction
2962
+ - Customer satisfaction and brand loyalty
2963
+ - Brand loyalty and market share
2964
+ - Market share and revenue growth
2965
+ """
2966
+ result = agent.run(task=task)
2967
+
2968
+ print(f"Extracted {len(agent.get_nodes())} variables")
2969
+ print(f"Created {len(agent.get_edges())} causal relationships")
2970
+ ```
2971
+
2972
+ **Variation 2: Error Handling**
2973
+
2974
+ ```python
2975
+ from CRCA import CRCAAgent
2976
+ from loguru import logger
2977
+
2978
+ agent = CRCAAgent(model_name="gpt-4o-mini")
2979
+
2980
+ try:
2981
+ # Task with unclear causal relationships
2982
+ task = "What is the weather today?"
2983
+ result = agent.run(task=task)
2984
+
2985
+ if len(agent.get_nodes()) == 0:
2986
+ logger.warning("No variables extracted - task may not contain causal relationships")
2987
+ # Provide more explicit task
2988
+ task = "Analyze how temperature affects ice cream sales"
2989
+ result = agent.run(task=task)
2990
+ except Exception as e:
2991
+ logger.error(f"Variable extraction failed: {e}")
2992
+ ```
2993
+
2994
+ ### Example 2: LLM-Based Causal Analysis
2995
+
2996
+ Full LLM-based causal analysis workflow:
2997
+
2998
+ ```python
2999
+ from CRCA import CRCAAgent
3000
+
3001
+ agent = CRCAAgent(
3002
+ model_name="gpt-4o",
3003
+ max_loops=3,
3004
+ agent_max_loops=3
3005
+ )
3006
+
3007
+ task = "Why do large software projects fail despite adequate funding and skilled engineers?"
3008
+ result = agent.run(task=task)
3009
+
3010
+ print("Causal Analysis:")
3011
+ print(result["causal_analysis"])
3012
+
3013
+ print("\nCounterfactual Scenarios:")
3014
+ for i, scenario in enumerate(result["counterfactual_scenarios"][:3], 1):
3015
+ print(f"{i}. {scenario.name}")
3016
+ print(f" Interventions: {scenario.interventions}")
3017
+ print(f" Reasoning: {scenario.reasoning[:100]}...")
3018
+ ```
3019
+
3020
+ **Variation 1: Extended Analysis with More Loops**
3021
+
3022
+ ```python
3023
+ from CRCA import CRCAAgent
3024
+
3025
+ # Use more loops for deeper analysis
3026
+ agent = CRCAAgent(
3027
+ model_name="gpt-4o",
3028
+ max_loops=5, # More causal reasoning loops
3029
+ agent_max_loops=5 # More standard agent loops
3030
+ )
3031
+
3032
+ task = "Analyze the root causes of economic recessions"
3033
+ result = agent.run(task=task)
3034
+
3035
+ # Get detailed analysis
3036
+ print(f"Analysis length: {len(result['causal_analysis'])} characters")
3037
+ print(f"Generated {len(result['counterfactual_scenarios'])} scenarios")
3038
+ ```
3039
+
3040
+ **Variation 2: Domain-Specific Analysis**
3041
+
3042
+ ```python
3043
+ from CRCA import CRCAAgent
3044
+
3045
+ agent = CRCAAgent(
3046
+ model_name="gpt-4o",
3047
+ system_prompt="You are an expert healthcare analyst specializing in public health policy."
3048
+ )
3049
+
3050
+ task = "Analyze how vaccination rates affect disease spread and healthcare costs"
3051
+ result = agent.run(task=task)
3052
+
3053
+ # Domain-specific analysis
3054
+ print(result["causal_analysis"])
3055
+ ```
3056
+
3057
+ ### Example 3: Deterministic Simulation
3058
+
3059
+ Traditional deterministic causal simulation:
3060
+
3061
+ ```python
3062
+ from CRCA import CRCAAgent
3063
+
3064
+ agent = CRCAAgent(variables=["price", "demand", "revenue"])
3065
+ agent.add_causal_relationship("price", "demand", strength=-0.5)
3066
+ agent.add_causal_relationship("price", "revenue", strength=1.0)
3067
+ agent.add_causal_relationship("demand", "revenue", strength=0.8)
3068
+
3069
+ initial_state = {"price": 100.0, "demand": 1000.0, "revenue": 100000.0}
3070
+ result = agent.run(initial_state=initial_state, max_steps=3)
3071
+
3072
+ print("Evolved State:")
3073
+ for var, value in result["evolved_state"].items():
3074
+ print(f" {var}: {value:.2f}")
3075
+
3076
+ print(f"\nGenerated {len(result['counterfactual_scenarios'])} scenarios")
3077
+ ```
3078
+
3079
+ **Variation 1: Multi-Step Simulation**
3080
+
3081
+ ```python
3082
+ from CRCA import CRCAAgent
3083
+
3084
+ agent = CRCAAgent(variables=["price", "demand", "inventory", "revenue"])
3085
+ agent.add_causal_relationship("price", "demand", strength=-0.5)
3086
+ agent.add_causal_relationship("demand", "inventory", strength=-0.3)
3087
+ agent.add_causal_relationship("price", "revenue", strength=1.0)
3088
+ agent.add_causal_relationship("demand", "revenue", strength=0.8)
3089
+
3090
+ # Simulate over multiple steps
3091
+ initial_state = {"price": 100.0, "demand": 1000.0, "inventory": 5000.0, "revenue": 100000.0}
3092
+ result = agent.run(initial_state=initial_state, max_steps=10)
3093
+
3094
+ # Track evolution over time
3095
+ print("State Evolution:")
3096
+ for step, state in enumerate(result.get("state_history", []), 1):
3097
+ print(f"Step {step}: price={state.get('price', 0):.2f}, demand={state.get('demand', 0):.2f}")
3098
+ ```
3099
+
3100
+ **Variation 2: Non-Linear Relationships**
3101
+
3102
+ ```python
3103
+ from CRCA import CRCAAgent
3104
+
3105
+ agent = CRCAAgent(
3106
+ variables=["price", "demand"],
3107
+ use_nonlinear=True # Enable non-linear SCM
3108
+ )
3109
+
3110
+ agent.add_causal_relationship("price", "demand", strength=-0.5)
3111
+
3112
+ # Non-linear simulation
3113
+ initial_state = {"price": 100.0, "demand": 1000.0}
3114
+ result = agent.run(initial_state=initial_state, max_steps=5)
3115
+
3116
+ print("Non-linear evolution:")
3117
+ print(result["evolved_state"])
3118
+ ```
3119
+
3120
+ ### Example 4: Integration with CRCA-SD
3121
+
3122
+ Using CRCAAgent with CRCA-SD for socioeconomic modeling:
3123
+
3124
+ ```python
3125
+ from crca_sd import get_crca_agent, StateVector
3126
+ from crca_sd.crca_sd_mpc import MPCSolver
3127
+
3128
+ # Get CRCAAgent for causal reasoning
3129
+ crca = get_crca_agent(
3130
+ variables=['GDP', 'unemployment', 'inflation'],
3131
+ model_name="gpt-4o-mini"
3132
+ )
3133
+
3134
+ # Create state vector
3135
+ state = StateVector({
3136
+ 'GDP': 1000.0,
3137
+ 'unemployment': 5.0,
3138
+ 'inflation': 2.0
3139
+ })
3140
+
3141
+ # Use CRCA for causal scenario generation in MPC
3142
+ if crca:
3143
+ solver = MPCSolver(crca_agent=crca)
3144
+ solution = solver.solve(initial_state=state, use_causal_scenarios=True)
3145
+ ```
3146
+
3147
+ **Variation 1: Complete CRCA-SD Workflow**
3148
+
3149
+ ```python
3150
+ from crca_sd import (
3151
+ get_crca_agent, StateVector, ControlVector, DynamicsModel,
3152
+ ConstraintChecker, ForwardSimulator
3153
+ )
3154
+ from crca_sd.crca_sd_mpc import MPCSolver, ScenarioGenerator
3155
+
3156
+ # Initialize CRCA agent
3157
+ crca = get_crca_agent(
3158
+ variables=['Y', 'U', 'S', 'P', 'L', 'W', 'K', 'I'],
3159
+ model_name="gpt-4o-mini"
3160
+ )
3161
+
3162
+ # Create state vector
3163
+ state = StateVector(
3164
+ Y=1000000.0, # GDP
3165
+ U=0.05, # Unemployment
3166
+ S=0.8, # Stability
3167
+ P=1000000.0, # Population
3168
+ L=500000.0, # Labor
3169
+ W=1.0, # Wages
3170
+ K=1000000.0, # Capital
3171
+ I=0.8 # Infrastructure
3172
+ )
3173
+
3174
+ # Create dynamics model
3175
+ dynamics = DynamicsModel()
3176
+ checker = ConstraintChecker()
3177
+ simulator = ForwardSimulator(dynamics, checker)
3178
+
3179
+ # Create MPC solver with CRCA
3180
+ solver = MPCSolver(
3181
+ dynamics_model=dynamics,
3182
+ crca_agent=crca
3183
+ )
3184
+
3185
+ # Solve with causal scenarios
3186
+ solution = solver.solve(
3187
+ initial_state=state,
3188
+ horizon=12,
3189
+ use_causal_scenarios=True
3190
+ )
3191
+
3192
+ print(f"Solution found: {solution['optimal']}")
3193
+ print(f"Control sequence: {solution['control_sequence']}")
3194
+ ```
3195
+
3196
+ **Variation 2: Scenario Generation with CRCA**
3197
+
3198
+ ```python
3199
+ from crca_sd.crca_sd_mpc import ScenarioGenerator
3200
+ from crca_sd import get_crca_agent, StateVector
3201
+
3202
+ # Get CRCA agent
3203
+ crca = get_crca_agent(
3204
+ variables=['GDP', 'unemployment', 'inflation'],
3205
+ model_name="gpt-4o-mini"
3206
+ )
3207
+
3208
+ # Create scenario generator
3209
+ gen = ScenarioGenerator(crca_agent=crca)
3210
+
3211
+ # Generate causal scenarios
3212
+ state = StateVector(GDP=1000.0, unemployment=5.0, inflation=2.0)
3213
+ scenarios = gen.generate_causal_scenarios(
3214
+ n_scenarios=10,
3215
+ horizon=12,
3216
+ current_state=state,
3217
+ target_variables=['GDP', 'unemployment']
3218
+ )
3219
+
3220
+ print(f"Generated {len(scenarios)} causal scenarios")
3221
+ for i, scenario in enumerate(scenarios[:3], 1):
3222
+ print(f"Scenario {i}: {scenario}")
3223
+ ```
3224
+
3225
+ ### Example 5: CRCA-SD Complete Workflow
3226
+
3227
+ Complete example from `examples/crca_sd_example.py`:
3228
+
3229
+ ```python
3230
+ from crca_sd.crca_sd_core import (
3231
+ StateVector, ControlVector, DynamicsModel,
3232
+ ConstraintChecker, ForwardSimulator
3233
+ )
3234
+ from crca_sd.crca_sd_mpc import MPCSolver, ScenarioGenerator
3235
+ from crca_sd import get_crca_agent
3236
+
3237
+ # Phase A: Basic simulation
3238
+ x_0 = StateVector(
3239
+ P=1000000.0, # Population
3240
+ L=500000.0, # Labor force
3241
+ U=0.05, # Unemployment
3242
+ W=1.0, # Wage proxy
3243
+ S=0.8, # Stability
3244
+ Y=1000000.0 # GDP
3245
+ )
3246
+
3247
+ dynamics = DynamicsModel()
3248
+ checker = ConstraintChecker()
3249
+ simulator = ForwardSimulator(dynamics, checker)
3250
+
3251
+ # Sample budget policies
3252
+ policies = [
3253
+ ControlVector.sample_budget_simplex(["energy", "food", "infrastructure"])
3254
+ for _ in range(5)
3255
+ ]
3256
+
3257
+ # Simulate each policy
3258
+ for i, policy in enumerate(policies):
3259
+ trajectory, feasibility, violation = simulator.simulate_scenario(
3260
+ x_0, policy, [{}] * 10, horizon=10
3261
+ )
3262
+ print(f"Policy {i+1}: {sum(feasibility)}/10 steps feasible")
3263
+
3264
+ # Phase B: MPC solver with CRCA
3265
+ crca = get_crca_agent(
3266
+ variables=['Y', 'U', 'S', 'P', 'L', 'W', 'K', 'I'],
3267
+ model_name="gpt-4o-mini"
3268
+ )
3269
+
3270
+ if crca:
3271
+ solver = MPCSolver(dynamics_model=dynamics, crca_agent=crca)
3272
+ solution = solver.solve(initial_state=x_0, horizon=12, use_causal_scenarios=True)
3273
+ print(f"MPC solution: {solution}")
3274
+ ```
3275
+
3276
+ ### Example 6: CorporateSwarm Complete Example
3277
+
3278
+ Complete example from `examples/logistics_corporation.py`:
3279
+
3280
+ ```python
3281
+ from crca_cg.corposwarm import (
3282
+ CorporateSwarm, CorporateRole, DepartmentType,
3283
+ ProposalType, BoardCommitteeType
3284
+ )
3285
+ from utils.tui import CorporateSwarmTUI
3286
+
3287
+ # Create logistics corporation
3288
+ swarm = CorporateSwarm(
3289
+ company_name="UAB Leiliona",
3290
+ industry="Logistics and Supply Chain Management"
3291
+ )
3292
+
3293
+ # Add board members
3294
+ swarm.add_board_member(
3295
+ name="John Doe",
3296
+ role=CorporateRole.CHAIRMAN,
3297
+ expertise=["logistics", "supply_chain"]
3298
+ )
3299
+
3300
+ # Add executives
3301
+ swarm.add_executive(
3302
+ name="Jane Smith",
3303
+ role=CorporateRole.CEO,
3304
+ department=DepartmentType.OPERATIONS
3305
+ )
3306
+
3307
+ # Create department
3308
+ swarm.create_department(
3309
+ name="Operations",
3310
+ dept_type=DepartmentType.OPERATIONS,
3311
+ head="Jane Smith"
3312
+ )
3313
+
3314
+ # Create proposal
3315
+ proposal = swarm.create_proposal(
3316
+ title="Expand warehouse capacity",
3317
+ description="Build new warehouse facility to increase capacity by 50%",
3318
+ proposal_type=ProposalType.STRATEGIC,
3319
+ budget_impact=5000000.0
3320
+ )
3321
+
3322
+ # Vote on proposal
3323
+ vote_result = swarm.board.vote_on_proposal(proposal)
3324
+ print(f"Proposal passed: {vote_result.passed}")
3325
+ print(f"Votes for: {vote_result.votes_for}, against: {vote_result.votes_against}")
3326
+
3327
+ # Use TUI for interactive management
3328
+ if TUI_AVAILABLE:
3329
+ tui = CorporateSwarmTUI(swarm)
3330
+ tui.run()
3331
+ ```
3332
+
3333
+ **Variation 1: ESG Scoring and Risk Assessment**
3334
+
3335
+ ```python
3336
+ from crca_cg.corposwarm import CorporateSwarm
3337
+
3338
+ swarm = CorporateSwarm(company_name="Example Corp")
3339
+
3340
+ # Calculate ESG score
3341
+ esg_score = swarm.calculate_esg_score()
3342
+ print(f"ESG Score: {esg_score['total_score']:.2f}")
3343
+ print(f"Environmental: {esg_score['environmental']:.2f}")
3344
+ print(f"Social: {esg_score['social']:.2f}")
3345
+ print(f"Governance: {esg_score['governance']:.2f}")
3346
+
3347
+ # Risk assessment
3348
+ risk_assessment = swarm.assess_risks()
3349
+ print(f"Overall risk level: {risk_assessment['overall_risk']}")
3350
+ print(f"Risk factors: {risk_assessment['risk_factors']}")
3351
+ ```
3352
+
3353
+ **Variation 2: Integration with CRCA-Q**
3354
+
3355
+ ```python
3356
+ from crca_cg.corposwarm import CorporateSwarm
3357
+
3358
+ # Create swarm with CRCA-Q integration
3359
+ swarm = CorporateSwarm(
3360
+ company_name="Trading Corp",
3361
+ enable_crca_q=True,
3362
+ crca_q_config={
3363
+ 'account_size': 1000000,
3364
+ 'conservative_mode': True
3365
+ }
3366
+ )
3367
+
3368
+ # Investment Committee uses CRCA-Q
3369
+ allocation = swarm.investment_committee.recommend_allocation()
3370
+ print(f"Recommended allocation: {allocation}")
3371
+ ```
3372
+
3373
+ ### Example 7: Policy Benchmarking
3374
+
3375
+ Example from `examples/policy_bench.py`:
3376
+
3377
+ ```python
3378
+ from schemas.policy import DoctrineV1, EpochConfig, MetricSpec, Objective, RiskBudget
3379
+ from templates.policy_loop import PolicyLoopMixin
3380
+ from utils.ledger import Ledger
3381
+
3382
+ # Create multiple policies for benchmarking
3383
+ policies = []
3384
+
3385
+ # Policy 1: Aggressive (high risk, high reward)
3386
+ policy1 = DoctrineV1(
3387
+ epoch=EpochConfig(unit="hours", length=1.0),
3388
+ metrics={"performance": MetricSpec(extractor_key="perf", unit="score")},
3389
+ objectives=[Objective(metric_name="performance", direction="maximize", weight=2.0)],
3390
+ invariants=[],
3391
+ levers={},
3392
+ risk_budget=RiskBudget(max_actions_per_epoch=10, max_risk_per_epoch=1.0)
3393
+ )
3394
+
3395
+ # Policy 2: Conservative (low risk, stable)
3396
+ policy2 = DoctrineV1(
3397
+ epoch=EpochConfig(unit="hours", length=1.0),
3398
+ metrics={"stability": MetricSpec(extractor_key="stab", unit="score")},
3399
+ objectives=[Objective(metric_name="stability", direction="maximize", weight=1.0)],
3400
+ invariants=[],
3401
+ levers={},
3402
+ risk_budget=RiskBudget(max_actions_per_epoch=3, max_risk_per_epoch=0.3)
3403
+ )
3404
+
3405
+ # Benchmark policies
3406
+ ledger = Ledger(db_path="benchmark.db")
3407
+ for i, policy in enumerate([policy1, policy2], 1):
3408
+ agent = PolicyLoopMixin(policy, ledger, seed=42)
3409
+ result = agent.run_epoch(epoch=1)
3410
+ print(f"Policy {i} result: {result['objectives_met']}")
3411
+ ```
3412
+
3413
+ ### Example 8: Real-Time Monitoring
3414
+
3415
+ Example from `examples/pridnestrovia_realtime.py`:
3416
+
3417
+ ```python
3418
+ from crca_sd.crca_sd_realtime import (
3419
+ DataAcquisition, DataPipeline, RealTimeMonitor
3420
+ )
3421
+
3422
+ # Initialize data acquisition
3423
+ data_acq = DataAcquisition(
3424
+ sources=["api", "database", "stream"],
3425
+ update_interval=60 # Update every 60 seconds
3426
+ )
3427
+
3428
+ # Create data pipeline
3429
+ pipeline = DataPipeline(
3430
+ stages=["filter", "validate", "transform", "aggregate"]
3431
+ )
3432
+
3433
+ # Create real-time monitor
3434
+ monitor = RealTimeMonitor(
3435
+ data_acquisition=data_acq,
3436
+ pipeline=pipeline,
3437
+ alert_thresholds={"cpu": 80.0, "memory": 85.0}
3438
+ )
3439
+
3440
+ # Start monitoring
3441
+ monitor.start()
3442
+
3443
+ # Monitor for 1 hour
3444
+ import time
3445
+ time.sleep(3600)
3446
+
3447
+ # Stop monitoring
3448
+ monitor.stop()
3449
+ print(f"Collected {monitor.get_metric_count()} data points")
3450
+ ```
3451
+
3452
+ ### Example 9: Configuration Example
3453
+
3454
+ Example from `examples/config.yaml.example`:
3455
+
3456
+ ```yaml
3457
+ # CRCA Configuration Example
3458
+ agent:
3459
+ model_name: "gpt-4o-mini"
3460
+ max_loops: 3
3461
+ agent_max_loops: 3
3462
+ enable_batch_predict: true
3463
+ max_batch_size: 32
3464
+
3465
+ policy_engine:
3466
+ epoch:
3467
+ unit: "hours"
3468
+ length: 1.0
3469
+ timezone: "UTC"
3470
+ ledger:
3471
+ db_path: "policy_ledger.db"
3472
+ rollback:
3473
+ db_path: "rollback.db"
3474
+ retention_days: 7
3475
+
3476
+ crca_sd:
3477
+ horizon: 12
3478
+ use_causal_scenarios: true
3479
+
3480
+ crca_cg:
3481
+ enable_crca_q: false
3482
+ enable_crca_sd: false
3483
+ ```
3484
+
3485
+ **Usage:**
3486
+
3487
+ ```python
3488
+ import yaml
3489
+ from schemas.policy import DoctrineV1
3490
+
3491
+ # Load configuration
3492
+ with open("config.yaml", "r") as f:
3493
+ config = yaml.safe_load(f)
3494
+
3495
+ # Use configuration
3496
+ doctrine = DoctrineV1(
3497
+ epoch=EpochConfig(**config["policy_engine"]["epoch"]),
3498
+ # ... other fields from config
3499
+ )
3500
+ ```
3501
+
3502
+ ---
3503
+
3504
+ ## Advanced Features
3505
+
3506
+ ### Optimization Methods
3507
+
3508
+ #### Gradient-Based Intervention Optimization
3509
+
3510
+ ```python
3511
+ agent = CRCAAgent(variables=["price", "demand", "revenue"])
3512
+ # ... add causal relationships ...
3513
+
3514
+ opt_result = agent.gradient_based_intervention_optimization(
3515
+ initial_state={"price": 100.0, "demand": 1000.0, "revenue": 100000.0},
3516
+ target="revenue",
3517
+ intervention_vars=["price"],
3518
+ constraints={"price": (80.0, 120.0)},
3519
+ method="L-BFGS-B"
3520
+ )
3521
+
3522
+ print(f"Optimal intervention: {opt_result['optimal_intervention']}")
3523
+ print(f"Optimal target value: {opt_result['optimal_target_value']}")
3524
+ ```
3525
+
3526
+ #### Bellman Optimal Intervention
3527
+
3528
+ Multi-step dynamic programming optimization:
3529
+
3530
+ ```python
3531
+ bellman_result = agent.bellman_optimal_intervention(
3532
+ initial_state={"price": 100.0, "demand": 1000.0},
3533
+ target="revenue",
3534
+ intervention_vars=["price"],
3535
+ horizon=5,
3536
+ discount=0.9
3537
+ )
3538
+
3539
+ print(f"Optimal sequence: {bellman_result['optimal_sequence']}")
3540
+ print(f"Final state: {bellman_result['final_state']}")
3541
+ ```
3542
+
3543
+ ### Time-Series Analysis
3544
+
3545
+ #### Granger Causality Test
3546
+
3547
+ ```python
3548
+ import pandas as pd
3549
+
3550
+ df = pd.read_csv("time_series_data.csv", parse_dates=["date"])
3551
+
3552
+ granger_result = agent.granger_causality_test(
3553
+ df=df,
3554
+ var1="price",
3555
+ var2="demand",
3556
+ max_lag=4
3557
+ )
3558
+
3559
+ print(f"Granger causes: {granger_result['granger_causes']}")
3560
+ print(f"P-value: {granger_result['p_value']:.4f}")
3561
+ ```
3562
+
3563
+ #### Vector Autoregression Estimation
3564
+
3565
+ ```python
3566
+ var_result = agent.vector_autoregression_estimation(
3567
+ df=df,
3568
+ variables=["price", "demand", "inventory"],
3569
+ max_lag=2
3570
+ )
3571
+
3572
+ print(f"VAR coefficients: {var_result['coefficient_matrices']}")
3573
+ ```
3574
+
3575
+ ### Bayesian Inference
3576
+
3577
+ ```python
3578
+ bayesian_result = agent.bayesian_edge_inference(
3579
+ df=df,
3580
+ parent="price",
3581
+ child="demand",
3582
+ prior_mu=0.0,
3583
+ prior_sigma=1.0
3584
+ )
3585
+
3586
+ print(f"Posterior mean: {bayesian_result['posterior_mean']:.4f}")
3587
+ print(f"95% Credible interval: {bayesian_result['credible_interval_95']}")
3588
+ ```
3589
+
3590
+ ### Advanced Analysis Methods
3591
+
3592
+ #### Sensitivity Analysis
3593
+
3594
+ ```python
3595
+ sensitivity_result = agent.sensitivity_analysis(
3596
+ intervention={"price": 100.0, "demand": 1000.0},
3597
+ target="revenue",
3598
+ perturbation_size=0.01
3599
+ )
3600
+
3601
+ print(f"Sensitivities: {sensitivity_result['sensitivities']}")
3602
+ print(f"Most influential: {sensitivity_result['most_influential_variable']}")
3603
+ ```
3604
+
3605
+ #### Root Cause Analysis
3606
+
3607
+ ```python
3608
+ rca_result = agent.deep_root_cause_analysis(
3609
+ problem_variable="revenue_decline",
3610
+ max_depth=20,
3611
+ min_path_strength=0.01
3612
+ )
3613
+
3614
+ print(f"Ultimate root causes: {rca_result['ultimate_root_causes']}")
3615
+ ```
3616
+
3617
+ #### Shapley Value Attribution
3618
+
3619
+ ```python
3620
+ shapley_result = agent.shapley_value_attribution(
3621
+ baseline_state={"price": 0.0, "demand": 0.0},
3622
+ target_state={"price": 100.0, "demand": 1000.0},
3623
+ target="revenue",
3624
+ samples=100
3625
+ )
3626
+
3627
+ print(f"Shapley values: {shapley_result['shapley_values']}")
3628
+ ```
3629
+
3630
+ #### Multi-Layer What-If Analysis
3631
+
3632
+ ```python
3633
+ scenarios = [
3634
+ {"price": 110.0},
3635
+ {"price": 120.0},
3636
+ {"demand": 1200.0}
3637
+ ]
3638
+
3639
+ ml_result = agent.multi_layer_whatif_analysis(
3640
+ scenarios=scenarios,
3641
+ depth=3
3642
+ )
3643
+
3644
+ print(f"Multi-layer analysis: {ml_result['multi_layer_analysis']}")
3645
+ ```
3646
+
3647
+ #### Reality Exploration
3648
+
3649
+ ```python
3650
+ explore_result = agent.explore_alternate_realities(
3651
+ factual_state={"price": 100.0, "demand": 1000.0},
3652
+ target_outcome="revenue",
3653
+ target_value=150000.0,
3654
+ max_realities=50
3655
+ )
3656
+
3657
+ print(f"Best reality: {explore_result['best_reality']}")
3658
+ print(f"Top 10 realities: {explore_result['top_10_realities']}")
3659
+ ```
3660
+
3661
+ ### Async Operations
3662
+
3663
+ ```python
3664
+ import asyncio
3665
+
3666
+ async def parallel_analysis():
3667
+ agent = CRCAAgent(variables=["x", "y", "z"])
3668
+
3669
+ # Run multiple analyses in parallel
3670
+ results = await asyncio.gather(
3671
+ agent.run_async(initial_state={"x": 1.0}, max_steps=2),
3672
+ agent.run_async(initial_state={"x": 2.0}, max_steps=2),
3673
+ agent.run_async(initial_state={"x": 3.0}, max_steps=2)
3674
+ )
3675
+
3676
+ return results
3677
+
3678
+ results = asyncio.run(parallel_analysis())
3679
+ ```
3680
+
3681
+ ---
3682
+
3683
+ ## Testing
3684
+
3685
+ The CR-CA framework includes a comprehensive test suite located in the `tests/` directory.
3686
+
3687
+ ### Test Files
3688
+
3689
+ - **test_core.py**: Core CRCAAgent functionality tests
3690
+ - Variable extraction tests
3691
+ - Causal graph construction tests
3692
+ - Prediction functionality tests
3693
+ - Counterfactual generation tests
3694
+ - Optimization method tests
3695
+ - Time-series analysis tests
3696
+ - Bayesian inference tests
3697
+ - Advanced analysis method tests
3698
+ - Cache behavior tests
3699
+ - Error handling tests
3700
+
3701
+ - **test_crca_sd.py**: CRCA-SD module tests
3702
+ - State vector tests
3703
+ - Control vector tests
3704
+ - Dynamics model tests
3705
+ - Constraint checker tests
3706
+ - Forward simulator tests
3707
+ - MPC solver tests
3708
+ - Scenario generator tests
3709
+ - Governance system tests
3710
+ - Real-time monitoring tests
3711
+
3712
+ - **sanity_check**: Sanity check script for basic functionality
3713
+ - Quick verification of core features
3714
+ - Import tests
3715
+ - Basic agent creation tests
3716
+
3717
+ - **sanity.yml**: GitHub Actions workflow for automated sanity checks
3718
+ - Runs on every push and pull request
3719
+ - Validates basic functionality
3720
+ - Checks import integrity
3721
+
3722
+ ### Running Tests
3723
+
3724
+ **Example 1: Run All Tests**
3725
+
3726
+ ```bash
3727
+ # Run all tests with verbose output
3728
+ pytest tests/ -v
3729
+
3730
+ # Run with coverage report
3731
+ pytest tests/ --cov=CRCA --cov-report=html
3732
+
3733
+ # Run with coverage and show missing lines
3734
+ pytest tests/ --cov=CRCA --cov-report=term-missing
3735
+ ```
3736
+
3737
+ **Example 2: Run Specific Test File**
3738
+
3739
+ ```bash
3740
+ # Run core tests only
3741
+ pytest tests/test_core.py -v
3742
+
3743
+ # Run CRCA-SD tests only
3744
+ pytest tests/test_crca_sd.py -v
3745
+
3746
+ # Run specific test class
3747
+ pytest tests/test_core.py::TestCRCAAgent -v
3748
+
3749
+ # Run specific test method
3750
+ pytest tests/test_core.py::TestCRCAAgent::test_variable_extraction -v
3751
+ ```
3752
+
3753
+ **Example 3: Run with Markers**
3754
+
3755
+ ```bash
3756
+ # Run only fast tests
3757
+ pytest tests/ -m "not slow" -v
3758
+
3759
+ # Run only integration tests
3760
+ pytest tests/ -m "integration" -v
3761
+
3762
+ # Run only unit tests
3763
+ pytest tests/ -m "unit" -v
3764
+ ```
3765
+
3766
+ **Example 4: Run Sanity Check**
3767
+
3768
+ ```bash
3769
+ # Run sanity check script
3770
+ python tests/sanity_check
3771
+
3772
+ # Or with pytest
3773
+ pytest tests/sanity_check -v
3774
+ ```
3775
+
3776
+ **Example 5: Run with Debugging**
3777
+
3778
+ ```bash
3779
+ # Run with print statements
3780
+ pytest tests/ -v -s
3781
+
3782
+ # Run with pdb on failure
3783
+ pytest tests/ --pdb
3784
+
3785
+ # Run with detailed traceback
3786
+ pytest tests/ -v --tb=long
3787
+ ```
3788
+
3789
+ ### Test Structure
3790
+
3791
+ Tests validate:
3792
+ - **Basic Functionality**: Core prediction, graph operations, variable extraction
3793
+ - **Cache Behavior**: Thread-safe caching, cache invalidation
3794
+ - **Graph Utilities**: DAG validation, topological sort, path finding
3795
+ - **Variable Extraction**: Automatic extraction from natural language
3796
+ - **Causal Analysis**: LLM-based analysis generation
3797
+ - **Integration**: Module integration (CRCA-SD, CRCA-CG, CRCA-Q)
3798
+ - **Error Handling**: Exception handling, edge cases
3799
+ - **Performance**: Batch prediction, async operations
3800
+ - **Optimization**: Gradient-based, Bellman optimization
3801
+ - **Time-Series**: Granger causality, VAR estimation
3802
+ - **Bayesian**: Posterior inference, credible intervals
3803
+ - **Advanced Analysis**: Sensitivity, root cause, Shapley values
3804
+
3805
+ ### Writing Tests
3806
+
3807
+ **Example 6: Writing a New Test**
3808
+
3809
+ ```python
3810
+ import pytest
3811
+ from CRCA import CRCAAgent
3812
+
3813
+ class TestNewFeature:
3814
+ """Test suite for new feature."""
3815
+
3816
+ def test_basic_functionality(self):
3817
+ """Test basic functionality of new feature."""
3818
+ agent = CRCAAgent(variables=["x", "y"])
3819
+ result = agent.run(initial_state={"x": 1.0, "y": 2.0})
3820
+ assert "evolved_state" in result
3821
+
3822
+ def test_edge_case(self):
3823
+ """Test edge case handling."""
3824
+ agent = CRCAAgent(variables=["x"])
3825
+ # Test with empty state
3826
+ result = agent.run(initial_state={})
3827
+ assert result is not None
3828
+
3829
+ @pytest.mark.slow
3830
+ def test_performance(self):
3831
+ """Test performance (marked as slow)."""
3832
+ agent = CRCAAgent(variables=["x", "y", "z"])
3833
+ # Performance test
3834
+ import time
3835
+ start = time.time()
3836
+ agent.run(initial_state={"x": 1.0, "y": 2.0, "z": 3.0})
3837
+ elapsed = time.time() - start
3838
+ assert elapsed < 1.0 # Should complete in < 1 second
3839
+ ```
3840
+
3841
+ ### Continuous Integration
3842
+
3843
+ Tests run automatically on:
3844
+ - Every push to main branch
3845
+ - Every pull request
3846
+ - Scheduled nightly builds
3847
+
3848
+ See `.github/workflows/` for CI/CD configuration.
3849
+
3850
+ ---
3851
+
3852
+ ## API Reference
3853
+
3854
+ ### CRCAAgent Core Methods
3855
+
3856
+ #### Initialization
3857
+
3858
+ ```python
3859
+ CRCAAgent(
3860
+ variables: Optional[List[str]] = None,
3861
+ causal_edges: Optional[List[Tuple[str, str]]] = None,
3862
+ max_loops: Optional[Union[int, str]] = 3,
3863
+ model_name: str = "gpt-4o",
3864
+ system_prompt: Optional[str] = None,
3865
+ enable_batch_predict: bool = False,
3866
+ max_batch_size: int = 32,
3867
+ bootstrap_workers: int = 0,
3868
+ use_async: bool = False,
3869
+ seed: Optional[int] = None,
3870
+ agent_max_loops: Optional[Union[int, str]] = None,
3871
+ **kwargs
3872
+ )
3873
+ ```
3874
+
3875
+ #### Core Methods
3876
+
3877
+ - `run(task=None, initial_state=None, target_variables=None, max_steps=1, **kwargs)`: Main entry point for causal analysis
3878
+ - `add_causal_relationship(source, target, strength=1.0, relation_type=DIRECT, confidence=1.0)`: Add causal edge
3879
+ - `get_nodes()`: Get all nodes in causal graph
3880
+ - `get_edges()`: Get all edges in causal graph
3881
+ - `is_dag()`: Check if graph is acyclic
3882
+ - `generate_counterfactual_scenarios(factual_state, target_variables, max_scenarios=5)`: Generate counterfactuals
3883
+
3884
+ #### Advanced Methods
3885
+
3886
+ - `gradient_based_intervention_optimization(...)`: Gradient optimization
3887
+ - `bellman_optimal_intervention(...)`: Dynamic programming optimization
3888
+ - `granger_causality_test(...)`: Granger causality testing
3889
+ - `vector_autoregression_estimation(...)`: VAR estimation
3890
+ - `bayesian_edge_inference(...)`: Bayesian inference
3891
+ - `sensitivity_analysis(...)`: Sensitivity analysis
3892
+ - `deep_root_cause_analysis(...)`: Root cause analysis
3893
+ - `shapley_value_attribution(...)`: Shapley value calculation
3894
+ - `multi_layer_whatif_analysis(...)`: Multi-layer analysis
3895
+ - `explore_alternate_realities(...)`: Reality exploration
3896
+
3897
+ #### Async Methods
3898
+
3899
+ - `run_async(...)`: Async run wrapper
3900
+ - `quantify_uncertainty_async(...)`: Async uncertainty quantification
3901
+ - `granger_causality_test_async(...)`: Async Granger test
3902
+ - `vector_autoregression_estimation_async(...)`: Async VAR estimation
3903
+
3904
+ ### Module APIs
3905
+
3906
+ See individual module documentation for detailed API references:
3907
+ - `utils/`: Formatter, TUI, router utilities
3908
+ - `tools/`: MCP client utilities
3909
+ - `templates/`: Agent creation framework
3910
+ - `crca_sd/`: Socioeconomic dynamics components
3911
+ - `crca_cg/`: Corporate governance components
3912
+
3913
+ ---
3914
+
3915
+ ## Architecture & Design
3916
+
3917
+ ### System Architecture
3918
+
3919
+ The CR-CA framework follows a modular architecture with clear separation of concerns:
3920
+
3921
+ ```
3922
+ ┌─────────────────────────────────────────────────────────┐
3923
+ │ Application Layer │
3924
+ │ (CRCA-SD, CRCA-CG, CRCA-Q) │
3925
+ └────────────────────┬────────────────────────────────────┘
3926
+
3927
+ ┌────────────────────▼────────────────────────────────────┐
3928
+ │ Core CRCAAgent │
3929
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
3930
+ │ │ LLM Analysis │ │ Deterministic│ │ Auto Extract │ │
3931
+ │ │ Engine │ │ Simulation │ │ Engine │ │
3932
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
3933
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
3934
+ │ │ Causal Graph │ │ Counterfact. │ │ Optimization │ │
3935
+ │ │ Management │ │ Generation │ │ Methods │ │
3936
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
3937
+ └────────────────────┬────────────────────────────────────┘
3938
+
3939
+ ┌────────────────────▼────────────────────────────────────┐
3940
+ │ Supporting Infrastructure │
3941
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
3942
+ │ │ Utils │ │ Tools │ │ Templates │ │
3943
+ │ │ (Formatter, │ │ (MCP) │ │ (Agents) │ │
3944
+ │ │ TUI, etc.) │ │ │ │ │ │
3945
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
3946
+ └────────────────────┬────────────────────────────────────┘
3947
+
3948
+ ┌────────────────────▼────────────────────────────────────┐
3949
+ │ External Dependencies │
3950
+ │ (swarms, litellm, rustworkx, numpy, pandas, scipy) │
3951
+ └─────────────────────────────────────────────────────────┘
3952
+ ```
3953
+
3954
+ ### Design Principles
3955
+
3956
+ 1. **Modularity**: Clear module boundaries with well-defined interfaces
3957
+ 2. **Extensibility**: Template system for creating specialized agents
3958
+ 3. **Flexibility**: Dual-mode operation (LLM and deterministic)
3959
+ 4. **Performance**: Batch prediction and async support for scalability
3960
+ 5. **Research-Focused**: Grounded in causal inference theory (Pearl's framework)
3961
+
3962
+ ### Data Flow
3963
+
3964
+ 1. **Input**: Task string or state dictionary
3965
+ 2. **Mode Detection**: Automatic selection of LLM or deterministic mode
3966
+ 3. **Variable Extraction**: Automatic extraction if graph is empty
3967
+ 4. **Analysis/Simulation**: LLM analysis or deterministic evolution
3968
+ 5. **Counterfactual Generation**: Generate scenarios from results
3969
+ 6. **Output**: Structured results with analysis and scenarios
3970
+
3971
+ ---
3972
+
3973
+ ## Research & Theory
3974
+
3975
+ ### Theoretical Foundations
3976
+
3977
+ CR-CA is grounded in Judea Pearl's causal hierarchy and structural causal models (SCMs):
3978
+
3979
+ 1. **Association**: Observing correlations (Level 1)
3980
+ 2. **Intervention**: Understanding effects of actions (Level 2)
3981
+ 3. **Counterfactuals**: Reasoning about what would have happened (Level 3)
3982
+
3983
+ ### Structural Causal Models
3984
+
3985
+ SCMs represent variables as nodes in a directed acyclic graph (DAG), where edges represent causal relationships. The framework implements:
3986
+
3987
+ - **Linear SCMs**: Standardized z-space evolution with linear relationships
3988
+ - **Non-linear SCMs**: Tanh activation and interaction terms for non-linear dynamics
3989
+ - **Do-Calculus**: Pearl's do-operator for intervention reasoning
3990
+ - **Counterfactual Reasoning**: Abduction-Action-Prediction (AAP) workflow
3991
+
3992
+ ### Causal Inference Methods
3993
+
3994
+ The framework implements various causal inference techniques:
3995
+
3996
+ - **Granger Causality**: Time-series causality testing
3997
+ - **Vector Autoregression**: Multi-variable time-series modeling
3998
+ - **Bayesian Inference**: Posterior estimation for edge strengths
3999
+ - **Sensitivity Analysis**: Perturbation-based sensitivity measures
4000
+ - **Shapley Values**: Fair attribution of variable contributions
4001
+
4002
+ ### Research Applications
4003
+
4004
+ CR-CA can be used for:
4005
+
4006
+ - **Causal Discovery**: Learning causal structures from data
4007
+ - **Policy Analysis**: Evaluating policy interventions
4008
+ - **Root Cause Analysis**: Identifying ultimate causes of problems
4009
+ - **Scenario Planning**: Exploring alternative futures
4010
+ - **Decision Support**: Causal reasoning for decision-making
4011
+
4012
+ ### Extending the Framework
4013
+
4014
+ Researchers can extend CR-CA by:
4015
+
4016
+ 1. **Creating Specialized Agents**: Using the template system
4017
+ 2. **Adding New Methods**: Implementing custom analysis methods
4018
+ 3. **Custom Optimization**: Implementing domain-specific optimizers
4019
+ 4. **Theoretical Extensions**: Adding new causal inference methods
4020
+
4021
+ ---
4022
+
4023
+ ## Prompts Directory
4024
+
4025
+ The `prompts/` directory contains system prompts for guiding LLM behavior in the CR-CA framework.
4026
+
4027
+ ### Default CRCA Prompt (`prompts/default_crca.py`)
4028
+
4029
+ The default system prompt for CRCAAgent provides comprehensive guidance on:
4030
+ - Tool usage instructions
4031
+ - Variable extraction guidance
4032
+ - Counterfactual generation guidance
4033
+ - Best practices for causal reasoning
4034
+
4035
+ **Example 1: Using Default Prompt**
4036
+
4037
+ ```python
4038
+ from CRCA import CRCAAgent
4039
+
4040
+ # Default prompt is automatically applied
4041
+ agent = CRCAAgent(model_name="gpt-4o-mini")
4042
+
4043
+ # The default prompt guides the LLM on:
4044
+ # - How to use extract_causal_variables tool
4045
+ # - How to use generate_causal_analysis tool
4046
+ # - When to extract variables vs. perform analysis
4047
+ # - Best practices for causal reasoning
4048
+ ```
4049
+
4050
+ **Example 2: Custom Prompt Override**
4051
+
4052
+ ```python
4053
+ from CRCA import CRCAAgent
4054
+
4055
+ # Custom prompt (appended to default)
4056
+ agent = CRCAAgent(
4057
+ model_name="gpt-4o-mini",
4058
+ system_prompt="You are an expert healthcare analyst. Focus on public health policy implications."
4059
+ )
4060
+
4061
+ # Default CRCA prompt is applied first, then custom prompt
4062
+ ```
4063
+
4064
+ **Example 3: Viewing Default Prompt**
4065
+
4066
+ ```python
4067
+ from prompts.default_crca import DEFAULT_CRCA_SYSTEM_PROMPT
4068
+
4069
+ # View the default prompt
4070
+ print(DEFAULT_CRCA_SYSTEM_PROMPT)
4071
+
4072
+ # Key sections:
4073
+ # - Tool usage instructions
4074
+ # - extract_causal_variables tool guide
4075
+ # - generate_causal_analysis tool guide
4076
+ # - Workflow guidance
4077
+ # - Best practices
4078
+ # - Common patterns
4079
+ ```
4080
+
4081
+ **Example 4: Prompt Customization for Domain**
4082
+
4083
+ ```python
4084
+ from CRCA import CRCAAgent
4085
+
4086
+ # Domain-specific prompt
4087
+ domain_prompt = """
4088
+ You are a financial analyst specializing in market causal relationships.
4089
+ When analyzing trading scenarios:
4090
+ - Focus on market microstructure effects
4091
+ - Consider regulatory impacts
4092
+ - Analyze liquidity relationships
4093
+ - Evaluate risk transmission mechanisms
4094
+ """
4095
+
4096
+ agent = CRCAAgent(
4097
+ model_name="gpt-4o-mini",
4098
+ system_prompt=domain_prompt
4099
+ )
4100
+
4101
+ # Agent now has domain-specific guidance
4102
+ result = agent.run("Analyze how interest rate changes affect stock prices")
4103
+ ```
4104
+
4105
+ ## Configuration & Customization
4106
+
4107
+ ### Agent Configuration
4108
+
4109
+ ```python
4110
+ agent = CRCAAgent(
4111
+ # Model configuration
4112
+ model_name="gpt-4o",
4113
+ system_prompt="Custom system prompt",
4114
+
4115
+ # Loop configuration
4116
+ max_loops=3, # Causal reasoning loops
4117
+ agent_max_loops=3, # Standard agent loops
4118
+
4119
+ # Performance configuration
4120
+ enable_batch_predict=True,
4121
+ max_batch_size=32,
4122
+ bootstrap_workers=4, # Parallel bootstrap sampling
4123
+
4124
+ # Reproducibility
4125
+ seed=42,
4126
+
4127
+ # Feature flags
4128
+ use_crca_tools=True, # Enable automatic extraction tools
4129
+ use_async=False
4130
+ )
4131
+ ```
4132
+
4133
+ ### System Prompt Customization
4134
+
4135
+ The default CRCA system prompt is automatically applied. Custom prompts are appended:
4136
+
4137
+ ```python
4138
+ agent = CRCAAgent(
4139
+ system_prompt="Your custom instructions here"
4140
+ # Default CRCA prompt is applied first, then custom prompt
4141
+ )
4142
+ ```
4143
+
4144
+ ### Feature Flags
4145
+
4146
+ - `use_crca_tools`: Enable/disable automatic variable extraction tools (default: True)
4147
+ - `enable_batch_predict`: Enable batch prediction mode (default: False)
4148
+ - `use_async`: Enable async operations (default: False)
4149
+
4150
+ ### Custom Specialized Agents
4151
+
4152
+ Using the template system:
4153
+
4154
+ ```python
4155
+ from templates.base_specialized_agent import BaseSpecializedAgent
4156
+ from templates.feature_mixins import GraphFeatureMixin, PredictionFeatureMixin
4157
+
4158
+ class MySpecializedAgent(BaseSpecializedAgent, GraphFeatureMixin, PredictionFeatureMixin):
4159
+ def __init__(self, **kwargs):
4160
+ super().__init__(**kwargs)
4161
+ self.init_graph_feature(variables=["A", "B", "C"])
4162
+ self.init_prediction_feature(use_nonlinear=True)
4163
+
4164
+ def _get_domain_schema(self):
4165
+ return {
4166
+ "type": "function",
4167
+ "function": {
4168
+ "name": "my_domain_tool",
4169
+ "description": "Domain-specific tool",
4170
+ "parameters": {...}
4171
+ }
4172
+ }
4173
+ ```
4174
+
4175
+ ---
4176
+
4177
+ ## Troubleshooting
4178
+
4179
+ ### Common Issues
4180
+
4181
+ #### Installation Problems
4182
+
4183
+ **Issue**: Import errors for rustworkx or other dependencies
4184
+
4185
+ **Solution**: Ensure all dependencies are installed:
4186
+ ```bash
4187
+ pip install -r requirements.txt
4188
+ ```
4189
+
4190
+ **Issue**: MCP-related import errors
4191
+
4192
+ **Solution**: MCP is an optional dependency. If not using MCP features, the framework will work without it.
4193
+
4194
+ #### LLM API Issues
4195
+
4196
+ **Issue**: API key not found
4197
+
4198
+ **Solution**: Set `OPENAI_API_KEY` environment variable or in `.env` file:
4199
+ ```bash
4200
+ export OPENAI_API_KEY=your_key_here
4201
+ ```
4202
+
4203
+ **Issue**: Rate limiting or timeout errors
4204
+
4205
+ **Solution**: Use a model with higher rate limits or implement retry logic. Consider using `gpt-4o-mini` for development.
4206
+
4207
+ #### Variable Extraction Failures
4208
+
4209
+ **Issue**: Automatic extraction returns empty graph
4210
+
4211
+ **Solution**:
4212
+ - Ensure the task clearly describes causal relationships
4213
+ - Check that `use_crca_tools=True` (default)
4214
+ - Verify LLM API key is set correctly
4215
+ - Try a more explicit task description
4216
+
4217
+ #### Performance Issues
4218
+
4219
+ **Issue**: Slow batch predictions
4220
+
4221
+ **Solution**:
4222
+ - Enable `enable_batch_predict=True`
4223
+ - Adjust `max_batch_size` based on available memory
4224
+ - Use `bootstrap_workers` for parallel operations
4225
+
4226
+ ### Debugging
4227
+
4228
+ #### Enable Debug Logging
4229
+
4230
+ ```python
4231
+ from loguru import logger
4232
+
4233
+ logger.add("debug.log", level="DEBUG")
4234
+ ```
4235
+
4236
+ #### Check Graph State
4237
+
4238
+ ```python
4239
+ print(f"Nodes: {agent.get_nodes()}")
4240
+ print(f"Edges: {agent.get_edges()}")
4241
+ print(f"Is DAG: {agent.is_dag()}")
4242
+ ```
4243
+
4244
+ #### Verify Tool Execution
4245
+
4246
+ ```python
4247
+ # Check if tools are registered
4248
+ print(f"Tools: {agent.tools}")
4249
+ print(f"Tool schemas: {agent.tools_list_dictionary}")
4250
+ ```
4251
+
4252
+ ---
4253
+
4254
+ ## Contributing
4255
+
4256
+ ### Development Setup
4257
+
4258
+ 1. Clone the repository
4259
+ 2. Install development dependencies:
4260
+ ```bash
4261
+ pip install -r requirements.txt
4262
+ pip install pytest black mypy
4263
+ ```
4264
+
4265
+ 3. Create a feature branch
4266
+ 4. Make changes following code style guidelines
4267
+ 5. Add tests for new functionality
4268
+ 6. Run tests: `pytest tests/ -v`
4269
+ 7. Submit a pull request
4270
+
4271
+ ### Code Style
4272
+
4273
+ - Follow PEP 8 style guidelines
4274
+ - Use type hints for all function signatures
4275
+ - Add docstrings to all classes and methods
4276
+ - Use `loguru` for logging (no `print` statements in production code)
4277
+ - Keep functions focused and modular
4278
+
4279
+ ### Testing Requirements
4280
+
4281
+ - All new features must include tests
4282
+ - Maintain or improve test coverage
4283
+ - Tests should be fast and isolated
4284
+ - Use fixtures for common setup
4285
+
4286
+ ### Documentation
4287
+
4288
+ - Update README.md for user-facing changes
4289
+ - Add docstrings for all public APIs
4290
+ - Include usage examples for new features
4291
+ - Update changelog for significant changes
4292
+
4293
+ ---
4294
+
4295
+ ## Changelog
4296
+
4297
+ ### v1.4.0 (Current)
4298
+
4299
+ - **Comprehensive Documentation Overhaul**: Complete README rewrite with 100+ code examples
4300
+ - **Policy Engine System Documentation**: Full documentation with 21+ examples covering DoctrineV1, Ledger, Rollback, PolicyLoop, MPC, Drift Detection, Sensors, and Actuators
4301
+ - **Expanded Module Documentation**: Extensive examples for Utils (15+), Tools (15+), Templates (12+), Schemas, and Prompts
4302
+ - **Architecture Diagrams**: Added system architecture, policy engine flow, and data flow diagrams
4303
+ - **Integration Examples**: Added 5 comprehensive integration examples
4304
+ - **CI/CD Documentation**: Added GitHub Actions workflows documentation
4305
+ - **Project Structure**: Added comprehensive directory structure documentation
4306
+ - **Bolt.diy Documentation**: Added WIP section for web application
4307
+
4308
+ ### v1.3.0
4309
+
4310
+ - **Automatic Variable Extraction**: Major feature allowing automatic extraction of variables and causal relationships from natural language tasks
4311
+ - **Enhanced LLM Integration**: Improved tool execution and ML-based extraction methods
4312
+ - **Module Expansions**: Comprehensive updates to all modules (utils, tools, templates, schemas)
4313
+ - **Integration Improvements**: Better integration patterns for CRCA-SD, CRCA-CG, and CRCA-Q
4314
+ - **Documentation**: Initial README improvements
4315
+
4316
+ ### v1.2.0
4317
+
4318
+ - **Advanced Analysis Suite**:
4319
+ - Batch prediction with vectorized operations
4320
+ - Async/await support for concurrent operations
4321
+ - Optimization methods (gradient-based, Bellman dynamic programming)
4322
+ - Time-series analysis (Granger causality, VAR estimation)
4323
+ - Bayesian inference with credible intervals
4324
+ - Information-theoretic measures
4325
+ - Advanced analysis (sensitivity, root cause, Shapley values, multi-layer what-if, reality exploration)
4326
+ - **Performance Improvements**: Parallel bootstrap sampling, reproducible randomness
4327
+ - **Code Optimization**: Reduced file size while maintaining functionality
4328
+
4329
+ ### v1.1.0
4330
+
4331
+ - **Production Hardening**:
4332
+ - Thread-safe prediction cache with lock protection
4333
+ - Requirements.txt pin list for CI
4334
+ - GitHub Actions sanity workflow
4335
+ - Pytest smoke tests
4336
+ - Cache lock documentation
4337
+
4338
+ ### v1.0.0
4339
+
4340
+ - **Initial Release**:
4341
+ - Core CRCAAgent with LLM integration
4342
+ - Causal DAG management
4343
+ - Linear SCM evolution
4344
+ - Counterfactual generation
4345
+ - Basic deterministic simulation
4346
+
4347
+ ---
4348
+
4349
+ ## CI/CD Workflows
4350
+
4351
+ The CR-CA framework includes GitHub Actions workflows for automated testing and publishing.
4352
+
4353
+ ### Automated Testing
4354
+
4355
+ **Workflow**: `.github/workflows/sanity.yml`
4356
+
4357
+ - Runs on every push and pull request
4358
+ - Validates basic functionality
4359
+ - Checks import integrity
4360
+ - Fast feedback loop for developers
4361
+
4362
+ **Example: Viewing Test Results**
4363
+
4364
+ ```bash
4365
+ # Tests run automatically on GitHub
4366
+ # View results in the "Actions" tab of the repository
4367
+ ```
4368
+
4369
+ ### PyPI Publishing
4370
+
4371
+ **Workflow 1: Trusted Publishing** (`.github/workflows/publish.yml`)
4372
+
4373
+ Uses PyPI trusted publishing (OIDC) for secure, token-free publishing.
4374
+
4375
+ **Trigger:**
4376
+ - Automatic: On GitHub release publication
4377
+ - Manual: Via workflow_dispatch with version input
4378
+
4379
+ **Example: Manual Publishing**
4380
+
4381
+ 1. Go to GitHub Actions → "Publish to PyPI"
4382
+ 2. Click "Run workflow"
4383
+ 3. Enter version (e.g., "1.4.0")
4384
+ 4. Optionally check "Publish to TestPyPI"
4385
+ 5. Click "Run workflow"
4386
+
4387
+ **Workflow 2: Manual with API Token** (`.github/workflows/publish-manual.yml`)
4388
+
4389
+ Uses PyPI API token stored in GitHub Secrets.
4390
+
4391
+ **Setup:**
4392
+ 1. Create PyPI API token at https://pypi.org/manage/account/token/
4393
+ 2. Add token to GitHub Secrets as `PYPI_API_TOKEN`
4394
+ 3. For TestPyPI, add `TEST_PYPI_API_TOKEN`
4395
+
4396
+ **Example: Publishing Process**
4397
+
4398
+ ```bash
4399
+ # Workflow automatically:
4400
+ # 1. Checks out code
4401
+ # 2. Sets up Python 3.11
4402
+ # 3. Installs build dependencies (build, twine)
4403
+ # 4. Verifies no .env files are present
4404
+ # 5. Builds package (python -m build)
4405
+ # 6. Publishes to PyPI or TestPyPI
4406
+ ```
4407
+
4408
+ **Example: Local Publishing (for testing)**
4409
+
4410
+ ```bash
4411
+ # Install build tools
4412
+ pip install build twine
4413
+
4414
+ # Build package
4415
+ python -m build
4416
+
4417
+ # Upload to TestPyPI (for testing)
4418
+ twine upload --repository testpypi dist/*
4419
+
4420
+ # Upload to PyPI (production)
4421
+ twine upload dist/*
4422
+ ```
4423
+
4424
+ ### Workflow Configuration
4425
+
4426
+ **Example: Custom Workflow**
4427
+
4428
+ ```yaml
4429
+ name: Custom Workflow
4430
+
4431
+ on:
4432
+ push:
4433
+ branches: [main]
4434
+ pull_request:
4435
+ branches: [main]
4436
+
4437
+ jobs:
4438
+ test:
4439
+ runs-on: ubuntu-latest
4440
+ steps:
4441
+ - uses: actions/checkout@v4
4442
+ - uses: actions/setup-python@v5
4443
+ with:
4444
+ python-version: '3.11'
4445
+ - run: pip install -r requirements.txt
4446
+ - run: pytest tests/ -v
4447
+ ```
4448
+
4449
+ ## Project Structure
4450
+
4451
+ ```
4452
+ CR-CA/
4453
+ ├── CRCA.py # Core CRCAAgent implementation
4454
+ ├── branches/
4455
+ │ ├── CRCA-Q.py # Quantitative trading agent
4456
+ │ └── crca_cg/ # Corporate governance module
4457
+ │ ├── corposwarm.py # CorporateSwarm implementation
4458
+ │ └── ...
4459
+ │ └── crca_sd/ # Socioeconomic dynamics module
4460
+ │ ├── crca_sd_core.py
4461
+ │ ├── crca_sd_mpc.py
4462
+ │ ├── crca_sd_governance.py
4463
+ │ └── crca_sd_realtime.py
4464
+ ├── utils/ # Utility modules
4465
+ │ ├── agent.py # Extended agent functionality
4466
+ │ ├── formatter.py # Markdown formatting
4467
+ │ ├── tui.py # Terminal UI (CorporateSwarmTUI)
4468
+ │ ├── router.py # Swarm router
4469
+ │ ├── HHCS.py # Hybrid Hierarchical-Cluster Swarm
4470
+ │ ├── aop.py # Agent Orchestration Platform
4471
+ │ ├── ledger.py # Event-sourced ledger
4472
+ │ ├── rollback.py # Rollback manager
4473
+ │ ├── canonical.py # Deterministic hashing
4474
+ │ ├── conversation.py # Conversation management
4475
+ │ ├── Agent_types.py # Type definitions
4476
+ │ ├── AnyToStr.py # Type conversion
4477
+ │ └── out_types.py # Output type definitions
4478
+ ├── tools/ # External tool integrations
4479
+ │ ├── mcpClientUtils.py # MCP client utilities
4480
+ │ ├── actuators.py # Intervention actuators
4481
+ │ ├── sensors.py # Metric sensors
4482
+ │ ├── code_generator.py # Code generation tools
4483
+ │ ├── mandate_generator.py # Proposal to mandate conversion
4484
+ │ ├── file_operations.py # File manipulation tools
4485
+ │ └── bolt.diy/ # Web application (WIP)
4486
+ ├── templates/ # Agent creation framework
4487
+ │ ├── base_specialized_agent.py
4488
+ │ ├── feature_mixins.py
4489
+ │ ├── module_registry.py
4490
+ │ ├── graph_management.py
4491
+ │ ├── prediction_framework.py
4492
+ │ ├── statistical_methods.py
4493
+ │ ├── llm_integration.py
4494
+ │ ├── policy_loop.py # Policy loop mixin
4495
+ │ ├── mpc_planner.py # MPC planner
4496
+ │ ├── drift_detection.py # Drift detection
4497
+ │ └── examples/ # Example templates
4498
+ │ ├── causal_agent_template.py
4499
+ │ ├── drag_drop_example.py
4500
+ │ ├── logistics_agent_template.py
4501
+ │ └── trading_agent_template.py
4502
+ ├── schemas/ # Type definitions
4503
+ │ ├── mcpSchemas.py # MCP schemas
4504
+ │ └── policy.py # Policy schemas
4505
+ ├── prompts/ # System prompts
4506
+ │ └── default_crca.py # Default CRCA prompt
4507
+ ├── examples/ # Usage examples
4508
+ │ ├── crca_sd_example.py
4509
+ │ ├── logistics_corporation.py
4510
+ │ ├── policy_bench.py
4511
+ │ ├── pridnestrovia_realtime.py
4512
+ │ ├── pridnestrovia-sd.py
4513
+ │ └── config.yaml.example
4514
+ ├── tests/ # Test suite
4515
+ │ ├── test_core.py
4516
+ │ ├── test_crca_sd.py
4517
+ │ ├── sanity_check
4518
+ │ └── sanity.yml
4519
+ ├── docs/ # Documentation
4520
+ │ └── CRCA-Q.md
4521
+ ├── .github/
4522
+ │ └── workflows/ # CI/CD workflows
4523
+ │ ├── publish.yml
4524
+ │ └── publish-manual.yml
4525
+ ├── requirements.txt # Python dependencies
4526
+ ├── pyproject.toml # Project metadata
4527
+ ├── LICENSE # Apache-2.0 license
4528
+ └── README.md # This file
4529
+ ```
4530
+
4531
+ ## Architecture Diagrams
4532
+
4533
+ ### System Architecture
4534
+
4535
+ ```
4536
+ ┌─────────────────────────────────────────────────────────────┐
4537
+ │ Application Layer │
4538
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
4539
+ │ │ CRCA-SD │ │ CRCA-CG │ │ CRCA-Q │ │
4540
+ │ │ (Socioecon) │ │ (Corporate) │ │ (Trading) │ │
4541
+ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
4542
+ └─────────┼─────────────────┼─────────────────┼─────────────┘
4543
+ │ │ │
4544
+ ┌─────────▼─────────────────▼─────────────────▼─────────────┐
4545
+ │ Core CRCAAgent │
4546
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
4547
+ │ │ LLM Analysis │ │ Deterministic│ │ Auto Extract │ │
4548
+ │ │ Engine │ │ Simulation │ │ Engine │ │
4549
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
4550
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
4551
+ │ │ Causal Graph │ │ Counterfact. │ │ Optimization │ │
4552
+ │ │ Management │ │ Generation │ │ Methods │ │
4553
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
4554
+ └─────────┬───────────────────────────────────────────────────┘
4555
+
4556
+ ┌─────────▼───────────────────────────────────────────────────┐
4557
+ │ Policy Engine System │
4558
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
4559
+ │ │ Doctrine │ │ Ledger │ │ Rollback │ │
4560
+ │ │ (Policy) │ │ (Audit) │ │ (Recovery) │ │
4561
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
4562
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
4563
+ │ │ Policy Loop │ │ MPC Planner │ │ Drift │ │
4564
+ │ │ (Execution) │ │ (Optimization)│ │ Detection │ │
4565
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
4566
+ │ ┌──────────────┐ ┌──────────────┐ │
4567
+ │ │ Sensors │ │ Actuators │ │
4568
+ │ │ (Metrics) │ │(Interventions)│ │
4569
+ │ └──────────────┘ └──────────────┘ │
4570
+ └─────────┬───────────────────────────────────────────────────┘
4571
+
4572
+ ┌─────────▼───────────────────────────────────────────────────┐
4573
+ │ Supporting Infrastructure │
4574
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
4575
+ │ │ Utils │ │ Tools │ │ Templates │ │
4576
+ │ │ (Router, │ │ (MCP, │ │ (Agents, │ │
4577
+ │ │ TUI, etc.) │ │ Actuators) │ │ Mixins) │ │
4578
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
4579
+ └─────────┬───────────────────────────────────────────────────┘
4580
+
4581
+ ┌─────────▼───────────────────────────────────────────────────┐
4582
+ │ External Dependencies │
4583
+ │ (swarms, litellm, rustworkx, numpy, pandas, scipy, etc.) │
4584
+ └──────────────────────────────────────────────────────────────┘
4585
+ ```
4586
+
4587
+ ### Policy Engine Flow
4588
+
4589
+ ```
4590
+ ┌─────────────┐
4591
+ │ Doctrine │ (Policy Specification)
4592
+ └──────┬──────┘
4593
+
4594
+
4595
+ ┌─────────────┐
4596
+ │ Compiled │ (Normalized Policy)
4597
+ │ Policy │
4598
+ └──────┬──────┘
4599
+
4600
+
4601
+ ┌─────────────────────────────────────┐
4602
+ │ Policy Loop (Epoch) │
4603
+ │ ┌──────────┐ │
4604
+ │ │ Observe │ ← Sensors │
4605
+ │ └────┬─────┘ │
4606
+ │ │ │
4607
+ │ ▼ │
4608
+ │ ┌──────────┐ │
4609
+ │ │ Plan │ ← MPC Planner │
4610
+ │ └────┬─────┘ │
4611
+ │ │ │
4612
+ │ ▼ │
4613
+ │ ┌──────────┐ │
4614
+ │ │ Act │ → Actuators │
4615
+ │ └────┬─────┘ │
4616
+ │ │ │
4617
+ │ ▼ │
4618
+ │ ┌──────────┐ │
4619
+ │ │ Update │ → Online Learning │
4620
+ │ └────┬─────┘ │
4621
+ └───────┼─────────────────────────────┘
4622
+
4623
+
4624
+ ┌─────────────┐
4625
+ │ Ledger │ (Event Store)
4626
+ └─────────────┘
4627
+ ```
4628
+
4629
+ ### Data Flow
4630
+
4631
+ ```
4632
+ Input (Task/State)
4633
+
4634
+
4635
+ Mode Detection (LLM vs Deterministic)
4636
+
4637
+ ├─→ LLM Mode ──→ Auto Extraction ──→ Causal Analysis ──→ Counterfactuals
4638
+
4639
+ └─→ Deterministic Mode ──→ Standardize ──→ SCM Evolution ──→ Counterfactuals
4640
+
4641
+
4642
+ Output (Results)
4643
+ ```
4644
+
4645
+ ## Integration Examples
4646
+
4647
+ ### Example 1: CRCA + CRCA-SD Integration
4648
+
4649
+ ```python
4650
+ from CRCA import CRCAAgent
4651
+ from crca_sd import get_crca_agent, StateVector
4652
+ from crca_sd.crca_sd_mpc import MPCSolver
4653
+
4654
+ # Create CRCA agent
4655
+ crca = get_crca_agent(
4656
+ variables=['GDP', 'unemployment', 'inflation'],
4657
+ model_name="gpt-4o-mini"
4658
+ )
4659
+
4660
+ # Create state vector
4661
+ state = StateVector(GDP=1000.0, unemployment=5.0, inflation=2.0)
4662
+
4663
+ # Use CRCA for causal scenario generation in MPC
4664
+ solver = MPCSolver(crca_agent=crca)
4665
+ solution = solver.solve(initial_state=state, use_causal_scenarios=True)
4666
+ ```
4667
+
4668
+ ### Example 2: CRCA + CRCA-CG Integration
4669
+
4670
+ ```python
4671
+ from CRCA import CRCAAgent
4672
+ from crca_cg.corposwarm import CorporateSwarm
4673
+
4674
+ # Create CRCA agent for policy analysis
4675
+ crca = CRCAAgent(
4676
+ variables=['revenue', 'costs', 'employee_satisfaction'],
4677
+ model_name="gpt-4o"
4678
+ )
4679
+
4680
+ # Create CorporateSwarm with CRCA
4681
+ swarm = CorporateSwarm(crca_agent=crca)
4682
+
4683
+ # Analyze policy impact using causal reasoning
4684
+ result = swarm.analyze_policy_impact(
4685
+ policy_description="Increase R&D spending by 20%",
4686
+ use_causal_analysis=True
4687
+ )
4688
+ ```
4689
+
4690
+ ### Example 3: CRCA-Q + CorporateSwarm Integration
4691
+
4692
+ ```python
4693
+ from crca_cg.corposwarm import CorporateSwarm
4694
+
4695
+ # Create swarm with CRCA-Q integration
4696
+ swarm = CorporateSwarm(
4697
+ enable_crca_q=True,
4698
+ crca_q_config={
4699
+ 'account_size': 1000000,
4700
+ 'conservative_mode': True
4701
+ }
4702
+ )
4703
+
4704
+ # Investment Committee uses CRCA-Q for trading decisions
4705
+ investment_decision = swarm.investment_committee.recommend_allocation()
4706
+ ```
4707
+
4708
+ ### Example 4: Policy Engine + CorporateSwarm Integration
4709
+
4710
+ ```python
4711
+ from schemas.policy import DoctrineV1
4712
+ from templates.policy_loop import PolicyLoopMixin
4713
+ from utils.ledger import Ledger
4714
+ from crca_cg.corposwarm import CorporateSwarm
4715
+
4716
+ # Create doctrine
4717
+ doctrine = DoctrineV1.from_json("corporate_policy.json")
4718
+
4719
+ # Create ledger
4720
+ ledger = Ledger(db_path="corporate_ledger.db")
4721
+
4722
+ # Create policy agent
4723
+ policy_agent = PolicyLoopMixin(doctrine, ledger, seed=42)
4724
+
4725
+ # Create corporate swarm
4726
+ swarm = CorporateSwarm()
4727
+
4728
+ # Integrate policy engine with corporate governance
4729
+ # Policy decisions can inform corporate proposals
4730
+ result = policy_agent.run_epoch(epoch=1)
4731
+ proposal = swarm.create_proposal(
4732
+ title="Policy-driven initiative",
4733
+ description=f"Based on policy analysis: {result['rationale']}"
4734
+ )
4735
+ ```
4736
+
4737
+ ### Example 5: Multiple Components Working Together
4738
+
4739
+ ```python
4740
+ from CRCA import CRCAAgent
4741
+ from crca_sd import get_crca_agent, StateVector
4742
+ from crca_sd.crca_sd_mpc import MPCSolver
4743
+ from crca_cg.corposwarm import CorporateSwarm
4744
+ from schemas.policy import DoctrineV1
4745
+ from templates.policy_loop import PolicyLoopMixin
4746
+ from utils.ledger import Ledger
4747
+
4748
+ # 1. Create CRCA agent for causal reasoning
4749
+ crca = CRCAAgent(
4750
+ variables=['revenue', 'costs', 'market_share'],
4751
+ model_name="gpt-4o-mini"
4752
+ )
4753
+
4754
+ # 2. Create CRCA-SD solver with CRCA
4755
+ sd_crca = get_crca_agent(variables=['GDP', 'unemployment'], model_name="gpt-4o-mini")
4756
+ solver = MPCSolver(crca_agent=sd_crca)
4757
+
4758
+ # 3. Create CorporateSwarm with CRCA
4759
+ swarm = CorporateSwarm(
4760
+ crca_agent=crca,
4761
+ enable_crca_q=True,
4762
+ enable_crca_sd=True
4763
+ )
4764
+
4765
+ # 4. Create policy engine
4766
+ doctrine = DoctrineV1.from_json("policy.json")
4767
+ ledger = Ledger(db_path="ledger.db")
4768
+ policy_agent = PolicyLoopMixin(doctrine, ledger, seed=42)
4769
+
4770
+ # 5. Integrated workflow
4771
+ # - Policy engine makes decisions
4772
+ policy_result = policy_agent.run_epoch(epoch=1)
4773
+
4774
+ # - CorporateSwarm analyzes impact
4775
+ impact = swarm.analyze_policy_impact(
4776
+ policy_description=policy_result['rationale'],
4777
+ use_causal_analysis=True
4778
+ )
4779
+
4780
+ # - CRCA-SD optimizes scenarios
4781
+ state = StateVector(GDP=1000.0, unemployment=5.0)
4782
+ solution = solver.solve(initial_state=state, use_causal_scenarios=True)
4783
+
4784
+ print(f"Policy decision: {policy_result['interventions']}")
4785
+ print(f"Corporate impact: {impact}")
4786
+ print(f"Optimized solution: {solution}")
4787
+ ```
4788
+
4789
+ ## References & Resources
4790
+
4791
+ ### Academic References
4792
+
4793
+ - Pearl, J. (2009). *Causality: Models, Reasoning, and Inference* (2nd ed.). Cambridge University Press.
4794
+ - Pearl, J., & Mackenzie, D. (2018). *The Book of Why: The New Science of Cause and Effect*. Basic Books.
4795
+ - Spirtes, P., Glymour, C., & Scheines, R. (2000). *Causation, Prediction, and Search* (2nd ed.). MIT Press.
4796
+ - Peters, J., Janzing, D., & Schölkopf, B. (2017). *Elements of Causal Inference: Foundations and Learning Algorithms*. MIT Press.
4797
+
4798
+ ### Framework Documentation
4799
+
4800
+ - **Swarms Framework**: [https://github.com/kyegomez/swarms](https://github.com/kyegomez/swarms)
4801
+ - **LiteLLM**: [https://github.com/BerriAI/litellm](https://github.com/BerriAI/litellm)
4802
+ - **RustworkX**: [https://github.com/Qiskit/rustworkx](https://github.com/Qiskit/rustworkx)
4803
+
4804
+ ### Additional Resources
4805
+
4806
+ - **CRCA-Q Documentation**: See `docs/CRCA-Q.md` for quantitative trading details
4807
+ - **Template Guide**: See `templates/TEMPLATE_GUIDE.md` for agent creation patterns
4808
+
4809
+ ### Community
4810
+
4811
+ - **GitHub Repository**: [https://github.com/IlumCI/CR-CA](https://github.com/IlumCI/CR-CA)
4812
+ - **Issues**: Report bugs and request features via GitHub Issues
4813
+ - **Discussions**: Join discussions about causal reasoning and framework usage
4814
+
4815
+ ---
4816
+
4817
+ ## Bolt.diy Web Application (WIP)
4818
+
4819
+ **Status**: Work In Progress
4820
+ **Location**: `tools/bolt.diy/`
4821
+
4822
+ Bolt.diy is a full-stack web application and IDE built with Remix, React, TypeScript, and Electron. It provides an in-browser development environment with AI agent integration, code generation, and autonomous execution capabilities.
4823
+
4824
+ ### Overview
4825
+
4826
+ Bolt.diy combines:
4827
+ - **WebContainer**: In-browser Node.js runtime for code execution
4828
+ - **AI Agent Integration**: Multiple LLM providers for code generation and assistance
4829
+ - **Code Editor**: CodeMirror-based editor with syntax highlighting
4830
+ - **Git Integration**: Version control within the browser
4831
+ - **Supabase Integration**: Backend services and database
4832
+ - **Deployment**: Netlify/Vercel deployment support
4833
+ - **Execution Services**: Execution Governor and Headless Executor
4834
+ - **MCP Integration**: Model Context Protocol for tool execution
4835
+ - **Electron Support**: Desktop application packaging
4836
+ - **Docker Deployment**: Containerized deployment option
4837
+ - **WebSocket Support**: Real-time communication
4838
+ - **Mandate System**: Execution mandates from corporate proposals
4839
+ - **Observability**: Dashboard for monitoring and metrics
4840
+
4841
+ ### Architecture
4842
+
4843
+ **Frontend:**
4844
+ - **Framework**: Remix (React SSR)
4845
+ - **Language**: TypeScript
4846
+ - **Styling**: SCSS/CSS
4847
+ - **UI Components**: Custom components with modern design
4848
+ - **State Management**: React hooks and context
4849
+
4850
+ **Backend:**
4851
+ - **Runtime**: WebContainer API (in-browser Node.js)
4852
+ - **Services**: Execution Governor, Headless Executor
4853
+ - **Database**: Supabase (PostgreSQL)
4854
+ - **Deployment**: Cloudflare Pages, Netlify, Vercel
4855
+
4856
+ **Desktop:**
4857
+ - **Framework**: Electron
4858
+ - **Build**: electron-builder
4859
+ - **Platforms**: Windows, macOS, Linux
4860
+
4861
+ ### Key Features
4862
+
4863
+ **1. WebContainer-Based Execution**
4864
+
4865
+ ```typescript
4866
+ // Example: Running code in WebContainer
4867
+ import { WebContainer } from '@webcontainer/api';
4868
+
4869
+ const container = await WebContainer.boot();
4870
+ await container.mount(filesystem);
4871
+
4872
+ // Execute code
4873
+ const process = await container.spawn('npm', ['run', 'dev']);
4874
+ ```
4875
+
4876
+ **2. AI Agent Integration**
4877
+
4878
+ ```typescript
4879
+ // Example: AI agent for code generation
4880
+ import { Agent } from '@bolt/agent';
4881
+
4882
+ const agent = new Agent({
4883
+ provider: 'openai',
4884
+ model: 'gpt-4o-mini'
4885
+ });
4886
+
4887
+ const code = await agent.generateCode({
4888
+ specification: 'Create a React component for a todo list',
4889
+ language: 'typescript'
4890
+ });
4891
+ ```
4892
+
4893
+ **3. Mandate-Based Execution**
4894
+
4895
+ ```typescript
4896
+ // Example: Converting corporate proposal to execution mandate
4897
+ import { proposalToMandate } from '@bolt/mandate';
4898
+
4899
+ const mandate = proposalToMandate({
4900
+ proposal: corporateProposal,
4901
+ objectives: ['build_api', 'deploy_service'],
4902
+ budget: 50000,
4903
+ constraints: ['use_typescript', 'deploy_to_cloud']
4904
+ });
4905
+
4906
+ // Execute mandate
4907
+ await executeMandate(mandate);
4908
+ ```
4909
+
4910
+ **4. MCP Integration**
4911
+
4912
+ ```typescript
4913
+ // Example: MCP tool execution
4914
+ import { MCPClient } from '@bolt/mcp';
4915
+
4916
+ const client = new MCPClient({
4917
+ serverUrl: 'http://localhost:8000'
4918
+ });
4919
+
4920
+ const result = await client.executeTool('analyze_code', {
4921
+ code: sourceCode,
4922
+ language: 'typescript'
4923
+ });
4924
+ ```
4925
+
4926
+ ### Project Structure
4927
+
4928
+ ```
4929
+ tools/bolt.diy/
4930
+ ├── app/ # Remix application
4931
+ │ ├── components/ # React components
4932
+ │ ├── routes/ # Remix routes
4933
+ │ ├── lib/ # Shared libraries
4934
+ │ ├── utils/ # Utility functions
4935
+ │ └── types/ # TypeScript types
4936
+ ├── electron/ # Electron desktop app
4937
+ │ ├── main/ # Main process
4938
+ │ └── preload/ # Preload scripts
4939
+ ├── services/ # Backend services
4940
+ │ ├── execution-governor/ # Execution governance
4941
+ │ └── headless-executor/ # Headless execution
4942
+ ├── public/ # Static assets
4943
+ ├── scripts/ # Build scripts
4944
+ ├── tests/ # Test files
4945
+ ├── docker-compose.yaml # Docker Compose config
4946
+ ├── Dockerfile # Docker build config
4947
+ ├── electron-builder.yml # Electron build config
4948
+ └── package.json # Dependencies
4949
+ ```
4950
+
4951
+ ### Dependencies
4952
+
4953
+ **Core:**
4954
+ - `remix`: React SSR framework
4955
+ - `react`: UI library
4956
+ - `typescript`: Type safety
4957
+ - `@webcontainer/api`: In-browser Node.js runtime
4958
+ - `@modelcontextprotocol/sdk`: MCP SDK
4959
+ - `electron`: Desktop app framework
4960
+
4961
+ **Services:**
4962
+ - `@supabase/supabase-js`: Backend services
4963
+ - `@remix-run/node`: Server-side Remix
4964
+ - `@remix-run/react`: Client-side Remix
4965
+
4966
+ **Development:**
4967
+ - `vite`: Build tool
4968
+ - `eslint`: Linting
4969
+ - `playwright`: Testing
4970
+ - `typescript`: Type checking
4971
+
4972
+ ### Setup (WIP)
4973
+
4974
+ **Note**: Bolt.diy is currently under active development. Setup instructions will be provided once stable.
4975
+
4976
+ **Planned Setup Steps:**
4977
+
4978
+ 1. Install dependencies:
4979
+ ```bash
4980
+ cd tools/bolt.diy
4981
+ pnpm install
4982
+ ```
4983
+
4984
+ 2. Configure environment variables:
4985
+ ```bash
4986
+ cp .env.example .env
4987
+ # Edit .env with your API keys
4988
+ ```
4989
+
4990
+ 3. Start development server:
4991
+ ```bash
4992
+ pnpm dev
4993
+ ```
4994
+
4995
+ 4. Build for production:
4996
+ ```bash
4997
+ pnpm build
4998
+ ```
4999
+
5000
+ 5. Package Electron app:
5001
+ ```bash
5002
+ pnpm electron:build
5003
+ ```
5004
+
5005
+ ### Current Limitations
5006
+
5007
+ - **Status**: Work In Progress
5008
+ - **Documentation**: Incomplete
5009
+ - **Testing**: Limited test coverage
5010
+ - **Deployment**: Not production-ready
5011
+ - **Features**: Some features may be incomplete or unstable
5012
+
5013
+ ### Future Plans
5014
+
5015
+ - Complete WebContainer integration
5016
+ - Full MCP protocol support
5017
+ - Enhanced AI agent capabilities
5018
+ - Improved observability dashboard
5019
+ - Production deployment guides
5020
+ - Comprehensive documentation
5021
+ - Extended test coverage
5022
+
5023
+ ### Contributing
5024
+
5025
+ Contributions to Bolt.diy are welcome, but please note:
5026
+ - The project is in active development
5027
+ - APIs may change without notice
5028
+ - Some features may be experimental
5029
+ - Documentation may be incomplete
5030
+
5031
+ For questions or contributions, please open an issue or pull request on GitHub.
5032
+
5033
+ ---
5034
+
5035
+ **CR-CA Framework** — Enabling causal reasoning and counterfactual analysis for research and practical applications.