Skip to content

Refactor Analista Processual Squad: 3-tier architecture with 7 specialized agents#5

Merged
felippepestana merged 1 commit intomainfrom
claude/aiox-implementation-KJDTE
Mar 30, 2026
Merged

Refactor Analista Processual Squad: 3-tier architecture with 7 specialized agents#5
felippepestana merged 1 commit intomainfrom
claude/aiox-implementation-KJDTE

Conversation

@felippepestana
Copy link
Copy Markdown
Owner

@felippepestana felippepestana commented Mar 28, 2026

Summary

Completely restructured the Analista Processual Squad from a 4-agent model to a sophisticated 3-tier architecture with 7 specialized agents, introducing dual-mode processing for both generic organizational processes and Brazilian judicial cases.

Key Changes

  • Architecture Redesign: Implemented 3-tier pipeline:

    • Tier 0 (Intake): Mapeador Processual + Avaliador Processual for process mapping and maturity assessment
    • Tier 1 (Execution): Leitor de Peças, Pesquisador Jurídico, Estrategista Processual, Advogado Orientador for specialized legal analysis
    • Tier Síntese: Documentador Processual for dual-mode report generation
  • New Agents:

    • leitor-de-pecas: Extracts 7 structured categories from legal documents (parties, dates, claims, legal grounds, decisions, evidence)
    • pesquisador-juridico: Researches Brazilian jurisprudence (STF/STJ/TJs) with 5-dimension framework
    • estrategista-processual: Analyzes positioning, risks, and 3 scenarios with probability percentages
    • advogado-orientador: Translates strategy into concrete action plans with timelines
  • Orchestrator System Prompt: Replaced simple sequential flow with intelligent use-case classification (UC-AP-001 through UC-AP-004) that routes to appropriate agent combinations based on demand type

  • Dual-Mode Documentation: Documentador Processual now detects context and generates either:

    • MODO_PROCESSUAL: Generic process reports with maturidade score and roadmap
    • MODO_JURIDICO: Judicial case reports with legal analysis, citations block, and client guidance
  • Enhanced Tool Support: Added WebSearch and Grep tools; expanded Read/Write/Glob usage across agents

  • Quality Gates: Introduced 4 quality gates (QG-AP-001 through QG-AP-004) to ensure classification, structured outputs, and file persistence

  • Module Structure: Added __main__.py to enable execution as python -m squads.analista-processual

Notable Implementation Details

  • Each agent has detailed, protocol-driven prompts with explicit output formats (Markdown tables, structured sections)
  • Agents include explicit VETO rules to prevent scope creep (e.g., mapeador never evaluates risks; leitor never emits legal opinions)
  • Documentador uses filename pattern relatorio-[processo-slug]-[AAAA-MM-DD].md and MUST confirm Write usage
  • Pesquisador Juridico enforces minimum 5 sources per research with tribunal/date/ementa citation format
  • Estrategista Processual requires 3 scenarios with probabilities that sum to exactly 100%

https://claude.ai/code/session_019XqLzo93ohjSCYVSg9sHEW

Summary by Sourcery

Refatorar a squad Analista Processual em um pipeline de orquestração multi-camadas e multi-agentes, com suporte duplo para análise de processos genéricos e fluxos de trabalho de casos judiciais brasileiros.

Novos recursos:

  • Introduzir agentes jurídicos especializados para leitura de documentos, pesquisa de jurisprudência, análise estratégica e planejamento de ações orientado ao cliente.
  • Adicionar um agente de documentação de modo duplo que gera e persiste relatórios estruturados em Markdown tanto para processos genéricos quanto para casos judiciais, com base no contexto.
  • Implementar um prompt de sistema orquestrador que classifica as demandas dos usuários em casos de uso distintos e as direciona por combinações apropriadas de agentes com etapas de garantia de qualidade.

Melhorias:

  • Redesenhar os agentes existentes de mapeamento e avaliação de processos com prompts mais claros, orientados por protocolo, formatos de saída explícitos e limites de escopo mais rígidos.
  • Expandir o uso de ferramentas pelos agentes para incluir Grep, WebSearch e configurações refinadas de Read/Write/Glob.
  • Revisar o “squad runner” para usar uma interface de entrada mais genérica, um registro de agentes atualizado e mensagens de uso de CLI aprimoradas.
Original summary in English

Summary by Sourcery

Refactor the Analista Processual squad into a multi-tier, multi-agent orchestration pipeline with dual support for generic process analysis and Brazilian judicial case workflows.

New Features:

  • Introduce specialized legal agents for document reading, jurisprudence research, strategic analysis, and client-oriented action planning.
  • Add a dual-mode documentation agent that generates and persists structured Markdown reports for both generic processes and judicial cases based on context.
  • Implement an orchestrator system prompt that classifies user demands into distinct use cases and routes them through appropriate agent combinations with quality gates.

Enhancements:

  • Redesign existing process mapping and evaluation agents with clearer, protocol-driven prompts, explicit output formats, and stricter scope boundaries.
  • Expand tool usage across agents to include Grep, WebSearch, and refined Read/Write/Glob configurations.
  • Revise the squad runner to use a more generic input interface, updated agent registry, and improved CLI usage messaging.

Summary by CodeRabbit

Release Notes

  • New Features
    • Module is now executable via python -m squads.analista-processual
    • Analista Processual Squad enhanced with a 3-tier processing pipeline (intake/mapping → juridical execution → synthesis)
    • Expanded agent capabilities for comprehensive legal analysis
    • Updated output reporting format

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Mar 28, 2026

Guia do Revisor

Refatora a squad Analista Processual de um fluxo linear simples de 3 agentes para uma arquitetura orquestrada em 3 camadas, com 7 agentes especializados, modos duplos processual/jurídico, gates de qualidade explícitos, uso mais rico de ferramentas e um ponto de entrada compatível com CLI para execução.

Diagrama de sequência para o fluxo completo de análise judicial UC-AP-002

