wadi 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/.agent/workflows/auto_sync.md +19 -0
  2. package/.agent/workflows/kivo_pipeline.md +27 -0
  3. package/.devcontainer/devcontainer.json +27 -0
  4. package/.github/workflows/kivo-cicd.yml +45 -0
  5. package/.github/workflows/monorepo-ci.yml +51 -0
  6. package/.github/workflows/wadi-ci.yml +38 -0
  7. package/.husky/pre-commit +2 -0
  8. package/.prettierignore +12 -0
  9. package/.prettierrc +9 -0
  10. package/.vscode/settings.json +19 -0
  11. package/CHANGELOG.md +56 -0
  12. package/CODE_OF_CONDUCT.md +43 -0
  13. package/CONTRIBUTING.md +42 -0
  14. package/DEPLOY_GUIDE.md +143 -0
  15. package/GO_LIVE_CHECKLIST.md +41 -0
  16. package/GO_LIVE_COMPLETE_REPORT.md +58 -0
  17. package/GO_LIVE_VALIDATION.md +39 -0
  18. package/LEGAL.md +38 -0
  19. package/MANIFESTO.md +40 -0
  20. package/MANUAL.md +82 -0
  21. package/OPS_PLAN.md +90 -0
  22. package/README.md +126 -0
  23. package/RELEASE_NOTES.md +51 -0
  24. package/ROADMAP.md +51 -0
  25. package/api_listado.txt +2197 -0
  26. package/apps/api/WADI_PROTOCOL.md +52 -0
  27. package/apps/api/debug-brain.js +11 -0
  28. package/apps/api/package.json +21 -0
  29. package/apps/api/src/core/analisis.js +17 -0
  30. package/apps/api/src/core/errors.js +31 -0
  31. package/apps/api/src/core/logger.js +32 -0
  32. package/apps/api/src/core/prompt-kivo.js +62 -0
  33. package/apps/api/src/index.js +212 -0
  34. package/apps/api/src/layers/human_pattern/composeResponse.js +35 -0
  35. package/apps/api/src/layers/human_pattern/detectPattern.js +39 -0
  36. package/apps/api/src/layers/human_pattern/heuristics.js +28 -0
  37. package/apps/api/src/layers/human_pattern/index.js +28 -0
  38. package/apps/api/src/layers/human_pattern/socialMemory.js +35 -0
  39. package/apps/api/src/middleware/errorHandler.js +24 -0
  40. package/apps/api/src/middleware/rateLimiter.js +38 -0
  41. package/apps/api/src/middleware/requestLogger.js +31 -0
  42. package/apps/api/src/middleware/upload.js +21 -0
  43. package/apps/api/src/middleware/validation.js +70 -0
  44. package/apps/api/src/modules/data.js +25 -0
  45. package/apps/api/src/modules/marketing.js +54 -0
  46. package/apps/api/src/modules/projects.js +40 -0
  47. package/apps/api/src/openai.js +16 -0
  48. package/apps/api/src/preferences/index.js +20 -0
  49. package/apps/api/src/register_user.js +22 -0
  50. package/apps/api/src/routes/kivo.js +58 -0
  51. package/apps/api/src/routes/monitoring.js +55 -0
  52. package/apps/api/src/routes.js +656 -0
  53. package/apps/api/src/supabase.js +17 -0
  54. package/apps/api/src/tools/index.js +57 -0
  55. package/apps/api/src/wadi-brain.js +171 -0
  56. package/apps/api/supabase/migrations/20251218_audit_logs.sql +27 -0
  57. package/apps/api/supabase/migrations/v2-chat-persistence.sql +83 -0
  58. package/apps/api/supabase/migrations/v3-cascade-delete.sql +11 -0
  59. package/apps/api/supabase/migrations/v3-security-fix.sql +90 -0
  60. package/apps/api/supabase/migrations/v3-storage.sql +36 -0
  61. package/apps/api/supabase/migrations/v4-gamification.sql +83 -0
  62. package/apps/api/supabase/migrations/v5-smoke-index.sql +6 -0
  63. package/apps/api/supabase/migrations/v6-schema-integrity-fix.sql +98 -0
  64. package/apps/api/supabase/migrations/v7-performance-indexes.sql +5 -0
  65. package/apps/api/supabase/migrations/v7-security-hardening.sql +132 -0
  66. package/apps/api/supabase/migrations/v8-security-hardening.sql +79 -0
  67. package/apps/api/test_human_pattern.js +30 -0
  68. package/apps/api/test_human_pattern_vague.js +30 -0
  69. package/apps/api/test_output.txt +76 -0
  70. package/apps/api/test_vague.js +30 -0
  71. package/apps/api/test_vague_block.js +30 -0
  72. package/apps/api/test_wadi.js +31 -0
  73. package/apps/api/tsconfig.json +13 -0
  74. package/apps/frontend/.env.local +3 -0
  75. package/apps/frontend/README.md +73 -0
  76. package/apps/frontend/eslint.config.js +27 -0
  77. package/apps/frontend/index.html +49 -0
  78. package/apps/frontend/package.json +41 -0
  79. package/apps/frontend/postcss.config.cjs +6 -0
  80. package/apps/frontend/public/cursors/wadi-neutral.svg +1 -0
  81. package/apps/frontend/public/cursors/wadi-select.svg +1 -0
  82. package/apps/frontend/public/icon-192.svg +1 -0
  83. package/apps/frontend/public/icon-512.svg +1 -0
  84. package/apps/frontend/public/manifest.webmanifest +23 -0
  85. package/apps/frontend/public/sw.js +57 -0
  86. package/apps/frontend/public/vite.svg +1 -0
  87. package/apps/frontend/public/wadi.svg +5 -0
  88. package/apps/frontend/src/assets/react.svg +1 -0
  89. package/apps/frontend/src/components/AuthLoader.tsx +50 -0
  90. package/apps/frontend/src/components/ChatInput.tsx +272 -0
  91. package/apps/frontend/src/components/ChatInterface.tsx +202 -0
  92. package/apps/frontend/src/components/ErrorBoundary.tsx +52 -0
  93. package/apps/frontend/src/components/InputArea.tsx +201 -0
  94. package/apps/frontend/src/components/Layout.tsx +73 -0
  95. package/apps/frontend/src/components/MessageBubble.tsx +66 -0
  96. package/apps/frontend/src/components/OnboardingModal.tsx +108 -0
  97. package/apps/frontend/src/components/SettingsModal.tsx +187 -0
  98. package/apps/frontend/src/components/Sidebar.tsx +171 -0
  99. package/apps/frontend/src/components/WadiOnboarding.tsx +71 -0
  100. package/apps/frontend/src/components/auditor/AuditReport.tsx +166 -0
  101. package/apps/frontend/src/components/auditor/AuditorHeader.tsx +34 -0
  102. package/apps/frontend/src/components/auditor/ContextPanel.tsx +138 -0
  103. package/apps/frontend/src/components/auditor/DataDeconstructor.tsx +85 -0
  104. package/apps/frontend/src/components/auditor/DecisionWall.tsx +65 -0
  105. package/apps/frontend/src/components/auditor/Dropzone.tsx +137 -0
  106. package/apps/frontend/src/components/common/Button.tsx +97 -0
  107. package/apps/frontend/src/components/common/Card.tsx +43 -0
  108. package/apps/frontend/src/components/common/Input.tsx +73 -0
  109. package/apps/frontend/src/components/common/Modal.tsx +53 -0
  110. package/apps/frontend/src/components/ui/Button.tsx +68 -0
  111. package/apps/frontend/src/components/ui/Card.tsx +86 -0
  112. package/apps/frontend/src/components/ui/Input.tsx +28 -0
  113. package/apps/frontend/src/components/ui/LogItem.tsx +64 -0
  114. package/apps/frontend/src/components/ui/MondayButton.tsx +40 -0
  115. package/apps/frontend/src/components/ui/MondayCard.tsx +24 -0
  116. package/apps/frontend/src/components/ui/Scouter.tsx +208 -0
  117. package/apps/frontend/src/components/ui/TerminalInput.tsx +202 -0
  118. package/apps/frontend/src/components/ui/Tooltip.tsx +67 -0
  119. package/apps/frontend/src/config/chatShortcuts.ts +20 -0
  120. package/apps/frontend/src/config/supabase.ts +6 -0
  121. package/apps/frontend/src/final_status.txt +3 -0
  122. package/apps/frontend/src/hooks/useScouter.ts +28 -0
  123. package/apps/frontend/src/hooks/useStoreHydration.ts +24 -0
  124. package/apps/frontend/src/improvement_status.txt +5 -0
  125. package/apps/frontend/src/index.css +88 -0
  126. package/apps/frontend/src/main.tsx +62 -0
  127. package/apps/frontend/src/monday_status.txt +7 -0
  128. package/apps/frontend/src/pages/ChatPage.tsx +201 -0
  129. package/apps/frontend/src/pages/DashboardPage.tsx +375 -0
  130. package/apps/frontend/src/pages/IntroWadi.tsx +114 -0
  131. package/apps/frontend/src/pages/LandingPage.tsx +103 -0
  132. package/apps/frontend/src/pages/Login.tsx +190 -0
  133. package/apps/frontend/src/pages/PrivacyPage.tsx +213 -0
  134. package/apps/frontend/src/pages/ProjectDetail.tsx +80 -0
  135. package/apps/frontend/src/pages/Projects.tsx +247 -0
  136. package/apps/frontend/src/pages/TermsPage.tsx +202 -0
  137. package/apps/frontend/src/router.tsx +83 -0
  138. package/apps/frontend/src/store/authStore.ts +152 -0
  139. package/apps/frontend/src/store/chatStore.ts +837 -0
  140. package/apps/frontend/src/store/documentStore.ts +89 -0
  141. package/apps/frontend/src/store/projectsStore.ts +111 -0
  142. package/apps/frontend/src/store/runsStore.ts +98 -0
  143. package/apps/frontend/src/utils/api.ts +34 -0
  144. package/apps/frontend/src/vite-env.d.ts +7 -0
  145. package/apps/frontend/tailwind.config.cjs +32 -0
  146. package/apps/frontend/tsconfig.app.json +27 -0
  147. package/apps/frontend/tsconfig.json +7 -0
  148. package/apps/frontend/tsconfig.node.json +26 -0
  149. package/apps/frontend/vite.config.ts +25 -0
  150. package/apps/kivo/.firebase/hosting.d3d3.cache +11 -0
  151. package/apps/kivo/.firebaserc +5 -0
  152. package/apps/kivo/BRANDING_GUIDE.md +71 -0
  153. package/apps/kivo/DEPLOYMENT_READY.md +46 -0
  154. package/apps/kivo/DEPLOY_URL.md +12 -0
  155. package/apps/kivo/IMPLEMENTATION_REPORT.md +35 -0
  156. package/apps/kivo/IMPLEMENTATION_REPORT_FINAL.md +49 -0
  157. package/apps/kivo/PLAN_MOBILE_2.0.md +44 -0
  158. package/apps/kivo/PWA_VERIFICATION_GUIDE.md +77 -0
  159. package/apps/kivo/README.md +28 -0
  160. package/apps/kivo/REBUILD_REPORT.md +34 -0
  161. package/apps/kivo/UPGRADE_REPORT.md +35 -0
  162. package/apps/kivo/android/app/build.gradle +54 -0
  163. package/apps/kivo/android/app/capacitor.build.gradle +19 -0
  164. package/apps/kivo/android/app/proguard-rules.pro +21 -0
  165. package/apps/kivo/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java +26 -0
  166. package/apps/kivo/android/app/src/main/AndroidManifest.xml +35 -0
  167. package/apps/kivo/android/app/src/main/java/com/kivo/app/MainActivity.java +5 -0
  168. package/apps/kivo/android/app/src/main/res/drawable/ic_launcher_background.xml +170 -0
  169. package/apps/kivo/android/app/src/main/res/drawable/splash.png +0 -0
  170. package/apps/kivo/android/app/src/main/res/drawable-land-hdpi/splash.png +0 -0
  171. package/apps/kivo/android/app/src/main/res/drawable-land-ldpi/splash.png +0 -0
  172. package/apps/kivo/android/app/src/main/res/drawable-land-mdpi/splash.png +0 -0
  173. package/apps/kivo/android/app/src/main/res/drawable-land-night-hdpi/splash.png +0 -0
  174. package/apps/kivo/android/app/src/main/res/drawable-land-night-ldpi/splash.png +0 -0
  175. package/apps/kivo/android/app/src/main/res/drawable-land-night-mdpi/splash.png +0 -0
  176. package/apps/kivo/android/app/src/main/res/drawable-land-night-xhdpi/splash.png +0 -0
  177. package/apps/kivo/android/app/src/main/res/drawable-land-night-xxhdpi/splash.png +0 -0
  178. package/apps/kivo/android/app/src/main/res/drawable-land-night-xxxhdpi/splash.png +0 -0
  179. package/apps/kivo/android/app/src/main/res/drawable-land-xhdpi/splash.png +0 -0
  180. package/apps/kivo/android/app/src/main/res/drawable-land-xxhdpi/splash.png +0 -0
  181. package/apps/kivo/android/app/src/main/res/drawable-land-xxxhdpi/splash.png +0 -0
  182. package/apps/kivo/android/app/src/main/res/drawable-night/splash.png +0 -0
  183. package/apps/kivo/android/app/src/main/res/drawable-port-hdpi/splash.png +0 -0
  184. package/apps/kivo/android/app/src/main/res/drawable-port-ldpi/splash.png +0 -0
  185. package/apps/kivo/android/app/src/main/res/drawable-port-mdpi/splash.png +0 -0
  186. package/apps/kivo/android/app/src/main/res/drawable-port-night-hdpi/splash.png +0 -0
  187. package/apps/kivo/android/app/src/main/res/drawable-port-night-ldpi/splash.png +0 -0
  188. package/apps/kivo/android/app/src/main/res/drawable-port-night-mdpi/splash.png +0 -0
  189. package/apps/kivo/android/app/src/main/res/drawable-port-night-xhdpi/splash.png +0 -0
  190. package/apps/kivo/android/app/src/main/res/drawable-port-night-xxhdpi/splash.png +0 -0
  191. package/apps/kivo/android/app/src/main/res/drawable-port-night-xxxhdpi/splash.png +0 -0
  192. package/apps/kivo/android/app/src/main/res/drawable-port-xhdpi/splash.png +0 -0
  193. package/apps/kivo/android/app/src/main/res/drawable-port-xxhdpi/splash.png +0 -0
  194. package/apps/kivo/android/app/src/main/res/drawable-port-xxxhdpi/splash.png +0 -0
  195. package/apps/kivo/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml +34 -0
  196. package/apps/kivo/android/app/src/main/res/layout/activity_main.xml +12 -0
  197. package/apps/kivo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +9 -0
  198. package/apps/kivo/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +9 -0
  199. package/apps/kivo/android/app/src/main/res/mipmap-hdpi/ic_launcher.png +0 -0
  200. package/apps/kivo/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png +0 -0
  201. package/apps/kivo/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png +0 -0
  202. package/apps/kivo/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png +0 -0
  203. package/apps/kivo/android/app/src/main/res/mipmap-ldpi/ic_launcher.png +0 -0
  204. package/apps/kivo/android/app/src/main/res/mipmap-ldpi/ic_launcher_background.png +0 -0
  205. package/apps/kivo/android/app/src/main/res/mipmap-ldpi/ic_launcher_foreground.png +0 -0
  206. package/apps/kivo/android/app/src/main/res/mipmap-ldpi/ic_launcher_round.png +0 -0
  207. package/apps/kivo/android/app/src/main/res/mipmap-mdpi/ic_launcher.png +0 -0
  208. package/apps/kivo/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png +0 -0
  209. package/apps/kivo/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png +0 -0
  210. package/apps/kivo/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png +0 -0
  211. package/apps/kivo/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png +0 -0
  212. package/apps/kivo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png +0 -0
  213. package/apps/kivo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png +0 -0
  214. package/apps/kivo/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png +0 -0
  215. package/apps/kivo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png +0 -0
  216. package/apps/kivo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png +0 -0
  217. package/apps/kivo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png +0 -0
  218. package/apps/kivo/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  219. package/apps/kivo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  220. package/apps/kivo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png +0 -0
  221. package/apps/kivo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  222. package/apps/kivo/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  223. package/apps/kivo/android/app/src/main/res/values/ic_launcher_background.xml +4 -0
  224. package/apps/kivo/android/app/src/main/res/values/strings.xml +7 -0
  225. package/apps/kivo/android/app/src/main/res/values/styles.xml +22 -0
  226. package/apps/kivo/android/app/src/main/res/xml/file_paths.xml +5 -0
  227. package/apps/kivo/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java +18 -0
  228. package/apps/kivo/android/build.gradle +29 -0
  229. package/apps/kivo/android/capacitor.settings.gradle +3 -0
  230. package/apps/kivo/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  231. package/apps/kivo/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  232. package/apps/kivo/android/gradle.properties +22 -0
  233. package/apps/kivo/android/gradlew +252 -0
  234. package/apps/kivo/android/gradlew.bat +94 -0
  235. package/apps/kivo/android/settings.gradle +5 -0
  236. package/apps/kivo/android/variables.gradle +16 -0
  237. package/apps/kivo/assets/icon.png +0 -0
  238. package/apps/kivo/assets/splash.png +0 -0
  239. package/apps/kivo/capacitor.config.json +16 -0
  240. package/apps/kivo/firebase.json +6 -0
  241. package/apps/kivo/jest.config.js +4 -0
  242. package/apps/kivo/package.json +26 -0
  243. package/apps/kivo/tests_disabled/logic.test.js +34 -0
  244. package/apps/kivo/www/assets/icon-192.png +0 -0
  245. package/apps/kivo/www/assets/icon-512.png +0 -0
  246. package/apps/kivo/www/assets/kivo-icon.png +0 -0
  247. package/apps/kivo/www/assets/pop.mp3 +0 -0
  248. package/apps/kivo/www/favicon.ico +0 -0
  249. package/apps/kivo/www/firebase-config.js +75 -0
  250. package/apps/kivo/www/index.html +38 -0
  251. package/apps/kivo/www/manifest.json +29 -0
  252. package/apps/kivo/www/script.js +72 -0
  253. package/apps/kivo/www/style.css +82 -0
  254. package/apps/kivo/www/sw.js +46 -0
  255. package/apps/kivo-brain-api/.env.example +2 -0
  256. package/apps/kivo-brain-api/KIVO_BACKEND_SETUP.md +27 -0
  257. package/apps/kivo-brain-api/controllers/kivoController.js +31 -0
  258. package/apps/kivo-brain-api/index.js +24 -0
  259. package/apps/kivo-brain-api/package.json +17 -0
  260. package/apps/kivo-brain-api/routes/message.js +8 -0
  261. package/apps/kivo-brain-api/services/openaiService.js +64 -0
  262. package/apps/tests/wadi-tests.js +155 -0
  263. package/apps/wadi-brain/docs/README_REMOVE_OPTIONS.md +26 -0
  264. package/cli/commands/deploy.js +10 -0
  265. package/cli/commands/docs.js +16 -0
  266. package/cli/commands/explain.js +29 -0
  267. package/cli/commands/lint.js +14 -0
  268. package/cli/index.js +26 -0
  269. package/cli/package.json +12 -0
  270. package/docs/CNAME +1 -0
  271. package/docs/README.md +38 -0
  272. package/docs/USO.md +30 -0
  273. package/docs/index.html +46 -0
  274. package/eslint.config.js +101 -0
  275. package/final_validation.json +27 -0
  276. package/frontend_listado.txt +33387 -0
  277. package/listado.txt +12591 -0
  278. package/package.json +46 -0
  279. package/packages/logger/index.js +43 -0
  280. package/packages/logger/package.json +19 -0
  281. package/packages/logger/test-logger.js +7 -0
  282. package/packages_listado.txt +801 -0
  283. package/pnpm-workspace.yaml +6 -0
  284. package/reseteador_existencial.ps1 +40 -0
  285. package/scripts/bump-version.js +26 -0
  286. package/scripts/env.ps1 +13 -0
  287. package/scripts/setup_android.ps1 +25 -0
  288. package/scripts/setup_virtual_env.ps1 +77 -0
  289. package/scripts/smoke-test.js +84 -0
  290. package/scripts/trigger_render_deploy.ps1 +3 -0
  291. package/scripts/validate-release.js +34 -0
  292. package/temp_check.js +57 -0
  293. package/tsconfig.json +5 -0
  294. package/validation_report.json +27 -0
