File size: 25,211 Bytes
b259a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
"""

═══════════════════════════════════════════════════════════════════════

CHECKLIST DE IMPLEMENTAÇÃO β€” PASSO A PASSO

═══════════════════════════════════════════════════════════════════════

Guia prΓ‘tico para aplicar a soluΓ§Γ£o no seu ambiente

"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 1: PREPARAÇÃO (30 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE1 = """



βœ“ PASSO 1.1: BACKUP DO CΓ“DIGO EXISTENTE

───────────────────────────────────────────────────────────────

Local: i:\\Isaac Quarenta\\ProgramaΓ§Γ£o\\AKIRA-SOFTEDGE\\



β–‘ Fazer backup de api.py

  cp modules/api.py modules/api.py.backup.$(date +%Y%m%d_%H%M%S)

  

β–‘ Fazer backup de database.py

  cp modules/database.py modules/database.py.backup.$(date +%Y%m%d_%H%M%S)



β–‘ Fazer backup de todo o diretΓ³rio modules/

  ls -la modules/ > modules_backup_list.txt





βœ“ PASSO 1.2: VERIFICAR NOVOS ARQUIVOS

───────────────────────────────────────────────────────────────

β–‘ context_manager_v2.py βœ… EXISTS (jΓ‘ criado)

β–‘ listen_stream_processor.py βœ… EXISTS (jΓ‘ criado)

β–‘ INTEGRATION_GUIDE.md βœ… EXISTS (jΓ‘ criado)

β–‘ API_PATCH_DETAILED.md βœ… EXISTS (jΓ‘ criado)

β–‘ test_context_isolation.py βœ… EXISTS (jΓ‘ criado)

β–‘ SOLUCAO_ESCALAVEL_CONTEXT_ISOLATION.md βœ… EXISTS (jΓ‘ criado)

β–‘ ARQUITETURA_VISUAL.txt βœ… EXISTS (jΓ‘ criado)





βœ“ PASSO 1.3: VERIFICAR DEPENDÊNCIAS PYTHON

───────────────────────────────────────────────────────────────

NecessΓ‘rios (jΓ‘ devem existir):

β–‘ hashlib (built-in)

β–‘ threading (built-in)

β–‘ dataclasses (built-in)

β–‘ typing (built-in)

β–‘ datetime (built-in)

β–‘ enum (built-in)

β–‘ json (built-in)

β–‘ logging (built-in)

β–‘ re (built-in)

β–‘ time (built-in)



Comandos para verificar:

$ python -c "import hashlib, threading, dataclasses, enum; print('βœ… Tudo OK')"





βœ“ PASSO 1.4: REVISAR DOCUMENTAÇÃO

───────────────────────────────────────────────────────────────

β–‘ Ler ARQUITETURA_VISUAL.txt (compreender fluxo)

β–‘ Ler SOLUCAO_ESCALAVEL_CONTEXT_ISOLATION.md (entender problema/soluΓ§Γ£o)

β–‘ Ler INTEGRATION_GUIDE.md (entender integraΓ§Γ£o)

β–‘ Ler API_PATCH_DETAILED.md (ver modificaΓ§Γ΅es especΓ­ficas)



"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 2: TESTES (20 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE2 = """



βœ“ PASSO 2.1: EXECUTAR TESTES ISOLADOS

───────────────────────────────────────────────────────────────

LocaΓ§Γ£o: i:\\Isaac Quarenta\\ProgramaΓ§Γ£o\\AKIRA-SOFTEDGE\\



β–‘ Execute os testes:

  cd AKIRA-SOFTEDGE

  python test_context_isolation.py



Esperado:

  βœ… TEST 1 PASSED

  βœ… TEST 2 PASSED

  βœ… TEST 3 PASSED

  βœ… TEST 4 PASSED

  βœ… TEST 5 PASSED

  

  πŸŽ‰ TODOS OS TESTES PASSARAM!