sequenceDiagram
    actor User
    participant Orchestrator
    participant LeitorDePecas
    participant PesquisadorJuridico
    participant EstrategistaProcessual
    participant AdvogadoOrientador
    participant DocumentadorProcessual
    participant FileSystem

    User->>Orchestrator: Envia descrição do caso judicial
    Orchestrator->>Orchestrator: QG-AP-001 classifica como UC-AP-002

    par Extração_de_peças
        Orchestrator->>LeitorDePecas: Ativa leitor_de_pecas com documentos
        LeitorDePecas->>LeitorDePecas: Usa Read/Glob/Grep para extrair 7 categorias
        LeitorDePecas-->>Orchestrator: Tabelas estruturadas por documento
    and Pesquisa_jurisprudencial
        Orchestrator->>PesquisadorJuridico: Ativa pesquisador_juridico com tese jurídica
        PesquisadorJuridico->>PesquisadorJuridico: Usa WebSearch/Read/Grep
        PesquisadorJuridico-->>Orchestrator: Mínimo 5 fontes com citações formais
    end

    Orchestrator->>EstrategistaProcessual: Envia extrações + jurisprudência
    EstrategistaProcessual->>EstrategistaProcessual: Analisa riscos e cenários (3) com % = 100
    EstrategistaProcessual-->>Orchestrator: Relatório estratégico com cenários

    Orchestrator->>AdvogadoOrientador: Envia análise estratégica
    AdvogadoOrientador->>AdvogadoOrientador: Gera plano de ação e orientação ao cliente
    AdvogadoOrientador-->>Orchestrator: Plano com ações 7 dias e 4-8 semanas

    Orchestrator->>DocumentadorProcessual: Consolida outputs (modo jurídico)
    DocumentadorProcessual->>DocumentadorProcessual: Detecta MODO_JURIDICO (uso do leitor_de_pecas)
    DocumentadorProcessual->>DocumentadorProcessual: Monta relatório Markdown + bloco citacoes
    DocumentadorProcessual->>FileSystem: Write relatorio-[processo-slug]-[AAAA-MM-DD].md
    FileSystem-->>DocumentadorProcessual: Caminho confirmado
    DocumentadorProcessual-->>Orchestrator: Confirmação QG-AP-004 + resumo

    Orchestrator-->>User: Indica local do arquivo e apresenta resumo executivo
Loading

Diagrama de classes para o orquestrador e agentes especializados

classDiagram
    class AnalistaProcessualSquad {
        +run_squad(input_text)
        +main()
        -SYSTEM_PROMPT
        -agents
        -allowed_tools
    }

    class AgentDefinition {
        +description
        +prompt
        +tools
    }

    class MapeadorProcessual {
        +description
        +prompt
        +tools : [Read, Glob]
    }

    class AvaliadorProcessual {
        +description
        +prompt
        +tools : [Read]
    }

    class LeitorDePecas {
        +description
        +prompt
        +tools : [Read, Glob, Grep]
    }

    class PesquisadorJuridico {
        +description
        +prompt
        +tools : [Read, Glob, Grep, WebSearch]
    }

    class EstrategistaProcessual {
        +description
        +prompt
        +tools : [Read, Grep]
    }

    class AdvogadoOrientador {
        +description
        +prompt
        +tools : [Read]
    }

    class DocumentadorProcessual {
        +description
        +prompt
        +tools : [Read, Write, Grep, Glob]
        +modo
    }

    AnalistaProcessualSquad --> AgentDefinition : utiliza
    AgentDefinition <|-- MapeadorProcessual
    AgentDefinition <|-- AvaliadorProcessual
    AgentDefinition <|-- LeitorDePecas
    AgentDefinition <|-- PesquisadorJuridico
    AgentDefinition <|-- EstrategistaProcessual
    AgentDefinition <|-- AdvogadoOrientador
    AgentDefinition <|-- DocumentadorProcessual
Loading

Diagrama de estados para o comportamento em modo duplo do Documentador Processual

stateDiagram-v2
    [*] --> AguardandoContexto

    state AguardandoContexto {
        [*] --> SemModoDefinido
        SemModoDefinido --> ModoProcessual : Apenas mapeador_processual
        SemModoDefinido --> ModoJuridico : Inclui leitor_de_pecas
    }

    state ModoProcessual {
        [*] --> MontandoRelatorioProcessual
        MontandoRelatorioProcessual --> SalvandoArquivoProcessual : Write relatorio-[processo-slug]-[AAAA-MM-DD].md
        SalvandoArquivoProcessual --> QG_AP_004_Processual : Confirma uso de Write
        QG_AP_004_Processual --> [*]
    }

    state ModoJuridico {
        [*] --> MontandoRelatorioJuridico
        MontandoRelatorioJuridico --> AdicionandoBlocoCitacoes : Anexa bloco citacoes
        AdicionandoBlocoCitacoes --> SalvandoArquivoJuridico : Write relatorio-[processo-slug]-[AAAA-MM-DD].md
        SalvandoArquivoJuridico --> QG_AP_004_Juridico : Confirma uso de Write
        QG_AP_004_Juridico --> [*]
    }
Loading

Alterações em nível de arquivo

Change Details Files
Introduce tiered multi-agent architecture with specialized intake, execution, and synthesis agents.
  • Substituir os agentes genéricos anteriores de mapeamento, avaliação e documentação por definições mais detalhadas e orientadas a protocolo para MAEADOR_PROCESSUAL e AVALIADOR_PROCESSUAL, incluindo formatos de saída estritos e regras de VETO.
  • Adicionar agentes de execução de Nível 1 (LEITOR_DE_PECAS, PESQUISADOR_JURIDICO, ESTRATEGISTA_PROCESSUAL, ADVOGADO_ORIENTADOR) focados em extração de documentos jurídicos, pesquisa de jurisprudência, análise estratégica de cenários e planejamento de ações.
  • Adicionar agente de síntese DOCUMENTADOR_PROCESSUAL com comportamento em modo duplo (MODO_PROCESSUAL vs MODO_JURIDICO), salvamento obrigatório de arquivo via Write e um padrão de nome de arquivo padronizado e bloco de citações.
squads/analista-processual/squad.py
Replace simple coordinator prompt with an orchestrator system prompt that classifies use cases and enforces quality gates.
  • Definir um classificador de casos de uso explícito (UC-AP-001 a UC-AP-004) roteando diferentes intenções do usuário para pipelines específicos de agentes, incluindo execução paralela quando aplicável.
  • Adicionar quality gates (QG-AP-001 até QG-AP-004) para reforçar a classificação de UC, mapeamento estruturado, pontuação de maturidade e confirmação de Write pelo agente documentador.
  • Adicionar regras de orquestração proibindo o orquestrador de fazer análise por conta própria e exigindo o uso explícito de agentes e persistência de documentos.
