Compare commits

...
Sign in to create a new pull request.

408 commits
master ... main

Author SHA1 Message Date
4b67b0f486 Update botbook submodule reference 2026-04-07 13:36:38 -03:00
49bc6e52bc Update root: cleanup, botserver and botmodels updates 2026-04-07 13:34:11 -03:00
a8ae578a80 Update botapp to valid pushed commit 2026-04-06 14:12:51 -03:00
b2995cdcdb Update submodules: botserver (DETECT fix + anonymous auth), botui (session_id) 2026-04-06 13:37:52 -03:00
4f510d1196 docs: Update AGENTS.md with bot scripts architecture and TOOL_EXEC info 2026-04-05 19:55:53 -03:00
d28510a632 fix: deploy workflow - ignore missing binary on first deploy 2026-04-05 19:39:18 -03:00
e094dc138a Update submodules: tool execution via WebSocket, TOOL_EXEC message type 2026-04-05 19:11:28 -03:00
07b6af9bf3 docs: update AGENTS.md with correct data paths 2026-04-05 13:32:42 -03:00
a5f16fbab9 docs: update AGENTS.md with DETECT testing notes 2026-04-05 13:30:17 -03:00
2257c980cb Update botserver: fix diesel imports 2026-04-05 13:19:40 -03:00
123771c996 Update AGENTS.md: add data directory structure and testing tools section 2026-04-05 12:49:15 -03:00
f767337ed8 Update botserver submodule 2026-04-05 12:34:46 -03:00
d598bdc29a Update botserver submodule 2026-04-05 12:06:45 -03:00
b45f63a7a6 Update botserver submodule to latest commit with Zitadel fix 2026-04-05 11:32:46 -03:00
e1b456d199 Add submodule push rule to AGENTS.md 2026-04-05 11:30:32 -03:00
96ece5a3ea Trigger CI rebuild 2026-04-05 11:28:14 -03:00
1662905a32 Update botserver submodule 2026-04-05 11:08:20 -03:00
d0d68e792e Update AGENTS.md: Zitadel setup with container networking 2026-04-05 11:04:33 -03:00
fc95cba887 Update submodules: botserver, botui and project guidelines. 2026-04-05 09:12:32 -03:00
93dc55c47c Update botserver: Remove unused sync functions 2026-04-05 07:52:52 -03:00
0c1a988f82 Update botserver: Fix Vault SMTP module 2026-04-05 07:50:46 -03:00
dcabb6c0bc Update botserver submodule reference
- Update to latest commit with secrets and email types refactor

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-05 06:27:51 -03:00
083b56921f Update AGENTS.md and Cargo.lock
- Add CI/CD pipeline documentation with Forgejo runner details
- Add production container architecture and operations guide
- Add container management, troubleshooting, and maintenance procedures
- Add backup, recovery, and network diagnostics documentation
- Add container tricks, optimizations, and resource limits
- Update dependencies in Cargo.lock

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-05 06:26:47 -03:00
daa76e8a7b Update botserver: fix RwLock type 2026-04-05 01:19:52 -03:00
be03dfe880 Update botserver: fix duplicate deps 2026-04-05 01:11:00 -03:00
934e46e038 Update botserver: fix Cargo.toml 2026-04-05 01:09:06 -03:00
fbd2a8647d Update botserver: fix CachedSecret sync methods 2026-04-05 01:07:49 -03:00
8e6549a9ea Update botserver: fix ureq placement 2026-04-05 01:04:12 -03:00
05859d5276 Update botserver: fix vault blocking HTTP 2026-04-05 00:56:13 -03:00
96c61938d2 Update botserver: fix secrets mod cleanup 2026-04-05 00:48:21 -03:00
6386f65e58 Update botserver: fix secrets mod duplicate code 2026-04-05 00:44:27 -03:00
613409b5d6 Update botserver: fix ureq placement 2026-04-05 00:41:37 -03:00
ef8e7b9b56 Update botserver: fix email config blocking HTTP 2026-04-05 00:37:41 -03:00
915945e1b5 Update botserver: fix catch_unwind type error 2026-04-05 00:26:51 -03:00
d2e24c581b Update botserver: catch panics in send_mail 2026-04-05 00:22:34 -03:00
a65365d19f Update botserver: fix email config runtime nesting 2026-04-05 00:13:17 -03:00
6e63c47087 Update botserver: fix secrets manager usage 2026-04-04 23:58:24 -03:00
370fa6511d Update botserver: fix email config runtime 2026-04-04 23:48:18 -03:00
2368c30e59 Update botserver: fix email config timeout 2026-04-04 23:35:27 -03:00
6ddb1ebcc5 Update botserver: fix moved value 2026-04-04 23:15:20 -03:00
d9587863aa Update botserver: fix imports 2026-04-04 23:11:56 -03:00
48add934bd Update botserver: fix filter closure 2026-04-04 23:02:11 -03:00
9d87f4b60d Update botserver: fix remaining compilation errors 2026-04-04 22:53:30 -03:00
a492d1abc1 Update botserver: fix type annotations 2026-04-04 22:39:56 -03:00
27c1cd9671 Update botserver: fix compilation errors 2026-04-04 22:27:25 -03:00
50798824f8 Update botserver: fix leftover code 2026-04-04 22:19:10 -03:00
737fb45fc0 Update botserver: unify email sending, remove Gmail hardcoded defaults 2026-04-04 22:16:54 -03:00
ff1680cafc Update botserver: fix SMTP port 25 with credentials 2026-04-04 21:46:40 -03:00
0dcd46bfe7 Update botserver: remove private ClientId usage 2026-04-04 20:59:13 -03:00
55043a4d8a Update botserver: fix EHLO hostname for Stalwart 2026-04-04 20:34:55 -03:00
6a97db0931 Update botserver: fix SMTP transport for local Stalwart 2026-04-04 20:26:14 -03:00
b1c3800ca8 Update botserver: log email send errors 2026-04-04 19:03:42 -03:00
c4c52264db Update botserver: fix email fallback chain empty map check 2026-04-04 18:46:22 -03:00
277789e0bc Update botserver: fix email tracking non-fatal 2026-04-04 18:13:58 -03:00
c2d60d7cb8 Update botserver: fix CI build errors 2026-04-04 17:49:53 -03:00
72e6992f33 Update botserver: remove dead code in email/types.rs 2026-04-04 17:39:23 -03:00
9016868345 Update botserver: fix mime type handling 2026-04-04 17:30:08 -03:00
e7a42b5011 Update botserver: implement real email sending via lettre + Vault 2026-04-04 17:17:09 -03:00
1bd81a4c2c Update botserver: Generalize WhatsAppAdapter::new to accept &AppState 2026-04-04 15:46:31 -03:00
a367d8fca5 Update botserver: Add column drop protection in table schema sync 2026-04-04 11:03:05 -03:00
932fc30cea Update botserver: Replace hardcoded botserver-stack paths with dynamic helpers 2026-04-04 09:25:06 -03:00
bb79ac931f Update botserver: Fix anyhow error type in AuthConfig 2026-04-04 08:29:04 -03:00
99c64d32ff Update botserver: Fix AuthConfig nested runtime panic 2026-04-04 08:25:56 -03:00
80494ea4fe Update botserver: Fix SET USER nested runtime panic 2026-04-04 08:01:21 -03:00
7ee9d42560 Update botserver: Fix nested runtime panic in Rhai callbacks 2026-04-04 07:35:41 -03:00
272f56c79d Update botserver: fix clippy warnings (0 warnings) 2026-04-03 22:35:20 -03:00
fb02e72b8f Update botserver: force rebuild 2026-04-03 21:42:44 -03:00
50a3718d82 docs: update AGENTS.md with CI/CD systemctl deploy workflow 2026-04-03 21:40:52 -03:00
373bb6a6e4 Update botserver: force rebuild 2026-04-03 21:39:10 -03:00
ada9db7a42 Update botserver: trigger CI deploy 2026-04-03 21:32:54 -03:00
fb0b7f079f Update botserver: fix TransferResult type mismatch 2026-04-03 20:49:30 -03:00
92d8a0d858 Update botserver: fix nested runtime panic in transfer_to_human 2026-04-03 20:44:01 -03:00
1ae46149ee Update botserver: use systemctl for deploy 2026-04-03 20:39:52 -03:00
9068bc25f8 Update botserver: remove error masking in CI deploy 2026-04-03 20:36:42 -03:00
80c798ed05 Update botserver: fix CI deploy workflow 2026-04-03 20:35:53 -03:00
41cf536cd4 Update botserver: fix CI deploy workflow 2026-04-03 20:31:57 -03:00
901153803f Update botserver: fix CI deploy SSH workflow 2026-04-03 20:20:36 -03:00
a8521d7480 Update botserver: fix deploy kill step 2026-04-03 20:01:24 -03:00
f5b954df76 Update botserver: fix CI deploy step hanging 2026-04-03 19:51:48 -03:00
1bf9e1872b fix(ci): resolve deploy step hanging on pkill
- pgrep -f botserver matched the SSH command itself causing deadlock
- replaced with pkill -f '/opt/gbo/bin/botserver' || true
- added SSH keepalive (ServerAliveInterval=10, ServerAliveCountMax=3)
- added Step 7: explicitly start botserver after deploy
- fixed unquoted SSH_ARGS causing argument splitting
- increased verify sleep from 10s to 15s
2026-04-03 19:44:38 -03:00
a377af5ba3 docs: update AGENTS.md with CI/CD directives and remove deprecated patterns
- Added explicit CI/CD deployment directives (NEVER use scp, ALWAYS use CI)
- Updated CI runner documentation: runs as gbuser, sccache config, workspace paths
- Fixed deprecated block_in_place code example to use std:🧵:spawn pattern
- Added security headers: NEVER include sensitive data in documentation
- Updated container architecture table with all services
2026-04-03 18:46:24 -03:00
0dbc7cb081 Update botserver: Fix nested runtime panic in AuthConfig::from_env()
This fixes the critical bug that caused botserver to crash during
initialization with "Cannot start a runtime from within a runtime"
error.

Changes in botserver submodule:
- AuthConfig::from_env() now uses new_current_thread() pattern
- Fixes panic occurring after CORS layer initialization
- Aligns with previous get_database_url_sync fix pattern

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-03 14:02:39 -03:00
8eecc7f871 Update botserver: CI deploy SSH key fix for gbuser 2026-04-03 10:18:05 -03:00
5bebba4d7f Update botserver: CI improvements - gbuser, sccache, data dir 2026-04-03 09:40:30 -03:00
60ef1d0562 Update botserver: fix get_database_url_sync nested runtime panic 2026-04-03 09:26:35 -03:00
1df0ea8626 Update botserver: fix nested runtime panic with new_current_thread 2026-04-03 09:17:52 -03:00
54639690e2 Update botserver: skip local services when remote Vault detected 2026-04-03 07:36:28 -03:00
04454f2274 Update botserver: enforce Vault-only secrets policy 2026-04-03 07:12:29 -03:00
3dadec70a8 Update botserver: fix env var reading for distributed services 2026-04-02 21:17:32 -03:00
76a74b87f2 Update botui: favicon converted to proper ICO format 2026-04-02 18:44:03 -03:00
264bd6f4c9 Update botserver: fix health checks for non-root environments 2026-04-02 18:16:10 -03:00
466bd729af Update botserver submodule 2026-04-02 17:03:22 -03:00
9e3232ae85 Update submodules: botserver workflow, botui favicon 2026-04-02 16:50:04 -03:00
75eccecbe9 Update botserver: ci adds Step 7 to restart botserver after deploy 2026-04-02 16:01:45 -03:00
f9aa5dacd0 docs: add prod.md 2026-04-02 15:46:28 -03:00
82f5f24b44 Update botserver to working commit 7b4753af 2026-04-02 15:38:06 -03:00
752cdd6f3b Update botserver: Build inside container to fix glibc compatibility 2026-04-02 13:46:27 -03:00
3a6a571361 chore: sync workspace state 2026-04-02 13:38:38 -03:00
ed2052c8ec Update botserver: Fix SecretPaths to match Vault seeding paths 2026-04-02 07:27:12 -03:00
3e5c569354 Update botserver: Fix async Vault call in init_redis 2026-04-02 06:59:31 -03:00
9093340f4e Update botserver: Fix Valkey cache connection with Vault password 2026-04-01 20:17:47 -03:00
5cec129302 Update botserver: Vault as single source of truth for all service credentials and locations 2026-04-01 16:47:32 -03:00
4fa2018f5d Update botserver: Fix vault health check shell injection false positive 2026-03-31 21:35:36 -03:00
814b0214be Update submodules: botlib (log format fix) + botserver (vault recovery fix) 2026-03-31 21:02:13 -03:00
b6f83df229 Update submodules: botserver, botui, botmodels 2026-03-31 19:58:32 -03:00
66b19098b4 Update botserver: tar+zstd deploy 2026-03-31 19:07:38 -03:00
8ef34d011c Update submodules: botserver CI deploy fix 2026-03-31 19:02:33 -03:00
d8fb6c954a Update botserver: CI deploy via rsync 2026-03-31 18:20:05 -03:00
a2da4820b7 Update submodules: CI deploy fix 2026-03-31 18:16:15 -03:00
9815ab313b Update submodules: CI PATH fix for alm-ci 2026-03-31 15:32:54 -03:00
30e78ba40c Update submodule references: botserver CI fix 2026-03-31 15:29:15 -03:00
45df9d9caf Update submodules: botserver and botui CI workflow fixes 2026-03-31 15:24:53 -03:00
52aac0af21 docs: Add rule to never write internal IPs to logs 2026-03-31 11:12:57 -03:00
c79ab35409 Update submodules: fix compilation errors and warnings 2026-03-30 15:53:54 -03:00
90ee0257cb fix: compilation errors and warnings
- Add SafeCommand import to botapp/src/desktop/tray.rs
- Implement missing SecurityHeadersConfig and middleware in headers.rs
- Remove unused CspBuilder from headers.rs
- Remove unused ScriptService import in botserver/src/core/bot/mod.rs
- Remove unused SERVER_START_EPOCH and server_epoch function
2026-03-30 15:53:37 -03:00
1388463695 Update AGENTS-PROD.md: Remove all Podman references, update for LXC
Major changes:
- Remove all Podman-related sections and commands
- Update container architecture to reflect LXC (Linux Containers)
- Simplify infrastructure: all services run in LXC containers
- Update container management sections for LXC commands
- Replace Podman-specific backup procedures with LXC snapshots
- Update DNS and proxy management for LXC containers
- Remove MinIO/Drive migration procedures (not applicable)
- Add troubleshooting section for common LXC issues

All documentation now correctly references LXC containers instead of Podman.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-27 13:57:59 -03:00
6a13837bb8 Update botserver submodule: use local Rust/sccache in CI workflow 2026-03-25 14:53:32 -03:00
602dfdee93 Update submodules: botserver, botui with CI fixes 2026-03-25 13:33:34 -03:00
c404cc0b4d Update botserver: Remove sudo from CI workflow 2026-03-24 16:24:42 -03:00
926759f630 Update botui submodule 2026-03-24 14:04:27 -03:00
ebf516e967 Update botui submodule to latest 2026-03-24 13:59:32 -03:00
28326cb049 Update submodules 2026-03-24 13:43:33 -03:00
ff146657e0 docs: Add CI deployment rules and SSH hostname setup 2026-03-21 21:07:20 -03:00
9677c90907 Update botserver: add CI health check 2026-03-21 20:47:22 -03:00
f65b288cc5 Update botserver: fix triplicated suggestions by removing server_epoch() from start_bas_executed key 2026-03-21 20:40:50 -03:00
0ec849d323 Update botserver: add salesianos gbdialog tools 2026-03-21 19:21:58 -03:00
9f44d084ac chore: add temp files to gitignore 2026-03-21 18:56:35 -03:00
bb1cef6675 Update submodules: kb config per-bot, anomaly API, cleanup docs
[botserver] feat(kb): add with_bot_config to load embedding from bot config
[botbook] chore(docs): remove obsolete REORGANIZATION_PLAN.md
[botmodels] feat(api): add anomaly detection endpoints
2026-03-21 18:55:53 -03:00
af87de255b Update botserver: Fix SLA migration crash on prod 2026-03-21 17:00:59 -03:00
ff4ab52fef Update botserver: Fix duplicate start.bas execution 2026-03-21 16:38:05 -03:00
eb87414a78 Update botserver: Fix cache connection timeout 2026-03-21 14:37:07 -03:00
083024a438 Update submodule 2026-03-21 10:48:56 -03:00
f815943491 Update submodule 2026-03-21 10:37:59 -03:00
e61cf84bc4 Update submodule: fix Redis connection pool 2026-03-21 10:30:36 -03:00
22172cf64a Update submodule and docs: Redis connection pool 2026-03-21 10:14:21 -03:00
a7ccec940a Update submodule: fix Redis timeout blocking 2026-03-21 09:34:53 -03:00
ec2e93b22c Update botserver: Fix CI pkill 2026-03-20 22:57:17 -03:00
2cd3a5d692 Update botserver: Fix USE TOOL performance 2026-03-20 22:54:25 -03:00
d09a11e31e Update botserver: explicitly enable chat feature in CI 2026-03-20 22:44:32 -03:00
4941f74c6a Update botserver: fixed CI incremental build workspace 2026-03-20 21:40:10 -03:00
7a70798c85 Update botserver: fix CI deploy rm before scp 2026-03-20 20:59:28 -03:00
bd1aeb442d Update botserver submodule: fix CI workspace conflict 2026-03-20 19:15:09 -03:00
ae94a7b77c Update botui submodule: fix deploy workflow 2026-03-20 19:00:23 -03:00
94ba355910 fix: Update deploy workflow and document Forgejo CI/CD in AGENTS-PROD 2026-03-20 18:59:20 -03:00
4f4795b981 chore: Update submodule refs and workspace files 2026-03-20 17:39:20 -03:00
2658659ff0 Update botserver: GUID KB isolation + salesianos KB 2026-03-19 19:51:37 -03:00
3b6e2df6e2 Update botui submodule 2026-03-19 15:14:09 -03:00
4bf1dc4689 Update botui submodule 2026-03-19 14:47:16 -03:00
d933ac52af Update botui submodule 2026-03-19 14:42:35 -03:00
21add146a6 docs: Add CI/CD debugging section to AGENTS-PROD.md 2026-03-19 14:28:58 -03:00
bbea8fb9fd Update botui submodule 2026-03-19 14:17:09 -03:00
76b64182bd Update botui submodule 2026-03-19 14:03:08 -03:00
ce6a65a902 Update botui submodule 2026-03-19 13:51:44 -03:00
b9835d6d12 Update botui submodule 2026-03-19 13:41:38 -03:00
e0ab4bb1fe Update botserver submodule 2026-03-19 12:28:44 -03:00
e30b070eff docs: add rule to never compile directly for production 2026-03-19 12:21:23 -03:00
f0858a443e Update botserver: fix migration bot_id column 2026-03-19 12:00:02 -03:00
0ce43ed8f7 Update submodules to latest 2026-03-19 09:55:29 -03:00
8502eac494 Update botserver submodule 2026-03-18 19:41:31 -03:00
70cdd6e5a5 Update submodule 2026-03-18 14:38:57 -03:00
98e8179810 Update submodule 2026-03-18 14:18:20 -03:00
67d3c7f901 Update botui, botserver submodules 2026-03-18 12:24:30 -03:00
ec4c660887 Update submodule 2026-03-18 11:06:11 -03:00
7d3cf9bd61 docs: Add comprehensive bug fixing and feature addition workflows to AGENTS.md
- Added detailed bug fixing workflow (6 steps: diagnose, find code, fix, test, commit, document)
- Added feature addition workflow (6 steps: plan, implement, BASIC keywords, test, document, deploy)
- Includes real examples from today's suggestion bug fix
- Security checklists for new features
- Testing patterns and commit message templates
2026-03-18 10:50:39 -03:00
02c8efeca7 docs: Remove sensitive info from AGENTS-PROD.md
- Remove example conversation with specific server details
- Remove specific commit hash
- Generalize Vault unseal command
- Add warning about Vault keys
2026-03-18 10:41:45 -03:00
0be7cb1f61 docs: Add common production issues and fixes to AGENTS-PROD.md
- Valkey connection timeout (iptables loopback issue)
- Suggestions not showing (bot_id vs user_id bug)
- Deployment workflow for code fixes
2026-03-18 10:40:31 -03:00
dfad0f3989 Update botserver submodule: Fix suggestion Redis key bug 2026-03-18 10:39:56 -03:00
58be60fda0 Update botserver submodule with TLS certificate SAN fix 2026-03-18 09:30:38 -03:00
f7bcd16212 Update files 2026-03-18 09:00:35 -03:00
4900274887 Remove BOTCODE files 2026-03-18 08:48:04 -03:00
bfc9ced932 Update botserver and botui submodules 2026-03-17 16:53:33 -03:00
65583977fa Update botserver submodule: fix panic in secrets module 2026-03-17 15:04:49 -03:00
12d9dc50af Update botserver: SSH deploy CI + fix mcp.json 2026-03-17 13:13:04 -03:00
1ca4d2c712 Update botserver submodule: fix mcp.json for parameterless tools 2026-03-17 12:21:59 -03:00
176df967f7 Update botserver submodule: CoreDNS ACL + fail2ban proxy jail 2026-03-17 11:18:36 -03:00
7e9b8b00fe Update botserver submodule
Some checks failed
BotServer CI / build (push) Failing after 0s
2026-03-17 01:40:40 -03:00
e2ffa39bf8 Add WORKFLOW_PLAN.md to prompts 2026-03-16 23:41:05 -03:00
297af2f9e1 Update all submodules to latest
Some checks failed
BotServer CI / build (push) Failing after 15s
2026-03-16 13:30:16 -03:00
4caa147841 Update submodules: fix WS session_id forwarding and start.bas session lookup 2026-03-16 13:25:59 -03:00
29416db1b8 Update botserver and botui submodules - fix session persistence bug 2026-03-16 13:16:31 -03:00
9c3bd0c1d5 Update botbook submodule reference for THINK KB documentation 2026-03-16 08:43:51 -03:00
21b219f0d3 Remove ALWAYS.md - documentation moved to botbook 2026-03-16 08:42:32 -03:00
f7238b5d33 Add ALWAYS.md with THINK KB implementation summary 2026-03-16 08:41:48 -03:00
4c26b77143 Update submodule references to include THINK KB implementation
- botserver: f062cc4a (THINK KB keyword)
- botbook: ea5e92e (THINK KB documentation)
- botlib: 47a7643 (localization updates)
- bottemplates: d95f154 (marketing templates)
- bottest: 68f52ff (integration tests)
- botui: bdc8667 (UI updates)
2026-03-16 08:41:25 -03:00
Thiago Patriota
7de55efe79 chore: remover arquivo raiz indevido 2026-03-15 18:08:49 -03:00
Thiago Patriota
7d70035050 chore: ignorar e remover artefatos locais 2026-03-15 18:07:39 -03:00
Thiago Patriota
c19095f141 chore: registrar artefatos locais pendentes 2026-03-15 16:02:25 -03:00
Thiago Patriota
2572425cb1 chore: atualizar ponteiros de submódulos 2026-03-15 15:53:54 -03:00
Thiago Patriota
8a6fec467c feat: Windows build support, clippy zero-warnings, and dev tooling
New files:
- prompts/win.md: Complete Windows execution guide covering
  build dependencies (libpq), compilation steps, runtime
  compatibility table (3rdparty.toml Windows URLs), shell
  command adaptations, GPU detection for LLM, directory
  structure, and troubleshooting