Se falhar:

  - Verificar que context_manager_v2.py existe

  - Verificar que listen_stream_processor.py existe

  - Verificar que ambos estΓ£o em modules/

  - Verificar mensagens de erro especΓ­ficas





βœ“ PASSO 2.2: TESTAR ISOLADAMENTE CADA MΓ“DULO

───────────────────────────────────────────────────────────────

β–‘ Testar context_manager_v2:

  python -c "

from modules.context_manager_v2 import get_context_manager

cm = get_context_manager()

print('βœ… ContextManagerV2 carregado')

print(f'Stats: {cm.obter_stats()}')

"



β–‘ Testar listen_stream_processor:

  python -c "

from modules.listen_stream_processor import get_listen_processor

lp = get_listen_processor()

print('βœ… ListenStreamProcessor carregado')

resultado = lp.processar_mensagem_chegando({

    'usuario': 'teste',

    'numero': '1234567890',

    'texto': '@AKIRA teste',

    'tipo_conversa': 'pv'

})

print(f'Resultado: {resultado}')

"



Se tudo OK β†’ continuar para Fase 3





βœ“ PASSO 2.3: VALIDAR ISOLAÇÃO

───────────────────────────────────────────────────────────────

β–‘ Executar test_context_isolation.py novamente

β–‘ Verificar que TEST 4 passa (isolaΓ§Γ£o Isaac vs StefΓ’nio)

β–‘ Se TEST 4 falhar, revisar logic em listen_stream_processor.py



"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 3: INTEGRAÇÃO (45 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE3 = """



βœ“ PASSO 3.1: ADICIONAR IMPORTS NO api.py

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: modules/api.py (linha ~10-30)



ANTES:

```python

import json

import hashlib

import logging

from skills_registry import SkillsRegistry

...

```



DEPOIS (ADICIONAR):

```python

import json

import hashlib

import logging

from skills_registry import SkillsRegistry



# βœ… NOVOS IMPORTS PARA CONTEXT V2

from modules.context_manager_v2 import (

    ContextManagerV2,

    get_context_manager,

    MessageType,

    ContextType

)

from modules.listen_stream_processor import (

    ListenStreamProcessor,

    get_listen_processor

)



# Inicializa singletons

ctx_manager = get_context_manager()

listen_processor = get_listen_processor()

...

```



AΓ§Γ£o:

β–‘ Abrir modules/api.py

β–‘ Localizar seΓ§Γ£o de imports

β–‘ Adicionar imports acima

β–‘ SALVAR arquivo





βœ“ PASSO 3.2: MODIFICAR _get_user_context

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: modules/api.py::_get_user_context (line ~2311)



AÇÃO: Seguir API_PATCH_DETAILED.md seΓ§Γ£o "MODIFICATION 2"



β–‘ Abrir api.py

β–‘ Procurar funΓ§Γ£o "_get_user_context"

β–‘ Modificar assinatura (adicionar numero, tipo_conversa, grupo_id)

β–‘ Adicionar lΓ³gica de ContextManagerV2

β–‘ SALVAR e TESTAR





βœ“ PASSO 3.3: INTEGRAR LISTEN STREAM EM akira_endpoint

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: modules/api.py::akira_endpoint (line ~1224)



AÇÃO: Seguir API_PATCH_DETAILED.md seΓ§Γ£o "MODIFICATION 3"



Este Γ© o PRINCIPAL passo:



β–‘ Localizar onde se extrai dados (usuario, numero, texto, tipo_conversa)

β–‘ Adicionar extraΓ§Γ£o de novos campos (referenced_message_author, etc)

β–‘ ANTES de processar LLM:

   β”œβ”€ Chamar listen_processor.processar_mensagem_chegando(evento)

   β”œβ”€ Verificar resultado_processamento['deve_processar']

   β”œβ”€ Se False: retornar jsonify com status 'contextual'

   └─ Se True: continuar normalmente