squads/analista-processual/squad.py
Expand tool usage and capabilities for agents and orchestrator.
  • Estender allowed_tools no runner da squad para incluir Grep e WebSearch além de Read, Write, Glob e Agent.
  • Configurar cada agente com um conjunto de ferramentas sob medida (por exemplo, LEITOR_DE_PECAS usando Read/Glob/Grep, PESQUISADOR_JURIDICO usando WebSearch, DOCUMENTADOR_PROCESSUAL usando Write e ferramentas de sistema de arquivos).
squads/analista-processual/squad.py
Refine the runner interface and error handling for CLI usage.
  • Renomear o parâmetro de run_squad de processo para input_text, ajustar rótulos de impressão de “Relatório Final” para “Resultado Final” e atualizar a invocação de anyio.run de acordo.
  • Alterar o ponto de entrada da CLI para preferir entrada via argv, ler stdin caso contrário e emitir uma mensagem de uso mais saída com código diferente de zero quando nenhuma entrada for fornecida.
squads/analista-processual/squad.py
Add module entrypoint to allow running the squad via python -m.
  • Introduzir main.py em squads/analista-processual para delegar para a função main() em squad.py, permitindo que o módulo seja executado como python -m squads.analista-processual.
squads/analista-processual/__main__.py

Dicas e comandos

Interagindo com o Sourcery

  • Disparar uma nova revisão: Comente @sourcery-ai review no pull request.
  • Continuar discussões: Responda diretamente aos comentários de revisão do Sourcery.
  • Gerar uma issue do GitHub a partir de um comentário de revisão: Peça ao Sourcery para criar uma issue a partir de um comentário de revisão respondendo a ele. Você também pode responder a um comentário de revisão com @sourcery-ai issue para criar uma issue a partir dele.
  • Gerar um título de pull request: Escreva @sourcery-ai em qualquer lugar no título do pull request para gerar um título a qualquer momento. Você também pode comentar @sourcery-ai title no pull request para (re)gerar o título a qualquer momento.
  • Gerar um resumo do pull request: Escreva @sourcery-ai summary em qualquer lugar no corpo do pull request para gerar um resumo do PR a qualquer momento exatamente onde você quiser. Você também pode comentar @sourcery-ai summary no pull request para (re)gerar o resumo a qualquer momento.
  • Gerar o guia do revisor: Comente @sourcery-ai guide no pull request para (re)gerar o guia do revisor a qualquer momento.
  • Resolver todos os comentários do Sourcery: Comente @sourcery-ai resolve no pull request para resolver todos os comentários do Sourcery. Útil se você já tratou todos os comentários e não quer mais vê-los.
  • Dispensar todas as revisões do Sourcery: Comente @sourcery-ai dismiss no pull request para dispensar todas as revisões existentes do Sourcery. Especialmente útil se você quiser começar do zero com uma nova revisão — não esqueça de comentar @sourcery-ai review para disparar uma nova revisão!

Personalizando sua experiência

Acesse seu dashboard para:

  • Ativar ou desativar recursos de revisão, como o resumo de pull request gerado pelo Sourcery, o guia do revisor e outros.
  • Alterar o idioma da revisão.
  • Adicionar, remover ou editar instruções personalizadas de revisão.
  • Ajustar outras configurações de revisão.

Obtendo ajuda

Original review guide in English

Reviewer's Guide

Refactors the Analista Processual squad from a simple 3-agent linear flow into a 3‑tier orchestrated architecture with 7 specialized agents, dual process/judicial modes, explicit quality gates, richer tool usage, and a CLI-friendly runner entrypoint.

Sequence diagram for UC-AP-002 full judicial analysis flow

sequenceDiagram
    actor User
    participant Orchestrator
    participant LeitorDePecas
    participant PesquisadorJuridico
    participant EstrategistaProcessual
    participant AdvogadoOrientador
    participant DocumentadorProcessual
    participant FileSystem

    User->>Orchestrator: Envia descrição do caso judicial
    Orchestrator->>Orchestrator: QG-AP-001 classifica como UC-AP-002

    par Extração_de_peças
        Orchestrator->>LeitorDePecas: Ativa leitor_de_pecas com documentos
        LeitorDePecas->>LeitorDePecas: Usa Read/Glob/Grep para extrair 7 categorias
        LeitorDePecas-->>Orchestrator: Tabelas estruturadas por documento
    and Pesquisa_jurisprudencial
        Orchestrator->>PesquisadorJuridico: Ativa pesquisador_juridico com tese jurídica
        PesquisadorJuridico->>PesquisadorJuridico: Usa WebSearch/Read/Grep
        PesquisadorJuridico-->>Orchestrator: Mínimo 5 fontes com citações formais
    end

    Orchestrator->>EstrategistaProcessual: Envia extrações + jurisprudência
    EstrategistaProcessual->>EstrategistaProcessual: Analisa riscos e cenários (3) com % = 100
    EstrategistaProcessual-->>Orchestrator: Relatório estratégico com cenários

    Orchestrator->>AdvogadoOrientador: Envia análise estratégica
    AdvogadoOrientador->>AdvogadoOrientador: Gera plano de ação e orientação ao cliente
    AdvogadoOrientador-->>Orchestrator: Plano com ações 7 dias e 4-8 semanas

    Orchestrator->>DocumentadorProcessual: Consolida outputs (modo jurídico)
    DocumentadorProcessual->>DocumentadorProcessual: Detecta MODO_JURIDICO (uso do leitor_de_pecas)
    DocumentadorProcessual->>DocumentadorProcessual: Monta relatório Markdown + bloco citacoes
    DocumentadorProcessual->>FileSystem: Write relatorio-[processo-slug]-[AAAA-MM-DD].md
    FileSystem-->>DocumentadorProcessual: Caminho confirmado
    DocumentadorProcessual-->>Orchestrator: Confirmação QG-AP-004 + resumo

    Orchestrator-->>User: Indica local do arquivo e apresenta resumo executivo
Loading

Class diagram for orchestrator and specialized agents