- DEPENDENCIES.ps1: PowerShell script to auto-install
  PostgreSQL binaries and set PQ_LIB_DIR for Windows builds
- restart.ps1: PowerShell restart script for Windows dev env

Submodule updates:
- botserver: Full Windows compatibility (21 files changed)
  including 3rdparty.toml Windows URLs, installer/cache/facade
  Windows process management, certificate generation,
  #[cfg(unix)] guards, and clippy zero-warnings refactors
- bottest: #[cfg(unix)] guards for nix crate in postgres.rs,
  minio.rs, redis.rs service managers
- botapp: Remove unused import (clippy auto-fix)

Config:
- .cargo/config.toml: Updated for Windows toolchain
- Cargo.lock: Dependency updates
2026-03-14 17:28:26 -03:00
2fe4586be5 Add desktop UI navigation instructions for CRM testing 2026-03-12 18:20:05 -03:00
6297018124 chore: update botserver submodule
Some checks failed
BotServer CI / build (push) Failing after 11s
2026-03-10 21:18:19 -03:00
7d95a607f4 chore: update submodule references
Some checks failed
BotServer CI / build (push) Failing after 13s
2026-03-10 19:39:35 -03:00
91ad0232f0 update submodules
Some checks failed
BotServer CI / build (push) Failing after 22s
2026-03-10 17:19:59 -03:00
c43bda9b2a chore: sync botserver submodule
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-03-10 15:26:24 -03:00
144c4b0b79 chore: update submodule pointers
Some checks failed
BotServer CI / build (push) Failing after 15s
2026-03-10 15:15:46 -03:00
920666db40 Fix Bedrock config for OpenAI GPT-OSS models
Some checks failed
BotServer CI / build (push) Failing after 38s
2026-03-10 12:36:01 -03:00
731892db36 Update botserver: Redis-based rate limiting 2026-03-09 21:01:36 -03:00
0465216f66 Update botserver: fix WhatsApp streaming buffer 2026-03-09 20:24:03 -03:00
a695da5a05 Update botserver: simplify hallucination detector
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-03-09 20:03:08 -03:00
f1455ad7cb Update botserver: fix Redis BLPOP parsing
Some checks failed
BotServer CI / build (push) Failing after 14s
2026-03-09 19:44:12 -03:00
e42ee6ee43 Update botserver submodule: fix compilation errors
Some checks failed
BotServer CI / build (push) Has been cancelled
2026-03-09 19:32:54 -03:00
1f73d82c50 Update submodules: WhatsApp Meta rate limits + config inheritance fix
Some checks failed
BotServer CI / build (push) Failing after 11s
2026-03-09 19:18:18 -03:00
dd1d105ef0 chore: update submodule pointers
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-03-09 17:28:45 -03:00
b7275ed233 chore: update botserver submodule with WhatsApp routing fixes
Some checks failed
BotServer CI / build (push) Failing after 21s
- Phone number ID based bot routing
- System prompt loading from config.csv fix

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-09 12:31:16 -03:00
e245077700 feat(whatsapp): add phone_number_id based bot routing
Some checks failed
BotServer CI / build (push) Failing after 10s
- Add resolve_bot_by_phone_number_id function for automatic routing
- Webhooks now route to correct bot based on whatsapp-phone-number-id
- Enables multiple WhatsApp numbers to use single webhook URL
- Falls back to default bot if no match found

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-09 12:28:44 -03:00
a23b4f1983 chore: update botserver submodule with system-prompt fix
Some checks failed
BotServer CI / build (push) Failing after 13s
- Fix system-prompt loading from config.csv for GLM-5 and other LLMs
- System prompts are now correctly injected into LLM API calls

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-09 11:56:38 -03:00
ff9e3f56a9 feat(whatsapp): update submodule with list isolation and code removal
- Update botserver submodule to commit 97661d75
- Add list isolation as single messages in WhatsApp
- Add JavaScript/C# code block removal
- Update zap.md with streaming example and correction history
- Change restart.sh logging from trace to debug level

Related: botserver submodule update
2026-03-08 14:53:43 -03:00
62e2390da3 docs: Update zap.md with /clear command documentation
- Add Comandos Disponíveis section with /clear command
- Document usage, behavior, and implementation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-07 18:58:09 -03:00
39a6a4cf20 Update zap.md with WhatsApp integration fixes
- Document content extraction fix (JSON deserialization)
- Document list streaming fix (single message vs chunks)
- Update status to reflect working integration
- Add debug commands and next steps for production

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-07 07:46:49 -03:00
4da3910b3b Fix WhatsApp message content extraction issue
Messages from WhatsApp are being correctly received and processed by the bot now.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-06 17:16:31 -03:00
db119148cf chore: Update botserver submodule with KB search fixes
Some checks failed
BotServer CI / build (push) Failing after 12s
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-05 00:11:22 -03:00
d89a5c9d30 chore: Update botserver submodule with KB search fixes
- Lower KB search thresholds for better recall
- Add Cloudflare AI embedding support in cache

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-05 00:07:19 -03:00
f8c36c3778 chore: Update submodules with latest changes
- botserver: KB context, embedding generator, and website crawler enhancements
- botui: Organizations settings UI improvements
2026-03-04 15:43:55 -03:00
9123756e82 Revert: Remove hardcoded formatting from botserver
Reverting commit 4896296c - formatting should be in bot-specific .md file, not in server code
2026-03-03 16:24:00 -03:00
28c4f89e16 fix: Update botserver submodule with parameter formatting fix
- Updates botserver to commit 4896296c
- Fixes LLM prompt formatting for tool parameter collection
- Resolves formatting issues starting from item 5 in generated prompts
2026-03-03 16:19:51 -03:00
cc8b432aa8 Update submodules to latest commits 2026-03-03 15:19:28 -03:00
d65794fa93 chore: update botui submodule with fullscreen height fix
- Make maximized window fill entire screen with 100vh height
- Window now occupies all screen space when maximized (1920x1080)
- Recovers 28px of vertical space previously lost to minibar offset
2026-03-03 13:37:45 -03:00
2fe91226b0 chore: update botui submodule with top offset fix
- Remove 28px top offset for maximized windows
- Window now fills screen from top without blank space
- Fixes issue with padding before window title when maximized
2026-03-03 13:30:54 -03:00
465fa71c84 chore: update botui submodule with toolbar fix
- Hide toolbar when window is maximized to remove blank space at top
- Fixes issue where 50px blank space appeared before window title
2026-03-03 13:24:59 -03:00
853181cd1d chore: update botui submodule with latest changes
- Window maximization fix to hide sidebar when maximized
- Dynamic window title updates
- Remove quick action chips from desktop
2026-03-03 13:16:54 -03:00
c7fe607171 docs: Update AGENTS.md with guidelines for file saving and production push policy 2026-03-03 12:51:33 -03:00
12e7cba9bd fix: update botserver with PathBuf import fix 2026-03-03 10:04:20 -03:00
31f68d7bf0 fix: update botserver submodule with tool path resolution fix 2026-03-03 10:02:09 -03:00
334bb9239b chore: Update botui submodule - Fix desktop title branding
Some checks failed
BotServer CI / build (push) Failing after 9s
Update botui to latest commit which changes desktop title from
'Agent Farm' to 'General Bots' for brand consistency.
2026-03-03 08:42:30 -03:00
a9c4714929 chore: Update botserver with deployment API endpoints
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-03-02 07:42:45 -03:00
41efb790ef chore: Update submodules with Phase 1 Code Editor Integration
Some checks failed
BotServer CI / build (push) Failing after 10s
- botserver: Add editor API endpoints
- botui: Add Monaco Editor and code editor component

Phase 1 (P0 - Critical) COMPLETED:
- Monaco Editor installed and configured
- Full-featured code editor with file tree, tabs, syntax highlighting
- API endpoints for file operations
- Keyboard shortcuts and auto-save preparation
2026-03-02 07:27:14 -03:00
4e0737f60a chore: Update submodules with Phase 0 deployment infrastructure
Some checks failed
BotServer CI / build (push) Failing after 10s
- botserver: Add deployment router and Forgejo integration
- botui: Add deployment UI modal in Vibe

Phase 0 CRITICAL features completed:
- Phase 0.1: Deployment Router
- Phase 0.2: Forgejo Integration
- Phase 0.3: Deployment UI in Vibe
2026-03-02 07:13:12 -03:00
649afd7947 chore: Update submodules with enhanced logging
Some checks failed
BotServer CI / build (push) Failing after 8s
- botserver: Add comprehensive stage progress logging
- botui: Format vibe.html for better readability

This updates the submodules to include the latest changes for:
- Enhanced textual progress logging in console
- Better code formatting in Vibe UI
2026-03-01 22:37:24 -03:00
a99c17008e chore: update botserver submodule with Zitadel OAuth fix
Updates botserver to commit c326581a which includes:
- Fix for PAT extraction timing issue
- Retry loop with sync command for reliable PAT extraction
- Improved logging and verification
- Consolidated setup module
- OAuth client initialization now works correctly
2026-03-01 19:07:00 -03:00
abedde3af7 feat(directory): improve OAuth client creation with better credential handling
Some checks failed
BotServer CI / build (push) Failing after 11s
- Updated setup_directory() to try multiple credential sources:
  1. Existing config file
  2. Zitadel log extraction
  3. Default credentials
  4. Helpful error message if all fail

- Made ensure_admin_token() async to actually authenticate with credentials
- Added test_zitadel_credentials() helper function
- Improved error messages for debugging

This addresses the issue where OAuth client creation was failing because
credentials couldn't be extracted from Zitadel logs.

Related: zit.md plan for automatic OAuth client creation
2026-03-01 09:42:13 -03:00
9fc33725b7 fix: use OAuth client credentials when PAT is missing
The login flow now falls back to OAuth client credentials flow when
the admin PAT token is not available. This allows login.html to work
even when Zitadel PAT generation hasn't been configured yet.

- Added get_oauth_token() helper function
- Login now tries PAT first, then OAuth client credentials
- Includes proper Zitadel scope for API access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-28 14:46:54 -03:00
7d4708b516 chore: bump botui submodule for theme manager fix
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-02-28 13:30:41 -03:00
34af1f2a16 Complete agent UI workspace 2026-02-26 09:22:02 -03:00
21b96804e8 chore: update botui submodule with WebSocket improvements
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-24 22:24:47 -03:00
a6a221788b chore: update botui submodule with anonymous chat fix
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-24 21:47:36 -03:00
610741e123 chore: update botui submodule with correct app paths
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-24 21:21:14 -03:00
ddb11a7c06 chore: update botui submodule with desktop icon fixes
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-24 20:32:53 -03:00
57b09e5b66 chore: update botui submodule
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-24 20:18:10 -03:00
046dbc63ad docs: finalize UI.md migration status to COMPLETED 2026-02-24 20:11:06 -03:00
c3c235f8c4 feat(ui): migrate desktop environment to Window Manager
- Updated UI.md with the completed specification and status
- Synced botui submodule with new desktop.html and window-manager.js implementation
- Synced botserver submodule with latest changes
2026-02-24 19:02:48 -03:00
19b4a20a02 chore: update botserver submodule with work directory path fixes
Some checks failed
BotServer CI / build (push) Failing after 11s
Updated the botserver submodule to include fixes for work directory
paths that now use botserver-stack/data/system/work consistently.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-22 16:21:19 -03:00
792a13eb67 chore: synchronize submodules and update root dependencies
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-22 15:56:19 -03:00
9eb2bfe09c docs: update AGENTS.md and sync submodules after tool path fix
Some checks failed
BotServer CI / build (push) Failing after 23s
- Documented that /opt/gbo/data is also a location for bots
- Added warning to never search /target folder (compiled binaries)
- Synced all submodules with latest changes

Related to tool loading fix that moved .mcp.json files to
botserver-stack/data/system/work/ and updated code to use
relative paths instead of hardcoded HOME/gb path.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-02-22 11:22:10 -03:00
49930f2aa0 docs: fix contradictions in AGENTS.md regarding clippy and allow usage 2026-02-21 17:27:20 -03:00
d08dab26dc chore: push for ci
Some checks failed
BotServer CI / build (push) Failing after 11s
2026-02-20 21:10:42 -03:00
ba032f41eb fix(ui): update botui with robust contrast fix
Some checks failed
BotServer CI / build (push) Failing after 10s
2026-02-20 20:37:58 -03:00
ec8d002574 fix(ci): deploy botui static assets and implement cache busting
Some checks failed
BotServer CI / build (push) Failing after 16s
2026-02-20 20:36:30 -03:00
ce81951a69 chore: use relative URLs for submodules to support ALM CI
Some checks failed
BotServer CI / build (push) Failing after 13s
2026-02-20 20:08:52 -03:00
1d0c9ccdb8 update: sync for alm
Some checks failed
BotServer CI / build (push) Failing after 4s
2026-02-20 18:54:23 -03:00
f0e0553966 update: track submodules latest commits for alm deployment 2026-02-20 15:11:48 -03:00
9b02df3bec style: update text color for bot messages and suggestion chips to white 2026-02-20 12:38:17 -03:00
49d9b193b2 feat: Complete security remediation and submodule updates
Some checks failed
BotServer CI / build (push) Failing after 29s
- Added security audit documentation (tasks.md)
- Fixed RCE vulnerability via trusted_shell_script_arg command injection
- Fixed SSRF vulnerability in Rhai GET requests
- Updated all submodules with latest fixes:
  - botapp: desktop tray implementation
  - botlib: i18n bundle handling
  - botserver: security fixes (RCE & SSRF)
  - bottemplates: default gbot configuration
  - bottest: test harness and e2e tests
  - botui: chat UI theme management
- Added test_salesianos_bot.js for testing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 01:14:21 +00:00
b11140d106 chore: Remove TASKS.md after completing clippy cleanup
The comprehensive security and quality audit documented in TASKS.md
has been completed successfully:
- 24/26 security tasks resolved (92%)
- 0 clippy warnings achieved (perfect score)
- Security expert review completed with A- grade

Backup retained as TASKS_backup.md for reference.

Remaining tasks:
- SEC-02: Secret rotation (operational, not code)
- SEC-06: Passkey module (optional feature)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-19 18:49:58 +00:00
8e27900529 fix: Complete clippy cleanup and security review - perfect score achieved
## Clippy Fixes (61 → 0 warnings)
- Fixed regex compilation in loops (moved outside)
- Converted loop counters to .enumerate()
- Replaced manual prefix stripping with strip_prefix()
- Refactored unwrap patterns to unwrap_or_default()
- Fixed non-binding futures with std::mem::drop()
- Consolidated duplicate if blocks
- Converted match expressions to matches! macro
- Removed redundant guards using .filter()
- Reduced function arity via SiteCreationParams struct
- Renamed conflicting from_str methods to from_str_name
- Added type aliases for complex types (MiddlewareFuture, BatchProcessorFunc)
- Changed Result unit errors to Option types
- Removed duplicated attributes and empty lines

## Code Quality
-  0 clippy warnings (PERFECT SCORE)
-  All workspace compiles cleanly
-  Debug-only builds enforced (AGENTS.md updated)

## Security Review
- Comprehensive expert review completed
- Scored A- overall with critical gaps identified
- Cryptography: A+ (excellent)
- Session Management: A (production-ready)
- Input Validation: A (comprehensive)
- Access Control: A (RBAC complete)
- Code Quality: A+ (perfect)
- Blocking issue: SEC-02 secret rotation required

## Documentation
- Updated AGENTS.md with final clippy status
- Updated TASKS.md with completion status
- Added clippy cleanup progress section

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-19 18:47:28 +00:00
60e2054a02 chore: Update tasks and drive feature 2026-02-19 12:38:44 +00:00
40e735a56f chore: Update TASKS with SEC-01 resolution 2026-02-19 12:22:24 +00:00
a83d9a88aa chore: Track Cargo.lock and clean temp files 2026-02-19 12:21:23 +00:00
8b32eaf41f chore: Update tasks and fix warnings 2026-02-19 12:18:40 +00:00
c12ad1eda4 chore: Workspace cleanup and security policy updates 2026-02-19 12:06:06 +00:00
4729fe7071 chore: Update botserver and botlib submodules with warning fixes 2026-02-19 11:48:35 +00:00
e443aa9d1a refactor: Split README.md into human-focused README and agent-focused AGENTS.md 2026-02-19 11:42:10 +00:00
3891f137fd chore: update botui 2026-02-18 21:36:17 +00:00
f40449ed51 chore: update botui 2026-02-18 21:19:37 +00:00
146f04b373 chore: update botui submodule 2026-02-18 20:52:22 +00:00
1ecd5f4f0c chore: update botui submodule 2026-02-18 20:42:08 +00:00
b5bf1061f8 chore: remove TASK.md 2026-02-18 20:38:55 +00:00
7bda264f61 docs: update TASK.md — all tasks complete, all bugs fixed, pushed to GH 2026-02-18 20:37:46 +00:00
caafad484a fix: ENUM mapping, mail bugs, duplicate messages, and theme selector
Bug fixes in .bas tools:
- Fix BEGIN MAIL email → BEGIN MAIL emailContato in tools 07, 09, 10
- Fix newsletter BOOLEAN → STRING in tool 10 (LLM sends 'Sim' as string)
- Add natural language descriptions to ENUM params in tools 02-10

Botserver:
- Fix duplicate chat message when tool is executed (tool_was_executed flag)

BotUI:
- Remove theme selector button from minimal chat for non-logged users