β–‘ Usar listen_processor.obter_contexto_para_resposta() para histΓ³rico

β–‘ SALVAR e TESTAR





βœ“ PASSO 3.4: ACEITAR NOVOS CAMPOS NO PAYLOAD

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: modules/api.py::akira_endpoint (data extraction)



AÇÃO: Adicionar suporte aos novos campos



```python

# βœ… NOVOS CAMPOS PARA LISTEN STREAM

referenced_message_author = data.get('referenced_message_author', 

                                    data.get('quoted_author_name', ''))

referenced_message_texto = data.get('referenced_message_texto',

                                   data.get('mensagem_citada', ''))

referenced_message_id = data.get('referenced_message_id',

                                data.get('message_id_citada', ''))

```



β–‘ Adicionar apΓ³s extraΓ§Γ£o de tipo_conversa/grupo_id

β–‘ SALVAR





βœ“ PASSO 3.5: ATUALIZAR RESPOSTA JSON

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: modules/api.py::akira_endpoint (return jsonify)



AÇÃO: Adicionar campos de debug



```python

return jsonify({

    'resposta': resposta,

    'modelo_usado': modelo,

    'confidence': confidence,

    'conversation_id': conversation_id,  # βœ… NOVO

    'tipo_message': resultado_processamento['tipo_message'],  # βœ… NOVO

    'participants': participants if tipo_conversa == 'grupo' else [],  # βœ… NOVO

    ...

})

```



β–‘ Localizar primeiro return jsonify em akira_endpoint

β–‘ Adicionar campos acima

β–‘ SALVAR



"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 4: ATUALIZAR discord-ts (15 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE4 = """



βœ“ PASSO 4.1: ATUALIZAR APIClient.ts

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: discord-ts/index/modules/APIClient.ts



Adicionar ao payload enviado:



β–‘ tipo_conversa: "pv" | "grupo"

  └─ Se Γ© conversa privada ou grupo



β–‘ grupo_id: string | null

  └─ ID do grupo (se aplicΓ‘vel)



β–‘ referenced_message_author: string | null

  └─ Nome de quem foi mencionado/citado



β–‘ referenced_message_texto: string | null

  └─ Texto da mensagem citada



Exemplo de novo payload:

```typescript

const payload = {

    usuario: msg.author.username,

    numero: msg.author.id,

    texto: msg.content,

    tipo_conversa: msg.channel.isDMBased() ? 'pv' : 'grupo',

    grupo_id: !msg.channel.isDMBased() ? msg.channelId : null,

    referenced_message_author: msg.reference?.author?.username || null,

    referenced_message_texto: msg.reference?.content || null,

    // ... resto dos campos

};

```



β–‘ Modificar APIClient.ts

β–‘ TESTAR com Discord





βœ“ PASSO 4.2: VERIFICAR BAILEYS (WhatsApp)

───────────────────────────────────────────────────────────────

LocalizaΓ§Γ£o: discord-ts/index/modules/BotCore.ts ou similar



Verificar se:

β–‘ tipo_conversa Γ© capturado corretamente

β–‘ grupo_id Γ© enviado quando em grupo

β–‘ quoted messages sΓ£o extraΓ­das



Se nΓ£o estΓ£o:

β–‘ Adicionar lΓ³gica similar ao Discord

β–‘ TESTAR com WhatsApp



"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 5: TESTES DE INTEGRAÇÃO (30 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE5 = """



βœ“ PASSO 5.1: TESTE BÁSICO - CONVERSA PRIVADA

───────────────────────────────────────────────────────────────

β–‘ Enviar via POST /akira em conversa privada

  

Payload:

{

    "usuario": "IsaacTest",

    "numero": "test_123",

    "texto": "Oi AKIRA",

    "tipo_conversa": "pv"

}



Esperado:

βœ… deve_processar: true

βœ… tipo_message: "direct"