classDiagram
    class AnalistaProcessualSquad {
        +run_squad(input_text)
        +main()
        -SYSTEM_PROMPT
        -agents
        -allowed_tools
    }

    class AgentDefinition {
        +description
        +prompt
        +tools
    }

    class MapeadorProcessual {
        +description
        +prompt
        +tools : [Read, Glob]
    }

    class AvaliadorProcessual {
        +description
        +prompt
        +tools : [Read]
    }

    class LeitorDePecas {
        +description
        +prompt
        +tools : [Read, Glob, Grep]
    }

    class PesquisadorJuridico {
        +description
        +prompt
        +tools : [Read, Glob, Grep, WebSearch]
    }

    class EstrategistaProcessual {
        +description
        +prompt
        +tools : [Read, Grep]
    }

    class AdvogadoOrientador {
        +description
        +prompt
        +tools : [Read]
    }

    class DocumentadorProcessual {
        +description
        +prompt
        +tools : [Read, Write, Grep, Glob]
        +modo
    }

    AnalistaProcessualSquad --> AgentDefinition : utiliza
    AgentDefinition <|-- MapeadorProcessual
    AgentDefinition <|-- AvaliadorProcessual
    AgentDefinition <|-- LeitorDePecas
    AgentDefinition <|-- PesquisadorJuridico
    AgentDefinition <|-- EstrategistaProcessual
    AgentDefinition <|-- AdvogadoOrientador
    AgentDefinition <|-- DocumentadorProcessual
Loading

State diagram for Documentador Processual dual-mode behavior

stateDiagram-v2
    [*] --> AguardandoContexto

    state AguardandoContexto {
        [*] --> SemModoDefinido
        SemModoDefinido --> ModoProcessual : Apenas mapeador_processual
        SemModoDefinido --> ModoJuridico : Inclui leitor_de_pecas
    }

    state ModoProcessual {
        [*] --> MontandoRelatorioProcessual
        MontandoRelatorioProcessual --> SalvandoArquivoProcessual : Write relatorio-[processo-slug]-[AAAA-MM-DD].md
        SalvandoArquivoProcessual --> QG_AP_004_Processual : Confirma uso de Write
        QG_AP_004_Processual --> [*]
    }

    state ModoJuridico {
        [*] --> MontandoRelatorioJuridico
        MontandoRelatorioJuridico --> AdicionandoBlocoCitacoes : Anexa bloco citacoes
        AdicionandoBlocoCitacoes --> SalvandoArquivoJuridico : Write relatorio-[processo-slug]-[AAAA-MM-DD].md
        SalvandoArquivoJuridico --> QG_AP_004_Juridico : Confirma uso de Write
        QG_AP_004_Juridico --> [*]
    }
Loading

File-Level Changes

Change Details Files
Introduce tiered multi-agent architecture with specialized intake, execution, and synthesis agents.
  • Replace previous generic mapeador, avaliador, and documentador agents with more detailed, protocol-driven definitions for MAEADOR_PROCESSUAL and AVALIADOR_PROCESSUAL including strict output formats and VETO rules.
  • Add Tier 1 execution agents (LEITOR_DE_PECAS, PESQUISADOR_JURIDICO, ESTRATEGISTA_PROCESSUAL, ADVOGADO_ORIENTADOR) focused on legal document extraction, jurisprudence research, strategic scenario analysis, and action planning.
  • Add DOCUMENTADOR_PROCESSUAL synthesis agent with dual-mode behavior (MODO_PROCESSUAL vs MODO_JURIDICO), mandatory file saving via Write, and a standardized filename pattern and citations block.
squads/analista-processual/squad.py
Replace simple coordinator prompt with an orchestrator system prompt that classifies use cases and enforces quality gates.
  • Define explicit use-case classifier (UC-AP-001 to UC-AP-004) routing different user intents to specific agent pipelines, including parallel execution where applicable.
  • Add quality gates (QG-AP-001 through QG-AP-004) to enforce UC classification, structured mapping, maturity scoring, and Write confirmation by the documentador agent.
  • Add orchestration rules prohibiting the orchestrator from doing analysis itself and requiring explicit agent usage and document persistence.
squads/analista-processual/squad.py
Expand tool usage and capabilities for agents and orchestrator.
  • Extend allowed_tools in the squad runner to include Grep and WebSearch in addition to Read, Write, Glob, and Agent.
  • Configure each agent with a tailored tool set (e.g., LEITOR_DE_PECAS using Read/Glob/Grep, PESQUISADOR_JURIDICO using WebSearch, DOCUMENTADOR_PROCESSUAL using Write and filesystem tools).
squads/analista-processual/squad.py
Refine the runner interface and error handling for CLI usage.
  • Rename run_squad parameter from processo to input_text, adjust print labels from “Relatório Final” to “Resultado Final”, and update anyio.run invocation accordingly.
  • Change CLI entrypoint to prefer argv input, read stdin otherwise, and emit a usage message plus non-zero exit when no input is provided.
squads/analista-processual/squad.py
Add module entrypoint to allow running the squad via python -m.
  • Introduce main.py in squads/analista-processual to delegate to the main() function in squad.py so the module can be executed as python -m squads.analista-processual.
squads/analista-processual/__main__.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - encontrei 3 problemas e deixei alguns comentários em alto nível:

  • A constante do agente mapeador-processual está nomeada de forma inconsistente (MAEADOR_PROCESSUAL vs MAEDADOR_PROCESSUAL vs mapeador-processual), o que vai gerar um NameError em tempo de execução; alinhe o nome da constante e o seu uso no dicionário agents.
  • Dado os QUALITY GATES mais rigorosos descritos no system prompt (especialmente o QG-AP-004 sobre o uso de Write), considere adicionar uma pequena verificação programática em torno do ResultMessage final ou da camada de tooling para validar que o documentador-processual de fato invocou o Write, em vez de depender apenas das instruções de prompt.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- A constante do agente `mapeador-processual` está nomeada de forma inconsistente (`MAEADOR_PROCESSUAL` vs `MAEDADOR_PROCESSUAL` vs `mapeador-processual`), o que vai gerar um NameError em tempo de execução; alinhe o nome da constante e o seu uso no dicionário `agents`.
- Dado os QUALITY GATES mais rigorosos descritos no system prompt (especialmente o QG-AP-004 sobre o uso de Write), considere adicionar uma pequena verificação programática em torno do `ResultMessage` final ou da camada de tooling para validar que o `documentador-processual` de fato invocou o Write, em vez de depender apenas das instruções de prompt.

## Individual Comments