Testing: All 10 tools verified with NL ENUM mapping and DB records
2026-02-18 20:32:09 +00:00
ddc1bdb2db chore: Update botserver submodule with preprocessor fixes 2026-02-18 17:19:36 +00:00
faeb77fc07 docs: Enhance Playwright testing guide with backend validation
Add comprehensive bot testing and backend validation documentation:
- Bot-specific URL pattern (http://localhost:3000/<botname>)
- Backend validation commands for PostgreSQL, Qdrant, Redis
- End-to-end process validation workflow
- Enhanced test flows with database/service verification
- Expanded testing checklist with backend checks

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-17 15:15:33 +00:00
a31d7b355a fix: Remove secrets from repository and implement security best practices
SECURITY FIXES:
- Add restart.sh script that reads Vault credentials from /tmp/ only
- Add .gitignore rules for: vault-unseal-keys, start-and-unseal.sh, vault-token-*
- Add security warning to README.md about /tmp/ for secrets
- Update botserver port references from 8088 to 9000 in README

Secrets MUST be placed in /tmp/ only:
  - /tmp/vault-token-gb (Vault root token)
  - /tmp/vault-unseal-key-gb (Vault unseal key)

This commit removes the previous commit (c7a60b8) that contained hardcoded
secrets in restart.sh and start-and-unseal.sh files.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-17 15:02:58 +00:00
30ec64d878 chore: Update botserver with tool call fix
- Fix tool calls in JSON array format to be executed instead of displayed
- Prevents raw tool JSON from appearing in chat window

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 00:19:20 +00:00
dd64a4102c chore: Update botui with tool button fix
- Fix tool buttons sending display text instead of internal ID
- Tool buttons now work correctly on first click

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 00:05:01 +00:00
041c76209a chore: Update botui submodule
- Use typewriter theme for cristo bot
- Make suggestion buttons smaller

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:48:57 +00:00
c6e8ced648 chore: Update submodules with Forgejo CI workspace fixes
- botui: Fix workspace conflict in CI workflow
- botserver: Fix workspace conflict in CI workflow

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:27:06 +00:00
56e8054839 chore: Update submodules
- botui: Fix theme switching to apply immediately without refresh
- botserver: Load session tools in WebSocket connection

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
8519c3cfd2 fix: Extract Valkey to cache/bin/ with correct paths
- Binaries at cache/bin/valkey-server
- exec_cmd and check_cmd updated to use bin/ subdirectory

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
8a0216c654 fix: Extract Valkey binaries to correct cache/ path
- Binaries at cache/valkey-server (not cache/bin/)
- Uses --strip-components=2 to flatten structure

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
abcf959fdf fix: Use Valkey 8.1.5-jammy for GLIBC compatibility
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
b9ab17fb4c fix: Downgrade Valkey to 8.1.5 for stability
- Using valkey-8.1.5-noble-x86_64.tar.gz

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
84083b9ae0 feat: Update botserver with 5s cache retry delay
- 5 seconds between retry attempts
- 12 attempts max (60s total)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
079e802b17 feat: Update botserver with cache retry logic
- Wait up to 30 seconds for Valkey to be ready
- Prevents race condition during startup

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
33845109fd fix: Update botserver submodule with precompiled Valkey binary
- Uses valkey-9.0.2-jammy-x86_64.tar.gz from download.valkey.io
- No source compilation required

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
bd3857f2d4 fix: Update botserver submodule with cache and LLM improvements
- Cache connection verification with PING test
- Environment variable support for cache URL (CACHE_URL, REDIS_URL, VALKEY_URL)
- Environment variable support for LLM config (LLM_URL, LLM_MODEL, LLM_KEY)
- Better fallback to local LLM when no bot config exists

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
acea58eecb fix: Update botserver submodule after compilation fixes
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
ead23594c0 chore: Update botserver submodule reference
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
b606913d7d feat: Add local bot data documentation and update submodule
- Document /opt/gbo/data/ directory for local bot packages
- Document auto-loading, compilation, and hot-reload features
- Update botserver submodule with latest changes
- Add console and network config files

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
5ffa0d71af fix(i18n): Update botui with cache invalidation
- Increments i18n cache version to v2
- Forces fresh translation fetch from all users
- Resolves placeholder translation issue

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
0057ca3612 chore: Update botui submodule
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
504bb66a82 fix(i18n): Update botlib submodule with debug-embed support
- botlib now embeds i18n translations in both debug and release builds
- Uses debug-embed feature from rust-embed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
1e6289b223 feat(i18n): Update botlib submodule with embedded i18n by default
- botlib now uses embedded assets via rust-embed by default
- i18n feature is now part of default features
- Fixes placeholder translations issue

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
8c3f51a49d Update botserver submodule to latest commit
- Adds local Vault bootstrap .env file creation
- Fixes Vault initialization for local installations
- Generates TLS certificates during Vault install
- Creates .env with VAULT_ADDR, VAULT_TOKEN, VAULT_CACERT

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
cf0d94873d Debug: Add translation lookup logging 2026-02-15 23:21:30 +00:00
8eef47058d Debug: Add i18n logging to find missing translations 2026-02-15 23:21:30 +00:00
dcaf90d39f feat(i18n): Update botui with cache versioning
This adds cache versioning (v1) to prevent stale translation issues.
Old caches will be auto-invalidated when version is incremented.
2026-02-15 23:21:30 +00:00
a8e107059a fix(i18n): Update botui with cache logging 2026-02-15 23:21:30 +00:00
ea4cb78646 fix(i18n): Update botui submodule with logging 2026-02-15 23:21:30 +00:00
eda45af678 fix(i18n): Update botlib submodule with locale logging 2026-02-15 23:21:30 +00:00
fc994375b1 Update botui submodule 2026-02-15 23:21:30 +00:00
3fe4f7ece7 Update botserver submodule 2026-02-15 23:21:30 +00:00
4202f0dcf9 CI: Trigger pipeline 2026-02-15 23:21:30 +00:00
fad4e1457b CI: Bust cache to fix notify dependency build
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:30 +00:00
b798123f14 Update submodule references
- botserver: Fix notify dependency and source files
- botbook: Update PROMPT.md
- botui: Update UI components and themes

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 23:21:25 +00:00
5b34b21622 Fix all 61 warnings in botserver
- Remove unused imports across 14 files
- Fix unused variables (prefixed with _)
- Fix return types to use anyhow::Result where needed
- Remove cfg!(feature = "sigkill") (invalid feature)
- Fix typo: axum -> axum in imports

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-13 12:53:31 +00:00
cf80060818 Update botui submodule: Remove chat header and fix theming
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 14:07:31 +00:00
cda27734f0 Update submodules: bottemplates and botui
- bottemplates: Add register_student.bas for edu bot
- botui: Add config-colors.css and UI component updates

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 13:54:44 +00:00
f1b231ce3a Update botserver submodule: Fix start.bas repeated execution
- Add Redis-based tracking to prevent start.bas from running repeatedly
  when clicking suggestion buttons
- Add generic tool executor for LLM tool calling
- Fix suggestion duplication by clearing from Redis after fetch

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 13:50:13 +00:00
6a7cdf2800 Update bottemplates (removed default.gbai from git history) 2026-02-09 15:22:19 +00:00
21aa782fd2 Update bottemplates (remove default.gbai from core) 2026-02-09 15:15:31 +00:00
54966ff63f Update submodules (botserver, bottemplates, botui) 2026-02-09 15:13:11 +00:00
bcb43ce887 Add config hot-reload and fix model routing
- Add ConfigWatcher for monitoring ~/data/*.gbai/*.gbot/config.csv
- Skip DriveMonitor for default bot (managed via ConfigWatcher)
- Fix model routing hierarchy: session → bot → default
- Fix ConfigWatcher to handle local embedded (llm-server=true)
- Add notify dependency for file system watching
- Add data/ to .gitignore (contains API keys)
- Update package.json for botui

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 15:09:36 +00:00
4736383997 Trigger contributor stats refresh 2026-02-08 16:31:59 +00:00
93519eba14 Update botserver to latest main
- Updated to 84458b2a (feat: Add BOTSERVER_PORT environment variable override)
2026-02-08 16:20:54 +00:00
0e47fd9476 Update submodule references to latest main/master
- botbook: Updated to 3e418df (latest main)
- botdevice: Updated to 7a5dab5 (latest master)
- botlib: Updated to 38dc7c0 (latest)
- botserver: Updated to e8ce642b (latest main)
- bottemplates: Updated to 1ce3295 (latest master)
- bottest: Updated to 68542cd (latest main)
- botui: Updated to 1bf9510 (latest main)
2026-02-08 16:19:05 +00:00
2f200e1e99 Update botserver submodule to latest commit (BOTSERVER_PORT env var)
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-02-06 12:57:28 -03:00
8e02195eca Update botui submodule: CI fix for embed-ui
Some checks failed
BotServer CI / build (push) Failing after 10s
2026-02-06 12:24:19 -03:00
41e314fd67 Update botui submodule: trigger CI build
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-02-06 12:13:11 -03:00
fe865fdfa1 Trigger CI: build botui with embed-ui feature
Some checks failed
BotServer CI / build (push) Failing after 13s
2026-02-06 12:11:40 -03:00
068f011907 Update botui submodule to latest commit (CI workflow fix)
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-06 11:51:41 -03:00
df257e990e Update botui submodule to latest commit (rust-embed fix)
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-06 11:37:03 -03:00
03a03c3a3f Fix rust-embed: enable interpolate-folder-path in workspace
Some checks failed
BotServer CI / build (push) Failing after 11s
- Enable interpolate-folder-path in workspace rust-embed dependency
- Required for RustEmbed to expand $CARGO_MANIFEST_DIR variable
2026-02-06 11:36:31 -03:00
974e1e688a Update botui submodule: trigger CI workflow
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-06 10:57:19 -03:00
b5896c2493 Update botui submodule: reduce CI build jobs for stability
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-06 10:18:23 -03:00
5221bc9ec5 Remove config/directory_config.json
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-06 09:54:04 -03:00
65f1c762c1 Update botserver submodule: remove embed-ui from defaults
Some checks failed
BotServer CI / build (push) Failing after 14s
2026-02-06 09:41:09 -03:00
5c3d772010 Update submodules: fix embed-ui feature and deployment
Some checks failed
BotServer CI / build (push) Failing after 15s
- botui: Fixed rust-embed folder path for proper UI file embedding
- botserver: Removed Kubernetes deployment, added embed-ui documentation
- README: Updated with embed-ui feature explanation and deployment options
- Production deployments can now use single binary with embedded UI
2026-02-06 09:27:14 -03:00
164a0972a4 Update botserver submodule: Add embed-ui to default features
Production binaries should embed UI assets by default to avoid
requiring external ui/suite folder in deployment.

Note: botserver changes pushed to github, pragmatismo push pending
due to network issues.
2026-02-05 22:53:09 -03:00
1ccd1f9cc9 Update botserver submodule: Fix mold linker issue
Some checks failed
BotServer CI / build (push) Failing after 17s
2026-02-05 22:43:44 -03:00
e194dcf9e6 Update botbook submodule: Add libsoup-3.0 installation docs
Some checks failed
BotServer CI / build (push) Failing after 11s
2026-02-05 22:28:20 -03:00
3c5c01f4ea Update botserver submodule: Fix PostgreSQL readiness check timeout
Some checks are pending
BotServer CI / build (push) Waiting to run
2026-02-05 22:23:36 -03:00
e50bcee8c7 Update botbook submodule - add javascriptcoregtk dependencies
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-05 22:18:10 -03:00
198bcf8edb Update botbook submodule reference - fix GTK dependencies
Some checks failed
BotServer CI / build (push) Failing after 8s
2026-02-05 22:14:08 -03:00
613a14ecfb Add GTK/GNOME dependencies for Tauri desktop apps
Some checks failed
BotServer CI / build (push) Failing after 9s
- Added libglib2.0-dev, libgobject-2.0-dev, libgio-2.0-dev
- Added libgtk-3-dev, libwebkit2gtk-4.0-dev for Tauri GUI
- Added libayatana-appindicator3-dev, librsvg2-dev
- Updated all OS installers (Debian/Ubuntu, Fedora/RHEL, Arch, Alpine)
- Added build options in script output (full workspace vs server-only)
- Fixes build errors from missing gio-2.0.pc and related libraries
2026-02-05 22:10:04 -03:00
cd2dd0f6f6 Update botserver submodule to 07ff7a62 - Fix PostgreSQL health check
Some checks failed
BotServer CI / build (push) Failing after 12s
2026-02-05 21:56:10 -03:00
a13e3f7c51 docs: update botbook submodule to latest commit (a3a11ffd)
Some checks failed
BotServer CI / build (push) Failing after 8s
2026-02-05 21:52:00 -03:00
c9eabb0f0d docs: update botbook submodule to latest commit (9895e67f)
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-05 21:47:24 -03:00
edb40ea8e0 docs: update botbook submodule to latest commit (6f7044d9)
Some checks failed
BotServer CI / build (push) Failing after 9s
2026-02-05 21:46:07 -03:00
416d0c7de6 docs: update botbook submodule to latest commit (f68ad311)
Some checks failed
BotServer CI / build (push) Failing after 10s
2026-02-05 21:39:51 -03:00
24e0f3c3a6 docs: update botbook submodule to latest commit (8cfb624f)
Some checks failed
BotServer CI / build (push) Failing after 8s
2026-02-05 21:37:26 -03:00
22d7bdc16e Update botserver submodule to commit de3e5c4f
Some checks failed
BotServer CI / build (push) Failing after 12s
Fix PostgreSQL ready check for already-running instances to properly
detect when PostgreSQL is ready, even for non-interactive users.
2026-02-05 21:09:56 -03:00
f67e25fcd3 Change submodule URLs from ALM to GitHub
Some checks failed
BotServer CI / build (push) Failing after 11s
Remove ALM remote references to avoid authentication prompts when cloning.
All submodules now point to their GitHub repositories.
2026-02-05 20:51:24 -03:00
93e46dfdaa Update botserver submodule to commit 3258f3ef
Some checks are pending
BotServer CI / build (push) Waiting to run
Fix PostgreSQL startup failure for non-interactive users
2026-02-05 20:41:14 -03:00
0b591e663e chore: update botserver submodule reference
Some checks failed
BotServer CI / build (push) Failing after 12m19s
2026-02-05 20:02:06 -03:00
b3c35feff7 chore: update botserver submodule after CI optimization
Some checks are pending
BotServer CI / build (push) Waiting to run
2026-02-05 19:55:19 -03:00
0ac7c4ed03 chore: add config/directory_config.json to gitignore 2026-02-05 19:53:52 -03:00
cb9c94223d Update botserver submodule after database initialization fix
Some checks failed
BotServer CI / build (push) Failing after 13m57s
2026-02-05 19:09:23 -03:00
1f5c25ce79 Update botserver submodule after database initialization fix
Some checks are pending
BotServer CI / build (push) Waiting to run
2026-02-05 19:02:45 -03:00
2a45c5d7c4 Update botserver submodule after Router import fix
Some checks failed
BotServer CI / build (push) Failing after 23s
2026-02-05 18:41:51 -03:00
b6a0faf879 Update botui submodule after RustEmbed path fix
Some checks failed
BotServer CI / build (push) Failing after 8s
2026-02-05 18:40:49 -03:00
f34e760697 Update botserver submodule after compilation fixes
Some checks failed
BotServer CI / build (push) Failing after 14s
2026-02-05 18:31:38 -03:00
b6f69951f4 Add critical note about submodule push workflow
Some checks failed
BotServer CI / build (push) Failing after 21s
2026-02-05 18:27:00 -03:00
92f2c012f0 Update botserver submodule to latest commit
Some checks failed
BotServer CI / build (push) Failing after 14s
2026-02-05 18:12:57 -03:00
14d95994b9 Update botserver submodule after workflow fixes
Some checks failed
BotServer CI / build (push) Has been cancelled
2026-02-05 18:08:44 -03:00
4f7f0fff0e Fix: Remove GitHub Actions cache for Forgejo compatibility 2026-02-05 18:03:03 -03:00
d48791290a Fix: Remove path filters from CI workflow to ensure it triggers on all pushes 2026-02-05 17:59:49 -03:00
8831c56c90 Move CI workflow to workspace root (Forgejo only detects workflows at repo root)
Some checks failed
BotServer CI / build (push) Failing after 23s
2026-02-05 15:31:51 -03:00
b9d6816644 Fix migration: Remove orphaned COMMENT statements for session_kb_associations table 2026-02-05 14:28:38 -03:00
c258a61ad5 Update botserver submodule: Improve PostgreSQL error messages 2026-02-05 14:13:59 -03:00
3326e07234 Update botui submodule: Enable embed-ui feature by default 2026-02-05 13:43:24 -03:00
7bd5375d1a Update botserver submodule: Trigger CI test build 2026-02-05 12:30:23 -03:00
3dbadbafcb Update botserver submodule: Revert shared module duplicate fix 2026-02-05 11:53:24 -03:00
b431ae6602 Update botserver submodule: Fix CI compilation errors 2026-02-05 11:47:06 -03:00
7e89d183ff Update botserver submodule: Optimize CI build settings 2026-02-05 11:29:11 -03:00
b2f143f664 Update botui submodule to 6.1.2 2026-02-05 11:20:21 -03:00
860a460a93 Update botui submodule to 6.1.1 2026-02-05 10:30:38 -03:00
cda2d8f155 Update botui submodule: Fix UI directory detection for embed-ui 2026-02-05 09:44:59 -03:00
2a1f4305a2 Update botui submodule: Fix workflow trigger path 2026-02-05 09:21:03 -03:00
090b42618b Split Forgejo CI workflows and update documentation
CI/CD Improvements:
- Split monolithic botserver workflow into botserver-only and botui-only workflows
- BotServer CI: Triggers on botserver/**, botlib/** changes, builds only botserver
- BotUI CI: New workflow, triggers on botui/**, botlib/** changes, builds only botui
- Separate caches to avoid conflicts between projects
- Independent deployments and service restarts

Documentation:
- Remove WHATSAPP-CONFIG-GUIDE.md (duplicate of botbook documentation)
- Update README.md with new rule: check botbook/ before creating .md files
- Add workflow step to check existing documentation first

Submodule updates:
- botserver: Updated .forgejo/workflows/botserver.yaml (botserver-only)
- botui: Added .forgejo/workflows/botui.yaml (new botui workflow)
2026-02-05 08:45:41 -03:00
f97451482d Update botserver submodule to 64d5e2a1 2026-02-05 08:04:26 -03:00
8a2072919a Update botui submodule to fix ServeDir compilation 2026-02-05 08:01:27 -03:00
62749e9eba Add Playwright testing setup 2026-02-04 15:42:39 -03:00
52e551734a Update botserver submodule 2026-02-04 14:25:14 -03:00
00647f7edf Update botserver submodule 2026-02-04 14:10:05 -03:00
4100e53c28 Update botserver submodule 2026-02-04 14:02:01 -03:00
117ea78e39 Update all submodules: botapp, botbook, botlib, botmodels, bottemplates, bottest, botui 2026-02-04 13:54:40 -03:00
91ddf87dce Update botserver submodule 2026-02-04 13:47:02 -03:00
12b661fdc1 Update botserver submodule - Fix /api/auth/me token validation 2026-02-04 13:29:03 -03:00
3375394ca5 Update: botapp, botbook, botlib, botmodels, botserver, bottemplates, bottest, botui, and config changes 2026-02-04 13:27:32 -03:00
23fe731d30 Update botui submodule - Fix login redirect with absolute URL 2026-02-04 13:20:35 -03:00
9f46a41abf Update botui submodule - Fix login redirect to chat 2026-02-04 12:53:03 -03:00
13cea1b75c Update botui submodule - Hide voice icon, use light theme, add cursor blink 2026-02-04 09:56:33 -03:00
96076831ab Update botui submodule - Fix logged-out user menu 2026-02-04 08:57:44 -03:00
02cd170eeb Update botui submodule - Add logged-out navigation menu 2026-02-04 00:03:14 -03:00
3befc141e5 Fix token limits for local llama.cpp server
- Add token-aware text truncation utility in core/shared/utils.rs
- Fix embedding generators to use 600 token limit (safe under 768)
- Fix LLM context limit detection for local models (768 vs 4096)
- Prevent 'exceed context size' errors for both embeddings and chat
2026-02-02 11:56:13 -03:00
64c14a30c9 Update bottemplates submodule - Fix: Remove USE WEBSITE from edu start.bas 2026-02-01 21:10:51 -03:00
1ee5492bd8 chore: Update submodule references for template validation
- Update bottemplates submodule to include .valid file
- Update botserver submodule to include template validation code
2026-02-01 14:21:04 -03:00
43b168a4b5 Update workspace configuration and submodules 2026-01-30 23:25:02 -03:00
0dfabc46b3 chore: Update submodules with product configuration UI controls
- botserver: Add search_enabled and menu_launcher_enabled directives
- botui: Implement UI hiding logic based on product configuration

These changes allow disabling the suite search mechanism and hiding the
menu launcher when empty, providing a cleaner UI for deployments that
don't need these features.
2026-01-29 23:56:32 -03:00
79f849da6b Update botserver submodule with Windows security fixes 2026-01-28 20:11:22 -03:00
81ac2ae8c6 Fix tasks module compilation and add Windows protection installer support
- Fix installer.rs: Add Windows OS support with check_admin(), configure_windows_security(), and update_windows_signatures()
- Fix installer.rs: Remove duplicate check_root() function and fix invalid #[cfg] attributes
- Fix installer.rs: Use runtime cfg!(windows) checks instead of compile-time attributes
- Fix ui_server: Extract bot name from URL path and pass to frontend via window.__INITIAL_BOT_NAME__
- Fix tasks.js: Wrap activePollingTaskId, pollingInterval, pendingManifestUpdates, and taskStyleElement in checks to prevent redeclaration
- Fix autotask.html: Use absolute paths for all CSS/JS references (/suite/tasks/*)
- Fix navigation: Update tasks.html references to autotask.html in base.html, home.html, and index.html
2026-01-28 19:12:08 -03:00
68f3ada343 Enable LLM feature and fix compilation issues
- Update botserver submodule with LLM feature enabled by default
- Fix duplicate module declarations and move errors
- Remove unused imports and variables
- Improve code formatting

This enables the LLM feature by default so it's always available
when building the project.
2026-01-28 16:58:25 -03:00
599c338a4a chore(botui): Update submodule with asset path fixes 2026-01-28 16:26:09 -03:00
f54ad8175c chore: Update submodules with default info logging 2026-01-27 18:46:20 -03:00
cb61c130c3 chore: Remove RUST_LOG export from restart script as it is the internal default 2026-01-27 18:32:44 -03:00
1a5f54e576 chore: Restore restart.sh and update botlib submodule with new log format 2026-01-27 18:09:37 -03:00
2beeec3292 Update botserver submodule with noconsole fix 2026-01-27 16:29:15 -03:00
5f3f82748c Update botlib submodule with undeclared variable fix 2026-01-27 15:00:55 -03:00
5b0d274e5e Update botlib submodule with syntax fixes 2026-01-27 14:48:11 -03:00
dc0055d9e6 Update botserver submodule with migration fix 2026-01-27 14:15:35 -03:00
1ce77cc14f Update botlib submodule 2026-01-27 14:01:57 -03:00
4a9b969a9c Update botserver submodule
- Fixed migration errors by commenting out references to non-existent tables in consolidated migration.
- Reorganized migration files into feature-specific folders (products, dashboards, learn, video).
- Renamed migration directories to use version-based numbering (6.0.x, 6.1.x, 6.2.x) instead of timestamps.
- Updated migration execution logic in core/shared/utils.rs to respect feature dependencies.
2026-01-27 13:47:06 -03:00
ece4a72e10 chore: update botserver submodule with embedded 3rdparty.toml 2026-01-26 20:50:41 -03:00
ee26396c49 Update botserver submodule: Fix mkdir brace expansion and improved LXC logging 2026-01-26 17:39:58 -03:00
76c3ea15fb Update submodules: botbook (LXC migration docs) and botserver (system org default) 2026-01-26 17:01:03 -03:00
ac4b07fde9 chore: update botui for embedded fallback fix 2026-01-26 14:54:16 -03:00
b259c6a506 chore: update botui submodule for asset loading fix 2026-01-26 14:51:10 -03:00
3a7eb3729c refactor: update dependencies installation script 2026-01-26 13:55:48 -03:00
1c39e743d4 chore: update submodules to latest versions 2026-01-26 13:00:02 -03:00
36 changed files with 15514 additions and 844 deletions

View file

@ -1,5 +1,5 @@
[build]
rustc-wrapper = "sccache"
# rustc-wrapper = "sccache"
[target.x86_64-unknown-linux-gnu]
linker = "clang"

8
.env.example Normal file
View file

@ -0,0 +1,8 @@
# General Bots Environment Configuration
# Copy this file to .env and fill in values
# NEVER commit .env to version control
# Vault connection
VAULT_ADDR=https://127.0.0.1:8200
VAULT_TOKEN=<your-vault-token-here>
VAULT_CACERT=./botserver-stack/vault/certs/ca.crt

52
.gitignore vendored
View file

@ -2,11 +2,17 @@
target/
*.out
bin/
*.png
*.jpg
# Logs
*.log
*logfile*
*-log*
.vscode
.zed
.gemini
.claude
# Temporary files
.tmp*
@ -30,7 +36,47 @@ botserver-installers/*
!botserver-installers/.gitkeep
botserver-stack
TODO*
work
.swp
# Lock file
# Cargo.lock (should be tracked)
.kiro
config
# Data directory (contains bot configs and API keys)
data/
# Lock file (regenerated from Cargo.toml)
Cargo.lock
# Playwright
node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/
.playwright*
.ruff_cache
.opencode
config/directory_config.json
# CI cache bust: Fri Feb 13 22:33:51 UTC 2026
# Secrets - NEVER commit these files
vault-unseal-keys
start-and-unseal.sh
vault-token-*
init.json
*.pem
*.key
*.crt
*.cert
$null
AppData/
build_errors*.txt
build_errors_utf8.txt
check.json
clippy*.txt
errors.txt
errors_utf8.txt
vault-unseal-keysdefault-vault.tar
prompts/sec-bots.md
AGENTS-PROD.md

23
.gitmodules vendored
View file

@ -1,42 +1,43 @@
[submodule "botapp"]
path = botapp
url = https://alm.pragmatismo.com.br/GeneralBots/botapp.git
url = ../botapp.git
[submodule "botserver"]
path = botserver
url = https://alm.pragmatismo.com.br/GeneralBots/botserver.git
url = ../BotServer.git
[submodule "botlib"]
path = botlib
url = https://alm.pragmatismo.com.br/GeneralBots/botlib.git
url = ../botlib.git
[submodule "botui"]
path = botui
url = https://alm.pragmatismo.com.br/GeneralBots/botui.git
url = ../botui.git
[submodule "botbook"]
path = botbook
url = https://alm.pragmatismo.com.br/GeneralBots/botbook.git
url = ../botbook.git
[submodule "bottest"]
path = bottest
url = https://alm.pragmatismo.com.br/GeneralBots/bottest.git
url = ../bottest.git
[submodule "botdevice"]
path = botdevice
url = https://alm.pragmatismo.com.br/GeneralBots/botdevice.git
url = ../botdevice.git
[submodule "botmodels"]
path = botmodels
url = https://alm.pragmatismo.com.br/GeneralBots/botmodels.git
url = ../botmodels.git
[submodule "botplugin"]
path = botplugin
url = https://alm.pragmatismo.com.br/GeneralBots/botplugin.git
url = ../botplugin.git
[submodule "bottemplates"]
path = bottemplates
url = https://alm.pragmatismo.com.br/GeneralBots/bottemplates.git
url = ../bottemplates.git
[submodule ".github"]
path = .github
url = https://alm.pragmatismo.com.br/GeneralBots/.github.git
url = ../.github.git

24
.vscode/launch.json vendored
View file

@ -1,24 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'botserver'",
"cargo": {
"args": ["run", "--bin=botserver", "--package=botserver", "--manifest-path=${workspaceFolder}/botserver/Cargo.toml"],
"filter": {
"name": "botserver",
"kind": "bin"
}
},
"args": [],
"env": {
"RUST_LOG": "trace,aws_sigv4=off,aws_smithy_checksums=off,mio=off,reqwest=off,aws_runtime=off,aws_smithy_http_client=off,rustls=off,hyper_util=off,aws_smithy_runtime=off,aws_smithy_runtime_api=off,tracing=off,aws_sdk_s3=off"
},
"cwd": "${workspaceFolder}/botserver"
},
]
}

View file

@ -1,5 +0,0 @@
{
"git.ignoreLimitWarning": true,
"Codegeex.SidebarUI.LanguagePreference": "English",
"Codegeex.RepoIndex": true
}

710
AGENTS.md Normal file
View file

@ -0,0 +1,710 @@
# General Bots AI Agent Guidelines
- Use apenas a língua culta ao falar.
- Never save files on root! Use `/tmp` for temp files.
- Never push to ALM without asking first — it is production!
- If in trouble with a tool, go to the official website for install instructions.
- See `botserver/src/drive/local_file_monitor.rs` to load bots from `/opt/gbo/data`.
---
## 📁 Workspace Structure
| Crate | Purpose | Port | Tech Stack |
|-------|---------|------|------------|
| **botserver** | Main API server, business logic | 8080 | Axum, Diesel, Rhai BASIC |
| **botui** | Web UI server (dev) + proxy | 3000 | Axum, HTML/HTMX/CSS |
| **botapp** | Desktop app wrapper | - | Tauri 2 |
| **botlib** | Shared library | - | Core types, errors |
| **botbook** | Documentation | - | mdBook |
| **bottest** | Integration tests | - | tokio-test |
| **botdevice** | IoT/Device support | - | Rust |
| **botplugin** | Browser extension | - | JS |
### Key Paths
- **Binary:** `target/debug/botserver`
- **Run from:** `botserver/` directory
- **Env file:** `botserver/.env`
- **UI Files:** `botui/ui/suite/`
- **Bot data:** `/opt/gbo/data` (primary)
- **Test web:** `http://localhost:3000` — Login: `http://localhost:3000/suite/auth/login.html`
### 📦 Data Directory Structure
```
# DEV LOCAL (quando botserver-stack existe)
├── ./botserver-stack/data/system/work/{bot}.gbai/{bot}.gbdialog/
│ ├── *.bas # Scripts compilados (gerado automático)
│ └── *.ast # Cache compilado (deletar para forçar recompilação)
# PRODUCTION (com container Incus)
├── /opt/gbo/data/ # FONTE dos bots
└── (compilação fica em memória ou /opt/gbo/work/ se existir)
```
**IMPORTANTE:**
- **FONTE**: `/opt/gbo/data/{bot}.gbai/{bot}.gbdialog/{tool}.bas`
- **DEV LOCAL**: `./botserver-stack/data/system/work/{bot}.gbai/{bot}.gbdialog/`
- O botserver compila `.bas``.ast` automaticamente
- Se cache, deletar `.ast` para forçar recompilação
---
## 🧪 Debugging & Testing Tools
### 🔍 Ver Erros de Execução
```bash
tail -f botserver.log | grep -i "error\|tool"
```
### 🧪 Testar Ferramenta Específica
1. **Identificar o erro no log:**
```bash
grep -A5 "Tool error" botserver.log
```
2. **Corrigir o arquivo `.bas` na fonte:**
- **Dev local:** `./botserver-stack/data/system/work/{bot}.gbai/{bot}.gbdialog/{tool}.bas`
- **Production:** `/opt/gbo/data/{bot}.gbai/{bot}.gbdialog/{tool}.bas`
3. **Forçar recompilação (se necessário):**
```bash
rm ./botserver-stack/data/system/work/{bot}.gbai/{bot}.gbdialog/{tool}.ast
```
- Em dev local o AST fica em `./botserver-stack/...`
- Em production pode ficar em `/opt/gbo/work/...` se existir
4. **Testar novamente no browser:**
```
http://localhost:3000/{botname}
```
### ⚠️ Erros Comuns em Scripts BASIC
| Erro | Causa | Solução |
|------|-------|---------|
| `=== is not a valid operator` | BASIC usa `==`, não `===` | Substituir `===` por `--` em strings |
| `Syntax error` | Erro de sintaxe BASIC | Verificar parênteses, vírgulas |
| `Tool execution failed` | Erro no script | Ver logs para stack trace |
### 📝 Exemplo: Corrigir Operador Inválido
```bas
# ERRADO (JavaScript syntax):
PRINT "=== RESULTADO ==="
# CORRETO (BASIC syntax):
PRINT "-- RESULTADO --"
```
---
## 🧭 LLM Navigation Guide
1. Start with **[Component Dependency Graph](../README.md#-component-dependency-graph)**
2. Review **[Module Responsibility Matrix](../README.md#-module-responsibility-matrix)**
3. Study **[Data Flow Patterns](../README.md#-data-flow-patterns)**
4. Reference **[Common Architectural Patterns](../README.md#-common-architectural-patterns)**
5. Check [Security Rules](#-security-directives---mandatory) — violations are blocking
6. Follow [Code Patterns](#-mandatory-code-patterns) — consistency is mandatory
---
## ❌ Absolute Prohibitions
### Build & Deploy
- ❌ **NEVER** search `/target` folder
- ❌ **NEVER** build in release mode or use `--release`
- ❌ **NEVER** run `cargo build` — use `cargo check` for verification
- ❌ **NEVER** run `cargo clean` — causes 30min rebuilds; use `./reset.sh` for DB issues
- ❌ **NEVER** deploy manually — ALWAYS use CI/CD pipeline (push → ALM → alm-ci builds → deploys)
- ❌ **NEVER** use `scp`, direct SSH binary copy, or manual deployment
- ❌ **NEVER** run the binary directly — use `systemctl` or `./restart.sh`
### Code Quality
- ❌ **NEVER** use `panic!()`, `todo!()`, `unimplemented!()`, `unwrap()`, `expect()`
- ❌ **NEVER** use `Command::new()` directly — use `SafeCommand`
- ❌ **NEVER** return raw error strings to HTTP clients — use `ErrorSanitizer`
- ❌ **NEVER** use `#[allow()]` or lint exceptions in `Cargo.toml` — FIX the code
- ❌ **NEVER** use `_` prefix for unused vars — DELETE or USE them
- ❌ **NEVER** leave unused imports, dead code, or commented-out code
- ❌ **NEVER** use CDN links — all assets must be local
- ❌ **NEVER** create `.md` docs without checking `botbook/` first
- ❌ **NEVER** hardcode credentials — use `generate_random_string()` or env vars
### Build Pattern (MANDATORY) - Fix Fast Loop
When building botserver, use this pattern to fix errors ASAP:
```bash
# Run cargo in background, kill at 20 lines, fix errors, loop
# IMPORTANT: Never use --all-features (pulls docs/slides dependencies)
cd /home/rodriguez/src/gb
cargo check -p botserver > /tmp/check.log 2>&1 &
CARGO_PID=$!
while kill -0 $CARGO_PID 2>/dev/null; do
LINES=$(wc -l < /tmp/check.log 2>/dev/null || echo 0)
if [ "$LINES" -gt 20 ]; then
kill $CARGO_PID 2>/dev/null
echo "=== Got $LINES lines, killing cargo ==="
break
fi
sleep 1
done
# Check for errors - use strings to handle binary output
if strings /tmp/check.log | grep -q "^error"; then
echo "❌ Errors found:"
strings /tmp/check.log | grep "^error" | head -20
# Fix errors, then re-run this pattern
else
echo "✅ No errors - build clean!"
fi
```
**Key Rule:** Kill cargo at 20 lines, fix errors immediately, loop until clean.
**Why:** Compiling takes 2-3+ minutes. Getting errors in 20s saves 10+ minutes per error.
### Security
- ❌ **NEVER** include sensitive data (IPs, tokens, keys) in docs or code
- ❌ **NEVER** write internal IPs to logs — mask them (e.g., "10.x.x.x")
- ❌ **NEVER** create files with secrets in repo root
> **Secret files MUST be placed in `/tmp/` only** (ephemeral, not tracked by git).
---
## 🔐 Security Directives — MANDATORY
### 1. Error Handling — No Panics
```rust
// ❌ FORBIDDEN: unwrap(), expect(), panic!(), todo!()
// ✅ REQUIRED:
value?
value.ok_or_else(|| Error::NotFound)?
value.unwrap_or_default()
if let Some(v) = value { ... }
```
### 2. Command Execution — SafeCommand
```rust
// ❌ FORBIDDEN: Command::new("cmd").arg(user_input).output()
// ✅ REQUIRED:
use crate::security::command_guard::SafeCommand;
SafeCommand::new("allowed_command")?.arg("safe_arg")?.execute()
```
### 3. Error Responses — ErrorSanitizer
```rust
// ❌ FORBIDDEN: Json(json!({ "error": e.to_string() }))
// ✅ REQUIRED:
use crate::security::error_sanitizer::log_and_sanitize;
let sanitized = log_and_sanitize(&e, "context", None);
(StatusCode::INTERNAL_SERVER_ERROR, sanitized)
```
### 4. SQL — sql_guard
```rust
// ❌ FORBIDDEN: format!("SELECT * FROM {}", user_table)
// ✅ REQUIRED:
use crate::security::sql_guard::{sanitize_identifier, validate_table_name};
let safe_table = sanitize_identifier(&user_table);
validate_table_name(&safe_table)?;
```
### 5. Rate Limiting
- General: 100 req/s, Auth: 10 req/s, API: 50 req/s per token, WebSocket: 10 msgs/s
- Use `governor` crate with per-IP and per-User tracking
### 6. CSRF Protection
- ALL state-changing endpoints (POST/PUT/DELETE/PATCH) MUST require CSRF token
- Use `tower_csrf`, bound to user session. Exempt: Bearer Token endpoints
### 7. Security Headers (ALL responses)
`Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy: geolocation=(), microphone=(), camera=()`
### 8. Dependency Management
- App crates track `Cargo.lock`; lib crates don't
- Critical deps: exact versions (`=1.0.1`); regular: caret (`1.0`)
- Run `cargo audit` weekly; update only via PR with testing
---
## ✅ Mandatory Code Patterns
```rust
impl MyStruct { fn new() -> Self { Self { } } } // Use Self, not type name
#[derive(PartialEq, Eq)] // Always derive both
format!("Hello {name}") // Inline format args
match x { A | B => do_thing(), C => other() } // Combine identical arms
```
---
## 📏 File Size Limits
- **Max 450 lines per file** — split proactively at 350 lines
- Split by: `types.rs`, `handlers.rs`, `operations.rs`, `utils.rs`, `mod.rs`
- Re-export all public items in `mod.rs`
---
## 🔥 Error Fixing Workflow
### Preferred: Offline Batch Fix
1. Read ENTIRE error list first
2. Group errors by file
3. For each file: view → fix ALL errors → write once
4. Verify with build/diagnostics only AFTER all fixes
### ⚡ Streaming Build Rule
Don't wait for `cargo` to finish — cancel at first errors, fix, re-run.
### 🧠 Memory Issues (process "Killed")
```bash
pkill -9 cargo; pkill -9 rustc; pkill -9 botserver
CARGO_BUILD_JOBS=1 cargo check -p botserver 2>&1 | tail -200
```
---
## 🔄 Modos de Execução
O botserver suporta **dois modos** de execução:
### Modo 1: Local Standalone (sem Docker/Incus)
O botserver sobe **tudo localmente** (PostgreSQL, Valkey, MinIO, Vault, LLM).
```bash
cd /home/rodriguez/src/gb/botserver
cargo run -- --install # Instala dependências (PostgreSQL, Valkey, MinIO, etc.)
cargo run # Sobe tudo e inicia o servidor
```
**O que acontece:**
- `PackageManager` baixa e extrai binários para `botserver-stack/bin/`
- Cria `botserver-stack/data/pgdata/` com PostgreSQL
- Inicia PostgreSQL na porta 5432
- Inicia Valkey na porta 6379
- Inicia MinIO na porta 9100
- Configura Vault para secrets
- Baixa modelo LLM (llama.cpp) para detecção de anomalias
- Ao final: `http://localhost:8080`
**Verificar se está rodando:**
```bash
curl http://localhost:8080/health
curl http://localhost:5432 # PostgreSQL
curl http://localhost:6379 # Valkey
```
**Testar com Playwright:**
```bash
# Navegar para bot de teste
npx playwright open http://localhost:3000/salesianos
# Ou diretamente
npx playwright open http://localhost:3000/detecta
```
### Modo 2: Container (Incus) — Produção
Os serviços rodam em containers Incus separados.
```bash
# Subir todos os containers
sudo incus start system tables vault directory drive cache llm vector_db
# Verificar status
sudo incus list
# Acessar container system (onde roda botserver)
sudo incus exec system -- bash
# Ver logs do botserver
sudo incus exec system -- journalctl -u botserver -f
```
**Arquitetura de Containers:**
| Container | Services | Portas |
|-----------|----------|--------|
| system | BotServer, Valkey | 8080, 6379 |
| tables | PostgreSQL | 5432 |
| vault | Vault | 8200 |
| directory | Zitadel | 9000 |
| drive | MinIO | 9100 |
| cache | Valkey (backup) | 6379 |
| llm | llama.cpp | 8081 |
| vector_db | Qdrant | 6333 |
### reset.sh (Ambiente Local)
```bash
./reset.sh # Limpa e reinicia tudo localmente
```
### Service Commands
```bash
ps aux | grep -E "(botserver|botui)" | grep -v grep
curl http://localhost:8080/health
./restart.sh # Restart services
```
---
## 🎭 Playwright Browser Testing
### Browser Setup
If browser fails: `pkill -9 -f brave; pkill -9 -f chrome; pkill -9 -f chromium` → wait 3s → navigate again.
### Bot Testing Flow
1. Navigate to `http://localhost:3000/<botname>`
2. Snapshot → verify welcome message + suggestion buttons + Portuguese accents
3. Click suggestion → wait 3-5s → snapshot → fill data → submit
4. Verify DB records and backend logs
### Desktop UI Note
Chat window may cover other apps — click **middle button** (restore) to minimize, or navigate directly via URL.
### WhatsApp Testing
- Webhook is **global** — bot routing by typing bot name as first message
- Single WhatsApp number serves ALL bots; routing via `whatsapp-id` in `config.csv`
---
## Adding New Features
### Checklist
- [ ] Which module owns this? (Check Module Responsibility Matrix)
- [ ] Database migrations needed?
- [ ] New API endpoints?
- [ ] Security: input validation, auth, rate limiting, error sanitization?
- [ ] Screens in botui?
- [ ] No `unwrap()`/`expect()`?
### Pattern: types → schema → Diesel model → business logic → API endpoint → BASIC keyword (if applicable) → tests → docs in `botbook/`
### Commit & Deploy
```bash
cd botserver && git push alm main && git push origin main
cd .. && git add botserver && git commit -m "Update botserver: <desc>" && git push alm main && git push origin main
```
---
## 🎨 Frontend Standards
- **HTMX-first** — server returns HTML fragments, not JSON
- **Local assets only** — NO CDN links
- Use `hx-get`, `hx-post`, `hx-target`, `hx-swap`; WebSocket via htmx-ws
---
## 🚀 Performance & Quality
- `cargo clippy --workspace` must pass with **0 warnings**
- `cargo tree --duplicates` / `cargo machete` / `cargo audit` weekly
- Release profile: `opt-level = "z"`, `lto = true`, `codegen-units = 1`, `strip = true`, `panic = "abort"`
- Use `default-features = false` and opt-in to needed features
---
## 🧪 Testing
- **Unit:** per-crate `tests/` or `#[cfg(test)]` modules — `cargo test -p <crate>`
- **Integration:** `bottest/` crate — `cargo test -p bottest`
- **Coverage:** 80%+ on critical paths; ALL error paths and security guards tested
---
## 🚢 Deploy Workflow (CI/CD Only)
1. Push to ALM (triggers CI automatically)
2. CI builds on alm-ci → deploys to system container via SSH
3. Service auto-restarts on binary update
4. Verify: check service status + logs after ~10 min
### Container Architecture
| Container | Service | Port |
|-----------|---------|------|
| system | BotServer + Valkey | 8080/6379 |
| tables | PostgreSQL | 5432 |
| vault | Vault | 8200 |
---
## 🔑 Core Directives Summary
- **OFFLINE FIRST** — fix all errors from list before compiling
- **BATCH BY FILE** — fix ALL errors in a file at once, write once
- **VERIFY LAST** — only compile after ALL fixes applied
- **DELETE DEAD CODE** — never keep unused code
- **GIT WORKFLOW** — always push to ALL repositories
- **0 warnings, 0 errors** — loop until clean
---
## 🔧 Bot Scripts Architecture
### File Types
| File | Purpose |
|------|---------|
| `start.bas` | Entry point, executed on session start |
| `{tool}.bas` | Tool implementation (e.g., `detecta.bas`) |
| `tables.bas` | **SPECIAL** - Defines database tables, auto-creates on compile |
| `init_folha.bas` | Initialization script for specific features |
### tables.bas — SPECIAL FILE
- **DO NOT call via CALL keyword** - it's processed automatically
- Parsed at compile time by `process_table_definitions()`
- Tables are created/updated in database via `sync_bot_tables()`
- Location: `/opt/gbo/data/{bot}.gbai/{bot}.gbdialog/tables.bas`
### Tool Button Execution (TOOL_EXEC)
- Frontend sends `message_type: 6` via WebSocket
- Backend handles in `stream_response()` when `message_type == MessageType::TOOL_EXEC`
- Tool executes directly, skips KB injection and LLM
- Result appears in chat (tool output), no "/tool" text shown
### CALL Keyword
- Can call in-memory procedures OR .bas scripts
- Syntax: `CALL "script_name"` or `CALL "procedure_name"`
- If not in memory, looks for `{name}.bas` in bot's gbdialog folder
### DETECT Keyword
- Analyzes database table for anomalies
- Requires table to exist (defined in tables.bas)
- Example: `result = DETECT "folha_salarios"`
- Calls BotModels API at `/api/anomaly/detect`
### start.bas Execution
- Executed on WebSocket connect (for web clients)
- Also on first user message (blocking, once per session)
- Loads suggestions via `ADD_SUGGESTION_TOOL`
- Marks session with Redis key to prevent re-run
### MessageType Enum (botlib/src/message_types.rs)
| ID | Name | Purpose |
|----|------|---------|
| 0 | EXTERNAL | External message |
| 1 | USER | User message |
| 2 | BOT_RESPONSE | Bot response |
| 3 | CONTINUE | Continue processing |
| 4 | SUGGESTION | Suggestion button |
| 5 | CONTEXT_CHANGE | Context change |
| 6 | TOOL_EXEC | Direct tool execution (skips KB/LLM) |
**Usage:** When frontend sends `message_type: 6`, backend executes tool directly without going through LLM.
### 🚨 FUNDAMENTAL: Submodule Push Rule (MANDATORY)
**Every time you push the main repo, you MUST also push ALL submodules!**
```bash
# After ANY main repo push, ALWAYS run:
cd botserver && git push origin main && git push alm main
cd ../botui && git push origin main && git push alm main
cd ../botlib && git push origin main && git push alm main
# ... repeat for ALL submodules
```
**Why:** CI builds based on submodule commits. If submodule isn't pushed, CI deploys old code.
**Checklist before pushing:**
- [ ] botserver pushed?
- [ ] botui pushed?
- [ ] botlib pushed?
- [ ] All other submodules pushed?
- [ ] Main repo points to new submodule commits?
---
## 🔐 Zitadel Setup (Directory Service)
### Container Architecture
- **directory container**: Zitadel running on port **8080** internally
- **tables container**: PostgreSQL database on port 5432
- Use database **PROD-DIRECTORY** for Zitadel data
### Network Access (Container Mode)
- **Internal API**: `http://<directory-ip>:8080`
- **External port 9000** redirected via iptables NAT to directory:8080
- **Health check**: `curl -sf http://localhost:8080/debug/healthz`
### Zitadel Installation Steps
1. **Reset database** (on tables container):
```bash
psql -h localhost -U postgres -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'PROD-DIRECTORY' AND pid <> pg_backend_pid();"
psql -h localhost -U postgres -d postgres -c "DROP DATABASE IF EXISTS \"PROD-DIRECTORY\";"
psql -h localhost -U postgres -d postgres -c "CREATE DATABASE \"PROD-DIRECTORY\";"
```
2. **Create init config** (on directory container):
```bash
cat > /opt/gbo/conf/directory/zitadel-init-steps.yaml << "EOF"
FirstInstance:
InstanceName: "BotServer"
DefaultLanguage: "en"
PatPath: "/opt/gbo/conf/directory/admin-pat.txt"
Org:
Name: "BotServer"
Machine:
Machine:
Username: "admin-sa"
Name: "Admin Service Account"
Pat:
ExpirationDate: "2099-01-01T00:00:00Z"
Human:
UserName: "admin"
FirstName: "Admin"
LastName: "User"
Email:
Address: "admin@localhost"
Verified: true
Password: "Admin123!"
PasswordChangeRequired: false
EOF
```
3. **Start Zitadel** (on directory container):
```bash
pkill -9 zitadel || true
nohup env \
ZITADEL_DATABASE_POSTGRES_HOST=<tables-ip> \
ZITADEL_DATABASE_POSTGRES_PORT=5432 \
ZITADEL_DATABASE_POSTGRES_DATABASE=PROD-DIRECTORY \
ZITADEL_DATABASE_POSTGRES_USER_USERNAME=postgres \
ZITADEL_DATABASE_POSTGRES_USER_PASSWORD=postgres \
ZITADEL_DATABASE_POSTGRES_USER_SSL_MODE=disable \
ZITADEL_DATABASE_POSTGRES_ADMIN_USERNAME=postgres \
ZITADEL_DATABASE_POSTGRES_ADMIN_PASSWORD=postgres \
ZITADEL_DATABASE_POSTGRES_ADMIN_SSL_MODE=disable \
ZITADEL_EXTERNALSECURE=false \
ZITADEL_EXTERNALDOMAIN=<directory-ip> \
ZITADEL_EXTERNALPORT=9000 \
ZITADEL_TLS_ENABLED=false \
/opt/gbo/bin/zitadel start-from-init \
--masterkey MasterkeyNeedsToHave32Characters \
--tlsMode disabled \
--externalDomain <directory-ip> \
--externalPort 9000 \
--steps /opt/gbo/conf/directory/zitadel-init-steps.yaml \
> /opt/gbo/logs/zitadel.log 2>&1 &
```
4. **Wait for bootstrap** (~90 seconds), then verify:
```bash
curl -sf http://localhost:8080/debug/healthz
cat /opt/gbo/conf/directory/admin-pat.txt
```
5. **Configure iptables** (on system container):
```bash
iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination <directory-ip>:8080
iptables -t nat -A OUTPUT -p tcp -d <external-ip> --dport 9000 -j DNAT --to-destination <directory-ip>:8080
```
### Zitadel API Usage
**PAT file location**: `/opt/gbo/conf/directory/admin-pat.txt` (on directory container)
#### Get IAM Info (internal)
```bash
curl -s -H "Authorization: Bearer $PAT" http://<directory-ip>:8080/management/v1/iam
```
#### Get IAM Info (external via port 9000)
```bash
curl -s -H "Authorization: Bearer $PAT" -H "Host: <directory-ip>" http://<external-ip>:9000/management/v1/iam
```
#### Create Human User
```bash
curl -s -X POST \
-H "Authorization: Bearer $PAT" \
-H "Host: <directory-ip>" \
-H "Content-Type: application/json" \
http://<external-ip>:9000/management/v1/users/human \
-d '{
"userName": "janedoe",
"name": "Jane Doe",
"profile": {"firstName": "Jane", "lastName": "Doe"},
"email": {"email": "jane@example.com"}
}'
```
### Zitadel API Endpoints Reference
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/management/v1/iam` | GET | Get IAM info |
| `/management/v1/orgs/me` | GET | Get current org |
| `/management/v1/users/human` | POST | Create human user |
| `/management/v1/users/machine` | POST | Create machine user |
| `/oauth/v2/token` | POST | Get access token |
| `/debug/healthz` | GET | Health check |
### Important Notes
- **Zitadel listens on port 8080 internally**
- **External port 9000** is forwarded via iptables NAT
- **Use Host header** with directory IP for external API calls
- **PAT file**: `/opt/gbo/conf/directory/admin-pat.txt`
- **Admin credentials**: `admin` / `Admin123!` (human user)
- **Database**: `PROD-DIRECTORY` on tables container
- **Zitadel v4.13.1** is the current version
---
## 📊 SEPLAGSE Bot Configuration
### Bot Location
- **Source**: `/opt/gbo/data/seplagse.gbai/seplagse.gbdialog/`
- **Work**: `./botserver-stack/data/system/work/seplagse.gbai/seplagse.gbdialog/`
### Key Files
| File | Purpose |
|------|---------|
| `start.bas` | Entry point with suggestion buttons |
| `detecta.bas` | Tool for detecting anomalies in folha_salarios |
| `init_folha.bas` | Tool to initialize test data (INSERT keyword has issues) |
| `tables.bas` | Table definitions - auto-processed on compile |
### Tool Button Configuration (start.bas)
```bas
ADD_SUGGESTION_TOOL "detecta" AS "🔍 Detectar Desvios na Folha"
ADD_SUGGESTION_TOOL "init_folha" AS "⚙️ Inicializar Dados de Teste"
```
### Detection Flow
1. User clicks "Detectar Desvios na Folha" button
2. Frontend sends `message_type: 6` (TOOL_EXEC) via WebSocket
3. Backend executes `detecta.bas` directly (skips KB/LLM)
4. `detecta.bas` calls `DETECT "folha_salarios"` keyword
5. Keyword queries bot-specific database for table data
6. Data sent to BotModels API at `/api/anomaly/detect`
7. Results displayed in chat
### Fixes Applied
1. **TOOL_EXEC message type**: Added `MessageType::TOOL_EXEC` (id=6)
2. **Frontend WebSocket**: Sends `message_type: 6` for tool buttons
3. **Backend handler**: `stream_response()` handles TOOL_EXEC directly
4. **DETECT keyword**: Fixed to use bot-specific database (`bot_database_manager`)
5. **Bot execution**: Tool buttons work - no "/tool" text shown
### Known Issues
- **INSERT keyword**: Has parsing issues in multi-line scripts
- **Test data**: `init_folha.bas` cannot insert data due to INSERT issues
- **Workaround**: Insert data manually or via external SQL tool
### Testing
```bash
# Restart services
./restart.sh
# Test in browser
http://localhost:3000/seplagse
# Check logs
tail -f botserver.log | grep -i "detecta\|error"
```

11677
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -9,6 +9,7 @@ members = [
"bottest",
"botui",
]
exclude = ["backup-to-s3"]
[workspace.lints.rust]
@ -109,6 +110,7 @@ url = "2.5"
dirs = "5.0"
tempfile = "3"
walkdir = "2.5.0"
notify = "8.0"
# ─── COMPRESSION / ARCHIVES ───
flate2 = "1.0"
@ -174,7 +176,7 @@ indicatif = "0.18.0"
# ─── MEMORY ALLOCATOR ───
tikv-jemallocator = "0.6"
tikv-jemalloc-ctl = { version = "0.6", default-features = false }
tikv-jemalloc-ctl = { version = "0.6", default-features = false, features = ["stats"] }
# ─── SECRETS / VAULT ───
vaultrs = "0.7"
@ -196,7 +198,7 @@ csv = "1.3"
tonic = { version = "0.14.2", default-features = false }
# ─── STATIC FILES ───
rust-embed = "8.5"
rust-embed = { version = "8.5", features = ["interpolate-folder-path"] }
mime_guess = "2.0"
# ─── TAURI (Desktop/Mobile) ───

View file

@ -1,204 +0,0 @@
#!/bin/bash
#
# DEPENDENCIES-DEV.sh - Development Dependencies for General Bots
#
# This script installs additional packages needed for BUILDING botserver from source.
# Only install these if you plan to compile the code yourself.
#
# Usage: sudo ./DEPENDENCIES-DEV.sh
#
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN} General Bots Development Dependencies${NC}"
echo -e "${GREEN}========================================${NC}"
# Check root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}Error: Run as root (use sudo)${NC}"
exit 1
fi
# Detect OS
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
else
echo -e "${RED}Error: Cannot detect OS${NC}"
exit 1
fi
echo -e "${YELLOW}OS: $OS${NC}"
install_debian_ubuntu() {
apt-get update
apt-get install -y \
build-essential \
gcc \
g++ \
clang \
llvm-dev \
libclang-dev \
cmake \
make \
git \
pkg-config \
libssl-dev \
libpq-dev \
liblzma-dev \
zlib1g-dev \
libabseil-dev \
protobuf-compiler \
libprotobuf-dev \
automake \
bison \
flex \
gperf \
libtool \
m4 \
nasm \
python3 \
python3-pip \
nodejs \
npm
# Cross-compilation toolchains
apt-get install -y \
gcc-aarch64-linux-gnu \
gcc-arm-linux-gnueabihf \
gcc-x86-64-linux-gnu || true
}
install_fedora_rhel() {
dnf groupinstall -y "Development Tools"
dnf install -y \
gcc \
gcc-c++ \
clang \
llvm-devel \
clang-devel \
cmake \
make \
git \
pkgconf-devel \
openssl-devel \
libpq-devel \
xz-devel \
zlib-devel \
abseil-cpp-devel \
protobuf-compiler \
protobuf-devel \
automake \
bison \
flex \
gperf \
libtool \
m4 \
nasm \
python3 \
python3-pip \
nodejs \
npm
}
install_arch() {
pacman -Sy --noconfirm \
base-devel \
gcc \
clang \
llvm \
cmake \
make \
git \
pkgconf \
openssl \
postgresql-libs \
xz \
zlib \
abseil-cpp \
protobuf \
automake \
bison \
flex \
gperf \
libtool \
m4 \
nasm \
python \
python-pip \
nodejs \
npm
}
install_alpine() {
apk add --no-cache \
build-base \
gcc \
g++ \
clang \
llvm-dev \
clang-dev \
cmake \
make \
git \
pkgconf-dev \
openssl-dev \
postgresql-dev \
xz-dev \
zlib-dev \
abseil-cpp-dev \
protobuf-dev \
protoc \
automake \
bison \
flex \
gperf \
libtool \
m4 \
nasm \
python3 \
py3-pip \
nodejs \
npm
}
case $OS in
ubuntu|debian|linuxmint|pop)
install_debian_ubuntu
;;
fedora|rhel|centos|rocky|almalinux)
install_fedora_rhel
;;
arch|manjaro)
install_arch
;;
alpine)
install_alpine
;;
*)
echo -e "${RED}Unsupported OS: $OS${NC}"
echo "Required development packages:"
echo " - build-essential/base-devel"
echo " - gcc, g++, clang"
echo " - cmake, make, git"
echo " - Development headers for:"
echo " - OpenSSL, PostgreSQL, XZ, zlib"
echo " - Abseil, Protobuf, LLVM"
exit 1
;;
esac
echo -e "${GREEN}Development dependencies installed!${NC}"
echo ""
echo "Install Rust if not already installed:"
echo " curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"
echo ""
echo "Then build with:"
echo " cargo build --release"

77
DEPENDENCIES.ps1 Normal file
View file

@ -0,0 +1,77 @@
<#
.SYNOPSIS
Installs runtime dependencies for General Bots on Windows.
.DESCRIPTION
This script downloads and configures the system libraries required to build
and run BotServer on Windows. It downloads PostgreSQL binaries (for libpq)
and sets the PQ_LIB_DIR environment variable permanently.
.EXAMPLE
PS> .\DEPENDENCIES.ps1
#>
$ErrorActionPreference = 'Stop'
# ─── COLORS ───
function Write-Step { param($msg) Write-Host " * $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host " ! $msg" -ForegroundColor Yellow }
function Write-Err { param($msg) Write-Host " x $msg" -ForegroundColor Red }
Write-Host "========================================" -ForegroundColor Green
Write-Host " General Bots Runtime Dependencies" -ForegroundColor Green
Write-Host " (Windows)" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
# ─── PostgreSQL binaries (libpq.lib for Diesel ORM) ───
$PgsqlDir = "C:\pgsql\pgsql"
$PgsqlLib = "$PgsqlDir\lib\libpq.lib"
$PgsqlZipUrl = "https://get.enterprisedb.com/postgresql/postgresql-17.4-1-windows-x64-binaries.zip"
$PgsqlZip = "$env:TEMP\pgsql.zip"
if (Test-Path $PgsqlLib) {
Write-Step "PostgreSQL binaries already present at $PgsqlDir"
} else {
Write-Host "`nDownloading PostgreSQL binaries..." -ForegroundColor Cyan
Write-Host " URL: $PgsqlZipUrl"
Write-Host " This may take a few minutes (~300MB)...`n"
Invoke-WebRequest -Uri $PgsqlZipUrl -OutFile $PgsqlZip -UseBasicParsing
Write-Host "Extracting to C:\pgsql ..."
if (Test-Path "C:\pgsql") { Remove-Item "C:\pgsql" -Recurse -Force }
Expand-Archive -Path $PgsqlZip -DestinationPath "C:\pgsql" -Force
Remove-Item $PgsqlZip -Force -ErrorAction SilentlyContinue
if (Test-Path $PgsqlLib) {
Write-Step "PostgreSQL binaries installed successfully."
} else {
Write-Err "Failed to find libpq.lib after extraction!"
exit 1
}
}
# Set PQ_LIB_DIR permanently for the current user
$CurrentPqDir = [System.Environment]::GetEnvironmentVariable("PQ_LIB_DIR", "User")
if ($CurrentPqDir -ne "$PgsqlDir\lib") {
[System.Environment]::SetEnvironmentVariable("PQ_LIB_DIR", "$PgsqlDir\lib", "User")
$env:PQ_LIB_DIR = "$PgsqlDir\lib"
Write-Step "PQ_LIB_DIR set to '$PgsqlDir\lib' (User environment variable)"
} else {
Write-Step "PQ_LIB_DIR already configured."
}
# ─── Summary ───
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " Dependencies installed!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "You can now build and run:" -ForegroundColor Cyan
Write-Host " cargo build -p botserver"
Write-Host " cargo build -p botui"
Write-Host " .\restart.ps1"
Write-Host ""
Write-Host "NOTE: If this is the first time, restart your terminal" -ForegroundColor Yellow
Write-Host " so PQ_LIB_DIR takes effect." -ForegroundColor Yellow

View file

@ -1,140 +1,133 @@
#!/bin/bash
#
# DEPENDENCIES.sh - Runtime Dependencies for General Bots
#
# This script installs all system packages required to RUN botserver binary.
# These are the minimal dependencies needed for production deployment.
#
# Usage: sudo ./DEPENDENCIES.sh
#
#!/bin/bash
#
# DEPENDENCIES.sh - Runtime Dependencies for General Bots
#
# This script installs all system packages required to RUN botserver binary.
# These are the minimal dependencies needed for production deployment.
#
# Usage: sudo ./DEPENDENCIES.sh
#
set -e
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN} General Bots Runtime Dependencies${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN} General Bots Runtime Dependencies${NC}"
echo -e "${GREEN}========================================${NC}"
# Check root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}Error: Run as root (use sudo)${NC}"
exit 1
fi
# Check root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}Error: Run as root (use sudo)${NC}"
exit 1
fi
# Detect OS
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
else
echo -e "${RED}Error: Cannot detect OS${NC}"
exit 1
fi
# Detect OS
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
else
echo -e "${RED}Error: Cannot detect OS${NC}"
exit 1
fi
echo -e "${YELLOW}OS: $OS${NC}"
echo -e "${YELLOW}OS: $OS${NC}"
install_debian_ubuntu() {
apt-get update
apt-get install -y \
libpq5 \
libssl3 \
liblzma5 \
zlib1g \
ca-certificates \
curl \
wget \
libabseil20210324 \
libclang1 \
pkg-config \
snapd
# LXC for containers
snap install lxd || apt-get install -y lxd || true
# Initialize LXD
if command -v lxd &> /dev/null && ! lxc list &> /dev/null 2>&1; then
lxd init --auto || true
fi
}
install_debian_ubuntu() {
apt-get install -y \
libpq5 \
libssl3 \
liblzma5 \
zlib1g \
ca-certificates \
curl \
wget \
libclang1 \
pkg-config \
snapd
install_fedora_rhel() {
dnf install -y \
libpq \
openssl-libs \
xz-libs \
zlib \
ca-certificates \
curl \
wget \
abseil-cpp \
clang-libs \
pkgconf-pkg-config \
lxc \
lxc-templates
}
install_arch() {
pacman -Sy --noconfirm \
postgresql-libs \
openssl \
xz \
zlib \
ca-certificates \
curl \
wget \
abseil-cpp \
clang \
pkgconf \
lxc
}
}
install_alpine() {
apk add --no-cache \
libpq \
openssl \
xz-libs \
zlib \
ca-certificates \
curl \
wget \
abseil-cpp \
clang \
pkgconf \
lxc
}
install_fedora_rhel() {
dnf install -y \
libpq \
openssl-libs \
xz-libs \
zlib \
ca-certificates \
curl \
wget \
abseil-cpp \
clang-libs \
pkgconf-pkg-config \
lxc \
lxc-templates
}
case $OS in
ubuntu|debian|linuxmint|pop)
install_debian_ubuntu
;;
fedora|rhel|centos|rocky|almalinux)
install_fedora_rhel
;;
arch|manjaro)
install_arch
;;
alpine)
install_alpine
;;
*)
echo -e "${RED}Unsupported OS: $OS${NC}"
echo "Required libraries:"
echo " - libpq (PostgreSQL client)"
echo " - libssl (OpenSSL)"
echo " - liblzma (XZ compression)"
echo " - zlib (compression)"
echo " - abseil-cpp (Google Abseil)"
echo " - clang (LLVM runtime)"
echo " - LXC (containers)"
exit 1
;;
esac
install_arch() {
pacman -Sy --noconfirm \
postgresql-libs \
openssl \
xz \
zlib \
ca-certificates \
curl \
wget \
abseil-cpp \
clang \
pkgconf \
lxc
}
echo -e "${GREEN}Runtime dependencies installed!${NC}"
echo ""
echo "You can now run:"
echo " ./botserver"
install_alpine() {
apk add --no-cache \
libpq \
openssl \
xz-libs \
zlib \
ca-certificates \
curl \
wget \
abseil-cpp \
clang \
pkgconf \
lxc
}
case $OS in
ubuntu|debian|linuxmint|pop)
install_debian_ubuntu
;;
fedora|rhel|centos|rocky|almalinux)
install_fedora_rhel
;;
arch|manjaro)
install_arch
;;
alpine)
install_alpine
;;
*)
echo -e "${RED}Unsupported OS: $OS${NC}"
echo "Required libraries:"
echo " - libpq (PostgreSQL client)"
echo " - libssl (OpenSSL)"
echo " - liblzma (XZ compression)"
echo " - zlib (compression)"
echo " - abseil-cpp (Google Abseil)"
echo " - clang (LLVM runtime)"
echo " - LXC (containers)"
exit 1
;;
esac
echo -e "${GREEN}Runtime dependencies installed!${NC}"
echo ""
echo "You can now run:"
echo " ./botserver"

383
PROMPT.md
View file

@ -1,383 +0,0 @@
# General Bots Workspace - Master Development Guide
**Version:** 6.2.0 - DO NOT CHANGE
**Project:** General Bots Workspace (Rust Monorepo)
---
## 📁 WORKSPACE STRUCTURE
| Crate | Purpose | Port | Tech Stack |
|-------|---------|------|------------|
| **botserver** | Main API server, business logic | 8088 | Axum, Diesel, Rhai BASIC |
| **botui** | Web UI server (dev) + proxy | 3000 | Axum, HTML/HTMX/CSS |
| **botapp** | Desktop app wrapper | - | Tauri 2 |
| **botlib** | Shared library | - | Core types, errors |
| **botbook** | Documentation | - | mdBook |
| **bottest** | Integration tests | - | tokio-test |
| **botdevice** | IoT/Device support | - | Rust |
| **botmodels** | Data models visualization | - | - |
| **botplugin** | Browser extension | - | JS |
### Key Paths
- **Binary:** `target/debug/botserver`
- **Run from:** `botserver/` directory
- **Env file:** `botserver/.env`
- **Stack:** `botserver/botserver-stack/`
- **UI Files:** `botui/ui/suite/`
---
## 🔥 ERROR FIXING WORKFLOW
### Mode 1: OFFLINE Batch Fix (PREFERRED)
When given error output:
```
1. Read ENTIRE error list first
2. Group errors by file
3. For EACH file with errors:
a. View file → understand context
b. Fix ALL errors in that file
c. Write once with all fixes
4. Move to next file
5. REPEAT until ALL errors addressed
6. ONLY THEN → verify with build/diagnostics
```
**NEVER run cargo build/check/clippy DURING fixing**
**Fix ALL errors OFFLINE first, verify ONCE at the end**
### Mode 2: Interactive Loop
```
LOOP UNTIL (0 warnings AND 0 errors):
1. Run diagnostics → pick file with issues
2. Read entire file
3. Fix ALL issues in that file
4. Write file once with all fixes
5. Verify with diagnostics
6. CONTINUE LOOP
END LOOP
```
### Common Error Patterns
| Error | Fix |
|-------|-----|
| `expected i64, found u64` | `value as i64` |
| `expected Option<T>, found T` | `Some(value)` |
| `expected T, found Option<T>` | `value.unwrap_or(default)` |
| `cannot multiply f32 by f64` | `f64::from(f32_val) * f64_val` |
| `no field X on type Y` | Check struct definition |
| `no variant X found` | Check enum definition |
| `function takes N arguments` | Match function signature |
| `cannot find function` | Add missing function or fix import |
| `unused variable` | Delete or use with `..` in patterns |
| `unused import` | Delete the import line |
| `cannot move out of X because borrowed` | Use scoping `{ }` to limit borrow |
---
## 🧠 MEMORY MANAGEMENT
When compilation fails due to memory issues (process "Killed"):
```bash
pkill -9 cargo; pkill -9 rustc; pkill -9 botserver
CARGO_BUILD_JOBS=1 cargo check -p botserver 2>&1 | tail -200
```
---
## 📏 FILE SIZE LIMITS - MANDATORY
### Maximum 1000 Lines Per File
When a file grows beyond this limit:
1. **Identify logical groups** - Find related functions
2. **Create subdirectory module** - e.g., `handlers/`
3. **Split by responsibility:**
- `crud.rs` - Create, Read, Update, Delete
- `ai.rs` - AI/ML handlers
- `export.rs` - Export/import
- `validation.rs` - Validation
- `mod.rs` - Re-exports
4. **Keep files focused** - Single responsibility
5. **Update mod.rs** - Re-export all public items
**NEVER let a single file exceed 1000 lines - split proactively at 800 lines**
---
## 🚀 PERFORMANCE & SIZE STANDARDS
### Binary Size Optimization
- **Release Profile**: Always maintain `opt-level = "z"`, `lto = true`, `codegen-units = 1`, `strip = true`, `panic = "abort"`.
- **Dependencies**:
- Run `cargo tree --duplicates` weekly to find and resolve duplicate versions.
- Run `cargo machete` to remove unused dependencies.
- Use `default-features = false` and explicitly opt-in to needed features.
### Memory Optimization
- **Strings**: Prefer `&str` over `String` where possible. Use `Cow<str>` for conditional ownership.
- **Collections**: Use `Vec::with_capacity` when size is known. Consider `SmallVec` for hot paths.
- **Allocations**: Minimize heap allocations in hot paths.
### Linting & Code Quality
- **Clippy**: Code MUST pass `cargo clippy --all-targets --all-features` with **0 warnings**.
- **No Allow**: Do not use `#[allow(clippy::...)]` unless absolutely necessary and documented. Fix the underlying issue.
---
## 🔐 SECURITY DIRECTIVES - MANDATORY
### Error Handling - NO PANICS IN PRODUCTION
```rust
// ❌ FORBIDDEN
value.unwrap()
value.expect("message")
panic!("error")
todo!()
unimplemented!()
// ✅ REQUIRED
value?
value.ok_or_else(|| Error::NotFound)?
value.unwrap_or_default()
value.unwrap_or_else(|e| { log::error!("{}", e); default })
if let Some(v) = value { ... }
match value { Ok(v) => v, Err(e) => return Err(e.into()) }
```
### Command Execution - USE SafeCommand
```rust
// ❌ FORBIDDEN
Command::new("some_command").arg(user_input).output()
// ✅ REQUIRED
use crate::security::command_guard::SafeCommand;
SafeCommand::new("allowed_command")?
.arg("safe_arg")?
.execute()
```
### Error Responses - USE ErrorSanitizer
```rust
// ❌ FORBIDDEN
Json(json!({ "error": e.to_string() }))
format!("Database error: {}", e)
// ✅ REQUIRED
use crate::security::error_sanitizer::log_and_sanitize;
let sanitized = log_and_sanitize(&e, "context", None);
(StatusCode::INTERNAL_SERVER_ERROR, sanitized)
```
### SQL - USE sql_guard
```rust
// ❌ FORBIDDEN
format!("SELECT * FROM {}", user_table)
// ✅ REQUIRED
use crate::security::sql_guard::{sanitize_identifier, validate_table_name};
let safe_table = sanitize_identifier(&user_table);
validate_table_name(&safe_table)?;
```
---
## ❌ ABSOLUTE PROHIBITIONS
```
❌ NEVER use .unwrap() or .expect() in production code (tests OK)
❌ NEVER use panic!(), todo!(), unimplemented!()
❌ NEVER use Command::new() directly - use SafeCommand
❌ NEVER return raw error strings to HTTP clients
❌ NEVER use #[allow()] in source code - FIX the code instead
❌ NEVER add lint exceptions to Cargo.toml - FIX the code instead
❌ NEVER use _ prefix for unused variables - DELETE or USE them
❌ NEVER leave unused imports or dead code
❌ NEVER add comments - code must be self-documenting
❌ NEVER modify Cargo.toml lints section!
❌ NEVER use CDN links - all assets must be local
```
---
## ✅ MANDATORY CODE PATTERNS
### Use Self in Impl Blocks
```rust
impl MyStruct {
fn new() -> Self { Self { } } // ✅ Not MyStruct
}
```
### Derive Eq with PartialEq
```rust
#[derive(PartialEq, Eq)] // ✅ Always both
struct MyStruct { }
```
### Inline Format Args
```rust
format!("Hello {name}") // ✅ Not format!("{}", name)
```
### Combine Match Arms
```rust
match x {
A | B => do_thing(), // ✅ Combine identical arms
C => other(),
}
```
---
## 🖥️ UI Architecture (botui + botserver)
### Two Servers During Development
| Server | Port | Purpose |
|--------|------|---------|
| **botui** | 3000 | Serves UI files + proxies API to botserver |
| **botserver** | 8088 | Backend API + embedded UI fallback |
### How It Works
```
Browser → localhost:3000 → botui (serves HTML/CSS/JS)
→ /api/* proxied to botserver:8088
→ /suite/* served from botui/ui/suite/
```
### Adding New Suite Apps
1. Create folder: `botui/ui/suite/<appname>/`
2. Add to `SUITE_DIRS` in `botui/src/ui_server/mod.rs`
3. Rebuild botui: `cargo build -p botui`
4. Add menu entry in `botui/ui/suite/index.html`
### Hot Reload
- **UI files (HTML/CSS/JS)**: Edit & refresh browser (no restart)
- **botui Rust code**: Rebuild + restart botui
- **botserver Rust code**: Rebuild + restart botserver
### Production (Single Binary)
When `botui/ui/suite/` folder not found, botserver uses **embedded UI** compiled into binary via `rust-embed`.
---
## 🎨 FRONTEND STANDARDS
### HTMX-First Approach
- Use HTMX to minimize JavaScript
- Server returns HTML fragments, not JSON
- Use `hx-get`, `hx-post`, `hx-target`, `hx-swap`
- WebSocket via htmx-ws extension
### Local Assets Only - NO CDN
```html
<!-- ✅ CORRECT -->
<script src="js/vendor/htmx.min.js"></script>
<!-- ❌ WRONG -->
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
```
### Vendor Libraries Location
```
ui/suite/js/vendor/
├── htmx.min.js
├── htmx-ws.js
├── marked.min.js
└── gsap.min.js
```
---
## 📋 PROJECT-SPECIFIC PROMPTS
Each crate has its own PROMPT.md with specific guidelines:
| Crate | PROMPT.md Location | Focus |
|-------|-------------------|-------|
| botserver | `botserver/PROMPT.md` | API, security, Rhai BASIC |
| botui | `botui/PROMPT.md` | UI, HTMX, CSS design system |
| botapp | `botapp/PROMPT.md` | Tauri, desktop features |
| botlib | `botlib/PROMPT.md` | Shared types, errors |
| botbook | `botbook/PROMPT.md` | Documentation, mdBook |
| bottest | `bottest/PROMPT.md` | Test infrastructure |
### Special Prompts
| File | Purpose |
|------|---------|
| `botserver/src/tasks/PROMPT.md` | AutoTask LLM executor |
| `botserver/src/auto_task/APP_GENERATOR_PROMPT.md` | App generation |
---
## 🚀 STARTING DEVELOPMENT
### Start Both Servers
```bash
# Terminal 1: botserver
cd botserver && cargo run -- --noconsole
# Terminal 2: botui
cd botui && BOTSERVER_URL="http://localhost:8088" cargo run
```
### Build Commands
```bash
# Check single crate
cargo check -p botserver
# Build workspace
cargo build
# Run tests
cargo test -p bottest
```
---
## 📋 CONTINUATION PROMPT
When starting a new session or continuing work:
```
Continue on gb/ workspace. Follow PROMPT.md strictly:
1. Check current state with build/diagnostics
2. Fix ALL warnings and errors - NO #[allow()] attributes
3. Delete unused code, don't suppress warnings
4. Remove unused parameters, don't prefix with _
5. Verify after each fix batch
6. Loop until 0 warnings, 0 errors
```
---
## 🔑 REMEMBER
- **OFFLINE FIRST** - Fix all errors from list before compiling
- **ZERO WARNINGS, ZERO ERRORS** - The only acceptable state
- **FIX, DON'T SUPPRESS** - No #[allow()], no Cargo.toml lint exceptions
- **SECURITY FIRST** - No unwrap, no raw errors, no direct commands
- **READ BEFORE FIX** - Always understand context first
- **BATCH BY FILE** - Fix ALL errors in a file at once
- **WRITE ONCE** - Single edit per file with all fixes
- **VERIFY LAST** - Only compile/diagnostics after ALL fixes
- **DELETE DEAD CODE** - Don't keep unused code around
- **Version 6.2.0** - Do not change without approval
- **GIT WORKFLOW** - ALWAYS push to ALL repositories (github, pragmatismo)

719
README.md
View file

@ -1,85 +1,644 @@
# General Bots Workspace
**Version:** 6.1.0
## ⚠️ CRITICAL SECURITY WARNING
**NEVER CREATE FILES WITH SECRETS IN THE REPOSITORY ROOT**
Secret files MUST be placed in `/tmp/` only:
- ✅ `/tmp/vault-token-gb` - Vault root token
- ✅ `/tmp/vault-unseal-key-gb` - Vault unseal key
- ❌ `vault-unseal-keys` - FORBIDDEN (tracked by git)
- ❌ `start-and-unseal.sh` - FORBIDDEN (contains secrets)
**Files added to .gitignore:** `vault-unseal-keys`, `start-and-unseal.sh`, `vault-token-*`
**Why `/tmp/`?**
- Cleared on reboot (ephemeral)
- Not tracked by git
- Standard Unix security practice
- Prevents accidental commits
---
**Version:** 6.3.0
**Type:** Rust Workspace (Monorepo with Independent Subproject Repos)
---
## Structure
## Overview
This workspace contains multiple General Bots projects:
General Bots is a comprehensive automation platform built with Rust, providing a unified workspace for building AI-powered bots, web interfaces, desktop applications, and integration tools. The workspace follows a modular architecture with independent subprojects that can be developed and deployed separately while sharing common libraries and standards.
For comprehensive documentation, see **[docs.pragmatismo.com.br](https://docs.pragmatismo.com.br)** or the **[BotBook](./botbook)** for detailed guides, API references, and tutorials.
---
## 📁 Workspace Structure
| Crate | Purpose | Port | Tech Stack |
|-------|---------|------|------------|
| **botserver** | Main API server, business logic | 9000 | Axum, Diesel, Rhai BASIC |
| **botui** | Web UI server (dev) + proxy | 3000 | Axum, HTML/HTMX/CSS |
| **botapp** | Desktop app wrapper | - | Tauri 2 |
| **botlib** | Shared library | - | Core types, errors |
| **botbook** | Documentation | - | mdBook |
| **bottest** | Integration tests | - | tokio-test |
| **botdevice** | IoT/Device support | - | Rust |
| **botmodels** | Data models visualization | - | - |
| **botplugin** | Browser extension | - | JS |
### Key Paths
- **Binary:** `target/debug/botserver`
- **Run from:** `botserver/` directory
- **Env file:** `botserver/.env`
- **Stack:** `botserver-stack/`
- **UI Files:** `botui/ui/suite/`
- **Local Bot Data:** `/opt/gbo/data/` (place `.gbai` packages here)
### Local Bot Data Directory
Place local bot packages in `/opt/gbo/data/` for automatic loading and monitoring:
**Directory Structure:**
```
gb/
├── PROMPT.md ← Workspace-level development guide (READ THIS FIRST)
├── Cargo.toml ← Workspace configuration
├── README.md ← This file
├── botapp/ ← Desktop application (Tauri)
├── botserver/ ← Main server (API + business logic)
├── botlib/ ← Shared library (types, utilities)
├── botui/ ← Web UI (HTML/CSS/JS)
├── botbook/ ← Documentation
├── bottest/ ← Integration tests
├── botdevice/ ← Device integration
├── botmodels/ ← AI models
├── botplugin/ ← Plugin system
├── bottemplates/ ← Templates
└── target/ ← Build artifacts
/opt/gbo/data/
└── mybot.gbai/
├── mybot.gbdialog/
│ ├── start.bas
│ └── main.bas
└── mybot.gbot/
└── config.csv
```
**Features:**
- **Auto-loading:** Bots automatically mounted on server startup
- **Auto-compilation:** `.bas` files compiled to `.ast` on change
- **Auto-creation:** New bots automatically added to database
- **Hot-reload:** Changes trigger immediate recompilation
- **Monitored by:** LocalFileMonitor and ConfigWatcher services
**Usage:**
1. Create bot directory structure in `/opt/gbo/data/`
2. Add `.bas` files to `<bot_name>.gbai/<bot_name>.gbdialog/`
3. Server automatically detects and loads the bot
4. Optional: Add `config.csv` for bot configuration
---
## 🏗️ BotServer Component Architecture
### 🔧 Infrastructure Components (Auto-Managed)
BotServer automatically installs, configures, and manages all infrastructure components on first run. **DO NOT manually start these services** - BotServer handles everything.
**Automatic Service Lifecycle:**
1. **Start**: When botserver starts, it automatically launches all infrastructure components (PostgreSQL, Vault, MinIO, Valkey, Qdrant, etc.)
2. **Credentials**: BotServer retrieves all service credentials (passwords, tokens, API keys) from Vault
3. **Connection**: BotServer uses these credentials to establish secure connections to each service
4. **Query**: All database queries, cache operations, and storage requests are authenticated using Vault-managed credentials
**Credential Flow:**
```
botserver starts
Launch PostgreSQL, MinIO, Valkey, Qdrant
Connect to Vault
Retrieve service credentials (from database)
Authenticate with each service using retrieved credentials
Ready to handle requests
```
| Component | Purpose | Port | Binary Location | Credentials From |
|-----------|---------|------|-----------------|------------------|
| **Vault** | Secrets management | 8200 | `botserver-stack/bin/vault/vault` | Auto-unsealed |
| **PostgreSQL** | Primary database | 5432 | `botserver-stack/bin/tables/bin/postgres` | Vault → database |
| **MinIO** | Object storage (S3-compatible) | 9000/9001 | `botserver-stack/bin/drive/minio` | Vault → database |
| **Zitadel** | Identity/Authentication | 8300 | `botserver-stack/bin/directory/zitadel` | Vault → database |
| **Qdrant** | Vector database (embeddings) | 6333 | `botserver-stack/bin/vector_db/qdrant` | Vault → database |
| **Valkey** | Cache/Queue (Redis-compatible) | 6379 | `botserver-stack/bin/cache/valkey-server` | Vault → database |
| **Llama.cpp** | Local LLM server | 8081 | `botserver-stack/bin/llm/build/bin/llama-server` | Vault → database |
### 📦 Component Installation System
Components are defined in `botserver/3rdparty.toml` and managed by the `PackageManager` (`botserver/src/core/package_manager/`):
```toml
[components.cache]
name = "Valkey Cache (Redis-compatible)"
url = "https://github.com/valkey-io/valkey/archive/refs/tags/8.0.2.tar.gz"
filename = "valkey-8.0.2.tar.gz"
[components.llm]
name = "Llama.cpp Server"
url = "https://github.com/ggml-org/llama.cpp/releases/download/b7345/llama-b7345-bin-ubuntu-x64.zip"
filename = "llama-b7345-bin-ubuntu-x64.zip"
```
**Installation Flow:**
1. **Download:** Components downloaded to `botserver-installers/` (cached)
2. **Extract/Build:** Binaries placed in `botserver-stack/bin/<component>/`
3. **Configure:** Config files generated in `botserver-stack/conf/<component>/`
4. **Start:** Components started with proper TLS certificates
5. **Monitor:** Components monitored and auto-restarted if needed
**Bootstrap Process:**
- First run: Full bootstrap (downloads, installs, configures all components)
- Subsequent runs: Only starts existing components (uses cached binaries)
- Config stored in: `botserver-stack/conf/system/bootstrap.json`
### 🚀 PROPER STARTUP PROCEDURES
**❌ FORBIDDEN:**
- NEVER manually start infrastructure components (Vault, PostgreSQL, MinIO, etc.)
- NEVER run `cargo run` or `cargo build` for botserver directly without ./restart.sh
- NEVER modify botserver-stack/ files manually (use botserver API)
**✅ REQUIRED:**
**Option 1: Development (Recommended)**
```bash
./restart.sh
```
This script:
1. Kills existing processes cleanly
2. Builds botserver and botui sequentially (no race conditions)
3. Starts botserver in background with logging to `botserver.log`
4. Starts botui in background with logging to `botui.log`
5. Shows process IDs and access URLs
**Option 2: Production/Release**
```bash
# Build release binary first
cargo build --release -p botserver
# Start with release binary
RUST_LOG=info ./target/release/botserver --noconsole 2>&1 | tee botserver.log &
```
**Option 3: Using Exec (Systemd/Supervisord)**
```bash
# In systemd service or similar
ExecStart=/home/rodriguez/src/gb/target/release/botserver --noconsole
```
### 🔒 Component Communication
All components communicate through internal networks with mTLS:
- **Vault**: mTLS for secrets access
- **PostgreSQL**: TLS encrypted connections
- **MinIO**: TLS with client certificates
- **Zitadel**: mTLS for user authentication
Certificates auto-generated in: `botserver-stack/conf/system/certificates/`
### 📊 Component Status
Check component status anytime:
```bash
# Check if all components are running
ps aux | grep -E "vault|postgres|minio|zitadel|qdrant|valkey" | grep -v grep
# View component logs
tail -f botserver-stack/logs/vault/vault.log
tail -f botserver-stack/logs/tables/postgres.log
tail -f botserver-stack/logs/drive/minio.log
# Test component connectivity
cd botserver-stack/bin/vault && ./vault status
cd botserver-stack/bin/cache && ./valkey-cli ping
```
---
## CRITICAL: PROMPT.md Files
## 🏗️ Component Dependency Graph
**Each project has a PROMPT.md that defines its development rules.**
```
┌─────────────────────────────────────────────────────────────────┐
│ Client Layer │
├─────────────────────────────────────────────────────────────────┤
│ botui (Web UI) │ botapp (Desktop) │ botplugin (Ext) │
│ HTMX + Axum │ Tauri 2 Wrapper │ Browser Extension │
└─────────┬───────────────────┬──────────────────┬─────────────────┘
│ │ │
└───────────────────┼──────────────────┘
┌─────────▼─────────┐
│ botlib │
│ (Shared Types) │
└─────────┬─────────┘
┌───────────────────┼───────────────────┐
│ │ │
┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
│ botserver │ │ bottest │ │ botdevice │
│ API Core │ │ Tests │ │ IoT/Device │
└───────────┘ └───────────┘ └───────────┘
```
The diagnostics tool reads and respects these PROMPT.md files.
### Dependency Rules
### Hierarchy
| Crate | Depends On | Why |
|-------|-----------|-----|
| **botserver** | botlib | Shared types, error handling, models |
| **botui** | botlib | Common data structures, API client |
| **botapp** | botlib | Shared types, desktop-specific utilities |
| **bottest** | botserver, botlib | Integration testing with real components |
| **botdevice** | botlib | Device types, communication protocols |
| **botplugin** | - | Standalone browser extension (JS) |
1. **`PROMPT.md`** (this directory) - Workspace-wide rules
2. **`botapp/PROMPT.md`** - Desktop app specifics
3. **`botserver/PROMPT.md`** - Server specifics
4. **`botlib/PROMPT.md`** - Library specifics
5. **`botui/PROMPT.md`** - UI specifics
6. **`botbook/PROMPT.md`** - Documentation specifics
7. **`bottest/PROMPT.md`** - Test specifics
**Key Principle:** `botlib` contains ONLY shared types and utilities. No business logic. All business logic lives in botserver or specialized crates.
**ALWAYS read the relevant PROMPT.md before working on a project.**
## 📦 Module Responsibility Matrix
---
### botserver/src/ Module Structure
## Main Directive
| Module | Responsibility | Key Types | Dependencies |
|--------|---------------|-----------|--------------|
| **core/bot/** | WebSocket handling, bot orchestration | BotOrchestrator, UserMessage | basic, shared |
| **core/session/** | Session management, conversation history | SessionManager, UserSession | shared, database |
| **basic/** | Rhai BASIC scripting engine | ScriptService, Engine | rhai, keywords |
| **basic/keywords/** | BASIC keyword implementations (TALK, HEAR, etc.) | Keyword functions | basic, state |
| **llm/** | Multi-vendor LLM API integration | LLMClient, ModelConfig | reqwest, shared |
| **drive/** | S3 file storage and monitoring | DriveMonitor, compile_tool | s3, basic |
| **security/** | Security guards (command, SQL, error) | SafeCommand, ErrorSanitizer | state |
| **shared/** | Database models, schema definitions | Bot, Session, Message | diesel |
| **tasks/** | AutoTask execution system | TaskRunner, TaskScheduler | core/basic |
| **auto_task/** | LLM-powered app generation | AppGenerator, template engine | llm, tasks |
| **learn/** | Knowledge base management | KBManager, vector storage | database, drive |
| **attendance/** | LLM-assisted customer service | AttendantManager, queue | core/bot |
**LOOP AND COMPACT UNTIL 0 WARNINGS - MAXIMUM YOLO**
### Data Flow Patterns
- 0 warnings
- 0 errors
- Trust project diagnostics
- Respect all rules
- No `#[allow()]` in source code
- Real code fixes only
```
1. User Request Flow:
Client → WebSocket → botserver/src/core/bot/mod.rs
BotOrchestrator::stream_response()
┌───────────┴───────────┐
│ │
LLM API Call Script Execution
(llm/mod.rs) (basic/mod.rs)
│ │
└───────────┬───────────┘
Response → WebSocket → Client
2. File Sync Flow:
S3 Drive → drive_monitor/src/drive_monitor/mod.rs
Download .bas files
compile_file() → Generate .ast
Store in ./work/{bot_name}.gbai/
3. Script Execution Flow:
.bas file → ScriptService::compile()
preprocess_basic_script()
engine.compile() → AST
ScriptService::run() → Execute
TALK commands → WebSocket messages
```
### Common Architectural Patterns
| Pattern | Where Used | Purpose |
|---------|-----------|---------|
| **State via Arc<AppState>** | All handlers | Shared async state (DB, cache, config) |
| **Extension(state) extractor** | Axum handlers | Inject Arc<AppState> into route handlers |
| **tokio::spawn_blocking** | CPU-intensive tasks | Offload blocking work from async runtime |
| **WebSocket with split()** | Real-time comms | Separate sender/receiver for WS streams |
| **ErrorSanitizer for responses** | All HTTP errors | Prevent leaking sensitive info in errors |
| **SafeCommand for execution** | Command running | Whitelist-based command validation |
| **Rhai for scripting** | BASIC interpreter | Embeddable scripting language |
| **Diesel ORM** | Database access | Type-safe SQL queries |
| **Redis for cache** | Session data | Fast key-value storage |
| **S3 for storage** | File system | Scalable object storage |
---
## Quick Start
### 🚀 Simple Startup (ALWAYS USE restart.sh)
```bash
./restart.sh
```
**⚠️ CRITICAL: ALWAYS use restart.sh - NEVER start servers individually!**
The script handles BOTH servers properly:
1. Stop existing processes cleanly
2. Build botserver and botui sequentially (no race conditions)
3. Start botserver in background → **automatically starts all infrastructure services (PostgreSQL, Vault, MinIO, Valkey, Qdrant)**
4. BotServer retrieves credentials from Vault and authenticates with all services
5. Start botui in background → proxy to botserver
6. Show process IDs and monitoring commands
**Infrastructure services are fully automated - no manual configuration required!**
**Monitor startup:**
```bash
tail -f botserver.log botui.log
```
**Access:**
- Web UI: http://localhost:3000
- API: http://localhost:9000
### 📊 Monitor & Debug
```bash
tail -f botserver.log botui.log
```
**Quick status check:**
```bash
ps aux | grep -E "botserver|botui" | grep -v grep
```
**Quick error scan:**
```bash
grep -E " E |W |CLIENT:" botserver.log | tail -20
```
### 🔧 Manual Startup (If needed)
**⚠️ WARNING: Only use if restart.sh fails. Always prefer restart.sh!**
```bash
cd botserver && cargo run -- --noconsole > ../botserver.log 2>&1 &
cd botui && BOTSERVER_URL="http://localhost:9000" cargo run > ../botui.log 2>&1 &
```
### 🛑 Stop Servers
```bash
pkill -f botserver; pkill -f botui
```
### ⚠️ Common Issues
**Vault init error?** Delete stale state:
```bash
rm -rf botserver-stack/data/vault botserver-stack/conf/vault/init.json && ./restart.sh
```
**Port in use?** Find and kill:
```bash
lsof -ti:9000 | xargs kill -9
lsof -ti:3000 | xargs kill -9
```
**⚠️ IMPORTANT: Stack Services Management**
All infrastructure services (PostgreSQL, Vault, Redis, Qdrant, MinIO, etc.) are **automatically started by botserver** and managed through `botserver-stack/` directory, NOT global system installations. The system uses:
- **Local binaries:** `botserver-stack/bin/` (PostgreSQL, Vault, Redis, etc.)
- **Configurations:** `botserver-stack/conf/`
- **Data storage:** `botserver-stack/data/`
- **Service logs:** `botserver-stack/logs/` (check here for troubleshooting)
- **Credentials:** Stored in Vault, retrieved by botserver at startup
**Do NOT install or reference global PostgreSQL, Redis, or other services.** When botserver starts, it automatically:
1. Launches all required stack services
2. Connects to Vault
3. Retrieves credentials from the `bot_configuration` database table
4. Authenticates with each service using retrieved credentials
5. Begins handling requests with authenticated connections
If you encounter service errors, check the individual service logs in `./botserver-stack/logs/[service]/` directories.
### UI File Deployment - Production Options
**Option 1: Embedded UI (Recommended for Production)**
The `embed-ui` feature compiles UI files directly into the botui binary, eliminating the need for separate file deployment:
```bash
# Build with embedded UI files
cargo build --release -p botui --features embed-ui
# The binary now contains all UI files - no additional deployment needed!
# The botui binary is self-contained and production-ready
```
**Benefits of embed-ui:**
- ✅ Single binary deployment (no separate UI files)
- ✅ Faster startup (no filesystem access)
- ✅ Smaller attack surface
- ✅ Simpler deployment process
**Option 2: Filesystem Deployment (Development Only)**
For development, UI files are served from the filesystem:
```bash
# UI files must exist at botui/ui/suite/
# This is automatically available in development builds
```
**Option 3: Manual File Deployment (Legacy)**
If you need to deploy UI files separately (not recommended):
```bash
# Deploy UI files to production location
./botserver/deploy/deploy-ui.sh /opt/gbo
# Verify deployment
ls -la /opt/gbo/bin/ui/suite/index.html
```
See `botserver/deploy/README.md` for deployment scripts.
### Start Both Servers (Automated)
```bash
# Use restart script (RECOMMENDED)
./restart.sh
```
### Start Both Servers (Manual)
```bash
# Terminal 1: botserver
cd botserver && cargo run -- --noconsole
# Terminal 2: botui
cd botui && BOTSERVER_URL="http://localhost:9000" cargo run
```
### Build Commands
```bash
# Check single crate
cargo check -p botserver
# Build workspace
cargo build
cargo test
# Run tests
cargo test -p bottest
```
---
## Development Workflow
## 🤖 AI Agent Guidelines
1. Read `PROMPT.md` (workspace-level rules)
2. Read `<project>/PROMPT.md` (project-specific rules)
3. Use diagnostics tool to check warnings
4. Fix all warnings with full file rewrites
5. Verify with diagnostics after each file
6. Never suppress warnings with `#[allow()]`
> **For LLM instructions, coding rules, security directives, testing workflows, and error handling patterns, see [AGENTS.md](./AGENTS.md).**
---
## 📖 Glossary
| Term | Definition | Usage |
|------|-----------|-------|
| **Bot** | AI agent with configuration, scripts, and knowledge bases | Primary entity in system |
| **Session** | Single conversation instance between user and bot | Stored in `sessions` table |
| **Dialog** | Collection of BASIC scripts (.bas files) for bot logic | Stored in `{bot_name}.gbdialog/` |
| **Tool** | Reusable function callable by LLM | Defined in .bas files, compiled to .ast |
| **Knowledge Base (KB)** | Vector database of documents for semantic search | Managed in `learn/` module |
| **Scheduler** | Time-triggered task execution | Cron-like scheduling in BASIC scripts |
| **Drive** | S3-compatible storage for files | Abstracted in `drive/` module |
| **Rhai** | Embedded scripting language for BASIC dialect | Rhai engine in `basic/` module |
| **WebSocket Adapter** | Component that sends messages to connected clients | `web_adapter` in state |
| **AutoTask** | LLM-generated task automation system | In `auto_task/` and `tasks/` modules |
| **Orchestrator** | Coordinates LLM, tools, KBs, and user input | `BotOrchestrator` in `core/bot/` |
---
## 🖥️ UI Architecture (botui + botserver)
### Two Servers During Development
| Server | Port | Purpose |
|--------|------|---------|
| **botui** | 3000 | Serves UI files + proxies API to botserver |
| **botserver** | 9000 | Backend API + embedded UI fallback |
### How It Works
```
Browser → localhost:3000 → botui (serves HTML/CSS/JS)
→ /api/* proxied to botserver:9000
→ /suite/* served from botui/ui/suite/
```
### Adding New Suite Apps
1. Create folder: `botui/ui/suite/<appname>/`
2. Add to `SUITE_DIRS` in `botui/src/ui_server/mod.rs`
3. Rebuild botui: `cargo build -p botui`
4. Add menu entry in `botui/ui/suite/index.html`
### Hot Reload
- **UI files (HTML/CSS/JS)**: Edit & refresh browser (no restart)
- **botui Rust code**: Rebuild + restart botui
- **botserver Rust code**: Rebuild + restart botserver
### Production (Single Binary)
When `botui/ui/suite/` folder not found, botserver uses **embedded UI** compiled into binary via `rust-embed`.
---
## 🎨 Frontend Standards
### HTMX-First Approach
- Use HTMX to minimize JavaScript
- Server returns HTML fragments, not JSON
- Use `hx-get`, `hx-post`, `hx-target`, `hx-swap`
- WebSocket via htmx-ws extension
### Local Assets Only - NO CDN
```html
<!-- ✅ CORRECT -->
<script src="js/vendor/htmx.min.js"></script>
<!-- ❌ WRONG -->
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
```
### Vendor Libraries Location
```
ui/suite/js/vendor/
├── htmx.min.js
├── htmx-ws.js
├── marked.min.js
└── gsap.min.js
```
---
## 📋 Project-Specific Guidelines
Each crate has its own README.md with specific guidelines:
| Crate | README.md Location | Focus |
|-------|-------------------|-------|
| botserver | `botserver/README.md` | API, security, Rhai BASIC |
| botui | `botui/README.md` | UI, HTMX, CSS design system |
| botapp | `botapp/README.md` | Tauri, desktop features |
| botlib | `botlib/README.md` | Shared types, errors |
| botbook | `botbook/README.md` | Documentation, mdBook |
| bottest | `bottest/README.md` | Test infrastructure |
### Special Prompts
| File | Purpose |
|------|---------|
| `botserver/src/tasks/README.md` | AutoTask LLM executor |
| `botserver/src/auto_task/APP_GENERATOR_PROMPT.md` | App generation |
---
## 📚 Documentation
For complete documentation, guides, and API references:
- **[docs.pragmatismo.com.br](https://docs.pragmatismo.com.br)** - Full online documentation
- **[BotBook](./botbook)** - Local comprehensive guide with tutorials and examples
- **[General Bots Repository](https://github.com/GeneralBots/BotServer)** - Main project repository
---
## 🔧 Immediate Technical Debt
### Critical Issues to Address
1. **Error Handling Debt**: 955 instances of `unwrap()`/`expect()` in production code
2. **Performance Debt**: 12,973 excessive `clone()`/`to_string()` calls
3. **File Size Debt**: 7 files exceed 450 lines (largest: 3220 lines)
4. **Test Coverage**: Missing integration tests for critical paths
5. **Documentation**: Missing inline documentation for complex algorithms
### Weekly Maintenance Tasks
```bash
# Check for duplicate dependencies
cargo tree --duplicates
# Remove unused dependencies
cargo machete
# Check binary size
cargo build --release && ls -lh target/release/botserver
# Performance profiling
cargo bench
# Security audit
cargo audit
```
---
@ -87,43 +646,57 @@ cargo test
**Note:** Each subproject has its own git repository. This root repository only tracks workspace-level files:
- `PROMPT.md` - Development guide
- `Cargo.toml` - Workspace configuration
- `README.md` - This file
- `.gitignore` - Ignore patterns
- `ADDITIONAL-SUGGESTIONS.md` - Enhancement ideas
- `TODO-*.md` - Task tracking files
Subprojects (botapp, botserver, etc.) are **not** git submodules - they are independent repositories.
Subprojects (botapp, botserver, botui, etc.) are **independent repositories referenced as git submodules**.
### ⚠️ CRITICAL: Submodule Push Workflow
When making changes to any submodule (botserver, botui, botlib, etc.):
1. **Commit and push changes within the submodule directory:**
```bash
cd botserver
git add .
git commit -m "Your changes"
git push pragmatismo main
git push github main
```
2. **Update the global gb repository submodule reference:**
```bash
cd .. # Back to gb root
git add botserver
git commit -m "Update botserver submodule to latest commit"
git push pragmatismo main
git push github main
```
**Failure to push the global gb repository will cause submodule changes to not trigger CI/CD pipelines.**
Both repositories must be pushed for changes to take effect in production.
---
## Rules Summary
## Development Workflow
```
✅ FULL FILE REWRITES ONLY
✅ BATCH ALL FIXES BEFORE WRITING
✅ VERIFY WITH DIAGNOSTICS AFTER EACH FILE
✅ TRUST PROJECT DIAGNOSTICS
✅ RESPECT ALL RULES
❌ NEVER use #[allow()] in source code
❌ NEVER use partial edits
❌ NEVER run cargo check/clippy manually
❌ NEVER leave unused code
❌ NEVER use .unwrap()/.expect()
❌ NEVER use panic!/todo!/unimplemented!()
❌ NEVER add comments
```
1. Read this README.md (workspace structure)
2. Read **[AGENTS.md](./AGENTS.md)** (coding rules & workflows)
3. **BEFORE creating any .md file, search botbook/ for existing documentation**
4. Read `<project>/README.md` (project-specific rules)
5. Use diagnostics tool to check warnings
6. Fix all warnings with full file rewrites
7. Verify with diagnostics after each file
8. Never suppress warnings with `#[allow()]`
---
## Links
- Main Server: http://localhost:8081
- Desktop App: Uses Tauri to wrap botui
- Documentation: See botbook/
---
## License
See individual project repositories for license information.
See individual project repositories for license information.

2
botapp

@ -1 +1 @@
Subproject commit 1a1e17fa1012e4db10a0f716c9b63a03b4863c9f
Subproject commit 0b556948f970832e8606f886853793e2bc8dc35c

@ -1 +1 @@
Subproject commit fc31150198d302f5407ad8612488899ce9a182f6
Subproject commit 7b2b7ab3c53c65a68930a8cb2e7ca359d8e22bcf

@ -1 +1 @@
Subproject commit 97778e06dd804be55ff761c7fe2788af0ef50626
Subproject commit 35411f4f9e64e54b1039360ab654d537cd2958c9

2
botlib

@ -1 +1 @@
Subproject commit bfaa68dc35e96ced2915d43ffe6fca8267a9a598
Subproject commit e926818f35879c1db4086efaa9634caac45f5743

@ -1 +1 @@
Subproject commit 462a6dfa51b12f22e87712e613a559f66f9013cb
Subproject commit e088a8e69eb8fe064bf1510a720d42abe159ab00

@ -1 +1 @@
Subproject commit 17a3caebabddbe843c2b7fd93f624b0ccd9c44fb
Subproject commit 1727e48307fdb7b54c726af8cd6b12669764e908

@ -1 +1 @@
Subproject commit b436762026c8a93291a261a9e6d33e84f25e06f7
Subproject commit 73002b36cc3def17546085574cbafe0f42c7b04f

@ -1 +1 @@
Subproject commit 17a614974ce2e0bc6dd32266d8e4f78536979ced
Subproject commit 3110dd587290047f283300d674ad325f4f9b3046

@ -1 +1 @@
Subproject commit 51458e391df2a47f5ccbcf10ec45edeeb9cf5902
Subproject commit 346120cb0b916f72abd2fdad577ae1c606aba1a2

2
botui

@ -1 +1 @@
Subproject commit 5657e330067e4a311a717c1cfd5d35a2c0419126
Subproject commit ff6dfcf126dc20ff8a46d3ac44ef04045cfaf268

1113
prompts/container.md Normal file

File diff suppressed because it is too large Load diff

146
prompts/crmex.md Normal file
View file

@ -0,0 +1,146 @@
# Email Campaigns — Feature Plan
## Existing Foundation (botserver/src/marketing/)
- `campaigns.rs` — CrmCampaign model, CRUD handlers
- `metrics.rs` — CampaignMetrics, ChannelBreakdown, open/click/conversion rates
- `lists.rs` — recipient lists
- `templates.rs` — content templates
- `triggers.rs` — event-based sending
- `email/tracking.rs` — open/click tracking pixels
---
## Features to Build
### 1. Insights Dashboard
**What:** Time series views of delivery + engagement metrics per campaign.
**Data points per time bucket (hourly/daily):**
- Sent, delivered, bounced, failed
- Opens (unique + total), clicks, replies, unsubscribes
- Delivery rate, open rate, click-to-open rate (CTOR)
**Filters/pivots:**
- By mailbox provider (Gmail, Outlook, Yahoo, etc. — parsed from MX/SMTP response)
- By sender identity (from address / domain)
- By campaign or list
- Message search → show exact SMTP response from provider
**Implementation:**
- Add `email_delivery_events` table: `(id, campaign_id, recipient_id, event_type, provider, smtp_response, ts)`
- API: `GET /api/campaigns/:id/insights?from=&to=&group_by=provider|identity|day`
- UI: HTMX + chart.js time series (local vendor)
---
### 2. Advisor Recommendations
**What:** Analyze sending config + results and surface actionable fixes.
**Checks to run:**
| Check | Signal | Recommendation |
|---|---|---|
| SPF/DKIM/DMARC | DNS lookup | "Add missing record" |
| Bounce rate > 5% | delivery_events | "Clean list — remove hard bounces" |
| Open rate < 15% | metrics | "Improve subject line / send time" |
| Spam complaints > 0.1% | FBL data | "Remove complainers immediately" |
| Sending from new IP | warmup_schedule | "Follow warmup plan" |
| List age > 6 months | list.last_sent | "Re-engagement campaign before bulk send" |
**Implementation:**
- `marketing/advisor.rs``AdvisorEngine::analyze(campaign_id) -> Vec<Recommendation>`
- API: `GET /api/campaigns/:id/advisor`
- Runs automatically after each campaign completes
---
### 3. IP Warmup (like OneSignal / Mailchimp)
**What:** Gradually increase daily send volume over 46 weeks to build sender reputation.
**Warmup schedule (standard):**
| Day | Max emails/day |
|---|---|
| 12 | 50 |
| 34 | 100 |
| 57 | 500 |
| 810 | 1,000 |
| 1114 | 5,000 |
| 1521 | 10,000 |
| 2228 | 50,000 |
| 29+ | unlimited |
**Rules:**
- Only send to most engaged subscribers first (opened in last 90 days)
- Stop warmup if bounce rate > 3% or complaint rate > 0.1%
- Resume next day at same volume if paused
**Implementation:**
- `marketing/warmup.rs``WarmupSchedule`, `WarmupEngine::get_daily_limit(ip, day) -> u32`
- `warmup_schedules` table: `(id, ip, started_at, current_day, status, paused_reason)`
- Scheduler checks warmup limit before each send batch
- API: `GET /api/warmup/status`, `POST /api/warmup/start`
---
### 4. Optimized Shared Delivery
**What:** Auto-select best sending IP based on real-time reputation signals.
**Logic:**
- Track per-IP: bounce rate, complaint rate, delivery rate (last 24h)
- Score each IP: `score = delivery_rate - (bounce_rate * 10) - (complaint_rate * 100)`
- Route each send to highest-scored IP for that destination provider
- Rotate IPs to spread load and preserve reputation
**Implementation:**
- `marketing/ip_router.rs``IpRouter::select(destination_domain) -> IpAddr`
- `ip_reputation` table: `(ip, provider, bounces, complaints, delivered, window_start)`
- Plugs into Stalwart send path via botserver API
---
### 5. Modern Email Marketing Features
| Feature | Description |
|---|---|
| **Send time optimization** | ML-based per-contact best send time (based on past open history) |
| **A/B testing** | Split subject/content, auto-pick winner after N hours |
| **Suppression list** | Global unsubscribe/bounce/complaint list, auto-applied to all sends |
| **Re-engagement flows** | Auto-trigger "we miss you" to contacts inactive > 90 days |
| **Transactional + marketing separation** | Separate IPs/domains for transactional vs bulk |
| **One-click unsubscribe** | RFC 8058 `List-Unsubscribe-Post` header on all bulk sends |
| **Preview & spam score** | Pre-send SpamAssassin score check |
| **Link tracking** | Redirect all links through tracker, record clicks per contact |
| **Webhook events** | Push delivery events to external URLs (Stalwart webhook → botserver) |
---
## DB Tables to Add
```sql
email_delivery_events (id, campaign_id, recipient_id, event_type, provider, smtp_code, smtp_response, ts)
warmup_schedules (id, ip, started_at, current_day, daily_limit, status, paused_reason)
ip_reputation (id, ip, provider, delivered, bounced, complained, window_start)
advisor_recommendations (id, campaign_id, check_name, severity, message, created_at, dismissed)
ab_tests (id, campaign_id, variant_a, variant_b, split_pct, winner, decided_at)
suppression_list (id, org_id, email, reason, added_at)
```
---
## Files to Create
```
botserver/src/marketing/
├── warmup.rs — IP warmup engine + schedule
├── advisor.rs — recommendation engine
├── ip_router.rs — optimized IP selection
├── ab_test.rs — A/B test logic
├── suppression.rs — global suppression list
└── send_time.rs — send time optimization
```
---
## Existing Code to Extend
- `marketing/metrics.rs` → add time-series queries + provider breakdown
- `marketing/campaigns.rs` → add warmup_enabled, ab_test_id fields
- `email/tracking.rs` → already has open/click tracking, extend with provider parsing
- `core/shared/schema/` → add new tables above

59
prompts/folha.md Normal file
View file

@ -0,0 +1,59 @@
# SEPLAGSE - Detecção de Desvios na Folha
## Objetivo
- Bot seplagse deve usar start.bas para inserir dados via init_folha.bas
- detecta.bas deve detectar anomalias nos dados inseridos
## ✅ Status Atual
### Correção REM em mod.rs (FEITA)
**Arquivo:** `botserver/src/basic/mod.rs` linha ~588-594
Filtro adicionado para `REM ` e `REM\t` no `compile_tool_script`:
```rust
!(trimmed.starts_with("PARAM ") ||
trimmed.starts_with("PARAM\t") ||
trimmed.starts_with("DESCRIPTION ") ||
trimmed.starts_with("DESCRIPTION\t") ||
trimmed.starts_with("REM ") || // <-- ADICIONADO
trimmed.starts_with("REM\t") || // <-- ADICIONADO
trimmed.starts_with('\'') ||
trimmed.starts_with('#') ||
trimmed.is_empty())
```
### Arquivos Envolvidos (VERIFICADOS)
- `/opt/gbo/data/seplagse.gbai/seplagse.gbdialog/start.bas` ✅ OK
- Contém botões de sugestão: detecta e init_folha
- `/opt/gbo/data/seplagse.gbai/seplagse.gbdialog/init_folha.bas` ✅ OK
- 4 INSERT statements para dados de exemplo
- `/opt/gbo/data/seplagse.gbai/seplagse.gbdialog/detecta.bas` ✅ OK
- Usa DETECT keyword
- `/opt/gbo/data/seplagse.gbai/seplagse.gbdialog/tables.bas` ✅ OK
- TABLE folha_salarios definida
### Botserver (RODANDO)
- ✅ Botserver compilado com sucesso
- ✅ Botserver rodando em http://localhost:8080
- ✅ Health check OK
## Próximos Passos (Pendentes)
1. **Testar via navegador** - Necessário instalar Playwright browsers
- Navegar para http://localhost:3000/seplagse
- Clicar em "⚙️ Inicializar Dados de Teste"
- Verificar se INSERT funciona
- Clicar em "🔍 Detectar Desvios na Folha"
- Verificar se DETECT funciona
2. **Verificar se há warnings relevantes**
- Alguns warnings de código podem precisar ser corrigidos
## Cache
- AST limpo: `rm ./botserver-stack/data/system/work/seplagse.gbai/seplagse.gbdialog/*.ast`
- Reiniciado: `./restart.sh`
- Botserver: ✅ Rodando
## Arquivos de Trabalho
- Work directory: `./botserver-stack/data/system/work/seplagse.gbai/seplagse.gbdialog/`
- Todos os arquivos BASIC estão presentes e parecem válidos

272
prompts/integratedsuite.md Normal file
View file

@ -0,0 +1,272 @@
# Integrated Suite — Conversational Interface Plan
> **Pattern:** Every suite app exposes its own `PROMPT.md` + internal tools.
> The shared chat bar activates app-specific context when the user is inside that app.
> WhatsApp campaigns is the first full example.
---
## Architecture
```
User (WhatsApp / Suite chat bar)
BotOrchestrator (core/bot/mod.rs)
detect active app context
load app PROMPT.md + app InternalTools
LLM with tools → tool_executor.rs
app data / actions
```
### Key existing pieces
| File | Role |
|---|---|
| `core/bot/mod.rs` | `get_session_tools()` + `ToolExecutor::execute_tool_call()` |
| `tasks/PROMPT.md` | Pattern for app-level LLM prompt |
| `marketing/whatsapp.rs` | WhatsApp campaign send/metrics |
| `marketing/campaigns.rs` | Campaign CRUD |
| `marketing/lists.rs` | Recipient lists |
| `botui/ui/suite/campaigns/` | Campaigns UI |
---
## Standard: Every Suite App
### 1. `PROMPT.md` per app folder
Location: `botserver/src/<app>/PROMPT.md`
```markdown
# <App> — Internal Tools Guide
You are the <App> assistant. When the user is in <App>, you have access to:
- tool: list_<entities>
- tool: create_<entity>
- tool: search_<entity>
- tool: <app_specific_action>
Rules:
- Always confirm destructive actions before executing
- Show results as structured summaries, not raw JSON
- If user uploads a file, parse it and confirm before acting
```
### 2. `tools.rs` per app
Location: `botserver/src/<app>/tools.rs`
Registers `Vec<Tool>` (LLM function-calling schema) + handler mapping.
Loaded by `get_session_tools()` when session's active app = this app.
### 3. App context detection
`core/bot/mod.rs` reads `session.active_app` (set by UI via `POST /api/session/context`).
Loads `<app>/PROMPT.md` as system prompt prefix + `<app>/tools.rs` tools.
---
## WhatsApp Campaigns — Full Conversational Flow
### Meta Rules (enforced in tools)
- Only approved Message Templates for marketing (non-session-initiated)
- 24h session window for free-form after user replies
- Media: image/video/document via Media Upload API before send
- Opt-out: always honor STOP, add to suppression list immediately
- Rate: respect per-phone-number rate limits (1000 msg/s business tier)
- Template category: MARKETING requires explicit opt-in from recipient
### Conversation Flow (WhatsApp → campaign creation)
```
User sends to bot number:
"I want to send a campaign"
Bot: "Great! Send me:
1. Your contact list (.xlsx or .csv)
2. The message text
3. An image (optional)
4. When to send (or 'now')"
User uploads contacts.xlsx
[tool: parse_contact_file]
→ extract phone numbers, names
→ validate E.164 format
→ show preview: "Found 342 contacts. First 3: +55..."
User sends message text
[tool: check_template_compliance]
→ check if free-form or needs approved template
→ if template needed: list available approved templates
→ suggest closest match
User sends image (optional)
[tool: upload_media]
→ upload to Meta Media API
→ return media_id
Bot: "Ready to send to 342 contacts at 14:00 today.
Preview: [image] Hello {name}, ...
Estimated cost: $X
Confirm? (yes/no)"
User: "yes"
[tool: create_and_schedule_campaign]
→ create campaign record
→ apply warmup limit if IP warming
→ schedule via TaskScheduler
```
### WhatsApp Campaign Tools (`marketing/whatsapp_tools.rs`)
```rust
// Tool definitions for LLM function calling
pub fn whatsapp_campaign_tools() -> Vec<Tool> {
vec![
Tool::new("parse_contact_file", "Parse uploaded xlsx/csv into contact list"),
Tool::new("list_templates", "List approved WhatsApp message templates"),
Tool::new("check_template_compliance", "Check if message needs approved template"),
Tool::new("upload_media", "Upload image/video to Meta Media API"),
Tool::new("preview_campaign", "Show campaign preview with cost estimate"),
Tool::new("create_and_schedule_campaign", "Create campaign and schedule send"),
Tool::new("get_campaign_status", "Get delivery/read metrics for a campaign"),
Tool::new("pause_campaign", "Pause an in-progress campaign"),
Tool::new("list_campaigns", "List recent campaigns with metrics"),
Tool::new("add_to_suppression", "Add number to opt-out list"),
]
}
```
### WhatsApp PROMPT.md (`marketing/WHATSAPP_PROMPT.md`)
```markdown
# WhatsApp Campaign Assistant
You help users create and manage WhatsApp marketing campaigns.
## Meta Platform Rules (MANDATORY)
- Marketing messages MUST use pre-approved templates outside 24h session window
- Always check opt-in status before adding to campaign
- Honor STOP/unsubscribe immediately via add_to_suppression tool
- Never send more than warmup daily limit if IP is warming up
- Image must be uploaded via upload_media before referencing in campaign
## Conversation Style
- Guide step by step: contacts → message → media → schedule → confirm
- Show cost estimate before confirming
- After send: proactively share open/read rates when available
## File Handling
- .xlsx/.csv → use parse_contact_file tool
- Images → use upload_media tool
- Always confirm parsed data before proceeding
```
---
## Integrated Suite Chat Bar — Standard
### How it works
1. User opens any suite app (CRM, Campaigns, Drive, etc.)
2. Chat bar at bottom activates with app context
3. `POST /api/session/context { app: "campaigns" }` sets `session.active_app`
4. BotOrchestrator loads `campaigns/PROMPT.md` + `campaigns/tools.rs`
5. User can ask natural language questions or trigger actions
### Examples per app
| App | Example query | Tool activated |
|---|---|---|
| **Campaigns** | "How did last week's campaign perform?" | `get_campaign_metrics` |
| **CRM** | "Show deals closing this month" | `list_deals` with filter |
| **Drive** | "Find the Q1 report" | `search_files` |
| **Tasks** | "Create a task to follow up with Acme" | `create_task` |
| **People** | "Who hasn't been contacted in 30 days?" | `list_contacts` with filter |
| **Mail** | "Summarize unread emails from clients" | `list_emails` + LLM summary |
| **Sheet** | "What's the total revenue in column D?" | `query_sheet` |
| **Learn** | "What does our refund policy say?" | `search_kb` |
---
## Implementation Plan
### Phase 1 — Infrastructure (1 sprint)
- [ ] `core/bot/mod.rs` — read `session.active_app`, load app PROMPT + tools
- [ ] `core/tool_context.rs` — app tool registry: `register_app_tools(app_name) -> Vec<Tool>`
- [ ] `POST /api/session/context` — set active app from UI
- [ ] Suite chat bar UI component (`botui/ui/suite/partials/chatbar.html`)
### Phase 2 — WhatsApp Campaigns (1 sprint)
- [ ] `marketing/whatsapp_tools.rs` — 10 tools above
- [ ] `marketing/WHATSAPP_PROMPT.md`
- [ ] `marketing/file_parser.rs` — xlsx/csv → contact list
- [ ] Meta warmup enforcement in send path
- [ ] Conversational campaign creation flow (state machine in session)
### Phase 3 — App-by-app rollout (1 app/sprint)
Priority order based on value:
1. CRM (deals, contacts, pipeline queries)
2. Campaigns (email + WhatsApp)
3. Tasks (create, assign, status)
4. Drive (search, summarize docs)
5. Mail (summarize, draft reply)
6. People (segment, find contacts)
7. Sheet (query, calculate)
8. Learn (KB search)
### Phase 4 — Cross-app intelligence
- [ ] Global search across all apps via single query
- [ ] "What happened today?" — aggregates activity across CRM + Mail + Tasks
- [ ] Proactive suggestions: "You have 3 deals closing this week and no follow-up tasks"
---
## File Structure to Create
```
botserver/src/
├── marketing/
│ ├── whatsapp_tools.rs ← NEW: LLM tool definitions + handlers
│ ├── WHATSAPP_PROMPT.md ← NEW: WhatsApp assistant system prompt
│ ├── file_parser.rs ← NEW: xlsx/csv → contacts
│ └── warmup.rs ← NEW: (from campaigns.md plan)
├── core/
│ ├── tool_registry.rs ← NEW: app → tools mapping
│ └── bot/
│ └── app_context.rs ← NEW: load app prompt + tools per session
├── crm/
│ ├── tools.rs ← NEW
│ └── PROMPT.md ← NEW
├── tasks/
│ └── tools.rs ← NEW (PROMPT.md exists)
└── <each app>/
├── tools.rs ← NEW per app
└── PROMPT.md ← NEW per app
botui/ui/suite/
└── partials/
└── chatbar.html ← NEW: shared chat bar component
```
---
## Chat Bar UI (`partials/chatbar.html`)
```html
<div id="suite-chatbar" class="chatbar">
<div id="chatbar-messages" hx-ext="ws" ws-connect="/ws/suite-chat"></div>
<form ws-send>
<input type="hidden" name="app_context" value="{{ active_app }}">
<input type="file" id="chatbar-file" name="file" accept=".xlsx,.csv,.png,.jpg,.pdf" style="display:none">
<button type="button" onclick="document.getElementById('chatbar-file').click()">📎</button>
<input type="text" name="message" placeholder="Ask anything about {{ active_app }}...">
<button type="submit"></button>
</form>
</div>
```
File uploads go to `POST /api/suite/upload` → stored in Drive → media_id passed to tool.

46
prompts/nodrive.md Normal file
View file

@ -0,0 +1,46 @@
# Progress: Removendo aws-sdk-s3 do default bundle
## Goal
Remover `aws-sdk-s3` (~120MB) do bundle default `["chat", "automation", "cache", "llm"]` e fazer compilar com:
```bash
cargo check -p botserver --no-default-features --features "chat,automation,cache,llm"
```
## ✅ COMPLETED
1. **Cargo.toml** - Features separadas: `drive` (S3) vs `local-files` (notify)
2. **main.rs** - `pub mod drive` com `#[cfg(any(feature = "drive", feature = "local-files"))]`
3. **state.rs** - `NoDrive` struct adicionada
4. **multimedia.rs** - `DefaultMultimediaHandler` com cfg gates (drive vs no-drive)
5. **drive/mod.rs** - Módulos condicionais:
- `#[cfg(feature = "drive")] pub mod document_processing;`
- `#[cfg(feature = "drive")] pub mod drive_monitor;`
- `#[cfg(feature = "drive")] pub mod vectordb;`
- `#[cfg(feature = "local-files")] pub mod local_file_monitor;`
- Todas ~21 funções com `#[cfg(feature = "drive")]`
6. **multimedia.rs - upload_media** - Duas implementações separadas com cfg gates:
- `#[cfg(feature = "drive")]` - Usa S3 client
- `#[cfg(not(feature = "drive"))]` - Usa armazenamento local
## ✅ VERIFIED
```bash
cargo check -p botserver --no-default-features --features "chat,automation,cache,llm"
```
**Resultado:** ✅ Build limpo (apenas warnings, 0 erros)
**Tempo de compilação:** 2m 29s
## Arquivo Não Fixado (opcional)
### auto_task/app_generator.rs
- `ensure_bucket_exists` method never used (warning, não impede compilação)
- Método já está com `#[cfg(feature = "drive")]` (correto)
## Resumo
O `aws-sdk-s3` foi removido com sucesso do bundle default. O sistema agora suporta dois modos:
- **Com feature "drive"**: Usa S3 (aws-sdk-s3 ~120MB)
- **Sem feature "drive"**: Usa armazenamento local (notify ~2MB)
O build padrão agora é leve (~120MB a menos) e funciona sem dependências de AWS.

259
prompts/prod.md Normal file
View file

@ -0,0 +1,259 @@
# Production Environment Guide
## Infrastructure
### Servers
| Host | IP | Purpose |
|------|-----|---------|
| `system` | `10.157.134.196` | Main botserver + botui container |
| `alm-ci` | `10.157.134.200` | CI/CD runner (Forgejo Actions) |
| `alm` | `10.157.134.34` | Forgejo git server |
| `dns` | `10.157.134.214` | DNS container |
| `drive` | `10.157.134.206` | Drive storage |
| `email` | `10.157.134.40` | Email service |
| `proxy` | `10.157.134.241` | Reverse proxy |
| `tables` | `10.157.134.174` | PostgreSQL |
| `table-editor` | `10.157.134.184` | Table editor |
| `webmail` | `10.157.134.86` | Webmail |
### Port Mapping (system container)
| Service | Internal Port | External URL |
|---------|--------------|--------------|
| botserver | `5858` | `https://system.pragmatismo.com.br` |
| botui | `5859` | `https://chat.pragmatismo.com.br` |
### Access
```bash
# SSH to host
ssh administrator@63.141.255.9
# Execute inside system container
sudo incus exec system -- bash -c 'command'
# SSH from host to container (used by CI)
ssh -o StrictHostKeyChecking=no system "command"
```
## Services
### botserver.service
- **Binary**: `/opt/gbo/bin/botserver`
- **Port**: `5858`
- **User**: `gbuser`
- **Logs**: `/opt/gbo/logs/out.log`, `/opt/gbo/logs/err.log`
- **Config**: `/etc/systemd/system/botserver.service`
- **Env**: `PORT=5858`
### ui.service
- **Binary**: `/opt/gbo/bin/botui`
- **Port**: `5859`
- **Config**: `/etc/systemd/system/ui.service`
- **Env**: `BOTSERVER_URL=http://localhost:5858`
- ⚠️ MUST be `http://localhost:5858` — NOT `https://system.pragmatismo.com.br`
- Rust proxy runs server-side, needs direct localhost access
- JS client uses relative URLs through `chat.pragmatismo.com.br`
### Data Directory
- **Path**: `/opt/gbo/data/`
- **Structure**: `<botname>.gbai/<botname>.gbdialog/*.bas`
- **Bots**: cristo, fema, jucees, oerlabs, poupatempo, pragmatismogb, salesianos, sentient, seplagse
- **Work dir**: `/opt/gbo/work/` (compiled .ast cache)
### Stack Services (managed by botserver bootstrap)
- **Vault**: Secrets management
- **PostgreSQL**: Database (port 5432)
- **Valkey**: Cache (port 6379, password auth)
- **MinIO**: Object storage
- **Zitadel**: Identity provider
- **LLM**: llama.cpp
## CI/CD Pipeline
### Repositories
| Repo | ALM URL | GitHub URL |
|------|---------|------------|
| gb | `https://alm.pragmatismo.com.br/GeneralBots/gb.git` | `git@github.com:GeneralBots/gb.git` |
| botserver | `https://alm.pragmatismo.com.br/GeneralBots/BotServer.git` | `git@github.com:GeneralBots/botserver.git` |
| botui | `https://alm.pragmatismo.com.br/GeneralBots/BotUI.git` | `git@github.com:GeneralBots/botui.git` |
| botlib | `https://alm.pragmatismo.com.br/GeneralBots/botlib.git` | `git@github.com:GeneralBots/botlib.git` |
### Push Order
```bash
# 1. Push submodules first
cd botserver && git push alm main && git push origin main && cd ..
cd botui && git push alm main && git push origin main && cd ..
# 2. Update root workspace references
git add botserver botui botlib
git commit -m "Update submodules: <description>"
git push alm main && git push origin main
```
### Build Environment
- **CI runner**: `alm-ci` container (Debian Trixie, glibc 2.41)
- **Target**: `system` container (Debian 12 Bookworm, glibc 2.36)
- **⚠️ GLIBC MISMATCH**: Building on CI runner produces binaries incompatible with system container
- **Solution**: CI workflow transfers source to system container and builds there via SSH
### Workflow File
- **Location**: `botserver/.forgejo/workflows/botserver.yaml`
- **Triggers**: Push to `main` branch
- **Steps**:
1. Setup workspace on CI runner (clone repos)
2. Transfer source to system container via `tar | ssh`
3. Build inside system container (matches glibc 2.36)
4. Deploy binary inside container
5. Verify botserver is running
## Common Operations
### Check Service Status
```bash
# From host
sudo incus exec system -- systemctl status botserver --no-pager
sudo incus exec system -- systemctl status ui --no-pager
# Check if running
sudo incus exec system -- pgrep -f botserver
sudo incus exec system -- pgrep -f botui
```
### View Logs
```bash
# Systemd journal
sudo incus exec system -- journalctl -u botserver --no-pager -n 50
sudo incus exec system -- journalctl -u ui --no-pager -n 50
# Application logs
sudo incus exec system -- tail -50 /opt/gbo/logs/out.log
sudo incus exec system -- tail -50 /opt/gbo/logs/err.log
# Live tail
sudo incus exec system -- tail -f /opt/gbo/logs/out.log
```
### Restart Services
```bash
sudo incus exec system -- systemctl restart botserver
sudo incus exec system -- systemctl restart ui
```
### Manual Deploy (emergency)
```bash
# Kill old process
sudo incus exec system -- killall botserver
# Copy binary (from host CI workspace or local)
sudo incus exec system -- cp /opt/gbo/ci/botserver/target/debug/botserver /opt/gbo/bin/botserver
sudo incus exec system -- chmod +x /opt/gbo/bin/botserver
sudo incus exec system -- chown gbuser:gbuser /opt/gbo/bin/botserver
# Start service
sudo incus exec system -- systemctl start botserver
```
### Transfer Bot Files to Production
```bash
# From local to prod host
tar czf /tmp/bots.tar.gz -C /opt/gbo/data <botname>.gbai
scp /tmp/bots.tar.gz administrator@63.141.255.9:/tmp/
# From host to container
sudo incus exec system -- bash -c 'tar xzf /tmp/bots.tar.gz -C /opt/gbo/data/'
# Clear compiled cache
sudo incus exec system -- find /opt/gbo/data -name "*.ast" -delete
sudo incus exec system -- find /opt/gbo/work -name "*.ast" -delete
```
### Snapshots
```bash
# List snapshots
sudo incus snapshot list system
# Restore snapshot
sudo incus snapshot restore system <snapshot-name>
```
## Troubleshooting
### GLIBC Version Mismatch
**Symptom**: `GLIBC_2.39 not found` or `GLIBC_2.38 not found`
**Cause**: Binary compiled on CI runner (glibc 2.41) but runs in system container (glibc 2.36)
**Fix**: CI workflow must build inside the system container. Check `botserver.yaml` uses SSH to build in container.
### botserver Not Starting
```bash
# Check binary
sudo incus exec system -- ldd /opt/gbo/bin/botserver | grep "not found"
# Check direct execution
sudo incus exec system -- timeout 10 /opt/gbo/bin/botserver 2>&1
# Check data directory
sudo incus exec system -- ls -la /opt/gbo/data/
```
### botui Can't Reach botserver
```bash
# Check BOTSERVER_URL
sudo incus exec system -- grep BOTSERVER_URL /etc/systemd/system/ui.service
# Must be http://localhost:5858, NOT https://system.pragmatismo.com.br
# Fix:
sudo incus exec system -- sed -i 's|BOTSERVER_URL=.*|BOTSERVER_URL=http://localhost:5858|' /etc/systemd/system/ui.service
sudo incus exec system -- systemctl daemon-reload
sudo incus exec system -- systemctl restart ui
```
### Suggestions Not Showing
```bash
# Check bot files exist
sudo incus exec system -- ls -la /opt/gbo/data/<bot>.gbai/<bot>.gbdialog/
# Check for compilation errors
sudo incus exec system -- tail -50 /opt/gbo/logs/out.log | grep -i "error\|fail\|compile"
# Clear cache and restart
sudo incus exec system -- find /opt/gbo/work -name "*.ast" -delete
sudo incus exec system -- systemctl restart botserver
```
### IPv6 DNS Issues
**Symptom**: External API calls (Groq, Cloudflare) timeout
**Cause**: Container DNS returns AAAA records but no IPv6 connectivity
**Fix**: Container has `IPV6=no` in network config and `gai.conf` labels. If issues persist, check `RES_OPTIONS=inet4` in botserver.service.
## Security
- **NEVER** push secrets to git
- **NEVER** commit files to root with credentials
- **Vault** is single source of truth for secrets
- **CI/CD** is the only deployment method — never manually scp binaries
- **ALM** is production — ask before pushing

154
prompts/usekb2.md Normal file
View file

@ -0,0 +1,154 @@
# USE KB 2.0: Group-Based Knowledge Base Access
## Overview
Modify the USE KB keyword to respect user group permissions, ensuring that THINK KB queries only return answers from knowledge base folders that belong to groups the logged-in user is a member of.
## Current Architecture
### USE KB Flow
1. User executes `USE KB "kb_name"` in BASIC script
2. `use_kb.rs:add_kb_to_session()` checks if KB exists in `kb_collections`
3. Creates default KB entry if not found
4. Adds association to `session_kb_associations` table
5. KB becomes active for the session
### THINK KB Flow
1. User executes `THINK KB "query"`
2. `think_kb.rs:think_kb_search()` gets all active KBs from `session_kb_associations`
3. For each active KB, calls `KnowledgeBaseManager.search()` on its Qdrant collection
4. Returns combined results from all active KBs
### Group System
- Groups stored in `rbac_groups` table
- User membership in `rbac_user_groups` table
- Group permissions via `rbac_group_roles` table
## Proposed Changes
### 1. Database Schema Changes
Add new table `kb_group_associations`:
```sql
CREATE TABLE kb_group_associations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
kb_id UUID NOT NULL REFERENCES kb_collections(id) ON DELETE CASCADE,
group_id UUID NOT NULL REFERENCES rbac_groups(id) ON DELETE CASCADE,
granted_by UUID REFERENCES users(id) ON DELETE SET NULL,
granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(kb_id, group_id)
);
```
Migration file: `botserver/migrations/6.2.0-01-kb-groups/up.sql`
### 2. Backend Logic Changes
#### Modify `think_kb_search()` in `think_kb.rs`
- Add user group lookup before searching
- Filter active KBs to only those accessible by user's groups
- Allow access if KB has no group associations (public KBs) OR user is in associated groups
```rust
async fn think_kb_search(
kb_manager: Arc<KnowledgeBaseManager>,
db_pool: DbPool,
session_id: Uuid,
bot_id: Uuid,
user_id: Uuid, // Add user_id parameter
query: &str,
) -> Result<serde_json::Value, String> {
// Get user's groups
let user_groups = get_user_groups(&db_pool, user_id)?;
// Get active KBs filtered by groups
let accessible_kbs = get_accessible_kbs_for_session(&db_pool, session_id, &user_groups)?;
// Search only accessible KBs
// ... rest of search logic
}
```
#### Add `get_accessible_kbs_for_session()` function
```rust
fn get_accessible_kbs_for_session(
conn_pool: &DbPool,
session_id: Uuid,
user_groups: &[String],
) -> Result<Vec<(String, String, String)>, String> {
// Query that joins session_kb_associations with kb_group_associations
// Returns KBs where group_id IS NULL (public) OR group_id IN user_groups
}
```
#### Modify `add_kb_to_session()` in `use_kb.rs`
- Add optional group access check
- Allow USE KB if user has access to the KB's groups
### 3. API Changes
Add new endpoints in `rbac.rs` for KB-group management:
```rust
// Assign KB to group
POST /api/rbac/kbs/{kb_id}/groups/{group_id}
// Remove KB from group
DELETE /api/rbac/kbs/{kb_id}/groups/{group_id}
// Get groups for KB
GET /api/rbac/kbs/{kb_id}/groups
// Get KBs accessible by user
GET /api/rbac/users/{user_id}/accessible-kbs
```
### 4. Frontend Changes
#### Update `botui/ui/suite/admin/groups.html`
- Add "Knowledge Bases" tab to group detail panel
- Show list of KBs assigned to the group
- Allow adding/removing KB assignments
#### Update `botui/ui/suite/drive/drive.html`
- Add group visibility indicators for KB folders
- Show which groups have access to each KB
### 5. Migration Strategy
1. Create new migration for `kb_group_associations` table
2. Run migration to create table
3. Assign existing KBs to default groups (e.g., "all_users" group)
4. Update application code
5. Deploy and test
### 6. Backward Compatibility
- Existing KBs without group associations remain public
- Existing USE KB calls continue to work
- THINK KB will filter results based on new permissions
## Implementation Steps
1. ✅ Database migration for kb_group_associations
2. ✅ Modify think_kb_search to accept user_id and filter by groups
3. ✅ Update THINK KB keyword registration to pass user_id
4. ✅ Add group access check to USE KB
5. ✅ Add API endpoints for KB-group management
6. ✅ Update admin UI for group-KB assignment
7. ✅ Update drive UI to show group access
8. ✅ Add tests for group-based access control
## Security Considerations
- All KB access checks must happen at the database level
- No client-side filtering of search results
- Group membership verified on each request
- Audit logging for KB access attempts
## Testing
- Unit tests for group access functions
- Integration tests for THINK KB with group filtering
- UI tests for admin group-KB management
- End-to-end tests with different user group scenarios

10
reset.sh Executable file
View file

@ -0,0 +1,10 @@
#!/bin/bash
set -e
echo "Cleaning up..."
rm -rf botserver-stack/ ./work/ .env
echo "Starting services..."
./restart.sh
echo "Reset complete!"

49
restart-fast.sh Normal file
View file

@ -0,0 +1,49 @@
#!/bin/bash
echo "=== Fast Restart: botserver + botmodels only ==="
# Kill only the app services, keep infra running
pkill -f "botserver --noconsole" || true
pkill -f "botmodels" || true
# Clean logs
rm -f botserver.log botmodels.log
# Build only botserver (botui likely already built)
cargo build -p botserver
# Start botmodels
cd botmodels
source venv/bin/activate
uvicorn src.main:app --host 0.0.0.0 --port 8085 > ../botmodels.log 2>&1 &
echo " botmodels PID: $!"
cd ..
# Wait for botmodels
for i in $(seq 1 20); do
if curl -s http://localhost:8085/api/health > /dev/null 2>&1; then
echo " botmodels ready"
break
fi
sleep 1
done
# Start botserver (keep botui running if already up)
if ! pgrep -f "botui" > /dev/null; then
echo "Starting botui..."
cargo build -p botui
cd botui
BOTSERVER_URL="http://localhost:8080" ./target/debug/botui > ../botui.log 2>&1 &
echo " botui PID: $!"
cd ..
fi
# Start botserver
BOTMODELS_HOST="http://localhost:8085" BOTMODELS_API_KEY="starter" RUST_LOG=info ./target/debug/botserver --noconsole > botserver.log 2>&1 &
echo " botserver PID: $!"
# Quick health check
sleep 2
curl -s http://localhost:8080/health > /dev/null 2>&1 && echo "✅ botserver ready" || echo "❌ botserver failed"
echo "Done. botserver $(pgrep -f 'botserver --noconsole') botui $(pgrep -f botui) botmodels $(pgrep -f botmodels)"

32
restart.ps1 Normal file
View file

@ -0,0 +1,32 @@
$ErrorActionPreference = "Continue"
Write-Host "Stopping..."
Stop-Process -Name "botserver" -Force -ErrorAction SilentlyContinue
Stop-Process -Name "botui" -Force -ErrorAction SilentlyContinue
Stop-Process -Name "rustc" -Force -ErrorAction SilentlyContinue
Write-Host "Cleaning..."
Remove-Item -Path "botserver.log", "botui.log" -Force -ErrorAction SilentlyContinue
Write-Host "Building..."
cargo build -p botserver
if ($LASTEXITCODE -ne 0) { Write-Host "Failed to build botserver"; exit 1 }
cargo build -p botui
if ($LASTEXITCODE -ne 0) { Write-Host "Failed to build botui"; exit 1 }
Write-Host "Starting botserver..."
$env:PORT = "8080"
$env:RUST_LOG = "debug"
$env:PATH += ";C:\pgsql\pgsql\bin;C:\pgsql\pgsql\lib"
$botserverProcess = Start-Process -PassThru -NoNewWindow -FilePath ".\target\debug\botserver.exe" -ArgumentList "--noconsole" -RedirectStandardOutput "botserver.log" -RedirectStandardError "botserver.log"
Write-Host " PID: $($botserverProcess.Id)"
Write-Host "Starting botui..."
$env:BOTSERVER_URL = "http://localhost:8080"
$env:PORT = "3000"
$botuiProcess = Start-Process -PassThru -NoNewWindow -FilePath ".\target\debug\botui.exe" -RedirectStandardOutput "botui.log" -RedirectStandardError "botui.log"
Write-Host " PID: $($botuiProcess.Id)"
Write-Host "Done. Logs are being written to botserver.log and botui.log"
Write-Host "To view logs, you can use: Get-Content botserver.log -Wait"

55
restart.sh Executable file
View file

@ -0,0 +1,55 @@
#!/bin/bash
set -e
echo "=== Fast Restart: botserver only (keeps infra running) ==="
# Only kill the app services, keep infra (postgres, valkey, minio, vault, zitadel) running
pkill -f "botserver --noconsole" || true
pkill -f "botmodels" || true
# Clean app logs only
rm -f botserver.log botmodels.log
# Build botserver (incremental, should be fast)
cargo build -p botserver
# Start botmodels if not running
if ! pgrep -f "botmodels" > /dev/null; then
echo "Starting botmodels..."
cd botmodels
source venv/bin/activate
uvicorn src.main:app --host 0.0.0.0 --port 8085 > ../botmodels.log 2>&1 &
echo " botmodels PID: $!"
cd ..
# Wait for botmodels
for i in $(seq 1 15); do
if curl -s http://localhost:8085/api/health > /dev/null 2>&1; then
echo " botmodels ready"
break
fi
sleep 1
done
else
echo " botmodels already running"
fi
# Start botserver
echo "Starting botserver..."
BOTMODELS_HOST="http://localhost:8085" BOTMODELS_API_KEY="starter" RUST_LOG=info \
./target/debug/botserver --noconsole > botserver.log 2>&1 &
echo " botserver PID: $!"
# Wait for botserver health with timeout
echo "Waiting for botserver..."
for i in $(seq 1 10); do
if curl -sf http://localhost:8080/health > /dev/null 2>&1; then
echo "✅ botserver ready"
exit 0
fi
sleep 1
done
echo "❌ botserver failed to start - check botserver.log"
tail -20 botserver.log
exit 1

4
stop.sh Executable file
View file

@ -0,0 +1,4 @@
pkill botui
pkill botserver -9