Files
fn_registry/dev/issues/0164-agents-cryptohelper-init-hang.md
egutierrez 621e8895c9 feat(infra): auto-commit con 86 cambios
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 19:38:15 +02:00

130 lines
7.3 KiB
Markdown

---
id: "0164"
title: "Bots agents_and_robots: cryptohelper.Init() cuelga al habilitar encryption=true"
status: pending
priority: high
created: 2026-05-24
related_flows: ["0009"]
related_issues: ["0144", "0162"]
dependencies: ["0162"]
tags: [matrix, e2ee, mautrix, cryptohelper, agents, hang, debug]
---
## Objetivo
Que los agents de `agents_and_robots` (`agent-wsl-lucas`, `agent-windows-lucas`, y futuros) puedan operar con `encryption.enabled=true` en su `config.yaml` y **leer + responder en DMs encrypted** (megolm) con el operator. Hoy todos corren con `enabled=false` para no colgarse; consecuencia: bot puede ENVIAR a room encrypted (cleartext que Element marca como warning) pero NO LEE replies del operator (megolm cifra, bot no descifra) → chat bidireccional roto.
Bloquea Flow 0009 DoD ("Element → PC interaction working") en el camino encrypted.
## Contexto
- mautrix-go v0.21.1 con cryptohelper (tag `goolm` pure-Go).
- Synapse en VPS organic-machine.com con MSC3861/MAS activo (issue 0162 done 2026-05-24).
- `encryption_enabled_by_default_for_room_type` activo en Synapse → TODA DM nueva nace con `m.megolm.v1.aes-sha2` (no override client-side).
- Bots usan password tokens (no application_service). Tokens emitidos pre-migracion siguen validos (verificado: `/account/whoami` OK con bot token post-MAS).
- `verify.sh agent-windows-lucas` corrio OK: genero crypto.db, upload cross-signing keys, escribio `SSSS_RECOVERY_KEY_AGENT_WINDOWS_LUCAS` en `.env`.
## Reproduccion
```bash
# En VPS, agent-windows-lucas:
sudo sed -i 's/enabled: false/enabled: true/' agents/agent-windows-lucas/config.yaml
sudo systemctl restart agents_and_robots
sleep 30
# Bot stuck:
sudo tail logs/agent-windows-lucas/2026-05-24.jsonl
# Last line forever: "initializing e2ee" — runner nunca llega a "starting matrix sync"
# /agents API endpoint reports running=false
```
## Diagnostico actual (incompleto)
SIGQUIT al proceso launcher revelo bots NO-encrypted en `Listener.Run → SyncWithContext` (normal). NO se pudo aislar la stack de **windows-lucas** durante hang — necesita pprof targeted o log adicional dentro de `InitCrypto`.
Hipotesis (ordenadas):
| ID | Hipotesis | Evidencia que la apoya | Como confirmar |
|---|---|---|---|
| H1 | `cryptohelper.Init()` bloquea en primer `/keys/device_signing/upload` por UIA — MAS no acepta el formato auth heredado | MAS recien activo, password_config disabled, mautrix-go usa UIA password flow | inyectar log antes/despues de cada llamada en `cryptohelper.Init` |
| H2 | `cryptohelper.Init()` bloquea en `OlmMachine.Load` por `crypto.db` schema mismatch | crypto.db generado por `cmd/verify` puede tener schema distinto al que cryptohelper espera | reset crypto.db + dejar que cryptohelper bootstrap solo (sin verify.sh) |
| H3 | El listener trata de hacer initial sync ANTES de e2ee init terminar, deadlock en mutex | "starting matrix sync" NUNCA aparece post-`initializing e2ee` | revisar order en `devagents/runtime.go` |
| H4 | Pickle key mismatch entre verify.sh (lo recibe en hex) y runtime (lo decodifica diferente) | Provision-script genero base64; nosotros pusimos hex; runtime acepta hex? | log de pickle key length en runtime |
## Tareas
### Fase 1 — Diagnostico
1.1. Inyectar logging EN `shell/matrix/client.go::InitCrypto` antes/despues de cada paso (cryptohelper construct, Init, OlmMachine.Load, etc) para identificar la linea que bloquea.
1.2. Reproducir hang en agent test aislado (`agent-e2ee-test`):
- Crear bot fresh con provision-agent-user.sh
- Activar encryption=true
- Restart launcher
- Capturar stack
1.3. Con stack identificado, decidir cual hipotesis (H1-H4) aplica.
### Fase 2 — Fix segun hipotesis
- **Si H1 (MAS UIA)**: investigar si mautrix-go v0.21.1 soporta MSC3861 UIA. Si no: bump a v0.22+ que soporta o usar `device_signing/upload` con SSSS-protected path.
- **Si H2 (schema mismatch)**: dejar cryptohelper bootstrap solo, NO usar verify.sh primero. Verify.sh queda como "post-bootstrap repair".
- **Si H3 (sync deadlock)**: refactor `devagents/runtime.go` para que e2ee init complete antes de spawn listener.
- **Si H4 (pickle key)**: arreglar provision-agent-user.sh para generar pickle key como hex.
### Fase 3 — Validacion (DoD triada)
#### Mecanica
- Bot con `encryption.enabled=true` start OK (running=true en /agents API).
- No hang en logs (paso de "initializing e2ee" → "starting matrix sync" en < 30s).
- Build limpio `go build -tags goolm`.
#### Cobertura
| Escenario | Cmd / evidencia | Resultado |
|---|---|---|
| Golden: operator envia mensaje encrypted en DM, bot lee + responde encrypted | Element web → `#agent-windows-lucas` DM → "hola" | bot responde en < 15s, log muestra decrypted msg + claude_code_response + encrypted send |
| Edge: bot reinicia, crypto.db persiste, re-key OK | `sudo systemctl restart agents_and_robots` mid-conversation | bot continua descifrando mensajes anteriores + nuevos sin re-bootstrap |
| Edge: operator reverify device | Element → device list → forget device → re-verify | bot detecta cambio, sigue cifrando OK |
| Error: crypto.db corrupto | `rm crypto.db` mid-run | bot detecta + auto-recovery (per `docs/e2ee.md`) + re-bootstrap < 60s |
| Error: token revoked | revocar via admin API | bot logout limpio + restart picks up nuevo token |
#### Vida util validada (7 dias)
| Metrica | Umbral | Donde | Ventana |
|---|---|---|---|
| Bot uptime con encryption=true | `> 99%` | `/agents/<id>` API | 7 dias |
| Mensajes encrypted leidos | `>= 10` real conversation | `logs/agent-*/...jsonl` decrypted lines | 7 dias |
| Crashes cryptohelper | `0` | journalctl `agents_and_robots` | 7 dias |
| Latency decrypt msg | `p95 < 2s` | log timestamps | 7 dias |
### Anti-criterios
- NO marcar done si bot solo escribe pero no lee.
- NO marcar done si hang reaparece tras reinicio del servicio.
- NO marcar done si solo funciona en 1 bot (debe replicarse: wsl-lucas + windows-lucas + 1 mas).
## Estado actual workaround
- `agent-wsl-lucas`: `encryption.enabled=false`. DM con operator es UNencrypted (probablemente porque fue creada antes de Synapse activar default-encrypt). Funciona bidireccional.
- `agent-windows-lucas`: `encryption.enabled=false`. DM con operator (room `!ymFSupZVqYpOWunuHI` o `!qeuqopdkeYHWdAfMaN`) es ENCRYPTED (Synapse forced). Bot envia clear-text → operator ve mensaje + warning. Operator reply encrypted → bot NO lee.
## Funciones del registry candidatas (post-fix)
- `mautrix_cryptohelper_init_with_timeout_go_infra` — wrapper con context.WithTimeout para evitar hang infinito.
- `agent_e2ee_bootstrap_bash_pipelines` — pipeline: provision agent → set encryption=true → verify.sh → restart + wait healthy.
## Notas
**Pickle key format bug**: `provision-agent-user.sh` genera base64 (`openssl rand -base64 32`). `cmd/verify` espera hex. Fix in scope de este issue o nuevo issue (`0165-provision-pickle-key-hex.md`).
**Subagent investigation report** (2026-05-24) confirmo:
- E2EE machinery YA existe end-to-end (InitCrypto, FetchCrossSigningKeys, SignOwnDevice, verify.sh).
- docs/e2ee.md cubre failure modes conocidos.
- mautrix-go v0.21.1 puede tener bug pre-MSC3861-aware con MAS.
**Pendiente upstream check**: mautrix-go release notes v0.22+ para MSC3861 support. Si esta soportado, bump version es probablemente el fix.
## Capability growth log
- v0.1.0 (2026-05-24) — issue creado tras reproducir hang post-MAS migration con verify.sh OK pero cryptohelper.Init aun cuelga.