βœ… resposta: [alguma resposta]

βœ… conversation_id: [hash ΓΊnico]





βœ“ PASSO 5.2: TESTE COM MENÇÃO EM GRUPO

───────────────────────────────────────────────────────────────

β–‘ Enviar em grupo COM @AKIRA



Payload:

{

    "usuario": "IsaacTest",

    "numero": "test_123",

    "texto": "@AKIRA qual Γ© a capital?",

    "tipo_conversa": "grupo",

    "grupo_id": "test_group_123"

}



Esperado:

βœ… deve_processar: true

βœ… tipo_message: "direct"

βœ… resposta: [resposta da pergunta]





βœ“ PASSO 5.3: TESTE SEM MENÇÃO EM GRUPO

───────────────────────────────────────────────────────────────

β–‘ Enviar em grupo SEM @AKIRA



Payload:

{

    "usuario": "StefanioTest",

    "numero": "test_456",

    "texto": "Bacano",

    "tipo_conversa": "grupo",

    "grupo_id": "test_group_123"

}



Esperado:

βœ… deve_processar: false

βœ… tipo_message: "contextual"

βœ… resposta: "" (vazia)

βœ… status: "context_registered"





βœ“ PASSO 5.4: TESTE DE ISOLAÇÃO

───────────────────────────────────────────────────────────────

β–‘ Executar sequΓͺncia em grupo:



1. Isaac: "@AKIRA qual Γ© capital de PT?" (responde)

2. StefΓ’nio: "Bacano" (contextual, nΓ£o responde)

3. Isaac: "@AKIRA e da FR?" (responde)



ValidaΓ§Γ£o:

β–‘ AKIRA respondeu em 1 e 3 (ambas Isaac)

β–‘ AKIRA nΓ£o respondeu em 2

β–‘ Logs mostram "πŸ” ClassificaΓ§Γ£o Listen: direct/contextual"

β–‘ conversation_id de Isaac mantΓ©m isolado





βœ“ PASSO 5.5: MONITORAR LOGS

───────────────────────────────────────────────────────────────

Observar no logs:

β–‘ "πŸ“¨ Mensagem chegando: ..."

β–‘ "πŸ” ClassificaΓ§Γ£o Listen: ..."

β–‘ "βœ“ Mensagem contextual (escuta). NΓ£o respondendo." (quando aplicΓ‘vel)

β–‘ "πŸ“– Contexto obtido: X mensagens diretas"



Se tudo OK β†’ Fase 6



"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 6: VALIDAÇÃO FINAL (15 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE6 = """



βœ“ PASSO 6.1: VERIFICAR STATS

───────────────────────────────────────────────────────────────

β–‘ Chamar ctx_manager.obter_stats()



Esperado:

{

    'total_contexts': N,

    'total_messages': M,

    'average_msgs_per_context': M/N,

    'cache_size': X,

    'memory_estimate_mb': Y

}



Validar:

β–‘ memory_estimate_mb < 100MB (escalΓ‘vel)

β–‘ total_contexts growing mas nΓ£o explosivo





βœ“ PASSO 6.2: VERIFICAR ISOLAÇÃO REAL

───────────────────────────────────────────────────────────────

β–‘ Fazer teste completo com 2+ usuΓ‘rios em grupo real

β–‘ Verificar que mensagens de um nΓ£o contamina outro

β–‘ Verificar que AKIRA responde apenas quando mencionada



Exemplo:

- Isaac: "@AKIRA Python Γ© melhor que Java?"

- VocΓͺ em outro grupo: "@AKIRA Qual Γ© o melhor framework?"

- Isaac: "@AKIRA Ok valeu"

βœ“ Confirm: Cada um tem seu prΓ³prio contexto isolado





βœ“ PASSO 6.3: PERFORMANCE

───────────────────────────────────────────────────────────────

β–‘ Medir tempo de resposta com novo sistema