### Comment 1
<location path="squads/analista-processual/squad.py" line_range="32-41" />
<code_context>
+MAEADOR_PROCESSUAL = AgentDefinition(
</code_context>
<issue_to_address>
**issue (bug_risk):** A nomenclatura inconsistente do agente mapeador vai causar um NameError em tempo de execução.

O agente é definido como `MAEADOR_PROCESSUAL`, mas o mapeamento `agents` utiliza `MAEDADOR_PROCESSUAL`, então o módulo vai levantar um NameError ao construir o dicionário. Por favor, escolha um nome único, consistente e correto (por exemplo, `MAPEADOR_PROCESSUAL`) tanto para a constante quanto para a sua entrada em `agents`.
</issue_to_address>

### Comment 2
<location path="squads/analista-processual/squad.py" line_range="164" />
<code_context>
+        "2. ANÁLISE DE RISCOS E OPORTUNIDADES:\n"
+        "   - Riscos jurídicos (prescrição, preclusão, nulidades)\n"
+        "   - Oportunidades processuais (tutelas, reconvenção, etc.)\n\n"
+        "3. CENAÁRIOS (3 obrigatórios com %):\n"
+        "   - Otimista: [descrição] — Probabilidade: X%\n"
+        "   - Realista: [descrição] — Probabilidade: X%\n"
</code_context>
<issue_to_address>
**nitpick (typo):** Erro de digitação na palavra “CENAÁRIOS” dentro do prompt do estrategista.

Como este é um texto de prompt exibido ao usuário, corrija a grafia para `CENÁRIOS` para manter a orientação clara e bem acabada.

```suggestion
        "3. CENÁRIOS (3 obrigatórios com %):\n"
```
</issue_to_address>

### Comment 3
<location path="squads/analista-processual/squad.py" line_range="127-129" />
<code_context>
+    prompt=(
+        "Você é um pesquisador jurídico especializado em jurisprudência brasileira.\n\n"
+        "FONTES AUTORIZADAS:\n"
+        "- stf.jus.br (controle constitucional, reperucussão geral)\n"
+        "- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
+        "- tst.jus.br (matéria trabalhista)\n"
</code_context>
<issue_to_address>
**nitpick (typo):** Pequeno erro de grafia em “reperucussão geral” dentro do prompt do pesquisador.

A grafia correta é `repercussão geral`. Atualizar isso deixa o prompt mais claro e evita que o termo incorreto seja reutilizado.

```suggestion
        "FONTES AUTORIZADAS:\n"
        "- stf.jus.br (controle constitucional, repercussão geral)\n"
        "- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
```
</issue_to_address>

Fix all in Cursor


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Ajude-me a ser mais útil! Por favor, clique em 👍 ou 👎 em cada comentário e eu usarei esse feedback para melhorar as suas revisões.
Original comment in English

Hey - I've found 3 issues, and left some high level feedback:

  • The mapeador-processual agent constant is inconsistently named (MAEADOR_PROCESSUAL vs MAEDADOR_PROCESSUAL vs mapeador-processual), which will raise a NameError at runtime; align the constant name and its usage in the agents dict.
  • Given the stricter QUALITY GATES described in the system prompt (especially QG-AP-004 around Write usage), consider adding a small programmatic check around the final ResultMessage or tooling layer to validate that documentador-processual actually invoked Write rather than relying solely on prompt instructions.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `mapeador-processual` agent constant is inconsistently named (`MAEADOR_PROCESSUAL` vs `MAEDADOR_PROCESSUAL` vs `mapeador-processual`), which will raise a NameError at runtime; align the constant name and its usage in the `agents` dict.
- Given the stricter QUALITY GATES described in the system prompt (especially QG-AP-004 around Write usage), consider adding a small programmatic check around the final `ResultMessage` or tooling layer to validate that `documentador-processual` actually invoked Write rather than relying solely on prompt instructions.

## Individual Comments

### Comment 1
<location path="squads/analista-processual/squad.py" line_range="32-41" />
<code_context>
+MAEADOR_PROCESSUAL = AgentDefinition(
</code_context>
<issue_to_address>
**issue (bug_risk):** Inconsistent naming of the mapeador agent will cause a NameError at runtime.

The agent is defined as `MAEADOR_PROCESSUAL`, but the `agents` mapping uses `MAEDADOR_PROCESSUAL`, so the module will raise a NameError when building the dict. Please choose one consistent, correct name (e.g. `MAPEADOR_PROCESSUAL`) for both the constant and its entry in `agents`.
</issue_to_address>

### Comment 2
<location path="squads/analista-processual/squad.py" line_range="164" />
<code_context>
+        "2. ANÁLISE DE RISCOS E OPORTUNIDADES:\n"
+        "   - Riscos jurídicos (prescrição, preclusão, nulidades)\n"
+        "   - Oportunidades processuais (tutelas, reconvenção, etc.)\n\n"
+        "3. CENAÁRIOS (3 obrigatórios com %):\n"
+        "   - Otimista: [descrição] — Probabilidade: X%\n"
+        "   - Realista: [descrição] — Probabilidade: X%\n"
</code_context>
<issue_to_address>
**nitpick (typo):** Typo in the word “CENAÁRIOS” inside the strategist prompt.

Since this is user-facing prompt text, please correct the spelling to `CENÁRIOS` to keep the guidance clear and polished.

```suggestion
        "3. CENÁRIOS (3 obrigatórios com %):\n"
```
</issue_to_address>

### Comment 3
<location path="squads/analista-processual/squad.py" line_range="127-129" />
<code_context>
+    prompt=(
+        "Você é um pesquisador jurídico especializado em jurisprudência brasileira.\n\n"
+        "FONTES AUTORIZADAS:\n"
+        "- stf.jus.br (controle constitucional, reperucussão geral)\n"
+        "- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
+        "- tst.jus.br (matéria trabalhista)\n"
</code_context>
<issue_to_address>
**nitpick (typo):** Minor spelling error in “reperucussão geral” within the researcher prompt.

It should be spelled `repercussão geral`. Updating this keeps the prompt clear and prevents the incorrect term from being reused.

```suggestion
        "FONTES AUTORIZADAS:\n"
        "- stf.jus.br (controle constitucional, repercussão geral)\n"
        "- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
```
</issue_to_address>

Fix all in Cursor


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +32 to +41
MAEADOR_PROCESSUAL = AgentDefinition(
description=(
"Especialista em mapeamento de processos. "
"Identifica todas as etapas, atores, entradas, saídas e decisões "
"de um processo e os organiza em um fluxo claro e sequencial."
"Especialista em mapeamento de processos organizacionais e jurídicos. "
"Recebe a descrição de um processo e produz tabela estruturada com: "
"etapas em ordem cronológica, ator responsável, entradas (inputs), "
"saídas (outputs), critério de conclusão e pontos de decisão (gateways). "
"Não avalia riscos — apenas mapeia o estado atual."
),
prompt=(
"Você é um analista de processos sênior especializado em mapeamento. "
"Dado um processo descrito pelo usuário:\n"
"1. Liste todas as etapas na ordem correta.\n"
"2. Para cada etapa, indique: ator responsável, entradas necessárias, "
"saídas produzidas e critérios de conclusão.\n"
"3. Identifique pontos de decisão (gateways) e ramificações.\n"
"4. Represente o fluxo em formato textual estruturado (pseudo-BPMN)."
"Você é um especialista sênior em mapeamento e modelagem de processos."
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): A nomenclatura inconsistente do agente mapeador vai causar um NameError em tempo de execução.

O agente é definido como MAEADOR_PROCESSUAL, mas o mapeamento agents utiliza MAEDADOR_PROCESSUAL, então o módulo vai levantar um NameError ao construir o dicionário. Por favor, escolha um nome único, consistente e correto (por exemplo, MAPEADOR_PROCESSUAL) tanto para a constante quanto para a sua entrada em agents.

Fix in Cursor

Original comment in English

issue (bug_risk): Inconsistent naming of the mapeador agent will cause a NameError at runtime.

The agent is defined as MAEADOR_PROCESSUAL, but the agents mapping uses MAEDADOR_PROCESSUAL, so the module will raise a NameError when building the dict. Please choose one consistent, correct name (e.g. MAPEADOR_PROCESSUAL) for both the constant and its entry in agents.

Fix in Cursor

"2. ANÁLISE DE RISCOS E OPORTUNIDADES:\n"
" - Riscos jurídicos (prescrição, preclusão, nulidades)\n"
" - Oportunidades processuais (tutelas, reconvenção, etc.)\n\n"
"3. CENAÁRIOS (3 obrigatórios com %):\n"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick (typo): Erro de digitação na palavra “CENAÁRIOS” dentro do prompt do estrategista.

Como este é um texto de prompt exibido ao usuário, corrija a grafia para CENÁRIOS para manter a orientação clara e bem acabada.

Suggested change
"3. CENAÁRIOS (3 obrigatórios com %):\n"
"3. CENÁRIOS (3 obrigatórios com %):\n"

Fix in Cursor

Original comment in English

nitpick (typo): Typo in the word “CENAÁRIOS” inside the strategist prompt.

Since this is user-facing prompt text, please correct the spelling to CENÁRIOS to keep the guidance clear and polished.

Suggested change
"3. CENAÁRIOS (3 obrigatórios com %):\n"
"3. CENÁRIOS (3 obrigatórios com %):\n"

Fix in Cursor

Comment on lines +127 to +129
"FONTES AUTORIZADAS:\n"
"- stf.jus.br (controle constitucional, reperucussão geral)\n"
"- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick (typo): Pequeno erro de grafia em “reperucussão geral” dentro do prompt do pesquisador.

A grafia correta é repercussão geral. Atualizar isso deixa o prompt mais claro e evita que o termo incorreto seja reutilizado.

Suggested change
"FONTES AUTORIZADAS:\n"
"- stf.jus.br (controle constitucional, reperucussão geral)\n"
"- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
"FONTES AUTORIZADAS:\n"
"- stf.jus.br (controle constitucional, repercussão geral)\n"
"- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"

Fix in Cursor

Original comment in English

nitpick (typo): Minor spelling error in “reperucussão geral” within the researcher prompt.

It should be spelled repercussão geral. Updating this keeps the prompt clear and prevents the incorrect term from being reused.

Suggested change
"FONTES AUTORIZADAS:\n"
"- stf.jus.br (controle constitucional, reperucussão geral)\n"
"- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"
"FONTES AUTORIZADAS:\n"
"- stf.jus.br (controle constitucional, repercussão geral)\n"
"- stj.jus.br (recurso especial, súmulas, teses repetitivas)\n"

Fix in Cursor

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the Analista Processual squad into a 3-tier pipeline for Brazilian organizational and legal process analysis. It introduces specialized agents for document extraction, legal research, and strategic planning, governed by a new orchestrator logic. Feedback identifies a critical import error caused by invalid package naming, multiple typos in variable definitions that will lead to runtime failures, and a regression in CLI usability where the interactive prompt was removed.

@@ -0,0 +1,4 @@
"""Allow running as: python -m squads.analista-processual"""
from squads.analista_processual.squad import main
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Esta instrução de importação causará um ImportError em tempo de execução. O caminho squads.analista_processual implica um diretório chamado analista_processual, mas o diretório real no repositório é analista-processual. Nomes de pacotes Python não podem conter hifens. Para que o módulo possa ser executado com python -m, o diretório analista-processual deve ser renomeado para um nome de pacote válido (por exemplo, analista_processual), e esta instrução de importação provavelmente precisará ser ajustada.

# ---------------------------------------------------------------------------

MAPEADOR = AgentDefinition(
MAEADOR_PROCESSUAL = AgentDefinition(
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Parece haver um erro de digitação no nome desta variável. Com base na função do agente ("mapeador"), o nome pretendido é provavelmente MAPEADOR_PROCESSUAL. Este erro, combinado com outro no seu uso na linha 312, causará um NameError em tempo de execução.

Suggested change
MAEADOR_PROCESSUAL = AgentDefinition(
MAPEADOR_PROCESSUAL = AgentDefinition(

"mapeador": MAPEADOR,
"avaliador": AVALIADOR,
"documentador": DOCUMENTADOR,
"mapeador-processual": MAEDADOR_PROCESSUAL,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Esta linha irá gerar um NameError porque a variável MAEDADOR_PROCESSUAL não está definida. Parece ser um erro de digitação da variável definida na linha 32 (MAEADOR_PROCESSUAL), que por sua vez também parece ser um erro de digitação para MAPEADOR_PROCESSUAL. Por favor, corrija tanto a definição na linha 32 quanto o uso aqui.

Suggested change
"mapeador-processual": MAEDADOR_PROCESSUAL,
"mapeador-processual": MAPEADOR_PROCESSUAL,

Comment on lines 333 to +336
if len(sys.argv) > 1:
processo = " ".join(sys.argv[1:])
elif not sys.stdin.isatty():
processo = sys.stdin.read().strip()
input_text = " ".join(sys.argv[1:])
else:
print("Descreva o processo que deseja analisar (Ctrl+D para finalizar):")
processo = sys.stdin.read().strip()
input_text = sys.stdin.read().strip()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

A implementação anterior lidava com o modo interativo de forma mais elegante, verificando sys.stdin.isatty() e exibindo um prompt. Esta alteração remove essa lógica, fazendo com que o script pareça travar sem nenhuma mensagem quando executado interativamente sem argumentos. Isso é uma regressão na usabilidade. Considere restaurar a verificação de um terminal interativo.

    if len(sys.argv) > 1:
        input_text = " ".join(sys.argv[1:])
    elif not sys.stdin.isatty():
        input_text = sys.stdin.read().strip()
    else:
        print("Descreva o processo que deseja analisar (Ctrl+D para finalizar):", file=sys.stderr)
        input_text = sys.stdin.read().strip()

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4482396688

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"mapeador": MAPEADOR,
"avaliador": AVALIADOR,
"documentador": DOCUMENTADOR,
"mapeador-processual": MAEDADOR_PROCESSUAL,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0 Badge Use the defined mapeador constant in agent registry

The agents dict references MAEDADOR_PROCESSUAL, but the only constant defined above is MAEADOR_PROCESSUAL. When run_squad() builds ClaudeAgentOptions, this unresolved name raises NameError, so the squad cannot execute any request. Point this entry to the declared constant (or rename consistently) so startup succeeds.

Useful? React with 👍 / 👎.

@@ -0,0 +1,4 @@
"""Allow running as: python -m squads.analista-processual"""
from squads.analista_processual.squad import main
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Import main from the package that actually exists

__main__.py imports squads.analista_processual.squad, but this commit creates squads/analista-processual/ and does not add a squads/analista_processual/ package. As a result, invoking python -m squads.analista-processual will hit ModuleNotFoundError at the new entrypoint instead of running the squad.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

"mapeador": MAPEADOR,
"avaliador": AVALIADOR,
"documentador": DOCUMENTADOR,
"mapeador-processual": MAEDADOR_PROCESSUAL,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mismatched variable name causes runtime NameError crash

High Severity

The mapeador agent definition is assigned to MAEADOR_PROCESSUAL (missing "P"), but the agents dictionary references MAEDADOR_PROCESSUAL (a different misspelling with an extra "D"). These are two distinct identifiers, so run_squad will crash with a NameError every time it's called. The intended name is likely MAPEADOR_PROCESSUAL.

Additional Locations (1)
Fix in Cursor Fix in Web

"Você é um especialista em síntese e documentação de relatórios processuais.\n\n"
"DETECÇÃO DE MODO:\n"
"- MODO_JURIDICO: se @leitor-de-pecas foi ativado (há extrações de peças)\n"
"- MODO_PROCESSUAL: se apenas @mapeador e @avaliador foram ativados\n\n"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documentador mode detection incompatible with UC-AP-003 routing

Medium Severity

The orchestrator routes UC-AP-003 (Análise Estratégica) to @documentador-processual with MODO_JURIDICO, but the documentador's own mode detection logic triggers MODO_JURIDICO only when @leitor-de-pecas was activated — which UC-AP-003 never activates. The MODO_PROCESSUAL condition also doesn't match since it expects "only mapeador and avaliador." This leaves UC-AP-003 in an undefined detection state, risking the wrong report format for strategic analyses.

Additional Locations (1)
Fix in Cursor Fix in Web

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 28, 2026

📝 Walkthrough

Walkthrough

A module entrypoint is added to enable direct execution of the analista-processual squad. The squad.py undergoes substantial restructuring, implementing a 3-tier architecture with intake, execution, and synthesis phases. Multiple agents are reorganized and renamed, tooling constraints are updated per agent, and a new system prompt orchestrates use-case classification and agent routing.

Changes

Cohort / File(s) Summary
Module Entrypoint
squads/analista-processual/__main__.py
New module execution entrypoint that imports and invokes main() from squad module, enabling python -m squads.analista-processual execution.
Squad Architecture & Pipeline
squads/analista-processual/squad.py
Restructured to implement a 3-tier pipeline: Tier 0 agents (mapeador-processual, avaliador-processual), Tier 1 agents (leitor-de-pecas, pesquisador-juridico, estrategista-processual, advogado-orientador), and documentador-processual. New system prompt classifies use cases and routes execution; function parameter renamed from processo to input_text; agent tooling and orchestration logic expanded.

Sequence Diagram

sequenceDiagram
    participant User
    participant Orchestrator
    participant T0_Mapeador as T0: Mapeador
    participant T1_Agents as T1: Juridical Agents
    participant Documentador
    participant Output

    User->>Orchestrator: input_text
    Orchestrator->>Orchestrator: Classify use case via SYSTEM_PROMPT
    
    alt Jurisprudence Query
        Orchestrator->>T1_Agents: Route to Pesquisador-Juridico
        T1_Agents-->>Orchestrator: jurisprudence results
        Orchestrator-->>Output: Return directly
    else Standard Processing
        Orchestrator->>T0_Mapeador: Execute Tier 0 mapping
        T0_Mapeador-->>Orchestrator: intake analysis
        Orchestrator->>T1_Agents: Execute Tier 1 agents
        T1_Agents-->>Orchestrator: juridical analysis
        Orchestrator->>Documentador: Route to synthesis
        Documentador-->>Output: Resultado Final
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A squad of agents marches three by three,
Mapping cases, seeking jurisprudence with glee,
With mapeador, pesquisador, and strategist wise,
The documentador weaves their findings in ties,
A three-tier dance of processual delight! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Refactor Analista Processual Squad: 3-tier architecture with 7 specialized agents' accurately captures the main change: a substantial architectural refactoring from a simpler agent model to a three-tier pipeline with seven specialized agents. The title is specific, concise, and directly reflects the primary change in both files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/aiox-implementation-KJDTE

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@squads/analista-processual/__main__.py`:
- Around line 2-4: The entrypoint imports main using a top-level module path
that doesn't match the package name; change the import to a relative import so
Python resolves the sibling module inside this package (replace the current
import of main from squads.analista_processual.squad with a relative import that
pulls main from .squad and then call main()).

In `@squads/analista-processual/squad.py`:
- Around line 220-223: The DOCUMENTADOR_PROCESSUAL mode selection currently only
sets MODO_JURIDICO when `@leitor-de-pecas` ran, which misses UC-AP-003; update the
routing logic that computes the documentador mode (the code that selects between
MODO_JURIDICO and MODO_PROCESSUAL) so that if the use case id equals "UC-AP-003"
it forces DOCUMENTADOR_PROCESSUAL -> MODO_JURIDICO regardless of whether
`@leitor-de-pecas` executed; apply the same change to the other identical
selection block (the later occurrence that mirrors lines 278-282) so both
branches consistently choose MODO_JURIDICO for UC-AP-003 and thus include the
required citacoes block.
- Line 32: The identifier for the mapeador-processual agent is misspelled: the
definition uses MAEADOR_PROCESSUAL but the reference that builds
ClaudeAgentOptions expects MAEDADOR_PROCESSUAL; update either the declaration or
the reference to use the same name consistently (preferably rename the
declaration to MAEDADOR_PROCESSUAL to match the reference used when constructing
ClaudeAgentOptions) so the symbol resolves at runtime.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 03cff67d-62b5-40fd-86e9-6a3e63851b14

📥 Commits

Reviewing files that changed from the base of the PR and between 0fffc28 and 4482396.

📒 Files selected for processing (3)
  • squads/analista-processual/__init__.py
  • squads/analista-processual/__main__.py
  • squads/analista-processual/squad.py

Comment on lines +2 to +4
from squads.analista_processual.squad import main

main()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify which analista-processual package paths actually exist in the repo.
# Expected: the executed package path should match the import target.
fd -t d 'analista[-_]processual' squads
fd -t f '__main__\.py$' squads
fd -t f 'squad\.py$' squads
rg -n 'from squads\.analista_processual\.squad import main|from \.squad import main' squads

Repository: felippepestana/Skill

Length of output: 314


Import main from the current package.

This entrypoint's directory is squads/analista-processual, but Line 2 imports from squads.analista_processual.squad (underscore-separated). Python cannot resolve this path since the actual directory uses hyphens. Running python -m squads.analista-processual fails before main() executes. Use a relative import to match the sibling squad entrypoint.

Fix
-from squads.analista_processual.squad import main
+from .squad import main
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@squads/analista-processual/__main__.py` around lines 2 - 4, The entrypoint
imports main using a top-level module path that doesn't match the package name;
change the import to a relative import so Python resolves the sibling module
inside this package (replace the current import of main from
squads.analista_processual.squad with a relative import that pulls main from
.squad and then call main()).

# ---------------------------------------------------------------------------

MAPEADOR = AgentDefinition(
MAEADOR_PROCESSUAL = AgentDefinition(
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the declaration/use mismatch for the mapeador agent constant.
# Expected: a single consistent identifier. Mixed results confirm the typo.
rg -n 'MAEADOR_PROCESSUAL|MAEDADOR_PROCESSUAL|MAPEADOR_PROCESSUAL' squads/analista-processual/squad.py

Repository: felippepestana/Skill

Length of output: 164


Fix the identifier mismatch for the mapeador-processual agent.

Line 32 declares MAEADOR_PROCESSUAL, but line 312 references MAEDADOR_PROCESSUAL—a NameError at runtime when ClaudeAgentOptions is built.

Fix
-MAEADOR_PROCESSUAL = AgentDefinition(
+MAPEADOR_PROCESSUAL = AgentDefinition(
-            "mapeador-processual": MAEDADOR_PROCESSUAL,
+            "mapeador-processual": MAPEADOR_PROCESSUAL,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@squads/analista-processual/squad.py` at line 32, The identifier for the
mapeador-processual agent is misspelled: the definition uses MAEADOR_PROCESSUAL
but the reference that builds ClaudeAgentOptions expects MAEDADOR_PROCESSUAL;
update either the declaration or the reference to use the same name consistently
(preferably rename the declaration to MAEDADOR_PROCESSUAL to match the reference
used when constructing ClaudeAgentOptions) so the symbol resolves at runtime.

Comment on lines +220 to +223
"DETECÇÃO DE MODO:\n"
"- MODO_JURIDICO: se @leitor-de-pecas foi ativado (há extrações de peças)\n"
"- MODO_PROCESSUAL: se apenas @mapeador e @avaliador foram ativados\n\n"
"=== MODO_PROCESSUAL ===\n"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Make DOCUMENTADOR_PROCESSUAL mode selection cover UC-AP-003.

UC-AP-003 is routed to MODO_JURIDICO, but the documentador only enters that mode when @leitor-de-pecas ran. In this path neither documented branch matches cleanly, so the final report can use the wrong template or miss the mandatory citacoes block.

One way to make the routing consistent
-        "- MODO_JURIDICO: se `@leitor-de-pecas` foi ativado (há extrações de peças)\n"
-        "- MODO_PROCESSUAL: se apenas `@mapeador` e `@avaliador` foram ativados\n\n"
+        "- MODO_JURIDICO: se qualquer agente jurídico foi ativado "
+        "(`@leitor-de-pecas`, `@pesquisador-juridico`, `@estrategista-processual` ou "
+        "@advogado-orientador)\n"
+        "- MODO_PROCESSUAL: se apenas `@mapeador-processual` e "
+        "@avaliador-processual foram ativados\n\n"

Also applies to: 278-282

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@squads/analista-processual/squad.py` around lines 220 - 223, The
DOCUMENTADOR_PROCESSUAL mode selection currently only sets MODO_JURIDICO when
`@leitor-de-pecas` ran, which misses UC-AP-003; update the routing logic that
computes the documentador mode (the code that selects between MODO_JURIDICO and
MODO_PROCESSUAL) so that if the use case id equals "UC-AP-003" it forces
DOCUMENTADOR_PROCESSUAL -> MODO_JURIDICO regardless of whether `@leitor-de-pecas`
executed; apply the same change to the other identical selection block (the
later occurrence that mirrors lines 278-282) so both branches consistently
choose MODO_JURIDICO for UC-AP-003 and thus include the required citacoes block.

@felippepestana felippepestana self-assigned this Mar 29, 2026
@felippepestana felippepestana merged commit dd71a1e into main Mar 30, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant