aiox-core 5.0.3 → 5.0.4

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 (468) hide show
  1. package/.aiox-core/core/execution/predictive-pipeline.js +1283 -0
  2. package/.aiox-core/core/memory/decision-memory.js +564 -0
  3. package/.aiox-core/data/entity-registry.yaml +1068 -1028
  4. package/.aiox-core/data/registry-update-log.jsonl +2 -2
  5. package/.aiox-core/development/templates/service-template/README.md.hbs +158 -158
  6. package/.aiox-core/development/templates/service-template/__tests__/index.test.ts.hbs +237 -237
  7. package/.aiox-core/development/templates/service-template/client.ts.hbs +403 -403
  8. package/.aiox-core/development/templates/service-template/errors.ts.hbs +182 -182
  9. package/.aiox-core/development/templates/service-template/index.ts.hbs +120 -120
  10. package/.aiox-core/development/templates/service-template/package.json.hbs +87 -87
  11. package/.aiox-core/development/templates/service-template/types.ts.hbs +145 -145
  12. package/.aiox-core/development/templates/squad-template/LICENSE +21 -21
  13. package/.aiox-core/infrastructure/templates/aiox-sync.yaml.template +182 -182
  14. package/.aiox-core/infrastructure/templates/coderabbit.yaml.template +279 -279
  15. package/.aiox-core/infrastructure/templates/github-workflows/ci.yml.template +169 -169
  16. package/.aiox-core/infrastructure/templates/github-workflows/pr-automation.yml.template +330 -330
  17. package/.aiox-core/infrastructure/templates/github-workflows/release.yml.template +196 -196
  18. package/.aiox-core/infrastructure/templates/gitignore/gitignore-aiox-base.tmpl +63 -63
  19. package/.aiox-core/infrastructure/templates/gitignore/gitignore-brownfield-merge.tmpl +18 -18
  20. package/.aiox-core/infrastructure/templates/gitignore/gitignore-node.tmpl +85 -85
  21. package/.aiox-core/infrastructure/templates/gitignore/gitignore-python.tmpl +145 -145
  22. package/.aiox-core/install-manifest.yaml +63 -55
  23. package/.aiox-core/local-config.yaml.template +71 -71
  24. package/.aiox-core/monitor/hooks/lib/__init__.py +1 -1
  25. package/.aiox-core/monitor/hooks/lib/enrich.py +58 -58
  26. package/.aiox-core/monitor/hooks/lib/send_event.py +47 -47
  27. package/.aiox-core/monitor/hooks/notification.py +29 -29
  28. package/.aiox-core/monitor/hooks/post_tool_use.py +45 -45
  29. package/.aiox-core/monitor/hooks/pre_compact.py +29 -29
  30. package/.aiox-core/monitor/hooks/pre_tool_use.py +40 -40
  31. package/.aiox-core/monitor/hooks/stop.py +29 -29
  32. package/.aiox-core/monitor/hooks/subagent_stop.py +29 -29
  33. package/.aiox-core/monitor/hooks/user_prompt_submit.py +38 -38
  34. package/.aiox-core/product/templates/adr.hbs +125 -125
  35. package/.aiox-core/product/templates/dbdr.hbs +241 -241
  36. package/.aiox-core/product/templates/epic.hbs +212 -212
  37. package/.aiox-core/product/templates/pmdr.hbs +186 -186
  38. package/.aiox-core/product/templates/prd-v2.0.hbs +216 -216
  39. package/.aiox-core/product/templates/prd.hbs +201 -201
  40. package/.aiox-core/product/templates/story.hbs +263 -263
  41. package/.aiox-core/product/templates/task.hbs +170 -170
  42. package/.aiox-core/product/templates/tmpl-comment-on-examples.sql +158 -158
  43. package/.aiox-core/product/templates/tmpl-migration-script.sql +91 -91
  44. package/.aiox-core/product/templates/tmpl-rls-granular-policies.sql +104 -104
  45. package/.aiox-core/product/templates/tmpl-rls-kiss-policy.sql +10 -10
  46. package/.aiox-core/product/templates/tmpl-rls-roles.sql +135 -135
  47. package/.aiox-core/product/templates/tmpl-rls-simple.sql +77 -77
  48. package/.aiox-core/product/templates/tmpl-rls-tenant.sql +152 -152
  49. package/.aiox-core/product/templates/tmpl-rollback-script.sql +77 -77
  50. package/.aiox-core/product/templates/tmpl-seed-data.sql +140 -140
  51. package/.aiox-core/product/templates/tmpl-smoke-test.sql +16 -16
  52. package/.aiox-core/product/templates/tmpl-staging-copy-merge.sql +139 -139
  53. package/.aiox-core/product/templates/tmpl-stored-proc.sql +140 -140
  54. package/.aiox-core/product/templates/tmpl-trigger.sql +152 -152
  55. package/.aiox-core/product/templates/tmpl-view-materialized.sql +133 -133
  56. package/.aiox-core/product/templates/tmpl-view.sql +177 -177
  57. package/.aiox-core/scripts/pm.sh +0 -0
  58. package/.claude/hooks/enforce-architecture-first.py +196 -196
  59. package/.claude/hooks/mind-clone-governance.py +192 -192
  60. package/.claude/hooks/read-protection.py +151 -151
  61. package/.claude/hooks/slug-validation.py +176 -176
  62. package/.claude/hooks/sql-governance.py +182 -182
  63. package/.claude/hooks/write-path-validation.py +194 -194
  64. package/LICENSE +33 -33
  65. package/bin/aiox-graph.js +0 -0
  66. package/bin/aiox-minimal.js +0 -0
  67. package/bin/aiox.js +0 -0
  68. package/package.json +1 -1
  69. package/packages/aiox-install/bin/aiox-install.js +0 -0
  70. package/packages/aiox-install/bin/edmcp.js +0 -0
  71. package/packages/aiox-pro-cli/bin/aiox-pro.js +0 -0
  72. package/packages/installer/src/wizard/pro-setup.js +28 -0
  73. package/pro/README.md +66 -66
  74. package/pro/feature-registry.yaml +225 -223
  75. package/pro/license/license-api.js +701 -679
  76. package/pro/package.json +39 -39
  77. package/pro/pro-config.yaml +63 -63
  78. package/pro/squads/README.md +24 -24
  79. package/pro/squads/design/HEADLINE.md +3 -3
  80. package/pro/squads/design/README.md +109 -109
  81. package/pro/squads/design/agents/brad-frost.md +1097 -1097
  82. package/pro/squads/design/agents/dan-mall.md +857 -857
  83. package/pro/squads/design/agents/dave-malouf.md +2272 -2272
  84. package/pro/squads/design/agents/design-chief.md +114 -114
  85. package/pro/squads/design/agents/ds-foundations-lead.md +194 -194
  86. package/pro/squads/design/agents/ds-token-architect.md +361 -361
  87. package/pro/squads/design/agents/nano-banana-generator.md +162 -162
  88. package/pro/squads/design/agents/storybook-expert.md +809 -809
  89. package/pro/squads/design/checklists/atomic-refactor-checklist.md +299 -299
  90. package/pro/squads/design/checklists/component-adaptation-checklist.md +81 -81
  91. package/pro/squads/design/checklists/design-fidelity-checklist.md +283 -283
  92. package/pro/squads/design/checklists/design-handoff-checklist.md +55 -55
  93. package/pro/squads/design/checklists/design-team-health-checklist.md +454 -454
  94. package/pro/squads/design/checklists/designops-maturity-checklist.md +518 -518
  95. package/pro/squads/design/checklists/ds-a11y-release-gate-checklist.md +45 -45
  96. package/pro/squads/design/checklists/ds-accessibility-wcag-checklist.md +147 -147
  97. package/pro/squads/design/checklists/ds-component-quality-checklist.md +150 -150
  98. package/pro/squads/design/checklists/ds-critical-eye-review-checklist.md +147 -147
  99. package/pro/squads/design/checklists/ds-migration-readiness-checklist.md +99 -99
  100. package/pro/squads/design/checklists/ds-pattern-audit-checklist.md +164 -164
  101. package/pro/squads/design/checklists/reading-accessibility-checklist.md +275 -275
  102. package/pro/squads/design/checklists/token-mapping-checklist.md +107 -107
  103. package/pro/squads/design/config/coding-standards.md +286 -286
  104. package/pro/squads/design/config/source-tree.md +59 -59
  105. package/pro/squads/design/config/tech-stack.md +48 -48
  106. package/pro/squads/design/config.yaml +204 -204
  107. package/pro/squads/design/data/agentic-design-systems-guide.md +46 -46
  108. package/pro/squads/design/data/agentic-ds-principles.md +100 -100
  109. package/pro/squads/design/data/atomic-design-principles.md +108 -108
  110. package/pro/squads/design/data/atomic-refactor-rules.md +582 -582
  111. package/pro/squads/design/data/base-component-specs.md +972 -972
  112. package/pro/squads/design/data/brad-frost-analysis-extract-implicit.yaml +270 -270
  113. package/pro/squads/design/data/brad-frost-analysis-find-0.8.yaml +176 -176
  114. package/pro/squads/design/data/brad-frost-analysis-qa-report.yaml +168 -168
  115. package/pro/squads/design/data/brad-frost-dna.yaml +713 -713
  116. package/pro/squads/design/data/capability-tools.yaml +124 -124
  117. package/pro/squads/design/data/component-adaptation-changelog.md +318 -318
  118. package/pro/squads/design/data/consolidation-algorithms.md +168 -168
  119. package/pro/squads/design/data/critical-eye-scoring-rules.yaml +240 -240
  120. package/pro/squads/design/data/design-token-best-practices.md +107 -107
  121. package/pro/squads/design/data/design-tokens-spec.yaml +418 -418
  122. package/pro/squads/design/data/ds-reference-architectures.md +93 -93
  123. package/pro/squads/design/data/f2-qa-report.md +168 -168
  124. package/pro/squads/design/data/f3-derived-components-changelog.md +100 -100
  125. package/pro/squads/design/data/f3-qa-report.md +208 -208
  126. package/pro/squads/design/data/figma-base-components-raw.md +101 -101
  127. package/pro/squads/design/data/figma-tokens-raw.md +1548 -1548
  128. package/pro/squads/design/data/fluent2-design-principles.md +114 -114
  129. package/pro/squads/design/data/high-retention-reading-guide.md +349 -349
  130. package/pro/squads/design/data/integration-patterns.md +207 -207
  131. package/pro/squads/design/data/internal-quality-chain.yaml +48 -48
  132. package/pro/squads/design/data/motion-tokens-guide.md +202 -202
  133. package/pro/squads/design/data/roi-calculation-guide.md +142 -142
  134. package/pro/squads/design/data/token-mapping-reference.md +213 -213
  135. package/pro/squads/design/data/w3c-dtcg-spec-reference.md +149 -149
  136. package/pro/squads/design/data/wcag-compliance-guide.md +267 -267
  137. package/pro/squads/design/docs/AUDIT_REPORT.md +97 -97
  138. package/pro/squads/design/docs/DS-CURATION-PIPELINE-PROPOSAL.md +577 -577
  139. package/pro/squads/design/docs/UPGRADE_PLAN.md +618 -618
  140. package/pro/squads/design/docs/brad-frost-research-validation.md +372 -372
  141. package/pro/squads/design/docs/dave-malouf-research-validation.md +391 -391
  142. package/pro/squads/design/docs/tool-discovery-report.md +87 -87
  143. package/pro/squads/design/docs/tool-integration-plan.md +44 -44
  144. package/pro/squads/design/protocols/ai-first-governance.md +56 -56
  145. package/pro/squads/design/protocols/governance-execution-boundary.md +59 -59
  146. package/pro/squads/design/protocols/handoff.md +60 -60
  147. package/pro/squads/design/rules/.claude-rules.md +88 -88
  148. package/pro/squads/design/scripts/design-system/curate_colors.cjs +447 -447
  149. package/pro/squads/design/scripts/design-system/curate_components.cjs +217 -217
  150. package/pro/squads/design/scripts/design-system/curate_radius.cjs +190 -190
  151. package/pro/squads/design/scripts/design-system/curate_shadows.cjs +208 -208
  152. package/pro/squads/design/scripts/design-system/curate_spacing.cjs +243 -243
  153. package/pro/squads/design/scripts/design-system/curate_typography.cjs +404 -404
  154. package/pro/squads/design/scripts/design-system/design-system-metadata.test.js +49 -49
  155. package/pro/squads/design/scripts/design-system/design_manifest_lib.cjs +142 -142
  156. package/pro/squads/design/scripts/design-system/fetch_page_images.cjs +195 -195
  157. package/pro/squads/design/scripts/design-system/generate_components_metadata.cjs +114 -114
  158. package/pro/squads/design/scripts/design-system/generate_curation_report.cjs +258 -258
  159. package/pro/squads/design/scripts/design-system/generate_tokens.cjs +342 -342
  160. package/pro/squads/design/scripts/design-system/sync_design_manifest.cjs +27 -27
  161. package/pro/squads/design/scripts/design-system/test_mcp_tools.cjs +232 -232
  162. package/pro/squads/design/scripts/design-system/validate_components_metadata.cjs +96 -96
  163. package/pro/squads/design/scripts/design-system/validate_curation.cjs +226 -226
  164. package/pro/squads/design/scripts/design-system/validate_design_manifest_drift.cjs +72 -72
  165. package/pro/squads/design/scripts/design-system/validate_mcp_skeleton.cjs +38 -38
  166. package/pro/squads/design/scripts/design-system/validate_registry.cjs +186 -186
  167. package/pro/squads/design/scripts/design-system/validate_task_checklist_bindings.cjs +78 -78
  168. package/pro/squads/design/scripts/dissect-artifact.cjs +806 -806
  169. package/pro/squads/design/scripts/validate-a11y-integration.cjs +40 -40
  170. package/pro/squads/design/scripts/validate-design-squad.py +411 -411
  171. package/pro/squads/design/squad.yaml +714 -714
  172. package/pro/squads/design/tasks/a11y-audit.md +340 -340
  173. package/pro/squads/design/tasks/aria-audit.md +525 -525
  174. package/pro/squads/design/tasks/atomic-refactor-execute.md +391 -391
  175. package/pro/squads/design/tasks/atomic-refactor-plan.md +262 -262
  176. package/pro/squads/design/tasks/audit-reading-experience.md +350 -350
  177. package/pro/squads/design/tasks/audit-tailwind-config.md +101 -101
  178. package/pro/squads/design/tasks/bootstrap-shadcn-library.md +96 -96
  179. package/pro/squads/design/tasks/bundle-audit.md +245 -245
  180. package/pro/squads/design/tasks/contrast-matrix.md +373 -373
  181. package/pro/squads/design/tasks/create-doc.md +135 -135
  182. package/pro/squads/design/tasks/dead-code-detection.md +329 -329
  183. package/pro/squads/design/tasks/design-compare.md +414 -414
  184. package/pro/squads/design/tasks/design-process-optimization.md +407 -407
  185. package/pro/squads/design/tasks/design-review-orchestration.md +99 -99
  186. package/pro/squads/design/tasks/design-team-scaling.md +407 -407
  187. package/pro/squads/design/tasks/design-tooling-audit.md +404 -404
  188. package/pro/squads/design/tasks/design-triage.md +89 -89
  189. package/pro/squads/design/tasks/designops-maturity-assessment.md +364 -364
  190. package/pro/squads/design/tasks/designops-metrics-setup.md +465 -465
  191. package/pro/squads/design/tasks/ds-agentic-audit.md +100 -100
  192. package/pro/squads/design/tasks/ds-agentic-setup.md +103 -103
  193. package/pro/squads/design/tasks/ds-audit-codebase.md +273 -273
  194. package/pro/squads/design/tasks/ds-build-component.md +349 -349
  195. package/pro/squads/design/tasks/ds-build-mcp-server.md +84 -84
  196. package/pro/squads/design/tasks/ds-calculate-roi.md +282 -282
  197. package/pro/squads/design/tasks/ds-compose-molecule.md +106 -106
  198. package/pro/squads/design/tasks/ds-consolidate-patterns.md +253 -253
  199. package/pro/squads/design/tasks/ds-context-contract.md +194 -194
  200. package/pro/squads/design/tasks/ds-critical-eye-compare.md +130 -130
  201. package/pro/squads/design/tasks/ds-critical-eye-decide.md +139 -139
  202. package/pro/squads/design/tasks/ds-critical-eye-inventory.md +111 -111
  203. package/pro/squads/design/tasks/ds-critical-eye-report.md +101 -101
  204. package/pro/squads/design/tasks/ds-critical-eye-score.md +109 -109
  205. package/pro/squads/design/tasks/ds-designops.md +99 -99
  206. package/pro/squads/design/tasks/ds-extend-pattern.md +91 -91
  207. package/pro/squads/design/tasks/ds-extract-tokens.md +312 -312
  208. package/pro/squads/design/tasks/ds-figma-pipeline.md +95 -95
  209. package/pro/squads/design/tasks/ds-fluent-audit.md +105 -105
  210. package/pro/squads/design/tasks/ds-fluent-build.md +110 -110
  211. package/pro/squads/design/tasks/ds-generate-ai-metadata.md +81 -81
  212. package/pro/squads/design/tasks/ds-generate-cursor-rules.md +74 -74
  213. package/pro/squads/design/tasks/ds-generate-documentation.md +101 -101
  214. package/pro/squads/design/tasks/ds-generate-migration-strategy.md +331 -331
  215. package/pro/squads/design/tasks/ds-generate-shock-report.md +323 -323
  216. package/pro/squads/design/tasks/ds-govern-a11y-compliance.md +93 -93
  217. package/pro/squads/design/tasks/ds-governance.md +187 -187
  218. package/pro/squads/design/tasks/ds-health-metrics.md +278 -278
  219. package/pro/squads/design/tasks/ds-integrate-squad.md +130 -130
  220. package/pro/squads/design/tasks/ds-integrate-workspace.md +100 -100
  221. package/pro/squads/design/tasks/ds-legacy-modernization.md +302 -302
  222. package/pro/squads/design/tasks/ds-mcp-status.md +65 -65
  223. package/pro/squads/design/tasks/ds-motion-audit.md +118 -118
  224. package/pro/squads/design/tasks/ds-multi-framework.md +96 -96
  225. package/pro/squads/design/tasks/ds-parallelization-gate.md +246 -246
  226. package/pro/squads/design/tasks/ds-query.md +90 -90
  227. package/pro/squads/design/tasks/ds-rebuild-artifact.md +369 -369
  228. package/pro/squads/design/tasks/ds-reverse-engineer.md +194 -194
  229. package/pro/squads/design/tasks/ds-scan-artifact.md +131 -131
  230. package/pro/squads/design/tasks/ds-setup-design-system.md +297 -297
  231. package/pro/squads/design/tasks/ds-sync-registry.md +287 -287
  232. package/pro/squads/design/tasks/ds-theme-multi-brand.md +90 -90
  233. package/pro/squads/design/tasks/ds-token-modes.md +108 -108
  234. package/pro/squads/design/tasks/ds-token-w3c-extract.md +105 -105
  235. package/pro/squads/design/tasks/ds-validate-ai-readiness.md +69 -69
  236. package/pro/squads/design/tasks/ds-visual-regression.md +130 -130
  237. package/pro/squads/design/tasks/execute-checklist.md +141 -141
  238. package/pro/squads/design/tasks/export-design-tokens-dtcg.md +97 -97
  239. package/pro/squads/design/tasks/f1-apply-foundations.md +154 -154
  240. package/pro/squads/design/tasks/f1-ingest-figma-tokens.md +130 -130
  241. package/pro/squads/design/tasks/f1-map-tokens-to-shadcn.md +145 -145
  242. package/pro/squads/design/tasks/f1-qa-foundations.md +95 -95
  243. package/pro/squads/design/tasks/f2-adapt-shadcn-components.md +155 -155
  244. package/pro/squads/design/tasks/f2-ingest-base-components.md +148 -148
  245. package/pro/squads/design/tasks/f2-qa-base-components.md +98 -98
  246. package/pro/squads/design/tasks/f3-derive-components.md +145 -145
  247. package/pro/squads/design/tasks/f3-qa-derived-components.md +101 -101
  248. package/pro/squads/design/tasks/focus-order-audit.md +450 -450
  249. package/pro/squads/design/tasks/sb-brownfield-migrate.md +367 -367
  250. package/pro/squads/design/tasks/sb-brownfield-scan.md +318 -318
  251. package/pro/squads/design/tasks/sb-configure.md +230 -230
  252. package/pro/squads/design/tasks/sb-expand-shadcn.md +213 -213
  253. package/pro/squads/design/tasks/sb-generate-all-stories.md +288 -288
  254. package/pro/squads/design/tasks/sb-install.md +152 -152
  255. package/pro/squads/design/tasks/sb-sync-workspace.md +239 -239
  256. package/pro/squads/design/tasks/sb-verify.md +203 -203
  257. package/pro/squads/design/tasks/tailwind-upgrade.md +117 -117
  258. package/pro/squads/design/tasks/token-usage-analytics.md +262 -262
  259. package/pro/squads/design/tasks/ux-rewrite-sixth-grade.md +82 -82
  260. package/pro/squads/design/tasks/validate-design-fidelity.md +222 -222
  261. package/pro/squads/design/templates/agent-template.yaml +46 -46
  262. package/pro/squads/design/templates/clone-mind-template.md +352 -352
  263. package/pro/squads/design/templates/component-prompt-injection-tmpl.md +236 -236
  264. package/pro/squads/design/templates/component-visual-spec-tmpl.md +378 -378
  265. package/pro/squads/design/templates/critical-eye-cycle-report-tmpl.md +165 -165
  266. package/pro/squads/design/templates/design-fidelity-report-tmpl.md +155 -155
  267. package/pro/squads/design/templates/ds-ai-component-metadata-schema-tmpl.json +138 -138
  268. package/pro/squads/design/templates/ds-artifact-analysis.md +70 -70
  269. package/pro/squads/design/templates/ds-health-report-tmpl.md +236 -236
  270. package/pro/squads/design/templates/ds-migration-strategy-tmpl.md +524 -524
  271. package/pro/squads/design/templates/ds-state-persistence-tmpl.yaml +194 -194
  272. package/pro/squads/design/templates/ds-tokens-schema-tmpl.yaml +139 -139
  273. package/pro/squads/design/templates/migration-strategy-tmpl.md +524 -524
  274. package/pro/squads/design/templates/reading-design-tokens.css +26 -26
  275. package/pro/squads/design/templates/state-persistence-tmpl.yaml +219 -219
  276. package/pro/squads/design/templates/tokens-schema-tmpl.yaml +305 -305
  277. package/pro/squads/design/workflows/agentic-readiness.yaml +83 -83
  278. package/pro/squads/design/workflows/audit-only.yaml +198 -198
  279. package/pro/squads/design/workflows/brownfield-complete.yaml +257 -257
  280. package/pro/squads/design/workflows/critical-eye.yaml +184 -184
  281. package/pro/squads/design/workflows/dtcg-tokens-governance.yaml +64 -64
  282. package/pro/squads/design/workflows/foundations-pipeline.yaml +192 -192
  283. package/pro/squads/design/workflows/greenfield-new.yaml +192 -192
  284. package/pro/squads/design/workflows/motion-quality.yaml +65 -65
  285. package/pro/squads/design/workflows/self-healing-workflow.yaml +237 -237
  286. package/pro/squads/design/workflows/storybook-brownfield-migration.yaml +400 -400
  287. package/pro/squads/design/workflows/storybook-full-setup.yaml +280 -280
  288. package/pro/squads/mmos-squad/minds/alex_hormozi/artifacts/ARQUITETURA_COGNITIVA_DE_ALEX_HORMOZI_EXTRA/303/207/303/203O_COMPLETA.md +215 -0
  289. package/pro/squads/mmos-squad/minds/alex_hormozi/artifacts/A_Rotina_de_Alta_Performance_de_Alex_Hormozi_Arquitetura,_Motiva/303/247/303/265es_e_Replica/303/247/303/243o.md +309 -0
  290. package/pro/squads/mmos-squad/minds/alex_hormozi/artifacts/O_sistema_completo_de_cria/303/247/303/243o_de_conte/303/272do_de_Alex_Hormozi.md +416 -0
  291. package/pro/squads/mmos-squad/minds/alex_hormozi/artifacts/Processo_Cria/303/247/303/243o_Conte/303/272do_Hormozi.md +0 -0
  292. package/pro/squads/mmos-squad/minds/brad_frost/.backup/2026-01-13/artifacts/DECIS/303/225ES_ESTRAT/303/211GICAS_DE_DESIGN_SYSTEMS_(2022_2025).md +1038 -0
  293. package/pro/squads/mmos-squad/minds/brad_frost/.backup/2026-01-13/artifacts/FRAMEWORK_COMPLETO_DE_IMPLEMENTA/303/207/303/203O_ATOMIC_DESIGN.md +797 -0
  294. package/pro/squads/mmos-squad/minds/brad_frost/.backup/2026-01-13/artifacts/O_Cemit/303/251rio_de_Design_Systems.md +447 -0
  295. package/pro/squads/mmos-squad/minds/brad_frost/.backup/2026-01-13/artifacts/PRINC/303/215PIOS_DE_RACIOC/303/215NIO.md +190 -0
  296. package/pro/squads/mmos-squad/minds/brad_frost/artifacts/DECIS/303/225ES_ESTRAT/303/211GICAS_DE_DESIGN_SYSTEMS_(2022_2025).md +1038 -0
  297. package/pro/squads/mmos-squad/minds/brad_frost/artifacts/FRAMEWORK_COMPLETO_DE_IMPLEMENTA/303/207/303/203O_ATOMIC_DESIGN.md +797 -0
  298. package/pro/squads/mmos-squad/minds/brad_frost/artifacts/O_Cemit/303/251rio_de_Design_Systems.md +447 -0
  299. package/pro/squads/mmos-squad/minds/brad_frost/artifacts/PRINC/303/215PIOS_DE_RACIOC/303/215NIO.md +190 -0
  300. package/pro/squads/mmos-squad/minds/elon_musk/artifacts/AN/303/201LISE_PSICOM/303/211TRICA_PROFUNDA_ELON_MUSK.md +291 -0
  301. package/pro/squads/mmos-squad/minds/elon_musk/artifacts/ASSINATURA_LINGU/303/215STICA_ELON_MUSK.md +485 -0
  302. package/pro/squads/mmos-squad/minds/elon_musk/artifacts/A_Arquitetura_Mental_de_Elon_Musk_Uma_An/303/241lise_Sistem/303/241tica_dos_Frameworks_de_Pensamento.md +907 -0
  303. package/pro/squads/mmos-squad/minds/elon_musk/artifacts/Dossi/303/252_Estrat/303/251gico_A_Arquitetura_Psicol/303/263gica_de_Elon_Musk.md +252 -0
  304. package/pro/squads/mmos-squad/minds/elon_musk/artifacts/Os_Padr/303/265es_de_Leitura_de_Elon_Musk_e_Sua_Influ/303/252ncia_Sistem/303/241tica.md +287 -0
  305. package/pro/squads/mmos-squad/minds/elon_musk/artifacts/Uma_an/303/241lise_psicol/303/263gica_abrangente.md +187 -0
  306. package/pro/squads/mmos-squad/minds/eugene_schwartz/artifacts/AN/303/201LISE_PSICOM/303/211TRICA_PROFUNDA_EUGENE_M._SCHWARTZ.md +790 -0
  307. package/pro/squads/mmos-squad/minds/eugene_schwartz/artifacts/An/303/241lise_Completa_Eugene_Schwartz_Arquitetura_Cognitiva_DEEP.md +210 -0
  308. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/5H_EXTRA/303/207/303/203O_COGNITIVA_COMPLETA_PEDRO_VAL/303/211RIO_LOPEZ.md +226 -0
  309. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/AN/303/201LISE_COMPARATIVA_REVISADA_PEDRO_VAL/303/211RIO_LOPEZ.md +246 -0
  310. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/AN/303/201LISE_LINGU/303/215STICA_CARIOCA_PEDRO_VAL/303/211RIO_LOPEZ.md +274 -0
  311. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/AN/303/201LISE_PSICOM/303/211TRICA_DEFINITIVA_PEDRO_VAL/303/211RIO_LOPEZ.md +821 -0
  312. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/AN/303/201LISE_PSICOM/303/211TRICA_PROFUNDA_PEDRO_VAL/303/211RIO.md +1844 -0
  313. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/C/303/201LCULO_DE_RARIDADE_ESTAT/303/215STICA_PEDRO_VAL/303/211RIO_LOPEZ.md +154 -0
  314. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/EXTRA/303/207/303/203O_PEDRO_VAL/303/211RIO.md +237 -0
  315. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/MAPEAMENTO_LINGU/303/215STICO_PROFUNDO.md +161 -0
  316. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/META_AXIOMAS_DE_PEDRO_VAL/303/211RIO.md +256 -0
  317. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/SISTEMA_IMUNOL/303/223GICO_COGNITIVO_PEDRO_VAL/303/211RIO_LOPEZ.md +586 -0
  318. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/SISTEMA_IMUNOL/303/223GICO_COGNITIVO_V2_/342/200/224_CLONE_IA.md +452 -0
  319. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/TABELA_COMPARATIVA_AN/303/201LISE_COMPLETA_DOS_CLONES_IA.md +102 -0
  320. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/WHATSAPP_PADR/303/225ES_LINGU/303/215STICOS_PEDRO_VAL/303/211RIO_LOPEZ.md +286 -0
  321. package/pro/squads/mmos-squad/minds/pedro_valerio/sources/artifacts_v1.6/heur/303/255sticas_de_decis/303/243o_e_algoritmos_mentais_/303/272nicos.md +268 -0
  322. package/pro/squads/mmos-squad/minds/ray_kurzweil/sources/books/PROTOCOLO_COMPLETO_DE_INTERROGA/303/207/303/203O_-_NAVAL_RAVIKANT.md +3624 -0
  323. package/pro/squads/mmos-squad/minds/steve_jobs/artifacts/FRAMEWORK_COMPLETO_DE_IMPLEMENTA/303/207/303/203O_JOBS.md +488 -0
  324. package/pro/squads/mmos-squad/minds/steve_jobs/artifacts/Framework_Cabe/303/247a_Steve.md +257 -0
  325. package/pro/squads/mmos-squad/minds/steve_jobs/artifacts/Relat/303/263rio_Abrangente_sobre_Steve_Jobs_para_Cria/303/247/303/243o_de_Clone_de_IA.md +370 -0
  326. package/pro/squads/mmos-squad/minds/steve_jobs/artifacts/Steve_Jobs_An/303/241lise_Psicol/303/263gica_Profunda_e_Valida/303/247/303/243o_Comportamental.md +65 -0
  327. package/pro/squads/squad-creator-pro/HEADLINE.md +3 -3
  328. package/pro/squads/squad-creator-pro/agents/oalanicolas.md +438 -438
  329. package/pro/squads/squad-creator-pro/agents/squad-chief.md +1651 -1651
  330. package/pro/squads/squad-creator-pro/agents/thiago_finch.md +976 -976
  331. package/pro/squads/squad-creator-pro/assessments/axioma-assessment-wf-create-squad.yaml +325 -325
  332. package/pro/squads/squad-creator-pro/checklists/create-agent-checklist.md +184 -184
  333. package/pro/squads/squad-creator-pro/checklists/create-squad-checklist.md +219 -219
  334. package/pro/squads/squad-creator-pro/checklists/create-workflow-checklist.md +224 -224
  335. package/pro/squads/squad-creator-pro/checklists/mental-model-integration-checklist.md +95 -95
  336. package/pro/squads/squad-creator-pro/checklists/squad-overview-checklist.md +393 -393
  337. package/pro/squads/squad-creator-pro/config/model-routing.yaml +693 -693
  338. package/pro/squads/squad-creator-pro/config/scoring-rubric.yaml +199 -199
  339. package/pro/squads/squad-creator-pro/config.yaml +35 -35
  340. package/pro/squads/squad-creator-pro/data/internal-infrastructure-library.yaml +99 -99
  341. package/pro/squads/squad-creator-pro/data/mental-model-task-matrix.yaml +692 -692
  342. package/pro/squads/squad-creator-pro/docs/ADR-001-model-tier-qualification.md +344 -344
  343. package/pro/squads/squad-creator-pro/docs/AGENT-COLLABORATION.md +609 -609
  344. package/pro/squads/squad-creator-pro/docs/MIGRATION-PLAN-AGENT-CONFORMITY.md +861 -861
  345. package/pro/squads/squad-creator-pro/docs/MODEL-TIER-QUALIFICATION.md +337 -337
  346. package/pro/squads/squad-creator-pro/docs/optimize-v4-proposal.md +354 -354
  347. package/pro/squads/squad-creator-pro/docs/task-optimization-framework.md +229 -229
  348. package/pro/squads/squad-creator-pro/minds/oalanicolas/heuristics/AN_KE_010.md +240 -240
  349. package/pro/squads/squad-creator-pro/protocols/ai-first-governance.md +63 -63
  350. package/pro/squads/squad-creator-pro/scripts/assess-sources.sh +443 -443
  351. package/pro/squads/squad-creator-pro/scripts/clone-review.sh +394 -394
  352. package/pro/squads/squad-creator-pro/scripts/create-agent-preflight.py +243 -243
  353. package/pro/squads/squad-creator-pro/scripts/cross-provider/compare-results.js +281 -281
  354. package/pro/squads/squad-creator-pro/scripts/cross-provider/cross-provider-runner.js +462 -462
  355. package/pro/squads/squad-creator-pro/scripts/fidelity-score.sh +519 -519
  356. package/pro/squads/squad-creator-pro/scripts/generate-squad-guide.js +558 -558
  357. package/pro/squads/squad-creator-pro/scripts/lib/config-loader.js +151 -151
  358. package/pro/squads/squad-creator-pro/scripts/model-tier-validator.cjs +369 -369
  359. package/pro/squads/squad-creator-pro/scripts/model-usage-logger.cjs +245 -245
  360. package/pro/squads/squad-creator-pro/scripts/modernization-score.sh +308 -308
  361. package/pro/squads/squad-creator-pro/scripts/scaffold-squad.cjs +281 -281
  362. package/pro/squads/squad-creator-pro/scripts/security_scanner.py +378 -378
  363. package/pro/squads/squad-creator-pro/scripts/squad-context-loader.cjs +205 -205
  364. package/pro/squads/squad-creator-pro/scripts/squad-state-manager.cjs +451 -451
  365. package/pro/squads/squad-creator-pro/scripts/squad-workflow-runner.cjs +471 -471
  366. package/pro/squads/squad-creator-pro/scripts/squad_utils.py +261 -261
  367. package/pro/squads/squad-creator-pro/scripts/tests/run_bash_tests.sh +29 -29
  368. package/pro/squads/squad-creator-pro/scripts/tests/test_assess_sources.sh +216 -216
  369. package/pro/squads/squad-creator-pro/scripts/tests/test_clone_review.sh +239 -239
  370. package/pro/squads/squad-creator-pro/scripts/tests/test_coherence_validator.py +212 -212
  371. package/pro/squads/squad-creator-pro/scripts/tests/test_fidelity_score.sh +298 -298
  372. package/pro/squads/squad-creator-pro/scripts/tests/test_modernization_score.sh +211 -211
  373. package/pro/squads/squad-creator-pro/scripts/tests/test_security_scanner.py +354 -354
  374. package/pro/squads/squad-creator-pro/scripts/tests/test_validate_clone.sh +252 -252
  375. package/pro/squads/squad-creator-pro/squad.yaml +36 -36
  376. package/pro/squads/squad-creator-pro/tasks/an-compare-outputs.md +354 -354
  377. package/pro/squads/squad-creator-pro/tasks/create-squad.md +933 -933
  378. package/pro/squads/squad-creator-pro/tasks/detect-squad-context.md +81 -81
  379. package/pro/squads/squad-creator-pro/tasks/lookup-model.md +78 -78
  380. package/pro/squads/squad-creator-pro/tasks/next-squad.md +487 -487
  381. package/pro/squads/squad-creator-pro/tasks/optimize-workflow.md +851 -851
  382. package/pro/squads/squad-creator-pro/tasks/parallel-discovery.md +58 -58
  383. package/pro/squads/squad-creator-pro/tasks/pv-axioma-assessment-wf-clone-mind.yaml +256 -256
  384. package/pro/squads/squad-creator-pro/tasks/qualify-task.md +265 -265
  385. package/pro/squads/squad-creator-pro/tasks/reexecute-squad-phase.md +64 -64
  386. package/pro/squads/squad-creator-pro/tasks/smoke-test-model-routing.md +167 -167
  387. package/pro/squads/squad-creator-pro/tasks/squad-overview.md +683 -683
  388. package/pro/squads/squad-creator-pro/tasks/validate-final-artifacts.md +80 -80
  389. package/pro/squads/squad-creator-pro/templates/orchestrator-tmpl.md +74 -74
  390. package/pro/squads/squad-creator-pro/test-cases/BATCH-PROGRESS.md +268 -268
  391. package/pro/squads/squad-creator-pro/test-cases/QUALIFICATION-DASHBOARD.yaml +13 -13
  392. package/pro/squads/squad-creator-pro/test-cases/_template.yaml +147 -147
  393. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/ASSESSMENT-SUMMARY.md +275 -275
  394. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/ASSESSMENT_SUMMARY.md +140 -140
  395. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/CHECKPOINT_MATRIX.md +202 -202
  396. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/EXECUTION-REPORT.md +413 -413
  397. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/EXECUTION_NOTES.md +358 -358
  398. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/README-v2.2.2.md +299 -299
  399. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/README.md +320 -320
  400. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/TEST-REPORT-v2.1.md +351 -351
  401. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/VERIFICATION-CHECKLIST.txt +247 -247
  402. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/formal-qualification-report.yaml +389 -389
  403. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/haiku-output.yaml +366 -366
  404. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/haiku-v2.1-output.yaml +452 -452
  405. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/haiku-v2.2.1-output.yaml +281 -281
  406. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/haiku-v2.2.2-output.yaml +332 -332
  407. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/opus-baseline.yaml +517 -517
  408. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/qualification-report.yaml +213 -213
  409. package/pro/squads/squad-creator-pro/test-cases/an-assess-sources/test-case.yaml +69 -69
  410. package/pro/squads/squad-creator-pro/test-cases/an-clone-review/haiku-round-1.yaml +213 -213
  411. package/pro/squads/squad-creator-pro/test-cases/an-clone-review/opus-baseline.yaml +566 -566
  412. package/pro/squads/squad-creator-pro/test-cases/an-clone-review/qualification-report.yaml +82 -82
  413. package/pro/squads/squad-creator-pro/test-cases/an-design-clone/test-case.yaml +102 -102
  414. package/pro/squads/squad-creator-pro/test-cases/an-extract-dna/test-case.yaml +105 -105
  415. package/pro/squads/squad-creator-pro/test-cases/an-fidelity-score/haiku-round-1.yaml +262 -262
  416. package/pro/squads/squad-creator-pro/test-cases/an-fidelity-score/opus-baseline.yaml +266 -266
  417. package/pro/squads/squad-creator-pro/test-cases/an-fidelity-score/qualification-report.yaml +94 -94
  418. package/pro/squads/squad-creator-pro/test-cases/an-validate-clone/haiku-round-1.yaml +282 -282
  419. package/pro/squads/squad-creator-pro/test-cases/an-validate-clone/opus-baseline.yaml +470 -470
  420. package/pro/squads/squad-creator-pro/test-cases/an-validate-clone/qualification-report.yaml +106 -106
  421. package/pro/squads/squad-creator-pro/test-cases/collect-sources/test-case.yaml +105 -105
  422. package/pro/squads/squad-creator-pro/test-cases/create-task/test-case.yaml +104 -104
  423. package/pro/squads/squad-creator-pro/test-cases/cross-provider/DASHBOARD.yaml +11 -11
  424. package/pro/squads/squad-creator-pro/test-cases/pv-audit/test-case.yaml +106 -106
  425. package/pro/squads/squad-creator-pro/test-cases/pv-axioma-assessment/haiku-output.yaml +209 -209
  426. package/pro/squads/squad-creator-pro/test-cases/pv-axioma-assessment/opus-baseline.yaml +96 -96
  427. package/pro/squads/squad-creator-pro/test-cases/pv-axioma-assessment/sonnet-output.yaml +30 -30
  428. package/pro/squads/squad-creator-pro/test-cases/pv-axioma-assessment/test-case.yaml +129 -129
  429. package/pro/squads/squad-creator-pro/test-cases/pv-modernization-score/comparison-round-1.yaml +242 -242
  430. package/pro/squads/squad-creator-pro/test-cases/pv-modernization-score/haiku-round-1.yaml +393 -393
  431. package/pro/squads/squad-creator-pro/test-cases/pv-modernization-score/opus-baseline.yaml +488 -488
  432. package/pro/squads/squad-creator-pro/test-cases/pv-modernization-score/qualification-report.yaml +74 -74
  433. package/pro/squads/squad-creator-pro/test-cases/qa-after-creation/haiku-round-1.yaml +292 -292
  434. package/pro/squads/squad-creator-pro/test-cases/qa-after-creation/opus-baseline.yaml +603 -603
  435. package/pro/squads/squad-creator-pro/test-cases/qa-after-creation/qualification-report.yaml +97 -97
  436. package/pro/squads/squad-creator-pro/test-cases/smoke-test-model-routing/test-case.yaml +100 -100
  437. package/pro/squads/squad-creator-pro/test-cases/upgrade-squad/test-case.yaml +106 -106
  438. package/pro/squads/squad-creator-pro/test-cases/validate-squad/comparison-round-1.yaml +223 -223
  439. package/pro/squads/squad-creator-pro/test-cases/validate-squad/haiku-round-1-MINE.yaml +36 -36
  440. package/pro/squads/squad-creator-pro/test-cases/validate-squad/haiku-round-1.yaml +193 -193
  441. package/pro/squads/squad-creator-pro/test-cases/validate-squad/haiku-round-2.yaml +303 -303
  442. package/pro/squads/squad-creator-pro/test-cases/validate-squad/haiku-round-3-v4-task.yaml +149 -149
  443. package/pro/squads/squad-creator-pro/test-cases/validate-squad/opus-baseline.yaml +529 -529
  444. package/pro/squads/squad-creator-pro/test-cases/validate-squad/opus-round-3-v4-task.yaml +132 -132
  445. package/pro/squads/squad-creator-pro/test-cases/validate-squad/qualification-report.yaml +104 -104
  446. package/pro/squads/squad-creator-pro/test-cases/wf-clone-mind/haiku-output-v2-calibrated.yaml +200 -200
  447. package/pro/squads/squad-creator-pro/test-cases/wf-clone-mind/haiku-output.yaml +183 -183
  448. package/pro/squads/squad-creator-pro/test-cases/wf-clone-mind/opus-baseline.yaml +112 -112
  449. package/pro/squads/squad-creator-pro/workflows/create-squad.yaml +348 -348
  450. package/pro/squads/squad-creator-pro/workflows/modules/module-discovery.yaml +16 -16
  451. package/pro/squads/squad-creator-pro/workflows/modules/module-integration.yaml +16 -16
  452. package/pro/squads/squad-creator-pro/workflows/modules/module-quality-gates.yaml +15 -15
  453. package/pro/squads/squad-creator-pro/workflows/wf-brownfield-upgrade-squad.yaml +46 -46
  454. package/pro/squads/squad-creator-pro/workflows/wf-context-aware-create-squad.yaml +47 -47
  455. package/pro/squads/squad-creator-pro/workflows/wf-create-squad.yaml +1619 -1619
  456. package/pro/squads/squad-creator-pro/workflows/wf-cross-provider-qualification.yaml +711 -711
  457. package/pro/squads/squad-creator-pro/workflows/wf-model-tier-qualification.yaml +800 -800
  458. package/pro/squads/squad-creator-pro/workflows/wf-optimize-squad.yaml +684 -684
  459. package/scripts/check-markdown-links.py +352 -352
  460. package/scripts/dashboard-parallel-dev.sh +0 -0
  461. package/scripts/dashboard-parallel-phase3.sh +0 -0
  462. package/scripts/dashboard-parallel-phase4.sh +0 -0
  463. package/scripts/install-monitor-hooks.sh +0 -0
  464. package/.claude/hooks/code-intel-pretool.cjs +0 -107
  465. package/docs/guides/aios-workflows/README.md +0 -247
  466. package/docs/guides/aios-workflows/bob-orchestrator-workflow.md +0 -1536
  467. package/scripts/glue/README.md +0 -355
  468. package/scripts/glue/compose-agent-prompt.cjs +0 -362