β–‘ Comparar com antes (deve ser ~5-10% mais rΓ‘pido)

β–‘ Verificar que nΓ£o hΓ‘ memory leaks apΓ³s 1 hora de uso





βœ“ PASSO 6.4: ROLLBACK PLAN

───────────────────────────────────────────────────────────────

Se algo der errado:



β–‘ Restaurar api.py do backup:

  cp modules/api.py.backup.* modules/api.py

  

β–‘ Remover imports dos novos mΓ³dulos



β–‘ Reiniciar servidor



β–‘ Verificar que volta ao estado anterior



β–‘ Documentar problema encontrado para debug



"""

# ═══════════════════════════════════════════════════════════════════════
# FASE 7: DEPLOY (5 minutos)
# ═══════════════════════════════════════════════════════════════════════

FASE7 = """



βœ“ PASSO 7.1: DEPLOY EM STAGING

───────────────────────────────────────────────────────────────

β–‘ Deploy do novo cΓ³digo em staging

β–‘ Rodar Fase 5 (testes de integraΓ§Γ£o) em staging

β–‘ Monitorar por 2-4 horas

β–‘ Verificar que nΓ£o hΓ‘ errors no log





βœ“ PASSO 7.2: DEPLOY EM PRODUÇÃO

───────────────────────────────────────────────────────────────

β–‘ Fazer ΓΊltimo backup do api.py em produΓ§Γ£o

β–‘ Deploy da soluΓ§Γ£o

β–‘ Monitorar logs continuamente

β–‘ Se problema: executar rollback plan





βœ“ PASSO 7.3: MONITORAMENTO PΓ“S-DEPLOY

───────────────────────────────────────────────────────────────

β–‘ Primeira hora: Verificar a cada 5 minutos

β–‘ Primeiras 24h: Verificar a cada 30 minutos

β–‘ ApΓ³s 24h: Verificar diariamente



MΓ©tricas a monitorar:

β”œβ”€ Taxa de erro (deve ser < 0.1%)

β”œβ”€ Tempo mΓ©dio de resposta (deve ser < 2s)

β”œβ”€ Memory usage (deve ser estΓ‘vel)

β”œβ”€ Context isolation (validar com teste manual diΓ‘rio)

└─ User complaints (deve ser zero sobre context mix)



"""

# ═══════════════════════════════════════════════════════════════════════
# RESUMO DE TEMPO ESTIMADO
# ═══════════════════════════════════════════════════════════════════════

RESUMO_TEMPO = """



FASE 1 (PreparaΓ§Γ£o): 30 minutos

β”œβ”€ Backup

β”œβ”€ Verificar novos arquivos

β”œβ”€ Verificar dependΓͺncias

└─ Revisar documentaΓ§Γ£o



FASE 2 (Testes Isolados): 20 minutos

β”œβ”€ Executar test_context_isolation.py

β”œβ”€ Testar cada mΓ³dulo

└─ Validar isolaΓ§Γ£o



FASE 3 (IntegraΓ§Γ£o): 45 minutos

β”œβ”€ Adicionar imports

β”œβ”€ Modificar _get_user_context

β”œβ”€ Integrar listen stream

β”œβ”€ Aceitar novos campos

└─ Atualizar resposta JSON



FASE 4 (Atualizar discord-ts): 15 minutos

β”œβ”€ Atualizar APIClient.ts

└─ Verificar Baileys



FASE 5 (Testes de IntegraΓ§Γ£o): 30 minutos

β”œβ”€ Teste PV

β”œβ”€ Teste menΓ§Γ£o em grupo

β”œβ”€ Teste sem menΓ§Γ£o

β”œβ”€ Teste isolaΓ§Γ£o

└─ Monitorar logs



FASE 6 (ValidaΓ§Γ£o): 15 minutos

β”œβ”€ Verificar stats

β”œβ”€ Verificar isolaΓ§Γ£o real