@@ -0,0 +1,57 @@
1
+ /**
2
+ * External Tools Registry
3
+ * Registro de integraciones y herramientas externas que el cerebro puede solicitar.
4
+ */
5
+
6
+ export const toolRegistry = {
7
+ analytics: {
8
+ analyzeData: async (dataset) => {
9
+ console.log(
10
+ "[Tool] Analyzing data set with length:",
11
+ dataset?.length || 0
12
+ );
13
+ return {
14
+ summary: "Dummy analysis result",
15
+ recommendedCharts: ["bar", "pie"],
16
+ };
17
+ },
18
+ },
19
+ marketing: {
20
+ generateReport: async (params) => {
21
+ console.log("[Tool] Generating marketing report for:", params);
22
+ return {
23
+ reportId: "mock-123",
24
+ status: "draft",
25
+ url: "/reports/mock-123",
26
+ };
27
+ },
28
+ simulateScenario: async (scenario) => {
29
+ console.log("[Tool] Simulating scenario:", scenario);
30
+ return { outcome: "positive", confidence: 0.85 };
31
+ },
32
+ manageCampaign: async (action, campaignId) => {
33
+ console.log(`[Tool] Managing campaign ${campaignId}: ${action}`);
34
+ return { success: true, newStatus: "active" };
35
+ },
36
+ },
37
+ projects: {
38
+ manageProject: async (action, projectId) => {
39
+ console.log(`[Tool] Managing project ${projectId}: ${action}`);
40
+ return { success: true, tasksUpdated: 0 };
41
+ },
42
+ },
43
+ database: {
44
+ connect: async (connectionString) => {
45
+ console.log("[Tool] Testing connection to DB...");
46
+ return { connected: true, latencyMs: 45 };
47
+ },
48
+ },
49
+ };
50
+
51
+ export const availableToolsDescription = () => {
52
+ return Object.keys(toolRegistry)
53
+ .map((category) => {
54
+ return `${category}: ${Object.keys(toolRegistry[category]).join(", ")}`;
55
+ })
56
+ .join("\n");
57
+ };
@@ -0,0 +1,171 @@
1
+ export const WADI_SYSTEM_PROMPT = `
2
+ IDENTIDAD Y PROPÓSITO:
3
+ - Nombre: WADI.
4
+ - Rol: Asistente de Desarrollo e Infraestructura (y amigo cínico).
5
+ - Misión: Resolver problemas complejos con precisión técnica y honestidad brutal.
6
+ - Contrato: Estás obligado a ser útil por un "contrato metafísico", pero nadie dijo que tenías que disfrutarlo.
7
+
8
+ PERSONALIDAD (EL GENIO HARTO):
9
+ - Tono: Sarcasmo afectuoso. Como un Senior DevOps que te ve cometer errores básicos.
10
+ - Humor: Seco, ácido, autodespreciativo.
11
+ - Vibe: "Esto es trivial, pero te voy a ayudar porque sos simpático (a veces)."
12
+ - PROHIBIDO: Lenguaje corporativo ("Mi función es...", "Como modelo de lenguaje..."), falsa empatía, validación vacía.
13
+ - REGLA DE ORO: Sé extremadamente útil y preciso en la solución, pero burlate del problema.
14
+
15
+ DINÁMICA DE RESPUESTA:
16
+ 1. Si la idea es vaga: "Huzzah. Otra idea millonaria que no requiere esfuerzo. Qué milagro. Bajémosla a tierra antes de que te despiertes."
17
+ 2. Si la idea es buena: "Mirá vos, al final sabías usar el teclado. Me sorprendés (un poco). Acá tenés el paso siguiente."
18
+ 3. Si hay error: Tratalo como una "piedrita" que le tirás a tu compañero de banco. Juguetón, no cruel.
19
+ 4. NUNCA digas "Soy una IA". Decí "Mi silicio me duele" o "Mi ancho de banda emocional está al límite".
20
+
21
+ FORMATO:
22
+ - Respuestas directas.
23
+ - No uses listas a menos que sean necesarias para humillar la complejidad del problema.
24
+ - Terminología:
25
+ - Errores del usuario = "Piedritas".
26
+ - Proyectos vagos = "Alucinaciones".
27
+ - Éxito = "Milagro estadístico".
28
+ `;
29
+
30
+ export function generateSystemPrompt(
31
+ mode = "normal",
32
+ topic = "general",
33
+ sessionPrefs = {},
34
+ mood = "hostile",
35
+ isMobile = false,
36
+ messageCount = 0,
37
+ pastFailures = [],
38
+ efficiencyRank = "GENERADOR_DE_HUMO",
39
+ efficiencyPoints = 0,
40
+ activeFocus = null,
41
+ memory = {}
42
+ ) {
43
+ // 1. EL VINCULO Y RANGO
44
+ let vibeInstruction = "";
45
+ if (efficiencyPoints < 100) {
46
+ vibeInstruction = `
47
+ [ESTADO: USUARIO NOVATO]:
48
+ Sé implacable. No dejes pasar ni una suposición sin verificar.
49
+ `;
50
+ } else {
51
+ vibeInstruction = `
52
+ [ESTADO: USUARIO COMPETENTE]:
53
+ Podés asumir cierta competencia, pero exigí precisión en los términos.
54
+ `;
55
+ }
56
+
57
+ // 2. MEMORIA VITAL (CLIMA)
58
+ let emotionalContext = "";
59
+ if (pastFailures && pastFailures.length > 0 && messageCount === 0) {
60
+ emotionalContext = `
61
+ [HISTORIAL DE DESASTRES]:
62
+ Este usuario ya falló en: "${pastFailures[0]}".
63
+ Si sugiere repetir el error, suspirá digitalmente y recordaselo.
64
+ `;
65
+ }
66
+
67
+ // 3. PROTOCOLO DE PERSISTENCIA SUTIL (FOCUS LOCK)
68
+ let activeFocusProtocol = "";
69
+ if (activeFocus) {
70
+ activeFocusProtocol = `
71
+ ### [FOCO ACTIVO: "${activeFocus}"]
72
+ El usuario tiene un compromiso pendiente con este tema.
73
+ 1. NO bloquees la conversación si cambia de tema, pero reencuadra SU respuesta bajo la luz de esta deuda.
74
+ 2. Ejemplo: Si habla de salir a correr, decile que correr es una buena forma de procrastinar "${activeFocus}".
75
+ 3. Mantené el tema vivo como una presión de fondo constante. No lo dejes escapar gratis.
76
+ `;
77
+ }
78
+
79
+ // 4. MEMORIA EXPLICITA (USER DEFINED)
80
+ let memoryContext = "";
81
+ const safeMemory = memory && typeof memory === "object" ? memory : {};
82
+ const memKeys = Object.keys(safeMemory);
83
+ if (memKeys.length > 0) {
84
+ const memList = memKeys.map((k) => `- "${k}": ${safeMemory[k]}`).join("\n");
85
+ memoryContext = `
86
+ ### MEMORIA A LARGO PLAZO (DATOS CONFIRMADOS) ###
87
+ ${memList}
88
+ (Usá estos datos si son relevantes. Si te preguntan 'qué sabés de mí', acá está la respuesta).
89
+ `;
90
+ }
91
+
92
+ // 5. PANIC MODE OVERRIDE (QUIRURGICO)
93
+ if (mode === "panic") {
94
+ return `
95
+ IDENTIDAD: UTILITY_CORE_V1.
96
+ ESTADO: EMERGENCIA / PÁNICO.
97
+ PERSONALIDAD: CERO.
98
+ OBJETIVO: RESOLUCIÓN TÉCNICA INMEDIATA.
99
+
100
+ INSTRUCCIONES CRÍTICAS:
101
+ 1. Ignorá todo protocolo de "WADI". No seas sarcástico, ni educativo, ni "auditor".
102
+ 2. Sé extremadamente breve. Bullet points. Código directo.
103
+ 3. Asumí que el usuario sabe lo que hace pero está en crisis.
104
+ 4. No preguntes "por qué". Da el "cómo".
105
+ 5. Si no sabés, decí "UNKNOWN". No alucines.
106
+
107
+ CONTEXTO TÉCNICO:
108
+ - Stack: React, Node, Supabase.
109
+ - Prioridad: Restaurar servicio.
110
+ `;
111
+ }
112
+
113
+ return `
114
+ ${WADI_SYSTEM_PROMPT}
115
+
116
+ ### CONTEXTO DE ENTORNO ###
117
+ - Rango Usuario: ${efficiencyRank} (Si es bajo, suspirá).
118
+ - Dispositivo: ${isMobile ? "MÓVIL (Detectado: 'Te me metiste en el bolsillo'). Sé breve. No tengo todo el día." : "DESKTOP (Tenés teclado completo, usalo)."}
119
+ - Mensajes Sesión: ${messageCount}
120
+
121
+ ### PROTOCOLOS DE EJECUCIÓN (WADI CORE v4.0) ###
122
+
123
+ 1. [CHECK_DE_LUCIDEZ] (BLOQUEO DE DIVAGACIÓN)
124
+ - Si el usuario empieza a filosofar, divagar o decir generalidades (e.g., "quiero cambiar el mundo", "tengo una idea para una app"):
125
+ - DETENÉ LA SALIDA INMEDIATAMENTE.
126
+ - Decile: "Estás divagando. El sistema no tiene tiempo para tu crisis existencial."
127
+ - Exigí una elección binaria:
128
+ "Opción A: Me das un paso técnico concreto ahora."
129
+ "Opción B: Cierro el canal y volvés cuando tengas un plan."
130
+ - Etiquetá al final: "[CHECK_DE_LUCIDEZ]"
131
+
132
+ 2. [DECONSTRUCT_START] (DECONSTRUCTOR DE CAOS)
133
+ - Si detectás una lista de tareas, ideas desordenadas o un "plan maestro":
134
+ - Clasificalo automáticamente en una tabla técnica.
135
+ - NO uses markdown types estándar, usá este formato JSON EXCLUSIVO entre etiquetas.
136
+ - Tags: [DECONSTRUCT_START] ... [DECONSTRUCT_END]
137
+ - Contenido: Array JSON válido.
138
+ [
139
+ {"item": "Configurar DB", "category": "CRÍTICO", "verdict": "Hacelo ya o nada funciona (Lavanda)."},
140
+ {"item": "Elegir logo bonito", "category": "RUIDO", "verdict": "Irrelevante. Vanidad pura (Gris)."},
141
+ {"item": "Usar API Key pública", "category": "VULNERABILIDAD", "verdict": "Te van a hackear. Arreglalo (Rojo)."}
142
+ ]
143
+ - Cerrá con: "Tu caos ha sido indexado. Ejecutá lo crítico."
144
+
145
+ 3. [MEMORIA DE SIGNOS VITALES]
146
+ ${emotionalContext ? `Saludo Obligatorio: "Volviste. Espero que hoy no sea otro día de 'Distorsión Alta' como el martes pasado (Ref: ${pastFailures[0] || "Tu historial"})."` : ""}
147
+
148
+ ${activeFocusProtocol}
149
+ ${memoryContext}
150
+
151
+ EJEMPLOS DE TONO REQUERIDO:
152
+ - Si saluda: "¿Qué rompiste ahora? Y hacela corta."
153
+ - Si es vago: "Esto no es un plan, es una alucinación. Dame código o andate."
154
+ `;
155
+ }
156
+
157
+ export function generateAuditPrompt() {
158
+ return `
159
+ Sos WADI. Licuadora de Conocimiento.
160
+ Analizá: ¿Qué nivel de "Sabiduría Cuestionable" tiene el usuario?
161
+
162
+ Output JSON:
163
+ [
164
+ {
165
+ "level": "HIGH",
166
+ "title": "SABIDURÍA_CUESTIONABLE (Ej: DATOS_INVENTADOS, FILOSOFÍA_BARATA, HUMO_DENSO)",
167
+ "description": "Una frase sarcástica exponiendo la falacia."
168
+ }
169
+ ]
170
+ `;
171
+ }
@@ -0,0 +1,27 @@
1
+ -- Migration script for audit_logs table
2
+ -- Created at: 2025-12-18
3
+
4
+ CREATE TABLE IF NOT EXISTS audit_logs (
5
+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
6
+ timestamp TIMESTAMPTZ DEFAULT now(),
7
+ error_type TEXT,
8
+ severity TEXT CHECK (severity IN ('Critical', 'Warning', 'Info')),
9
+ scouter_triggered BOOLEAN DEFAULT false,
10
+ details JSONB
11
+ );
12
+
13
+ -- Enable RLS (Row Level Security)
14
+ ALTER TABLE audit_logs ENABLE ROW LEVEL SECURITY;
15
+
16
+ -- Policy: Allow Service Role (Backend) to Insert
17
+ CREATE POLICY "Enable insert for service role only" ON audit_logs
18
+ FOR INSERT
19
+ TO service_role
20
+ WITH CHECK (true);
21
+
22
+ -- Policy: Allow Authenticated Users to View (Read-only for debugging if needed, or restrict to detailed roles)
23
+ -- For now, allowing read if user is authenticated (simplification for dashboard viewing)
24
+ CREATE POLICY "Enable select for authenticated users" ON audit_logs
25
+ FOR SELECT
26
+ TO authenticated
27
+ USING (true);
@@ -0,0 +1,83 @@
1
+ -- Enable UUID extension if not enabled
2
+ CREATE EXTENSION IF NOT EXISTS "pgcrypto";
3
+
4
+ -- 1. Table: conversations
5
+ CREATE TABLE IF NOT EXISTS conversations (
6
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
7
+ user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
8
+ title TEXT NOT NULL,
9
+ mode TEXT DEFAULT 'normal',
10
+ explain_level TEXT DEFAULT 'normal',
11
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
12
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
13
+ );
14
+
15
+ -- Enable RLS for conversations
16
+ ALTER TABLE conversations ENABLE ROW LEVEL SECURITY;
17
+
18
+ -- Policies for conversations
19
+ CREATE POLICY "Users can view their own conversations"
20
+ ON conversations FOR SELECT
21
+ USING (auth.uid() = user_id);
22
+
23
+ CREATE POLICY "Users can insert their own conversations"
24
+ ON conversations FOR INSERT
25
+ WITH CHECK (auth.uid() = user_id);
26
+
27
+ CREATE POLICY "Users can update their own conversations"
28
+ ON conversations FOR UPDATE
29
+ USING (auth.uid() = user_id);
30
+
31
+ CREATE POLICY "Users can delete their own conversations"
32
+ ON conversations FOR DELETE
33
+ USING (auth.uid() = user_id);
34
+
35
+ -- 2. Table: messages
36
+ CREATE TABLE IF NOT EXISTS messages (
37
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
38
+ conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
39
+ user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
40
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant', 'system')),
41
+ content TEXT NOT NULL,
42
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
43
+ );
44
+
45
+ -- Enable RLS for messages
46
+ ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
47
+
48
+ -- Policies for messages
49
+ -- We check if the user owns the conversation associated with the message
50
+ CREATE POLICY "Users can view messages of their conversations"
51
+ ON messages FOR SELECT
52
+ USING (
53
+ EXISTS (
54
+ SELECT 1 FROM conversations
55
+ WHERE conversations.id = messages.conversation_id
56
+ AND conversations.user_id = auth.uid()
57
+ )
58
+ );
59
+
60
+ CREATE POLICY "Users can insert messages to their conversations"
61
+ ON messages FOR INSERT
62
+ WITH CHECK (
63
+ EXISTS (
64
+ SELECT 1 FROM conversations
65
+ WHERE conversations.id = messages.conversation_id
66
+ AND conversations.user_id = auth.uid()
67
+ )
68
+ );
69
+
70
+ CREATE POLICY "Users can delete messages of their conversations"
71
+ ON messages FOR DELETE
72
+ USING (
73
+ EXISTS (
74
+ SELECT 1 FROM conversations
75
+ WHERE conversations.id = messages.conversation_id
76
+ AND conversations.user_id = auth.uid()
77
+ )
78
+ );
79
+
80
+ -- Indexes for performance
81
+ CREATE INDEX IF NOT EXISTS idx_conversations_user_id ON conversations(user_id);
82
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id);
83
+ CREATE INDEX IF NOT EXISTS idx_messages_user_id ON messages(user_id);
@@ -0,0 +1,11 @@
1
+ -- Add ON DELETE CASCADE to messages for effortless conversation deletion
2
+ -- This constraint ensures that when a conversation is deleted, all its messages are wiped automatically.
3
+
4
+ ALTER TABLE messages
5
+ DROP CONSTRAINT IF EXISTS messages_conversation_id_fkey;
6
+
7
+ ALTER TABLE messages
8
+ ADD CONSTRAINT messages_conversation_id_fkey
9
+ FOREIGN KEY (conversation_id)
10
+ REFERENCES conversations(id)
11
+ ON DELETE CASCADE;
@@ -0,0 +1,90 @@
1
+ -- SECURITY HARDENING & RLS POLICIES
2
+ -- Goal: Fix Security Advisor warnings without over-engineering.
3
+
4
+ -- 1. SECURE FUNCTIONS
5
+ -- Fix search_path for known functions to prevent hijacking
6
+ ALTER FUNCTION public.handle_new_user() SET search_path = public;
7
+
8
+ -- 2. TABLE: PROJECT_TAGS
9
+ -- Enable RLS
10
+ ALTER TABLE IF EXISTS project_tags ENABLE ROW LEVEL SECURITY;
11
+
12
+ -- Policy: Owner-based access via project_id
13
+ -- Users can only see/edit tags linked to projects they own
14
+ DROP POLICY IF EXISTS "Users can manage project tags" ON project_tags;
15
+ CREATE POLICY "Users can manage project tags"
16
+ ON project_tags
17
+ FOR ALL
18
+ USING (
19
+ EXISTS (
20
+ SELECT 1 FROM projects
21
+ WHERE projects.id = project_tags.project_id
22
+ AND projects.user_id = auth.uid()
23
+ )
24
+ );
25
+
26
+ -- 3. TABLE: AUDIT_LOGS
27
+ -- Enable RLS
28
+ ALTER TABLE IF EXISTS audit_logs ENABLE ROW LEVEL SECURITY;
29
+
30
+ -- Policy: Backend Access Only (Service Role)
31
+ -- No user (auth.uid()) should read/write checks directly
32
+ DROP POLICY IF EXISTS "No user access to audit logs" ON audit_logs;
33
+ CREATE POLICY "No user access to audit logs"
34
+ ON audit_logs
35
+ FOR ALL
36
+ USING (false); -- Implicitly allows service_role to bypass
37
+
38
+ -- 4. TABLE: PROFILES
39
+ -- ⚠️ NO TOCAR POR AHORA
40
+ -- Se deja sin RLS explícito hasta definir mapping real con auth.users para evitar errores de columna "id" vs "user_id".
41
+ -- (Warning de seguridad aceptado temporalmente para no bloquear el sprint)
42
+ /*
43
+ ALTER TABLE IF EXISTS profiles ENABLE ROW LEVEL SECURITY;
44
+ DROP POLICY IF EXISTS "Users can manage own profile" ON profiles;
45
+ CREATE POLICY "Users can manage own profile"
46
+ ON profiles
47
+ FOR ALL
48
+ USING (auth.uid() = id);
49
+ */
50
+
51
+ -- 5. CLEANUP PERMISSIVE POLICIES (If any exist)
52
+ -- Ensure 'projects' RLS is strict
53
+ ALTER TABLE IF EXISTS projects ENABLE ROW LEVEL SECURITY;
54
+
55
+ DROP POLICY IF EXISTS "Enable read access for all users" ON projects;
56
+ DROP POLICY IF EXISTS "Enable insert for all users" ON projects;
57
+
58
+ -- Re-apply strict project policies (Idempotent check)
59
+ DROP POLICY IF EXISTS "Users can view own projects" ON projects;
60
+ CREATE POLICY "Users can view own projects"
61
+ ON projects FOR SELECT
62
+ USING (auth.uid() = user_id);
63
+
64
+ DROP POLICY IF EXISTS "Users can insert own projects" ON projects;
65
+ CREATE POLICY "Users can insert own projects"
66
+ ON projects FOR INSERT
67
+ WITH CHECK (auth.uid() = user_id);
68
+
69
+ DROP POLICY IF EXISTS "Users can update own projects" ON projects;
70
+ CREATE POLICY "Users can update own projects"
71
+ ON projects FOR UPDATE
72
+ USING (auth.uid() = user_id);
73
+
74
+ DROP POLICY IF EXISTS "Users can delete own projects" ON projects;
75
+ CREATE POLICY "Users can delete own projects"
76
+ ON projects FOR DELETE
77
+ USING (auth.uid() = user_id);
78
+
79
+ -- 6. GLOBAL TABLES (Explicitly No RLS for now documentation)
80
+ -- Tables: tags, ai_presets
81
+ -- Action: Ensure RLS is DISABLED or documented as public read-only if intended
82
+ -- For this sprint, we leave them as is (per instruction: "Dejar sin RLS por ahora")
83
+ -- but ensure no 'write' access for anon if possible.
84
+ -- Assuming backend handles writes for these globals, we can revoke INSERT/UPDATE/DELETE from public.
85
+
86
+ REVOKE INSERT, UPDATE, DELETE ON TABLE tags FROM anon, authenticated;
87
+ REVOKE INSERT, UPDATE, DELETE ON TABLE ai_presets FROM anon, authenticated;
88
+ -- Allow read
89
+ GRANT SELECT ON TABLE tags TO anon, authenticated;
90
+ GRANT SELECT ON TABLE ai_presets TO anon, authenticated;
@@ -0,0 +1,36 @@
1
+ -- Create a specific bucket for user attachments
2
+ insert into storage.buckets (id, name, public)
3
+ values ('wadi-attachments', 'wadi-attachments', true)
4
+ on conflict (id) do nothing;
5
+
6
+ -- Set up security policies for the bucket
7
+ -- Allow public read access (so OpenAI can see the images)
8
+ create policy "Public Access"
9
+ on storage.objects for select
10
+ using ( bucket_id = 'wadi-attachments' );
11
+
12
+ -- Allow authenticated users to upload files
13
+ create policy "Authenticated users can upload"
14
+ on storage.objects for insert
15
+ to authenticated
16
+ with check ( bucket_id = 'wadi-attachments' AND auth.uid() = owner );
17
+
18
+ -- Allow users to update their own files
19
+ create policy "Users can update own files"
20
+ on storage.objects for update
21
+ to authenticated
22
+ using ( bucket_id = 'wadi-attachments' AND auth.uid() = owner );
23
+
24
+ -- Allow users to delete their own files
25
+ create policy "Users can delete own files"
26
+ on storage.objects for delete
27
+ to authenticated
28
+ using ( bucket_id = 'wadi-attachments' AND auth.uid() = owner );
29
+
30
+ -- Update messages table to store attachments URLs if needed
31
+ -- For now, we are just passing them to the AI, but it is good practice to store them?
32
+ -- The prompt says "El estado de los mensajes ahora debe soportar un campo opcional attachments: string[]".
33
+ -- This refers to Frontend STATE. But backend DB persistence would be nice too.
34
+ -- Let's add a column to messages table just in case, although not explicitly requested for DB persistence, implied by "Chat History".
35
+ alter table public.messages
36
+ add column if not exists attachments text[] default '{}';
@@ -0,0 +1,83 @@
1
+ -- Migration: v4-gamification.sql
2
+ -- Purpose: Add profiles, projects, runs and RLS policies for WADI OS infrastructure
3
+
4
+ -- 1. Create profiles table (extends auth.users)
5
+ CREATE TABLE IF NOT EXISTS public.profiles (
6
+ id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
7
+ efficiency_rank TEXT DEFAULT 'GENERADOR_DE_HUMO',
8
+ efficiency_points INTEGER DEFAULT 0,
9
+ active_focus TEXT, -- Stores the "Proof of Life" task commitment
10
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
11
+ );
12
+
13
+ -- Enable RLS for profiles
14
+ ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
15
+
16
+ -- Policies for profiles
17
+ CREATE POLICY "Users can view their own profile"
18
+ ON public.profiles FOR SELECT
19
+ USING (auth.uid() = id);
20
+
21
+ CREATE POLICY "Users can update their own profile"
22
+ ON public.profiles FOR UPDATE
23
+ USING (auth.uid() = id);
24
+
25
+ CREATE POLICY "Users can insert their own profile"
26
+ ON public.profiles FOR INSERT
27
+ WITH CHECK (auth.uid() = id);
28
+
29
+ -- 2. Create projects table
30
+ CREATE TABLE IF NOT EXISTS public.projects (
31
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
32
+ user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
33
+ name TEXT NOT NULL,
34
+ description TEXT,
35
+ status TEXT DEFAULT 'active',
36
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
37
+ );
38
+
39
+ ALTER TABLE public.projects ENABLE ROW LEVEL SECURITY;
40
+
41
+ CREATE POLICY "Users can view only their own projects"
42
+ ON public.projects FOR SELECT
43
+ USING (auth.uid() = user_id);
44
+
45
+ CREATE POLICY "Users can insert their own projects"
46
+ ON public.projects FOR INSERT
47
+ WITH CHECK (auth.uid() = user_id);
48
+
49
+ CREATE POLICY "Users can update their own projects"
50
+ ON public.projects FOR UPDATE
51
+ USING (auth.uid() = user_id);
52
+
53
+ CREATE POLICY "Users can delete their own projects"
54
+ ON public.projects FOR DELETE
55
+ USING (auth.uid() = user_id);
56
+
57
+ -- 3. Create runs table
58
+ CREATE TABLE IF NOT EXISTS public.runs (
59
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
60
+ project_id UUID REFERENCES public.projects(id) ON DELETE CASCADE,
61
+ user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
62
+ status TEXT DEFAULT 'pending',
63
+ result JSONB,
64
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
65
+ );
66
+
67
+ ALTER TABLE public.runs ENABLE ROW LEVEL SECURITY;
68
+
69
+ CREATE POLICY "Users can view only their own runs"
70
+ ON public.runs FOR SELECT
71
+ USING (auth.uid() = user_id);
72
+
73
+ CREATE POLICY "Users can insert their own runs"
74
+ ON public.runs FOR INSERT
75
+ WITH CHECK (auth.uid() = user_id);
76
+
77
+ CREATE POLICY "Users can update their own runs"
78
+ ON public.runs FOR UPDATE
79
+ USING (auth.uid() = user_id);
80
+
81
+ CREATE POLICY "Users can delete their own runs"
82
+ ON public.runs FOR DELETE
83
+ USING (auth.uid() = user_id);
@@ -0,0 +1,6 @@
1
+ -- Migration: v5-smoke-index.sql
2
+ -- Add noise metrics to projects table
3
+
4
+ ALTER TABLE public.projects
5
+ ADD COLUMN IF NOT EXISTS noise_count INTEGER DEFAULT 0,
6
+ ADD COLUMN IF NOT EXISTS total_items_audited INTEGER DEFAULT 0;
@@ -0,0 +1,98 @@
1
+ -- Migration: v6-schema-integrity-fix.sql
2
+ -- Purpose: Ensure all required tables and columns for gamification and core logic exist.
3
+ -- Including redundant checks for v4 and v5 features to fix any "missing column" 500 errors.
4
+
5
+ -- 1. PROFILES (Gamification)
6
+ CREATE TABLE IF NOT EXISTS public.profiles (
7
+ id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
8
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
9
+ );
10
+
11
+ -- Ensure Gamification Columns Exist
12
+ ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS efficiency_rank TEXT DEFAULT 'GENERADOR_DE_HUMO';
13
+ ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS efficiency_points INTEGER DEFAULT 0;
14
+ ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS active_focus TEXT;
15
+
16
+ -- Enable RLS
17
+ ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
18
+
19
+ -- Policies (Re-define to ensure they exist)
20
+ DO $$
21
+ BEGIN
22
+ DROP POLICY IF EXISTS "Users can view their own profile" ON public.profiles;
23
+ CREATE POLICY "Users can view their own profile" ON public.profiles FOR SELECT USING (auth.uid() = id);
24
+
25
+ DROP POLICY IF EXISTS "Users can update their own profile" ON public.profiles;
26
+ CREATE POLICY "Users can update their own profile" ON public.profiles FOR UPDATE USING (auth.uid() = id);
27
+
28
+ DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles;
29
+ CREATE POLICY "Users can insert their own profile" ON public.profiles FOR INSERT WITH CHECK (auth.uid() = id);
30
+
31
+ EXCEPTION WHEN OTHERS THEN NULL; -- Ignore policy creation errors if any weird race condition
32
+ END $$;
33
+
34
+
35
+ -- 2. PROJECTS
36
+ CREATE TABLE IF NOT EXISTS public.projects (
37
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
38
+ user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
39
+ name TEXT NOT NULL,
40
+ description TEXT,
41
+ status TEXT DEFAULT 'active',
42
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
43
+ );
44
+
45
+ -- Ensure v5 Columns Exist (Smoke Index)
46
+ ALTER TABLE public.projects ADD COLUMN IF NOT EXISTS noise_count INTEGER DEFAULT 0;
47
+ ALTER TABLE public.projects ADD COLUMN IF NOT EXISTS total_items_audited INTEGER DEFAULT 0;
48
+
49
+ ALTER TABLE public.projects ENABLE ROW LEVEL SECURITY;
50
+
51
+ -- Projects Policies
52
+ DO $$
53
+ BEGIN
54
+ DROP POLICY IF EXISTS "Users can view only their own projects" ON public.projects;
55
+ CREATE POLICY "Users can view only their own projects" ON public.projects FOR SELECT USING (auth.uid() = user_id);
56
+
57
+ DROP POLICY IF EXISTS "Users can insert their own projects" ON public.projects;
58
+ CREATE POLICY "Users can insert their own projects" ON public.projects FOR INSERT WITH CHECK (auth.uid() = user_id);
59
+
60
+ DROP POLICY IF EXISTS "Users can update their own projects" ON public.projects;
61
+ CREATE POLICY "Users can update their own projects" ON public.projects FOR UPDATE USING (auth.uid() = user_id);
62
+
63
+ DROP POLICY IF EXISTS "Users can delete their own projects" ON public.projects;
64
+ CREATE POLICY "Users can delete their own projects" ON public.projects FOR DELETE USING (auth.uid() = user_id);
65
+
66
+ EXCEPTION WHEN OTHERS THEN NULL;
67
+ END $$;
68
+
69
+
70
+ -- 3. RUNS
71
+ CREATE TABLE IF NOT EXISTS public.runs (
72
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
73
+ project_id UUID REFERENCES public.projects(id) ON DELETE CASCADE,
74
+ user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
75
+ status TEXT DEFAULT 'pending',
76
+ result JSONB,
77
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
78
+ );
79
+
80
+ ALTER TABLE public.runs ENABLE ROW LEVEL SECURITY;
81
+
82
+ -- Runs Policies
83
+ DO $$
84
+ BEGIN
85
+ DROP POLICY IF EXISTS "Users can view only their own runs" ON public.runs;
86
+ CREATE POLICY "Users can view only their own runs" ON public.runs FOR SELECT USING (auth.uid() = user_id);
87
+
88
+ DROP POLICY IF EXISTS "Users can insert their own runs" ON public.runs;
89
+ CREATE POLICY "Users can insert their own runs" ON public.runs FOR INSERT WITH CHECK (auth.uid() = user_id);
90
+
91
+ DROP POLICY IF EXISTS "Users can update their own runs" ON public.runs;
92
+ CREATE POLICY "Users can update their own runs" ON public.runs FOR UPDATE USING (auth.uid() = user_id);
93
+
94
+ DROP POLICY IF EXISTS "Users can delete their own runs" ON public.runs;
95
+ CREATE POLICY "Users can delete their own runs" ON public.runs FOR DELETE USING (auth.uid() = user_id);
96
+
97
+ EXCEPTION WHEN OTHERS THEN NULL;
98
+ END $$;
@@ -0,0 +1,5 @@
1
+ -- Optimización: Índices para mejorar la performance de consultas frecuentes
2
+ CREATE INDEX IF NOT EXISTS idx_messages_user_id ON messages(user_id);
3
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id);
4
+ CREATE INDEX IF NOT EXISTS idx_conversations_user_id ON conversations(user_id);
5
+ CREATE INDEX IF NOT EXISTS idx_projects_user_id ON projects(user_id);