@@ -0,0 +1,1283 @@
1
+ /**
2
+ * Predictive Pipeline
3
+ *
4
+ * Predicts task outcomes BEFORE execution using historical data patterns.
5
+ * Estimates success probability, expected duration, resource needs, and
6
+ * potential failure points based on weighted k-NN with feature similarity.
7
+ *
8
+ * Pipeline stages: preprocess → match → predict → score → recommend
9
+ *
10
+ * @module core/execution/predictive-pipeline
11
+ * @version 1.0.0
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const EventEmitter = require('events');
17
+
18
+ // ═══════════════════════════════════════════════════════════════════════════════
19
+ // CONSTANTS
20
+ // ═══════════════════════════════════════════════════════════════════════════════
21
+
22
+ /**
23
+ * Pipeline stage names in execution order
24
+ */
25
+ const PipelineStage = {
26
+ PREPROCESS: 'preprocess',
27
+ MATCH: 'match',
28
+ PREDICT: 'predict',
29
+ SCORE: 'score',
30
+ RECOMMEND: 'recommend',
31
+ };
32
+
33
+ /**
34
+ * Risk level thresholds
35
+ */
36
+ const RiskLevel = {
37
+ LOW: 'low',
38
+ MEDIUM: 'medium',
39
+ HIGH: 'high',
40
+ CRITICAL: 'critical',
41
+ };
42
+
43
+ /**
44
+ * Default configuration values
45
+ */
46
+ const DEFAULTS = {
47
+ kNeighbors: 5,
48
+ minSamplesForPrediction: 3,
49
+ anomalyThreshold: 0.3,
50
+ ewmaAlpha: 0.3,
51
+ highRiskThreshold: 0.6,
52
+ maxOutcomes: 10000,
53
+ confidenceSampleCap: 20,
54
+ };
55
+
56
+ // ═══════════════════════════════════════════════════════════════════════════════
57
+ // PIPELINE
58
+ // ═══════════════════════════════════════════════════════════════════════════════
59
+
60
+ class PredictivePipeline extends EventEmitter {
61
+ /**
62
+ * @param {string} projectRoot - Root directory for persistence
63
+ * @param {Object} [options] - Configuration options
64
+ * @param {number} [options.kNeighbors=5] - Number of neighbors for k-NN
65
+ * @param {number} [options.minSamplesForPrediction=3] - Minimum outcomes for prediction
66
+ * @param {number} [options.anomalyThreshold=0.3] - Max similarity for anomaly detection
67
+ * @param {number} [options.ewmaAlpha=0.3] - EWMA smoothing factor (0-1)
68
+ * @param {number} [options.highRiskThreshold=0.6] - Risk score above which high-risk is emitted
69
+ * @param {number} [options.maxOutcomes=10000] - Maximum stored outcomes before auto-prune
70
+ */
71
+ constructor(projectRoot, options = {}) {
72
+ super();
73
+
74
+ this.projectRoot = projectRoot ?? process.cwd();
75
+ this.kNeighbors = options.kNeighbors ?? DEFAULTS.kNeighbors;
76
+ this.minSamplesForPrediction = options.minSamplesForPrediction ?? DEFAULTS.minSamplesForPrediction;
77
+ this.anomalyThreshold = options.anomalyThreshold ?? DEFAULTS.anomalyThreshold;
78
+ this.ewmaAlpha = options.ewmaAlpha ?? DEFAULTS.ewmaAlpha;
79
+ this.highRiskThreshold = options.highRiskThreshold ?? DEFAULTS.highRiskThreshold;
80
+ this.maxOutcomes = options.maxOutcomes ?? DEFAULTS.maxOutcomes;
81
+ this.confidenceSampleCap = options.confidenceSampleCap ?? DEFAULTS.confidenceSampleCap;
82
+
83
+ // Persistence paths
84
+ this._dataDir = path.join(this.projectRoot, '.aiox', 'predictions');
85
+ this._outcomesPath = path.join(this._dataDir, 'outcomes.json');
86
+ this._modelPath = path.join(this._dataDir, 'model.json');
87
+
88
+ // In-memory state
89
+ this._outcomes = [];
90
+ this._model = this._emptyModel();
91
+ this._loaded = false;
92
+
93
+ // Serialized write chain
94
+ this._writeChain = Promise.resolve();
95
+
96
+ // Stage metrics
97
+ this._stageMetrics = {};
98
+ for (const stage of Object.values(PipelineStage)) {
99
+ this._stageMetrics[stage] = { calls: 0, totalMs: 0, errors: 0 };
100
+ }
101
+
102
+ // Global stats
103
+ this._stats = {
104
+ predictions: 0,
105
+ outcomesRecorded: 0,
106
+ anomaliesDetected: 0,
107
+ retrains: 0,
108
+ };
109
+ }
110
+
111
+ // ═════════════════════════════════════════════════════════════════════════════
112
+ // DATA LOADING
113
+ // ═════════════════════════════════════════════════════════════════════════════
114
+
115
+ /**
116
+ * Ensure data is loaded from disk (lazy, idempotent)
117
+ * @private
118
+ */
119
+ _ensureLoaded() {
120
+ if (this._loaded) return;
121
+ this._loadSync();
122
+ this._loaded = true;
123
+ }
124
+
125
+ /**
126
+ * Load outcomes and model from disk synchronously
127
+ * @private
128
+ */
129
+ _loadSync() {
130
+ try {
131
+ if (fs.existsSync(this._outcomesPath)) {
132
+ const raw = fs.readFileSync(this._outcomesPath, 'utf8');
133
+ const parsed = JSON.parse(raw);
134
+ this._outcomes = Array.isArray(parsed) ? parsed : [];
135
+ }
136
+ } catch {
137
+ this._outcomes = [];
138
+ }
139
+
140
+ try {
141
+ if (fs.existsSync(this._modelPath)) {
142
+ const raw = fs.readFileSync(this._modelPath, 'utf8');
143
+ const parsed = JSON.parse(raw);
144
+ if (parsed && typeof parsed === 'object') {
145
+ this._model = { ...this._emptyModel(), ...parsed };
146
+ }
147
+ }
148
+ } catch {
149
+ this._model = this._emptyModel();
150
+ }
151
+ }
152
+
153
+ /**
154
+ * @private
155
+ * @returns {Object} Empty model structure
156
+ */
157
+ _emptyModel() {
158
+ return {
159
+ taskTypeStats: {},
160
+ agentStats: {},
161
+ strategyStats: {},
162
+ lastRetrain: null,
163
+ version: 1,
164
+ };
165
+ }
166
+
167
+ // ═════════════════════════════════════════════════════════════════════════════
168
+ // PERSISTENCE
169
+ // ═════════════════════════════════════════════════════════════════════════════
170
+
171
+ /**
172
+ * Serialize a write operation through the write chain
173
+ * @private
174
+ * @param {Function} writeFn - Async function that performs the write
175
+ * @returns {Promise<void>}
176
+ */
177
+ _enqueueWrite(writeFn) {
178
+ this._writeChain = this._writeChain.then(() => writeFn()).catch((err) => {
179
+ this._emitSafeError({ type: 'persistence', error: err });
180
+ throw err;
181
+ });
182
+ return this._writeChain;
183
+ }
184
+
185
+ /**
186
+ * Persist outcomes to disk
187
+ * @private
188
+ * @returns {Promise<void>}
189
+ */
190
+ _persistOutcomes() {
191
+ return this._enqueueWrite(async () => {
192
+ this._ensureDataDir();
193
+ fs.writeFileSync(this._outcomesPath, JSON.stringify(this._outcomes, null, 2));
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Persist model to disk
199
+ * @private
200
+ * @returns {Promise<void>}
201
+ */
202
+ _persistModel() {
203
+ return this._enqueueWrite(async () => {
204
+ this._ensureDataDir();
205
+ fs.writeFileSync(this._modelPath, JSON.stringify(this._model, null, 2));
206
+ });
207
+ }
208
+
209
+ /**
210
+ * Ensure the data directory exists
211
+ * @private
212
+ */
213
+ _ensureDataDir() {
214
+ if (!fs.existsSync(this._dataDir)) {
215
+ fs.mkdirSync(this._dataDir, { recursive: true });
216
+ }
217
+ }
218
+
219
+ // ═════════════════════════════════════════════════════════════════════════════
220
+ // SAFE ERROR EMIT
221
+ // ═════════════════════════════════════════════════════════════════════════════
222
+
223
+ /**
224
+ * Emit error event only when listeners are present.
225
+ * Avoids unhandled EventEmitter 'error' exceptions.
226
+ * @private
227
+ * @param {Object} payload
228
+ */
229
+ _emitSafeError(payload) {
230
+ if (this.listenerCount('error') > 0) {
231
+ this.emit('error', payload);
232
+ return;
233
+ }
234
+ // Silently degrade — no listeners attached
235
+ }
236
+
237
+ // ═════════════════════════════════════════════════════════════════════════════
238
+ // DEEP CLONE
239
+ // ═════════════════════════════════════════════════════════════════════════════
240
+
241
+ /**
242
+ * Deep clone with structuredClone, JSON fallback
243
+ * @private
244
+ * @param {*} obj
245
+ * @returns {*}
246
+ */
247
+ _deepClone(obj) {
248
+ try {
249
+ return structuredClone(obj);
250
+ } catch {
251
+ return JSON.parse(JSON.stringify(obj));
252
+ }
253
+ }
254
+
255
+ // ═════════════════════════════════════════════════════════════════════════════
256
+ // RECORD OUTCOMES
257
+ // ═════════════════════════════════════════════════════════════════════════════
258
+
259
+ /**
260
+ * Record the actual outcome of a task for future predictions
261
+ * @param {Object} outcome - Outcome data
262
+ * @param {string} outcome.taskType - Type of task executed
263
+ * @param {string} [outcome.agent] - Agent that executed the task
264
+ * @param {string} [outcome.strategy] - Strategy used
265
+ * @param {number} outcome.duration - Execution duration in ms
266
+ * @param {boolean} outcome.success - Whether the task succeeded
267
+ * @param {number} [outcome.complexity] - Task complexity (1-10)
268
+ * @param {number} [outcome.contextSize] - Size of context provided
269
+ * @param {Object} [outcome.resources] - Resources consumed (memory, cpu, apiCalls)
270
+ * @param {Object} [outcome.metadata] - Additional metadata
271
+ * @returns {Promise<Object>} The stored outcome record
272
+ */
273
+ async recordOutcome(outcome) {
274
+ this._ensureLoaded();
275
+
276
+ if (!outcome || !outcome.taskType) {
277
+ throw new Error('outcome.taskType is required');
278
+ }
279
+ if (typeof outcome.duration !== 'number' || outcome.duration < 0) {
280
+ throw new Error('outcome.duration must be a non-negative number');
281
+ }
282
+ if (typeof outcome.success !== 'boolean') {
283
+ throw new Error('outcome.success must be a boolean');
284
+ }
285
+
286
+ const record = {
287
+ id: this._generateId(),
288
+ taskType: outcome.taskType,
289
+ agent: outcome.agent ?? null,
290
+ strategy: outcome.strategy ?? null,
291
+ duration: outcome.duration,
292
+ success: outcome.success,
293
+ complexity: outcome.complexity ?? 5,
294
+ contextSize: outcome.contextSize ?? 0,
295
+ resources: outcome.resources ?? null,
296
+ metadata: outcome.metadata ?? null,
297
+ timestamp: Date.now(),
298
+ };
299
+
300
+ this._outcomes.push(record);
301
+ this._stats.outcomesRecorded++;
302
+
303
+ // Update model stats
304
+ this._updateModelStats(record);
305
+
306
+ // Auto-prune if exceeding max
307
+ if (this._outcomes.length > this.maxOutcomes) {
308
+ const excess = this._outcomes.length - this.maxOutcomes;
309
+ this._outcomes.splice(0, excess);
310
+ this._recalculateModelStats();
311
+ }
312
+
313
+ await this._persistOutcomes();
314
+ await this._persistModel();
315
+
316
+ this.emit('outcome-recorded', { id: record.id, taskType: record.taskType });
317
+
318
+ return this._deepClone(record);
319
+ }
320
+
321
+ /**
322
+ * Update aggregated model statistics from a new outcome
323
+ * @private
324
+ * @param {Object} record
325
+ */
326
+ _updateModelStats(record) {
327
+ // Task type stats
328
+ if (!this._model.taskTypeStats[record.taskType]) {
329
+ this._model.taskTypeStats[record.taskType] = {
330
+ count: 0, successes: 0, totalDuration: 0, durations: [],
331
+ };
332
+ }
333
+ const ts = this._model.taskTypeStats[record.taskType];
334
+ ts.count++;
335
+ if (record.success) ts.successes++;
336
+ ts.totalDuration += record.duration;
337
+ ts.durations.push(record.duration);
338
+ // Keep only last 100 durations for memory
339
+ if (ts.durations.length > 100) ts.durations.shift();
340
+
341
+ // Agent stats
342
+ if (record.agent) {
343
+ if (!this._model.agentStats[record.agent]) {
344
+ this._model.agentStats[record.agent] = { count: 0, successes: 0, totalDuration: 0 };
345
+ }
346
+ const as = this._model.agentStats[record.agent];
347
+ as.count++;
348
+ if (record.success) as.successes++;
349
+ as.totalDuration += record.duration;
350
+ }
351
+
352
+ // Strategy stats
353
+ if (record.strategy) {
354
+ if (!this._model.strategyStats[record.strategy]) {
355
+ this._model.strategyStats[record.strategy] = { count: 0, successes: 0, totalDuration: 0 };
356
+ }
357
+ const ss = this._model.strategyStats[record.strategy];
358
+ ss.count++;
359
+ if (record.success) ss.successes++;
360
+ ss.totalDuration += record.duration;
361
+ }
362
+ }
363
+
364
+ // ═════════════════════════════════════════════════════════════════════════════
365
+ /**
366
+ * Recalculate all model stats from current outcomes.
367
+ * Called after splice/prune to keep stats consistent.
368
+ * @private
369
+ */
370
+ _recalculateModelStats() {
371
+ this._model.taskTypeStats = {};
372
+ this._model.agentStats = {};
373
+ this._model.strategyStats = {};
374
+ for (const outcome of this._outcomes) {
375
+ this._updateModelStats(outcome);
376
+ }
377
+ }
378
+
379
+ // FEATURE VECTORS
380
+ // ═════════════════════════════════════════════════════════════════════════════
381
+
382
+ /**
383
+ * Extract a feature vector from a task spec or outcome
384
+ * @private
385
+ * @param {Object} task
386
+ * @returns {Object} Feature vector
387
+ */
388
+ _extractFeatures(task) {
389
+ const complexity = Number(task.complexity);
390
+ const contextSize = Number(task.contextSize);
391
+ const agentExperience = this._getAgentExperience(task.agent);
392
+ return {
393
+ taskType: task.taskType ?? 'unknown',
394
+ complexity: Number.isFinite(complexity) ? complexity : 5,
395
+ agentExperience: Number.isFinite(agentExperience) ? agentExperience : 0,
396
+ contextSize: Number.isFinite(contextSize) ? contextSize : 0,
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Get the number of past outcomes for an agent
402
+ * @private
403
+ * @param {string|null} agent
404
+ * @returns {number}
405
+ */
406
+ _getAgentExperience(agent) {
407
+ if (!agent) return 0;
408
+ return this._model.agentStats[agent]?.count ?? 0;
409
+ }
410
+
411
+ /**
412
+ * Compute similarity between two feature vectors.
413
+ * Uses exact match for categorical (taskType) and cosine-like
414
+ * similarity for numeric features.
415
+ * @private
416
+ * @param {Object} a - Feature vector
417
+ * @param {Object} b - Feature vector
418
+ * @returns {number} Similarity score in [0, 1]
419
+ */
420
+ _computeSimilarity(a, b) {
421
+ // Categorical: taskType exact match contributes 0.4 weight
422
+ const typeMatch = a.taskType === b.taskType ? 1.0 : 0.0;
423
+
424
+ // Numeric features: normalized distance → similarity
425
+ const numericA = [a.complexity, a.agentExperience, a.contextSize];
426
+ const numericB = [b.complexity, b.agentExperience, b.contextSize];
427
+
428
+ const cosineSim = this._cosineSimilarity(numericA, numericB);
429
+
430
+ // Weighted combination: 40% categorical, 60% numeric
431
+ return 0.4 * typeMatch + 0.6 * cosineSim;
432
+ }
433
+
434
+ /**
435
+ * Cosine similarity between two numeric vectors
436
+ * @private
437
+ * @param {number[]} a
438
+ * @param {number[]} b
439
+ * @returns {number} Similarity in [0, 1]
440
+ */
441
+ _cosineSimilarity(a, b) {
442
+ let dotProduct = 0;
443
+ let normA = 0;
444
+ let normB = 0;
445
+
446
+ for (let i = 0; i < a.length; i++) {
447
+ dotProduct += a[i] * b[i];
448
+ normA += a[i] * a[i];
449
+ normB += b[i] * b[i];
450
+ }
451
+
452
+ normA = Math.sqrt(normA);
453
+ normB = Math.sqrt(normB);
454
+
455
+ if (normA === 0 || normB === 0) return 0;
456
+
457
+ return dotProduct / (normA * normB);
458
+ }
459
+
460
+ // ═════════════════════════════════════════════════════════════════════════════
461
+ // PIPELINE STAGES
462
+ // ═════════════════════════════════════════════════════════════════════════════
463
+
464
+ /**
465
+ * Execute a pipeline stage with timing
466
+ * @private
467
+ * @param {string} stageName
468
+ * @param {Function} fn
469
+ * @returns {*} Stage result
470
+ */
471
+ _runStage(stageName, fn) {
472
+ const start = Date.now();
473
+ try {
474
+ const result = fn();
475
+ this._stageMetrics[stageName].calls++;
476
+ this._stageMetrics[stageName].totalMs += Date.now() - start;
477
+ return result;
478
+ } catch (err) {
479
+ this._stageMetrics[stageName].errors++;
480
+ this._stageMetrics[stageName].totalMs += Date.now() - start;
481
+ throw err;
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Stage 1: Preprocess — extract and validate features
487
+ * @private
488
+ * @param {Object} taskSpec
489
+ * @returns {Object} Preprocessed features
490
+ */
491
+ _stagePreprocess(taskSpec) {
492
+ return this._runStage(PipelineStage.PREPROCESS, () => {
493
+ if (!taskSpec || !taskSpec.taskType) {
494
+ throw new Error('taskSpec.taskType is required for prediction');
495
+ }
496
+ return this._extractFeatures(taskSpec);
497
+ });
498
+ }
499
+
500
+ /**
501
+ * Stage 2: Match — find k nearest neighbors
502
+ * @private
503
+ * @param {Object} features
504
+ * @returns {Object[]} Nearest neighbors with similarity scores
505
+ */
506
+ _stageMatch(features) {
507
+ return this._runStage(PipelineStage.MATCH, () => {
508
+ const scored = this._outcomes.map((outcome) => {
509
+ const outFeatures = this._extractFeatures(outcome);
510
+ const similarity = this._computeSimilarity(features, outFeatures);
511
+ return { outcome, similarity };
512
+ });
513
+
514
+ // Sort by similarity descending
515
+ scored.sort((a, b) => b.similarity - a.similarity);
516
+
517
+ return scored.slice(0, this.kNeighbors);
518
+ });
519
+ }
520
+
521
+ /**
522
+ * Stage 3: Predict — compute predictions from matched neighbors
523
+ * @private
524
+ * @param {Object[]} neighbors - k nearest neighbors
525
+ * @param {Object} features - Original features
526
+ * @returns {Object} Raw predictions
527
+ */
528
+ _stagePredict(neighbors, features) {
529
+ return this._runStage(PipelineStage.PREDICT, () => {
530
+ if (neighbors.length < (this.minSamplesForPrediction || 3)) {
531
+ return this._defaultPrediction(features);
532
+ }
533
+
534
+ // Weighted success probability
535
+ let weightSum = 0;
536
+ let successWeight = 0;
537
+ let durationEwma = 0;
538
+ let durationValues = [];
539
+ let resourceEstimates = { memory: 0, cpu: 0, apiCalls: 0 };
540
+ let resourceCount = 0;
541
+
542
+ for (const { outcome, similarity } of neighbors) {
543
+ const weight = similarity;
544
+ weightSum += weight;
545
+ if (outcome.success) successWeight += weight;
546
+
547
+ durationValues.push(outcome.duration);
548
+
549
+ if (outcome.resources) {
550
+ resourceEstimates.memory += (outcome.resources.memory ?? 0) * weight;
551
+ resourceEstimates.cpu += (outcome.resources.cpu ?? 0) * weight;
552
+ resourceEstimates.apiCalls += (outcome.resources.apiCalls ?? 0) * weight;
553
+ resourceCount += weight;
554
+ }
555
+ }
556
+
557
+ const successProbability = weightSum > 0 ? successWeight / weightSum : 0.5;
558
+
559
+ // EWMA for duration
560
+ durationEwma = this._computeEwma(durationValues.reverse());
561
+
562
+ // Normalize resources
563
+ if (resourceCount > 0) {
564
+ resourceEstimates.memory /= resourceCount;
565
+ resourceEstimates.cpu /= resourceCount;
566
+ resourceEstimates.apiCalls /= resourceCount;
567
+ }
568
+
569
+ return {
570
+ successProbability,
571
+ estimatedDuration: Math.round(durationEwma),
572
+ resources: resourceEstimates,
573
+ sampleSize: neighbors.length,
574
+ avgSimilarity: weightSum / neighbors.length,
575
+ };
576
+ });
577
+ }
578
+
579
+ /**
580
+ * Stage 4: Score — compute confidence and detect anomalies
581
+ * @private
582
+ * @param {Object} prediction - Raw predictions
583
+ * @param {Object[]} neighbors - k nearest neighbors
584
+ * @param {Object} features - Original features
585
+ * @returns {Object} Scored prediction
586
+ */
587
+ _stageScore(prediction, neighbors, features) {
588
+ return this._runStage(PipelineStage.SCORE, () => {
589
+ const durations = neighbors.map((n) => n.outcome.duration);
590
+ const cv = this._coefficientOfVariation(durations);
591
+
592
+ // Confidence: min(sampleSize / cap, 1.0) * (1 - cv)
593
+ const sampleFactor = Math.min(prediction.sampleSize / this.confidenceSampleCap, 1.0);
594
+ const varianceFactor = Math.max(1 - cv, 0);
595
+ const confidence = sampleFactor * varianceFactor;
596
+
597
+ // Anomaly detection
598
+ const isAnomaly = prediction.avgSimilarity < this.anomalyThreshold;
599
+ if (isAnomaly) {
600
+ this._stats.anomaliesDetected++;
601
+ this.emit('anomaly-detected', {
602
+ taskType: features.taskType,
603
+ avgSimilarity: prediction.avgSimilarity,
604
+ });
605
+ }
606
+
607
+ return {
608
+ ...prediction,
609
+ confidence: Math.round(confidence * 1000) / 1000,
610
+ coefficientOfVariation: Math.round(cv * 1000) / 1000,
611
+ isAnomaly,
612
+ };
613
+ });
614
+ }
615
+
616
+ /**
617
+ * Stage 5: Recommend — suggest agent and strategy
618
+ * @private
619
+ * @param {Object} scored - Scored prediction
620
+ * @param {Object} features - Original features
621
+ * @returns {Object} Final prediction with recommendations
622
+ */
623
+ _stageRecommend(scored, features) {
624
+ return this._runStage(PipelineStage.RECOMMEND, () => {
625
+ const agentRec = this._findBestAgent(features.taskType);
626
+ const strategyRec = this._findBestStrategy(features.taskType);
627
+
628
+ return {
629
+ ...scored,
630
+ recommendedAgent: agentRec,
631
+ recommendedStrategy: strategyRec,
632
+ };
633
+ });
634
+ }
635
+
636
+ // ═════════════════════════════════════════════════════════════════════════════
637
+ // PUBLIC API
638
+ // ═════════════════════════════════════════════════════════════════════════════
639
+
640
+ /**
641
+ * Predict the outcome of a task before execution
642
+ * @param {Object} taskSpec - Task specification
643
+ * @param {string} taskSpec.taskType - Type of task
644
+ * @param {number} [taskSpec.complexity] - Task complexity (1-10)
645
+ * @param {string} [taskSpec.agent] - Agent to execute
646
+ * @param {number} [taskSpec.contextSize] - Size of context
647
+ * @returns {Object} Prediction result
648
+ */
649
+ predict(taskSpec) {
650
+ this._ensureLoaded();
651
+
652
+ const features = this._stagePreprocess(taskSpec);
653
+ const neighbors = this._stageMatch(features);
654
+ const raw = this._stagePredict(neighbors, features);
655
+ const scored = this._stageScore(raw, neighbors, features);
656
+ const final = this._stageRecommend(scored, features);
657
+
658
+ this._stats.predictions++;
659
+
660
+ const result = {
661
+ taskType: features.taskType,
662
+ ...final,
663
+ riskLevel: this._computeRiskLevel(final),
664
+ timestamp: Date.now(),
665
+ };
666
+
667
+ this.emit('prediction', result);
668
+
669
+ // Emit high-risk event
670
+ if (this._riskScore(final) >= this.highRiskThreshold) {
671
+ this.emit('high-risk-detected', result);
672
+ }
673
+
674
+ return result;
675
+ }
676
+
677
+ /**
678
+ * Predict outcomes for multiple tasks in batch
679
+ * @param {Object[]} taskSpecs - Array of task specifications
680
+ * @returns {Object[]} Array of prediction results
681
+ */
682
+ predictBatch(taskSpecs) {
683
+ if (!Array.isArray(taskSpecs)) {
684
+ throw new Error('taskSpecs must be an array');
685
+ }
686
+ return taskSpecs.map((spec) => this.predict(spec));
687
+ }
688
+
689
+ /**
690
+ * Find tasks similar to the given specification
691
+ * @param {Object} taskSpec - Task specification
692
+ * @param {Object} [opts] - Options
693
+ * @param {number} [opts.limit=10] - Maximum results to return
694
+ * @param {number} [opts.minSimilarity=0] - Minimum similarity threshold
695
+ * @returns {Object[]} Similar tasks with similarity scores
696
+ */
697
+ findSimilarTasks(taskSpec, opts = {}) {
698
+ this._ensureLoaded();
699
+
700
+ const limit = opts.limit ?? 10;
701
+ const minSimilarity = opts.minSimilarity ?? 0;
702
+ const features = this._extractFeatures(taskSpec);
703
+
704
+ const scored = this._outcomes.map((outcome) => {
705
+ const outFeatures = this._extractFeatures(outcome);
706
+ const similarity = this._computeSimilarity(features, outFeatures);
707
+ return { ...this._deepClone(outcome), similarity };
708
+ });
709
+
710
+ return scored
711
+ .filter((s) => s.similarity >= minSimilarity)
712
+ .sort((a, b) => b.similarity - a.similarity)
713
+ .slice(0, limit);
714
+ }
715
+
716
+ /**
717
+ * Get the strength of a pattern for a given task type
718
+ * @param {string} taskType - The task type to query
719
+ * @returns {Object} Pattern strength info
720
+ */
721
+ getPatternStrength(taskType) {
722
+ this._ensureLoaded();
723
+
724
+ const stats = this._model.taskTypeStats[taskType];
725
+ if (!stats) {
726
+ return { taskType, sampleSize: 0, strength: 0, successRate: 0, avgDuration: 0 };
727
+ }
728
+
729
+ const cv = this._coefficientOfVariation(stats.durations);
730
+ const sampleFactor = Math.min(stats.count / this.confidenceSampleCap, 1.0);
731
+ const strength = sampleFactor * Math.max(1 - cv, 0);
732
+
733
+ return {
734
+ taskType,
735
+ sampleSize: stats.count,
736
+ strength: Math.round(strength * 1000) / 1000,
737
+ successRate: stats.count > 0 ? Math.round((stats.successes / stats.count) * 1000) / 1000 : 0,
738
+ avgDuration: stats.count > 0 ? Math.round(stats.totalDuration / stats.count) : 0,
739
+ };
740
+ }
741
+
742
+ /**
743
+ * Assess the risk of executing a task
744
+ * @param {Object} taskSpec - Task specification
745
+ * @returns {Object} Risk assessment
746
+ */
747
+ assessRisk(taskSpec) {
748
+ this._ensureLoaded();
749
+
750
+ const features = this._extractFeatures(taskSpec);
751
+ const neighbors = this._stageMatch(features);
752
+ const factors = [];
753
+
754
+ // Factor 1: Low sample size
755
+ const typeStats = this._model.taskTypeStats[features.taskType];
756
+ const sampleSize = typeStats?.count ?? 0;
757
+ if (sampleSize < this.minSamplesForPrediction) {
758
+ factors.push({
759
+ factor: 'low-sample-size',
760
+ description: `Only ${sampleSize} historical outcomes for task type "${features.taskType}"`,
761
+ severity: sampleSize === 0 ? 'high' : 'medium',
762
+ });
763
+ }
764
+
765
+ // Factor 2: High variance
766
+ if (typeStats && typeStats.durations.length >= 2) {
767
+ const cv = this._coefficientOfVariation(typeStats.durations);
768
+ if (cv > 0.5) {
769
+ factors.push({
770
+ factor: 'high-variance',
771
+ description: `Duration coefficient of variation is ${(cv * 100).toFixed(1)}%`,
772
+ severity: cv > 1.0 ? 'high' : 'medium',
773
+ });
774
+ }
775
+ }
776
+
777
+ // Factor 3: New task type
778
+ if (!typeStats) {
779
+ factors.push({
780
+ factor: 'new-task-type',
781
+ description: `Task type "${features.taskType}" has no historical data`,
782
+ severity: 'high',
783
+ });
784
+ }
785
+
786
+ // Factor 4: Low success rate
787
+ if (typeStats && typeStats.count >= this.minSamplesForPrediction) {
788
+ const successRate = typeStats.successes / typeStats.count;
789
+ if (successRate < 0.5) {
790
+ factors.push({
791
+ factor: 'low-success-rate',
792
+ description: `Historical success rate is ${(successRate * 100).toFixed(1)}%`,
793
+ severity: successRate < 0.25 ? 'high' : 'medium',
794
+ });
795
+ }
796
+ }
797
+
798
+ // Factor 5: Low similarity to known tasks (anomaly)
799
+ if (neighbors.length > 0) {
800
+ const avgSim = neighbors.reduce((s, n) => s + n.similarity, 0) / neighbors.length;
801
+ if (avgSim < this.anomalyThreshold) {
802
+ factors.push({
803
+ factor: 'anomaly',
804
+ description: `Task has low similarity (${(avgSim * 100).toFixed(1)}%) to known patterns`,
805
+ severity: 'high',
806
+ });
807
+ }
808
+ }
809
+
810
+ // Factor 6: Overloaded agent
811
+ if (taskSpec.agent) {
812
+ const agentStats = this._model.agentStats[taskSpec.agent];
813
+ if (agentStats && agentStats.count > 0) {
814
+ const agentSuccessRate = agentStats.successes / agentStats.count;
815
+ if (agentSuccessRate < 0.5) {
816
+ factors.push({
817
+ factor: 'agent-low-success',
818
+ description: `Agent "${taskSpec.agent}" has ${(agentSuccessRate * 100).toFixed(1)}% success rate`,
819
+ severity: 'medium',
820
+ });
821
+ }
822
+ }
823
+ }
824
+
825
+ const riskScore = this._computeRiskScoreFromFactors(factors);
826
+ const riskLevel = this._riskLevelFromScore(riskScore);
827
+
828
+ return {
829
+ taskType: features.taskType,
830
+ riskScore: Math.round(riskScore * 1000) / 1000,
831
+ riskLevel,
832
+ factors,
833
+ mitigations: this._suggestMitigations(factors),
834
+ };
835
+ }
836
+
837
+ /**
838
+ * Recommend the best agent for a task type
839
+ * @param {Object} taskSpec - Task specification
840
+ * @returns {Object} Agent recommendation
841
+ */
842
+ recommendAgent(taskSpec) {
843
+ this._ensureLoaded();
844
+
845
+ if (!taskSpec || !taskSpec.taskType) {
846
+ throw new Error('taskSpec.taskType is required');
847
+ }
848
+
849
+ const best = this._findBestAgent(taskSpec.taskType);
850
+ return {
851
+ taskType: taskSpec.taskType,
852
+ recommendation: best,
853
+ };
854
+ }
855
+
856
+ /**
857
+ * Recommend the best strategy for a task type
858
+ * @param {Object} taskSpec - Task specification
859
+ * @returns {Object} Strategy recommendation
860
+ */
861
+ recommendStrategy(taskSpec) {
862
+ this._ensureLoaded();
863
+
864
+ if (!taskSpec || !taskSpec.taskType) {
865
+ throw new Error('taskSpec.taskType is required');
866
+ }
867
+
868
+ const best = this._findBestStrategy(taskSpec.taskType);
869
+ return {
870
+ taskType: taskSpec.taskType,
871
+ recommendation: best,
872
+ };
873
+ }
874
+
875
+ /**
876
+ * Get the pipeline stages in order
877
+ * @returns {string[]} Ordered stage names
878
+ */
879
+ getPipelineStages() {
880
+ return Object.values(PipelineStage);
881
+ }
882
+
883
+ /**
884
+ * Get metrics for a specific pipeline stage
885
+ * @param {string} stageName - Stage name
886
+ * @returns {Object|null} Stage metrics or null if not found
887
+ */
888
+ getStageMetrics(stageName) {
889
+ const metrics = this._stageMetrics[stageName];
890
+ if (!metrics) return null;
891
+
892
+ return {
893
+ stage: stageName,
894
+ calls: metrics.calls,
895
+ totalMs: metrics.totalMs,
896
+ avgMs: metrics.calls > 0 ? Math.round(metrics.totalMs / metrics.calls * 100) / 100 : 0,
897
+ errors: metrics.errors,
898
+ };
899
+ }
900
+
901
+ /**
902
+ * Get overall model accuracy based on recorded outcomes
903
+ * @returns {Object} Model accuracy info
904
+ */
905
+ getModelAccuracy() {
906
+ this._ensureLoaded();
907
+
908
+ const totalTasks = Object.values(this._model.taskTypeStats).reduce((s, t) => s + t.count, 0);
909
+ const totalSuccesses = Object.values(this._model.taskTypeStats).reduce((s, t) => s + t.successes, 0);
910
+
911
+ const perType = {};
912
+ for (const [type, stats] of Object.entries(this._model.taskTypeStats)) {
913
+ perType[type] = {
914
+ count: stats.count,
915
+ successRate: stats.count > 0 ? Math.round((stats.successes / stats.count) * 1000) / 1000 : 0,
916
+ avgDuration: stats.count > 0 ? Math.round(stats.totalDuration / stats.count) : 0,
917
+ };
918
+ }
919
+
920
+ return {
921
+ totalOutcomes: totalTasks,
922
+ overallSuccessRate: totalTasks > 0 ? Math.round((totalSuccesses / totalTasks) * 1000) / 1000 : 0,
923
+ perTaskType: perType,
924
+ lastRetrain: this._model.lastRetrain,
925
+ retrains: this._stats.retrains,
926
+ };
927
+ }
928
+
929
+ /**
930
+ * Retrain the model by recalculating all statistics from outcomes
931
+ * @returns {Promise<Object>} Retrain result
932
+ */
933
+ async retrain() {
934
+ this._ensureLoaded();
935
+
936
+ // Reset model
937
+ this._model = this._emptyModel();
938
+
939
+ // Rebuild from outcomes
940
+ for (const outcome of this._outcomes) {
941
+ this._updateModelStats(outcome);
942
+ }
943
+
944
+ this._model.lastRetrain = Date.now();
945
+ this._model.version++;
946
+ this._stats.retrains++;
947
+
948
+ await this._persistModel();
949
+
950
+ this.emit('model-retrained', {
951
+ version: this._model.version,
952
+ outcomeCount: this._outcomes.length,
953
+ taskTypes: Object.keys(this._model.taskTypeStats).length,
954
+ });
955
+
956
+ return {
957
+ version: this._model.version,
958
+ outcomeCount: this._outcomes.length,
959
+ taskTypes: Object.keys(this._model.taskTypeStats).length,
960
+ };
961
+ }
962
+
963
+ /**
964
+ * Prune old outcomes
965
+ * @param {Object} [options] - Prune options
966
+ * @param {number} [options.olderThan] - Remove outcomes older than this timestamp
967
+ * @returns {Promise<Object>} Prune result
968
+ */
969
+ async prune(options = {}) {
970
+ this._ensureLoaded();
971
+
972
+ const before = this._outcomes.length;
973
+
974
+ if (options.olderThan) {
975
+ this._outcomes = this._outcomes.filter((o) => o.timestamp >= options.olderThan);
976
+ }
977
+
978
+ const removed = before - this._outcomes.length;
979
+
980
+ if (removed > 0) {
981
+ // Retrain after pruning
982
+ this._model = this._emptyModel();
983
+ for (const outcome of this._outcomes) {
984
+ this._updateModelStats(outcome);
985
+ }
986
+ this._model.lastRetrain = Date.now();
987
+
988
+ await this._persistOutcomes();
989
+ await this._persistModel();
990
+ }
991
+
992
+ return { removed, remaining: this._outcomes.length };
993
+ }
994
+
995
+ /**
996
+ * Get general statistics
997
+ * @returns {Object} Stats summary
998
+ */
999
+ getStats() {
1000
+ this._ensureLoaded();
1001
+
1002
+ return {
1003
+ outcomes: this._outcomes.length,
1004
+ taskTypes: Object.keys(this._model.taskTypeStats).length,
1005
+ agents: Object.keys(this._model.agentStats).length,
1006
+ strategies: Object.keys(this._model.strategyStats).length,
1007
+ predictions: this._stats.predictions,
1008
+ outcomesRecorded: this._stats.outcomesRecorded,
1009
+ anomaliesDetected: this._stats.anomaliesDetected,
1010
+ retrains: this._stats.retrains,
1011
+ modelVersion: this._model.version,
1012
+ };
1013
+ }
1014
+
1015
+ // ═════════════════════════════════════════════════════════════════════════════
1016
+ // HELPERS
1017
+ // ═════════════════════════════════════════════════════════════════════════════
1018
+
1019
+ /**
1020
+ * Compute EWMA (Exponentially Weighted Moving Average) from values
1021
+ * @private
1022
+ * @param {number[]} values
1023
+ * @returns {number}
1024
+ */
1025
+ _computeEwma(values) {
1026
+ if (values.length === 0) return 0;
1027
+ if (values.length === 1) return values[0];
1028
+
1029
+ let ewma = values[0];
1030
+ for (let i = 1; i < values.length; i++) {
1031
+ ewma = this.ewmaAlpha * values[i] + (1 - this.ewmaAlpha) * ewma;
1032
+ }
1033
+ return ewma;
1034
+ }
1035
+
1036
+ /**
1037
+ * Compute coefficient of variation (stddev / mean)
1038
+ * @private
1039
+ * @param {number[]} values
1040
+ * @returns {number}
1041
+ */
1042
+ _coefficientOfVariation(values) {
1043
+ if (values.length < 2) return 0;
1044
+
1045
+ const mean = values.reduce((s, v) => s + v, 0) / values.length;
1046
+ if (mean === 0) return 0;
1047
+
1048
+ const variance = values.reduce((s, v) => s + (v - mean) ** 2, 0) / values.length;
1049
+ const stddev = Math.sqrt(variance);
1050
+
1051
+ return stddev / Math.abs(mean);
1052
+ }
1053
+
1054
+ /**
1055
+ * Default prediction when no matching outcomes exist
1056
+ * @private
1057
+ * @param {Object} features
1058
+ * @returns {Object}
1059
+ */
1060
+ _defaultPrediction(features) {
1061
+ return {
1062
+ successProbability: 0.5,
1063
+ estimatedDuration: 0,
1064
+ resources: { memory: 0, cpu: 0, apiCalls: 0 },
1065
+ sampleSize: 0,
1066
+ avgSimilarity: 0,
1067
+ };
1068
+ }
1069
+
1070
+ /**
1071
+ * Compute a numeric risk score from prediction data
1072
+ * @private
1073
+ * @param {Object} prediction
1074
+ * @returns {number} Risk score in [0, 1]
1075
+ */
1076
+ _riskScore(prediction) {
1077
+ let score = 0;
1078
+
1079
+ // Low success probability
1080
+ score += (1 - prediction.successProbability) * 0.4;
1081
+
1082
+ // Low confidence
1083
+ score += (1 - (prediction.confidence ?? 0)) * 0.3;
1084
+
1085
+ // Anomaly
1086
+ if (prediction.isAnomaly) score += 0.2;
1087
+
1088
+ // High variance
1089
+ score += Math.min((prediction.coefficientOfVariation ?? 0), 1) * 0.1;
1090
+
1091
+ return Math.min(score, 1.0);
1092
+ }
1093
+
1094
+ /**
1095
+ * Compute risk level from prediction
1096
+ * @private
1097
+ * @param {Object} prediction
1098
+ * @returns {string} Risk level
1099
+ */
1100
+ _computeRiskLevel(prediction) {
1101
+ const score = this._riskScore(prediction);
1102
+ return this._riskLevelFromScore(score);
1103
+ }
1104
+
1105
+ /**
1106
+ * Map a numeric score to a risk level
1107
+ * @private
1108
+ * @param {number} score
1109
+ * @returns {string}
1110
+ */
1111
+ _riskLevelFromScore(score) {
1112
+ if (score >= 0.8) return RiskLevel.CRITICAL;
1113
+ if (score >= 0.6) return RiskLevel.HIGH;
1114
+ if (score >= 0.3) return RiskLevel.MEDIUM;
1115
+ return RiskLevel.LOW;
1116
+ }
1117
+
1118
+ /**
1119
+ * Compute risk score from risk factors array
1120
+ * @private
1121
+ * @param {Object[]} factors
1122
+ * @returns {number}
1123
+ */
1124
+ _computeRiskScoreFromFactors(factors) {
1125
+ if (factors.length === 0) return 0;
1126
+
1127
+ let score = 0;
1128
+ for (const f of factors) {
1129
+ if (f.severity === 'high') score += 0.25;
1130
+ else if (f.severity === 'medium') score += 0.15;
1131
+ else score += 0.05;
1132
+ }
1133
+
1134
+ return Math.min(score, 1.0);
1135
+ }
1136
+
1137
+ /**
1138
+ * Find the best agent for a task type (highest success rate with enough samples)
1139
+ * @private
1140
+ * @param {string} taskType
1141
+ * @returns {Object|null} Agent recommendation or null
1142
+ */
1143
+ _findBestAgent(taskType) {
1144
+ const agentPerformance = {};
1145
+
1146
+ for (const outcome of this._outcomes) {
1147
+ if (outcome.taskType !== taskType || !outcome.agent) continue;
1148
+
1149
+ if (!agentPerformance[outcome.agent]) {
1150
+ agentPerformance[outcome.agent] = { count: 0, successes: 0, totalDuration: 0 };
1151
+ }
1152
+ const ap = agentPerformance[outcome.agent];
1153
+ ap.count++;
1154
+ if (outcome.success) ap.successes++;
1155
+ ap.totalDuration += outcome.duration;
1156
+ }
1157
+
1158
+ let best = null;
1159
+ let bestScore = -1;
1160
+
1161
+ for (const [agent, perf] of Object.entries(agentPerformance)) {
1162
+ if (perf.count < this.minSamplesForPrediction) continue;
1163
+
1164
+ const successRate = perf.successes / perf.count;
1165
+ // Score: success rate weighted by sample confidence
1166
+ const sampleConfidence = Math.min(perf.count / this.confidenceSampleCap, 1.0);
1167
+ const score = successRate * sampleConfidence;
1168
+
1169
+ if (score > bestScore) {
1170
+ bestScore = score;
1171
+ best = {
1172
+ agent,
1173
+ successRate: Math.round(successRate * 1000) / 1000,
1174
+ sampleSize: perf.count,
1175
+ avgDuration: Math.round(perf.totalDuration / perf.count),
1176
+ score: Math.round(score * 1000) / 1000,
1177
+ };
1178
+ }
1179
+ }
1180
+
1181
+ return best;
1182
+ }
1183
+
1184
+ /**
1185
+ * Find the best strategy for a task type
1186
+ * @private
1187
+ * @param {string} taskType
1188
+ * @returns {Object|null} Strategy recommendation or null
1189
+ */
1190
+ _findBestStrategy(taskType) {
1191
+ const stratPerformance = {};
1192
+
1193
+ for (const outcome of this._outcomes) {
1194
+ if (outcome.taskType !== taskType || !outcome.strategy) continue;
1195
+
1196
+ if (!stratPerformance[outcome.strategy]) {
1197
+ stratPerformance[outcome.strategy] = { count: 0, successes: 0, totalDuration: 0 };
1198
+ }
1199
+ const sp = stratPerformance[outcome.strategy];
1200
+ sp.count++;
1201
+ if (outcome.success) sp.successes++;
1202
+ sp.totalDuration += outcome.duration;
1203
+ }
1204
+
1205
+ let best = null;
1206
+ let bestScore = -1;
1207
+
1208
+ for (const [strategy, perf] of Object.entries(stratPerformance)) {
1209
+ if (perf.count < this.minSamplesForPrediction) continue;
1210
+
1211
+ const successRate = perf.successes / perf.count;
1212
+ const sampleConfidence = Math.min(perf.count / this.confidenceSampleCap, 1.0);
1213
+ const score = successRate * sampleConfidence;
1214
+
1215
+ if (score > bestScore) {
1216
+ bestScore = score;
1217
+ best = {
1218
+ strategy,
1219
+ successRate: Math.round(successRate * 1000) / 1000,
1220
+ sampleSize: perf.count,
1221
+ avgDuration: Math.round(perf.totalDuration / perf.count),
1222
+ score: Math.round(score * 1000) / 1000,
1223
+ };
1224
+ }
1225
+ }
1226
+
1227
+ return best;
1228
+ }
1229
+
1230
+ /**
1231
+ * Suggest mitigations for risk factors
1232
+ * @private
1233
+ * @param {Object[]} factors
1234
+ * @returns {string[]}
1235
+ */
1236
+ _suggestMitigations(factors) {
1237
+ const mitigations = [];
1238
+
1239
+ for (const f of factors) {
1240
+ switch (f.factor) {
1241
+ case 'low-sample-size':
1242
+ mitigations.push('Run a pilot execution to gather baseline data');
1243
+ break;
1244
+ case 'high-variance':
1245
+ mitigations.push('Break task into smaller, more predictable sub-tasks');
1246
+ break;
1247
+ case 'new-task-type':
1248
+ mitigations.push('Start with a dry-run or sandbox execution');
1249
+ break;
1250
+ case 'low-success-rate':
1251
+ mitigations.push('Review historical failures and adjust strategy before execution');
1252
+ break;
1253
+ case 'anomaly':
1254
+ mitigations.push('Manual review recommended — task does not match known patterns');
1255
+ break;
1256
+ case 'agent-low-success':
1257
+ mitigations.push('Consider using a different agent with higher success rate');
1258
+ break;
1259
+ default:
1260
+ mitigations.push('Monitor execution closely');
1261
+ }
1262
+ }
1263
+
1264
+ return mitigations;
1265
+ }
1266
+
1267
+ /**
1268
+ * Generate a unique ID
1269
+ * @private
1270
+ * @returns {string}
1271
+ */
1272
+ _generateId() {
1273
+ const ts = Date.now().toString(36);
1274
+ const rand = Math.random().toString(36).substring(2, 8);
1275
+ return `pred_${ts}_${rand}`;
1276
+ }
1277
+ }
1278
+
1279
+ module.exports = PredictivePipeline;
1280
+ module.exports.PredictivePipeline = PredictivePipeline;
1281
+ module.exports.PipelineStage = PipelineStage;
1282
+ module.exports.RiskLevel = RiskLevel;
1283
+ module.exports.DEFAULTS = DEFAULTS;