β”œβ”€ Performance check

└─ Rollback plan



FASE 7 (Deploy): 5 minutos

β”œβ”€ Deploy staging

β”œβ”€ Deploy produΓ§Γ£o

└─ Monitoramento inicial



────────────────────────────────────────────────────────────────

TOTAL: ~2 horas 50 minutos (primeira vez)

PRΓ“XIMAS IMPLEMENTAÇÕES: ~30 minutos (depois de entender)

────────────────────────────────────────────────────────────────



"""

# ═══════════════════════════════════════════════════════════════════════
# TROUBLESHOOTING RÁPIDO
# ═══════════════════════════════════════════════════════════════════════

TROUBLESHOOTING = """



PROBLEMA: "ModuleNotFoundError: No module named 'context_manager_v2'"

SOLUÇÃO:

  β–‘ Verificar que context_manager_v2.py estΓ‘ em modules/

  β–‘ Verificar que __init__.py existe em modules/

  β–‘ Adicionar modules/ ao PYTHONPATH se necessΓ‘rio





PROBLEMA: "NameError: name 'ctx_manager' is not defined"

SOLUÇÃO:

  β–‘ Verificar que imports estΓ£o no top do api.py

  β–‘ Verificar que get_context_manager() foi chamado

  β–‘ Verificar que listen_processor tambΓ©m foi inicializado





PROBLEMA: "AKIRA ainda estΓ‘ respondendo mensagens contextuais"

SOLUÇÃO:

  β–‘ Verificar que listen_processor.processar_mensagem_chegando() Γ© chamado

  β–‘ Verificar que if not resultado_processamento['deve_processar']: Γ© respeitado

  β–‘ Verificar logs: ver se πŸ” ClassificaΓ§Γ£o estΓ‘ correto

  β–‘ Se classifica como CONTEXTUAL mas processa, debugar lΓ³gica





PROBLEMA: "Contextos ainda estΓ£o misturando"

SOLUÇÃO:

  β–‘ Verificar que conversation_id Γ© ΓΊnico por usuΓ‘rio/grupo

  β–‘ Rodar test_context_isolation.py especialmente TEST 4

  β–‘ Debugar _gerar_conversation_id() em ContextManagerV2

  β–‘ Verificar que ctx_manager.obter_historico_direto() estΓ‘ sendo usado





PROBLEMA: "Performance degradada apΓ³s integraΓ§Γ£o"

SOLUÇÃO:

  β–‘ Verificar ctx_manager.obter_stats() para memory estimate

  β–‘ Se > 100MB: implementar cleanup mais agressivo

  β–‘ Verificar nΓΊmero de contextos: se > 10k, hΓ‘ problema

  β–‘ Revisar TTL do cache (atualmente 300s, pode reduzir)





PROBLEMA: "Mensagens antigas nΓ£o aparecem"

SOLUÇÃO:

  β–‘ Verificar TTL: contextos com last_access > 7 dias sΓ£o deletados

  β–‘ Se precisa histΓ³rico mais longo: modificar max_age_days em cleanup

  β–‘ Ou implementar persistΓͺncia em DB (fora do escopo atual)



"""

print(FASE1)
print("\n" + "="*70 + "\n")
print(FASE2)
print("\n" + "="*70 + "\n")
print(FASE3)
print("\n" + "="*70 + "\n")
print(FASE4)
print("\n" + "="*70 + "\n")
print(FASE5)
print("\n" + "="*70 + "\n")
print(FASE6)
print("\n" + "="*70 + "\n")
print(FASE7)
print("\n" + "="*70 + "\n")
print(RESUMO_TEMPO)
print("\n" + "="*70 + "\n")
print(TROUBLESHOOTING)

__all__ = ['FASE1', 'FASE2', 'FASE3', 'FASE4', 'FASE5', 'FASE6', 'FASE7', 'RESUMO_TEMPO', 'TROUBLESHOOTING']