argos-cli 0.3.1__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. {argos_cli-0.3.1/argos_cli.egg-info → argos_cli-0.4.0}/PKG-INFO +6 -2
  2. {argos_cli-0.3.1 → argos_cli-0.4.0}/README.md +1 -1
  3. argos_cli-0.4.0/argos/adapters/_libreoffice_worker.py +211 -0
  4. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/ai.py +42 -15
  5. argos_cli-0.4.0/argos/adapters/comunicacao.py +311 -0
  6. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/docx_pdf.py +481 -25
  7. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/report_publication.py +16 -3
  8. argos_cli-0.4.0/argos/adapters/xlsx_style.py +199 -0
  9. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/audit_result.py +16 -5
  10. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/catalog.py +130 -5
  11. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/audit.py +233 -14
  12. argos_cli-0.4.0/argos/engines/comunicacao.py +145 -0
  13. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/evaluation.py +155 -42
  14. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/matrix.py +25 -8
  15. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/report_document.py +17 -2
  16. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/reports.py +50 -3
  17. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/survey.py +251 -46
  18. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/executions.py +6 -1
  19. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/findings_matrix.py +18 -0
  20. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/fingerprints.py +52 -19
  21. argos_cli-0.4.0/argos/map_columns.py +443 -0
  22. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/project.py +8 -0
  23. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +1 -0
  24. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +4 -1
  25. argos_cli-0.4.0/argos/resources/logo-tce-rj.png +0 -0
  26. argos_cli-0.4.0/argos/resources/template-base-estilos-sigiloso.docx +0 -0
  27. argos_cli-0.4.0/argos/resources/template-base-estilos.docx +0 -0
  28. argos_cli-0.4.0/argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  29. argos_cli-0.4.0/argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  30. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/status.py +68 -24
  31. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/store.py +101 -6
  32. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/tui_models.py +2 -0
  33. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/version.py +1 -1
  34. {argos_cli-0.3.1 → argos_cli-0.4.0/argos_cli.egg-info}/PKG-INFO +6 -2
  35. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos_cli.egg-info/SOURCES.txt +11 -0
  36. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos_cli.egg-info/requires.txt +5 -0
  37. {argos_cli-0.3.1 → argos_cli-0.4.0}/pyproject.toml +6 -0
  38. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/README.md +4 -1
  39. argos_cli-0.4.0/skills/escrever-relatorio-auditoria/SKILL.md +67 -0
  40. argos_cli-0.4.0/skills/escrever-relatorio-auditoria/agents/openai.yaml +4 -0
  41. argos_cli-0.4.0/skills/escrever-relatorio-auditoria/references/linguagem-simples.md +163 -0
  42. argos_cli-0.4.0/skills/escrever-relatorio-auditoria/references/report-markup.md +405 -0
  43. argos_cli-0.4.0/skills/escrever-relatorio-auditoria/scripts/check_report_markup.py +314 -0
  44. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_attachments.py +39 -0
  45. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_audit_engine.py +192 -0
  46. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_cli_and_tui.py +9 -5
  47. argos_cli-0.4.0/tests/test_comunicacao.py +195 -0
  48. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_core_and_store.py +8 -2
  49. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_docx_pdf.py +133 -2
  50. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_essential_workflow.py +5 -0
  51. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_evaluation_engine.py +228 -0
  52. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_index_engine.py +35 -0
  53. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_init_generic.py +1 -1
  54. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_matrix_engine.py +46 -0
  55. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script_outputs_integration.py +42 -0
  56. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_project_templates.py +223 -2
  57. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_reports_engine.py +129 -0
  58. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_survey_engine.py +210 -0
  59. argos_cli-0.3.1/argos/adapters/_libreoffice_worker.py +0 -111
  60. argos_cli-0.3.1/argos/resources/template-base-estilos-sigiloso.docx +0 -0
  61. argos_cli-0.3.1/argos/resources/template-base-estilos.docx +0 -0
  62. argos_cli-0.3.1/argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  63. argos_cli-0.3.1/argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  64. {argos_cli-0.3.1 → argos_cli-0.4.0}/MANIFEST.in +0 -0
  65. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/__init__.py +0 -0
  66. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/__main__.py +0 -0
  67. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/__init__.py +0 -0
  68. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/ai_remote.py +0 -0
  69. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/attachment_conversion.py +0 -0
  70. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/capabilities.py +0 -0
  71. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/chart_render.py +0 -0
  72. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/limesurvey.py +0 -0
  73. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/model_call.py +0 -0
  74. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/url_fetch.py +0 -0
  75. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/adapters/xlsx.py +0 -0
  76. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/analytics.py +0 -0
  77. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/assets.py +0 -0
  78. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/booleans.py +0 -0
  79. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/cli.py +0 -0
  80. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/contracts.py +0 -0
  81. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/core.py +0 -0
  82. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/__init__.py +0 -0
  83. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/adjustments.py +0 -0
  84. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/analytics.py +0 -0
  85. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/index.py +0 -0
  86. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/matrix_html.py +0 -0
  87. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/engines/model_request.py +0 -0
  88. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/envfile.py +0 -0
  89. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/errors.py +0 -0
  90. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/evidence_staging.py +0 -0
  91. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/index_dsl.py +0 -0
  92. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/matrix_markdown.py +0 -0
  93. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/matrix_widths.py +0 -0
  94. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/pipeline.py +0 -0
  95. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/products.py +0 -0
  96. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/progress.py +0 -0
  97. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/report_config.py +0 -0
  98. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +0 -0
  99. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/anexo-evidencias-base.docx +0 -0
  100. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/argos-index-dsl-v1.schema.json +0 -0
  101. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/argos-report-config-v1.schema.json +0 -0
  102. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/diretrizes-projeto.md +0 -0
  103. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/env.example +0 -0
  104. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_achados_boilerplate.md +0 -0
  105. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_achados_draft.md +0 -0
  106. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_achados_larguras_v1_3.md +0 -0
  107. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_achados_v1_3.md +0 -0
  108. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_planejamento_boilerplate.md +0 -0
  109. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +0 -0
  110. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/exemplos/matriz_planejamento_v1_3.md +0 -0
  111. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/resources/template-matriz-planejamento.docx +0 -0
  112. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/response_profiles.py +0 -0
  113. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/scheduler.py +0 -0
  114. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/survey_collection.py +0 -0
  115. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/telemetry.py +0 -0
  116. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/tui.py +0 -0
  117. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/tui.tcss +0 -0
  118. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/tui_path.py +0 -0
  119. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos/tui_widgets.py +0 -0
  120. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos_cli.egg-info/dependency_links.txt +0 -0
  121. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos_cli.egg-info/entry_points.txt +0 -0
  122. {argos_cli-0.3.1 → argos_cli-0.4.0}/argos_cli.egg-info/top_level.txt +0 -0
  123. {argos_cli-0.3.1 → argos_cli-0.4.0}/build_hooks.py +0 -0
  124. {argos_cli-0.3.1 → argos_cli-0.4.0}/setup.cfg +0 -0
  125. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/criar-matriz-planejamento/SKILL.md +0 -0
  126. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/elaborar-survey-limesurvey/SKILL.md +0 -0
  127. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/operar-argos/SKILL.md +0 -0
  128. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/verificar-diretrizes-fiscalizacao/SKILL.md +0 -0
  129. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +0 -0
  130. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +0 -0
  131. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +0 -0
  132. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +0 -0
  133. {argos_cli-0.3.1 → argos_cli-0.4.0}/skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +0 -0
  134. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_additional_referrals.py +0 -0
  135. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_adjustments.py +0 -0
  136. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_ai_remote.py +0 -0
  137. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_charts.py +0 -0
  138. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_config.py +0 -0
  139. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_e2e.py +0 -0
  140. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_evaluations.py +0 -0
  141. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_facts.py +0 -0
  142. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_manifest.py +0 -0
  143. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_analytics_measures.py +0 -0
  144. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_assets_manifest.py +0 -0
  145. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_audit_result_format.py +0 -0
  146. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_avaliar_analytics_e2e.py +0 -0
  147. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_avaliar_fases.py +0 -0
  148. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_capabilities.py +0 -0
  149. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_documento.py +0 -0
  150. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_envfile.py +0 -0
  151. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_evidence_staging.py +0 -0
  152. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_matrix_html.py +0 -0
  153. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_model_call.py +0 -0
  154. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_model_request.py +0 -0
  155. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script.py +0 -0
  156. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script_e2e.py +0 -0
  157. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script_fingerprint.py +0 -0
  158. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script_integration.py +0 -0
  159. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script_outputs.py +0 -0
  160. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_pipeline_script_run.py +0 -0
  161. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_progress.py +0 -0
  162. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_relatorio_analises.py +0 -0
  163. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_report_assets.py +0 -0
  164. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_report_document.py +0 -0
  165. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_report_parity_tools.py +0 -0
  166. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_response_profiles.py +0 -0
  167. {argos_cli-0.3.1 → argos_cli-0.4.0}/tests/test_survey_collection.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: argos-cli
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: Núcleo genérico in-process para execução de auditorias
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -18,6 +18,7 @@ Requires-Dist: twine<7,>=6; extra == "dev"
18
18
  Requires-Dist: virtualenv>=21.7.13; extra == "dev"
19
19
  Provides-Extra: workbooks
20
20
  Requires-Dist: openpyxl>=3.1; extra == "workbooks"
21
+ Requires-Dist: Pillow>=10; extra == "workbooks"
21
22
  Provides-Extra: ai
22
23
  Requires-Dist: google-genai>=1.0; extra == "ai"
23
24
  Requires-Dist: json-repair<1,>=0.30; extra == "ai"
@@ -47,7 +48,10 @@ Requires-Dist: psutil<8,>=5.9; extra == "benchmarks"
47
48
  Provides-Extra: downloads
48
49
  Requires-Dist: requests>=2.31; extra == "downloads"
49
50
  Requires-Dist: urllib3>=2.8.0; extra == "downloads"
51
+ Provides-Extra: comunicacao
52
+ Requires-Dist: audcom>=0.1.1; extra == "comunicacao"
50
53
  Provides-Extra: all
54
+ Requires-Dist: audcom>=0.1.1; extra == "all"
51
55
  Requires-Dist: openpyxl>=3.1; extra == "all"
52
56
  Requires-Dist: google-genai>=1.0; extra == "all"
53
57
  Requires-Dist: json-repair<1,>=0.30; extra == "all"
@@ -540,7 +544,7 @@ Guias e exemplos:
540
544
  - [Configurações de exemplo](docs/configuracoes/) — catálogo de avaliações, fontes do mapa, comentários do gestor e mapeamento.
541
545
  - [Exemplos de matrizes](docs/exemplos/) e [exemplos do Index DSL](docs/index-dsl-v1/exemplos/).
542
546
 
543
- `skills/` é a fonte das quatro skills distribuídas por `init` para `.agents/skills/`: `criar-matriz-planejamento`, `elaborar-survey-limesurvey`, `operar-argos` e `verificar-diretrizes-fiscalizacao`.
547
+ `skills/` é a fonte das cinco skills distribuídas por `init` para `.agents/skills/`: `criar-matriz-planejamento`, `elaborar-survey-limesurvey`, `escrever-relatorio-auditoria`, `operar-argos` e `verificar-diretrizes-fiscalizacao`.
544
548
 
545
549
  ## Desenvolvimento e verificação
546
550
 
@@ -472,7 +472,7 @@ Guias e exemplos:
472
472
  - [Configurações de exemplo](docs/configuracoes/) — catálogo de avaliações, fontes do mapa, comentários do gestor e mapeamento.
473
473
  - [Exemplos de matrizes](docs/exemplos/) e [exemplos do Index DSL](docs/index-dsl-v1/exemplos/).
474
474
 
475
- `skills/` é a fonte das quatro skills distribuídas por `init` para `.agents/skills/`: `criar-matriz-planejamento`, `elaborar-survey-limesurvey`, `operar-argos` e `verificar-diretrizes-fiscalizacao`.
475
+ `skills/` é a fonte das cinco skills distribuídas por `init` para `.agents/skills/`: `criar-matriz-planejamento`, `elaborar-survey-limesurvey`, `escrever-relatorio-auditoria`, `operar-argos` e `verificar-diretrizes-fiscalizacao`.
476
476
 
477
477
  ## Desenvolvimento e verificação
478
478
 
@@ -0,0 +1,211 @@
1
+ """Worker isolado que atualiza campos DOCX e exporta PDF pela API UNO do LibreOffice."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import subprocess
7
+ import sys
8
+ import time
9
+
10
+
11
+ def _property(uno, name: str, value):
12
+ item = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
13
+ item.Name = name
14
+ item.Value = value
15
+ return item
16
+
17
+
18
+ def _start_desktop(uno, executable: str, profile_uri: str, port: str, timeout: float):
19
+ address = f"socket,host=127.0.0.1,port={port};urp;StarOffice.ServiceManager"
20
+ command = [
21
+ executable,
22
+ "--headless",
23
+ "--norestore",
24
+ "--nodefault",
25
+ "--nofirststartwizard",
26
+ f"-env:UserInstallation={profile_uri}",
27
+ f"--accept={address}",
28
+ ]
29
+ process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
30
+ local_context = uno.getComponentContext()
31
+ resolver = local_context.ServiceManager.createInstanceWithContext(
32
+ "com.sun.star.bridge.UnoUrlResolver", local_context
33
+ )
34
+ deadline = time.monotonic() + float(timeout)
35
+ remote_context = None
36
+ last_error = None
37
+ while time.monotonic() < deadline:
38
+ try:
39
+ remote_context = resolver.resolve(
40
+ f"uno:socket,host=127.0.0.1,port={port};urp;StarOffice.ComponentContext"
41
+ )
42
+ break
43
+ except Exception as exc: # pyuno expõe exceções dinâmicas
44
+ last_error = exc
45
+ if process.poll() is not None:
46
+ break
47
+ time.sleep(0.1)
48
+ if remote_context is None:
49
+ if process.poll() is None:
50
+ process.terminate()
51
+ try:
52
+ process.wait(timeout=5)
53
+ except subprocess.TimeoutExpired:
54
+ process.kill()
55
+ process.wait(timeout=5)
56
+ raise RuntimeError("Não foi possível conectar ao LibreOffice para atualizar o sumário.") from last_error
57
+ desktop = remote_context.ServiceManager.createInstanceWithContext(
58
+ "com.sun.star.frame.Desktop", remote_context
59
+ )
60
+ return process, desktop
61
+
62
+
63
+ def _shutdown(process, desktop) -> None:
64
+ if desktop is not None:
65
+ try:
66
+ desktop.terminate()
67
+ except Exception:
68
+ pass
69
+ if process is not None:
70
+ if process.poll() is None:
71
+ process.terminate()
72
+ try:
73
+ process.wait(timeout=5)
74
+ except subprocess.TimeoutExpired:
75
+ process.kill()
76
+ process.wait(timeout=5)
77
+
78
+
79
+ def _process_toc(uno, desktop, document_path: str, pdf_path: str | None = None) -> dict:
80
+ document = None
81
+ try:
82
+ document = desktop.loadComponentFromURL(
83
+ uno.systemPathToFileUrl(document_path),
84
+ "_blank",
85
+ 0,
86
+ (
87
+ _property(uno, "Hidden", True),
88
+ _property(uno, "UpdateDocMode", 3),
89
+ _property(uno, "ReadOnly", False),
90
+ ),
91
+ )
92
+ if document is None:
93
+ raise RuntimeError("O LibreOffice não conseguiu abrir o DOCX temporário.")
94
+ indexes = document.getDocumentIndexes()
95
+ count = indexes.getCount()
96
+ if count < 1:
97
+ raise RuntimeError("Nenhum campo de sumário foi reconhecido no DOCX.")
98
+ text_fields = document.getTextFields()
99
+ text_fields.refresh()
100
+ for index in range(count):
101
+ indexes.getByIndex(index).update()
102
+ text_fields.refresh()
103
+ document.store()
104
+ pdf_exported = False
105
+ if pdf_path:
106
+ document.storeToURL(
107
+ uno.systemPathToFileUrl(pdf_path),
108
+ (_property(uno, "FilterName", "writer_pdf_Export"),),
109
+ )
110
+ pdf_exported = True
111
+ return {"ok": True, "indexes": count, "pdf_exported": pdf_exported}
112
+ finally:
113
+ if document is not None:
114
+ try:
115
+ document.close(True)
116
+ except Exception:
117
+ pass
118
+
119
+
120
+ def _process_pdf(uno, desktop, document_path: str, pdf_path: str) -> dict:
121
+ document = None
122
+ try:
123
+ document = desktop.loadComponentFromURL(
124
+ uno.systemPathToFileUrl(document_path),
125
+ "_blank",
126
+ 0,
127
+ (
128
+ _property(uno, "Hidden", True),
129
+ _property(uno, "ReadOnly", True),
130
+ ),
131
+ )
132
+ if document is None:
133
+ raise RuntimeError("O LibreOffice não conseguiu abrir o DOCX para conversão em PDF.")
134
+ document.storeToURL(
135
+ uno.systemPathToFileUrl(pdf_path),
136
+ (_property(uno, "FilterName", "writer_pdf_Export"),),
137
+ )
138
+ return {"ok": True, "pdf_exported": True}
139
+ finally:
140
+ if document is not None:
141
+ try:
142
+ document.close(True)
143
+ except Exception:
144
+ pass
145
+
146
+
147
+ def _run_batch(uno, args: list[str]) -> int:
148
+ executable, profile_uri, port, timeout = args
149
+ process, desktop = _start_desktop(uno, executable, profile_uri, port, float(timeout))
150
+ try:
151
+ print(json.dumps({"ready": True}, ensure_ascii=False), flush=True)
152
+ for raw_line in sys.stdin:
153
+ line = raw_line.strip()
154
+ if not line:
155
+ continue
156
+ try:
157
+ request = json.loads(line)
158
+ except ValueError as exc:
159
+ print(json.dumps({"ok": False, "error": f"JSON inválido: {exc}"}, ensure_ascii=False), flush=True)
160
+ continue
161
+ action = request.get("action")
162
+ if action == "quit":
163
+ print(json.dumps({"ok": True}, ensure_ascii=False), flush=True)
164
+ break
165
+ try:
166
+ if action == "toc":
167
+ reply = _process_toc(uno, desktop, str(request["docx"]), request.get("pdf"))
168
+ elif action == "pdf":
169
+ reply = _process_pdf(uno, desktop, str(request["docx"]), str(request["pdf"]))
170
+ else:
171
+ reply = {"ok": False, "error": f"ação desconhecida: {action}"}
172
+ except Exception as exc:
173
+ reply = {"ok": False, "error": str(exc)}
174
+ print(json.dumps(reply, ensure_ascii=False), flush=True)
175
+ if process.poll() is not None:
176
+ return 1
177
+ return 0
178
+ finally:
179
+ _shutdown(process, desktop)
180
+
181
+
182
+ def main() -> int:
183
+ import uno
184
+
185
+ args = sys.argv[1:]
186
+ if args and args[0] == "--batch":
187
+ return _run_batch(uno, args[1:])
188
+ if len(args) == 5:
189
+ executable, document_path, profile_uri, port, timeout = args
190
+ pdf_path = None
191
+ elif len(args) == 6:
192
+ executable, document_path, profile_uri, port, timeout, pdf_path = args
193
+ pdf_path = pdf_path or None
194
+ else:
195
+ raise RuntimeError(f"Número inválido de argumentos: {len(args)}")
196
+
197
+ process, desktop = _start_desktop(uno, executable, profile_uri, port, float(timeout))
198
+ try:
199
+ result = _process_toc(uno, desktop, document_path, pdf_path)
200
+ print(json.dumps(result, ensure_ascii=False))
201
+ return 0
202
+ finally:
203
+ _shutdown(process, desktop)
204
+
205
+
206
+ if __name__ == "__main__":
207
+ try:
208
+ raise SystemExit(main())
209
+ except Exception as exc:
210
+ print(f"Falha na atualização de campos via LibreOffice: {exc}", file=sys.stderr)
211
+ raise SystemExit(1) from exc
@@ -156,10 +156,14 @@ class ProcessedAttachment:
156
156
  kind: str
157
157
  content: bytes | str
158
158
  metadata: Mapping[str, Any] = field(default_factory=dict)
159
+ # Identidade estável de um conteúdo derivado cujos bytes não são reprodutíveis
160
+ # (PDF cortado pelo PyMuPDF, PDF convertido pelo LibreOffice): vem da origem e dos
161
+ # parâmetros da derivação. Sem ela, a identidade é o hash dos próprios bytes.
162
+ identity: str | None = None
159
163
 
160
164
  def report(self) -> dict[str, Any]:
161
165
  content = self.content.encode("utf-8") if isinstance(self.content, str) else self.content
162
- return {
166
+ report = {
163
167
  "path": self.logical_path,
164
168
  "mime_type": self.mime_type,
165
169
  "kind": self.kind,
@@ -167,6 +171,9 @@ class ProcessedAttachment:
167
171
  "size_bytes": len(content),
168
172
  "metadata": dict(self.metadata),
169
173
  }
174
+ if self.identity:
175
+ report["identity"] = self.identity
176
+ return report
170
177
 
171
178
 
172
179
  @dataclass(frozen=True)
@@ -206,9 +213,17 @@ class AttachmentReport:
206
213
  ZIP foi recriado em ordem diferente.
207
214
  """
208
215
 
209
- def processed_key(item: ProcessedAttachment) -> tuple[str, str, str, int]:
216
+ def processed_entry(item: ProcessedAttachment) -> dict[str, Any]:
217
+ if item.identity:
218
+ # Bytes derivados não reprodutíveis: vale a identidade da origem.
219
+ return {"kind": item.kind, "mime_type": item.mime_type, "identity": item.identity}
210
220
  content = item.content.encode("utf-8") if isinstance(item.content, str) else item.content
211
- return (item.kind, item.mime_type, sha256_bytes(content), len(content))
221
+ return {
222
+ "kind": item.kind,
223
+ "mime_type": item.mime_type,
224
+ "sha256": sha256_bytes(content),
225
+ "size_bytes": len(content),
226
+ }
212
227
 
213
228
  def issue_key(item: AttachmentIssue) -> tuple[str, str, str]:
214
229
  suffix = Path(item.logical_path.split("!")[-1]).suffix.casefold()
@@ -220,17 +235,10 @@ class AttachmentReport:
220
235
  return json.dumps(semantic, sort_keys=True, ensure_ascii=False, default=str)
221
236
 
222
237
  return {
223
- "processed": [
224
- {
225
- "kind": kind,
226
- "mime_type": mime_type,
227
- "sha256": digest,
228
- "size_bytes": size,
229
- }
230
- for kind, mime_type, digest, size in sorted(
231
- (processed_key(item) for item in self.processed)
232
- )
233
- ],
238
+ "processed": sorted(
239
+ (processed_entry(item) for item in self.processed),
240
+ key=lambda entry: json.dumps(entry, sort_keys=True),
241
+ ),
234
242
  "pending": [
235
243
  {"suffix": suffix, "reason": reason, "sha256": digest}
236
244
  for suffix, reason, digest in sorted(issue_key(item) for item in self.pending)
@@ -343,6 +351,7 @@ class PDFAttachmentProcessor:
343
351
  base = {"pages_total": total, "pages_sent": keep}
344
352
  if delivery.pdf == "native":
345
353
  data = content
354
+ identity = None
346
355
  if keep < total:
347
356
  cut = pymupdf.open()
348
357
  try:
@@ -350,12 +359,15 @@ class PDFAttachmentProcessor:
350
359
  data = cut.tobytes()
351
360
  finally:
352
361
  cut.close()
362
+ # O PDF gerado traz identificador e datas novos a cada execução.
363
+ identity = sha256_bytes(f"pdf-paginas/v{self.version}|{sha256_bytes(content)}|{keep}".encode("utf-8"))
353
364
  return ProcessedAttachment(
354
365
  logical_path,
355
366
  "application/pdf",
356
367
  "native",
357
368
  data,
358
369
  {"provider_mode": "native-upload", **base, "gaps": gaps},
370
+ identity,
359
371
  )
360
372
  return self._text_parts(logical_path, content, document, keep, base, gaps, policy, delivery)
361
373
  finally:
@@ -979,6 +991,7 @@ class AttachmentProcessingService:
979
991
  **({"parent": logical_path(str(item.metadata["parent"]))} if "parent" in item.metadata else {}),
980
992
  **({"gaps": [gap(entry) for entry in item.metadata["gaps"]]} if item.metadata.get("gaps") else {}),
981
993
  },
994
+ item.identity,
982
995
  )
983
996
  for item in report.processed
984
997
  ),
@@ -1096,7 +1109,21 @@ class AttachmentProcessingService:
1096
1109
  )
1097
1110
  return
1098
1111
  try:
1099
- state.processed.extend(self._process_with(processor, content, logical_path, delivery, policy, extra))
1112
+ parts = self._process_with(processor, content, logical_path, delivery, policy, extra)
1113
+ if extra:
1114
+ # O arquivo convertido pelo LibreOffice muda de bytes a cada conversão
1115
+ # (datas embutidas): a identidade vem do original e da posição da parte.
1116
+ parts = [
1117
+ replace(
1118
+ part,
1119
+ identity=sha256_bytes(
1120
+ f"convertido|{suffix}|{effective_suffix}|{digest}|{index}|{part.kind}|"
1121
+ f"{part.metadata.get('pages_sent', '')}".encode("utf-8")
1122
+ ),
1123
+ )
1124
+ for index, part in enumerate(parts)
1125
+ ]
1126
+ state.processed.extend(parts)
1100
1127
  except Exception as exc: # noqa: BLE001 - a pendência bloqueia o pedido com o motivo real
1101
1128
  state.pending.append(AttachmentIssue(logical_path, str(exc), digest))
1102
1129
 
@@ -0,0 +1,311 @@
1
+ """Adaptador fino sobre o pacote ``audcom`` para comunicações de auditoria."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from ..contracts import sha256_bytes
10
+ from ..errors import ArgosError, InputValidationError
11
+
12
+
13
+ def _require_audcom() -> Any:
14
+ try:
15
+ import audcom
16
+ except ImportError as exc:
17
+ raise ArgosError(
18
+ "Operações de comunicação requerem o pacote `audcom`. "
19
+ "Instale com: pip install 'argos-cli[comunicacao]' (ou 'argos-cli[all]')."
20
+ ) from exc
21
+ return audcom
22
+
23
+
24
+ def configurar_comunicacao(
25
+ *,
26
+ mailbox: str | None,
27
+ mailboxes_extra: str | None = None,
28
+ env_file: Path | None = None,
29
+ data_dir: Path | None = None,
30
+ provider: str = "ews",
31
+ tenant: str = "tcerj.tc.br",
32
+ non_interactive: bool = False,
33
+ sem_gitignore: bool = False,
34
+ project_root: Path | None = None,
35
+ ) -> dict[str, Any]:
36
+ """Executa a configuração inicial do ``audcom`` (remetente explícito + `.gitignore`)."""
37
+ _require_audcom()
38
+ from audcom.cli import main as audcom_cli_main
39
+
40
+ argv = ["init", "--provider", provider, "--tenant", tenant]
41
+ if mailbox:
42
+ argv.extend(["--mailbox", mailbox])
43
+ if mailboxes_extra is not None:
44
+ argv.extend(["--mailboxes-extra", mailboxes_extra])
45
+ if env_file is not None:
46
+ argv.extend(["--env-file", str(env_file)])
47
+ if data_dir is not None:
48
+ argv.extend(["--data-dir", str(data_dir)])
49
+ if non_interactive:
50
+ argv.append("--non-interactive")
51
+ if sem_gitignore:
52
+ argv.append("--sem-gitignore")
53
+
54
+ cwd_anterior = Path.cwd()
55
+ try:
56
+ if project_root is not None:
57
+ os.chdir(project_root)
58
+ rc = audcom_cli_main(argv)
59
+ finally:
60
+ os.chdir(cwd_anterior)
61
+ if rc != 0:
62
+ raise InputValidationError("Falha na configuração inicial de comunicação (verifique o e-mail informado).")
63
+ return status_comunicacao()
64
+
65
+
66
+ def autorizar_ews() -> dict[str, Any]:
67
+ """Dispara o fluxo interativo device code + MFA do ``audcom``."""
68
+ _require_audcom()
69
+ from audcom.config import settings
70
+ from audcom.ews_token import fluxo_device_cli
71
+
72
+ if not settings.MAILBOX:
73
+ raise InputValidationError(
74
+ "Caixa de e-mail principal não configurada. Execute `argos comunicacao init --mailbox <email>` primeiro."
75
+ )
76
+ fluxo_device_cli()
77
+ return status_comunicacao()
78
+
79
+
80
+ def status_comunicacao() -> dict[str, Any]:
81
+ """Diagnóstico sanitizado da configuração do ``audcom`` (nunca expõe segredos)."""
82
+ audcom = _require_audcom()
83
+ from audcom.config import ENV_FILE, settings
84
+
85
+ cache = settings.ews_cache_path
86
+ return {
87
+ "audcom_version": audcom.__version__,
88
+ "env_file": str(ENV_FILE) if ENV_FILE else None,
89
+ "data_dir": str(settings.data_path),
90
+ "mail_provider": settings.MAIL_PROVIDER,
91
+ "mailbox": settings.MAILBOX or None,
92
+ "caixas": list(settings.caixas),
93
+ "ews_cache_path": str(cache),
94
+ "ews_cache_existe": cache.is_file(),
95
+ }
96
+
97
+
98
+ def _hash_anexos(specs: list[Any]) -> list[dict[str, Any]]:
99
+ registros: list[dict[str, Any]] = []
100
+ for spec in specs:
101
+ conteudo = spec.read_bytes()
102
+ registros.append(
103
+ {
104
+ "nome": spec.resolved_name,
105
+ "tamanho": len(conteudo),
106
+ "sha256": sha256_bytes(conteudo),
107
+ }
108
+ )
109
+ return registros
110
+
111
+
112
+ def executar_lote(
113
+ *,
114
+ template_path: Path,
115
+ manifest_path: Path,
116
+ sheet: str | None = None,
117
+ col_email: str | None = None,
118
+ col_id: str | None = None,
119
+ col_nome: str | None = None,
120
+ remetente: str | None = None,
121
+ dry_run: bool = True,
122
+ teste_para: str | None = None,
123
+ log_path: Path | None = None,
124
+ preview_dir: Path | None = None,
125
+ filtro_ids: set[str] | None = None,
126
+ limite: int | None = None,
127
+ intervalo_segundos: float = 1.0,
128
+ ja_enviados_controle: set[str] | None = None,
129
+ provider: Any | None = None,
130
+ ) -> dict[str, Any]:
131
+ """Valida e executa o lote via ``audcom.batch``, respeitando idempotência do ``controle.sqlite``."""
132
+ _require_audcom()
133
+ from audcom.batch import (
134
+ BatchSender,
135
+ BatchValidationError,
136
+ carregar_manifesto,
137
+ load_template,
138
+ )
139
+ from audcom.config import settings
140
+
141
+ template = load_template(template_path)
142
+ itens = carregar_manifesto(
143
+ manifest_path,
144
+ sheet=sheet,
145
+ col_email=col_email,
146
+ col_id=col_id,
147
+ col_nome=col_nome,
148
+ template=template,
149
+ )
150
+ log_efetivo = log_path or (settings.data_path / "logs" / f"{template_path.stem}.jsonl")
151
+ sender = BatchSender(template, log_path=log_efetivo, provider=provider)
152
+
153
+ # Validação fail-fast de 100% do lote antes de filtrar/enviar
154
+ try:
155
+ validados = sender.validate(itens, remetente_padrao=remetente)
156
+ except BatchValidationError as exc:
157
+ raise InputValidationError(str(exc)) from exc
158
+
159
+ hashes_por_id = {item.audcom_id: _hash_anexos(item.anexos) for item, *_ in validados}
160
+ ja_enviados = set(ja_enviados_controle or set())
161
+
162
+ # Separa itens já enviados no controle.sqlite (modo enviar) para garantir idempotência tripla
163
+ modo = "dry_run" if dry_run else ("teste" if teste_para else "enviar")
164
+ itens_filtrados = itens
165
+ if filtro_ids:
166
+ itens_filtrados = [i for i in itens_filtrados if i.audcom_id in filtro_ids]
167
+ if limite is not None and limite >= 0:
168
+ itens_filtrados = itens_filtrados[:limite]
169
+
170
+ itens_a_processar = []
171
+ pulados_controle: list[dict[str, Any]] = []
172
+ for item in itens_filtrados:
173
+ if modo == "enviar" and item.audcom_id in ja_enviados:
174
+ pulados_controle.append(
175
+ {
176
+ "audcom_id": item.audcom_id,
177
+ "remetente": item.remetente or remetente or template.remetente or settings.MAILBOX,
178
+ "destinatarios": list(item.destinatarios),
179
+ "assunto": "",
180
+ "anexos": hashes_por_id.get(item.audcom_id, []),
181
+ "status": "PULADO_JA_ENVIADO",
182
+ "origem_pulo": "controle_sqlite",
183
+ "erro": "",
184
+ "sent_item_id": "",
185
+ "internet_message_id": "",
186
+ "conversation_id": "",
187
+ }
188
+ )
189
+ else:
190
+ itens_a_processar.append(item)
191
+
192
+ itens_evento: list[dict[str, Any]] = list(pulados_controle)
193
+ enviados = 0
194
+ simulados = 0
195
+ pulados = len(pulados_controle)
196
+ erros = 0
197
+ preview_index = ""
198
+
199
+ if itens_a_processar:
200
+ try:
201
+ res = sender.run(
202
+ itens_a_processar,
203
+ dry_run=dry_run,
204
+ teste_para=teste_para,
205
+ intervalo_segundos=intervalo_segundos,
206
+ preview_dir=preview_dir,
207
+ remetente_padrao=remetente,
208
+ )
209
+ except (BatchValidationError, ValueError) as exc:
210
+ raise InputValidationError(str(exc)) from exc
211
+
212
+ enviados += res.enviados
213
+ simulados += res.simulados
214
+ pulados += res.pulados_ja_enviados
215
+ erros += res.erros
216
+ preview_index = res.preview_index
217
+ for it in res.itens:
218
+ status_final = it.status
219
+ if modo == "dry_run" and it.audcom_id in ja_enviados and status_final == "SIMULADO":
220
+ status_final = "PULADO_JA_ENVIADO"
221
+ simulados = max(0, simulados - 1)
222
+ pulados += 1
223
+ itens_evento.append(
224
+ {
225
+ "audcom_id": it.audcom_id,
226
+ "remetente": it.remetente,
227
+ "destinatarios": list(it.destinatarios),
228
+ "assunto": it.assunto,
229
+ "anexos": hashes_por_id.get(it.audcom_id, []),
230
+ "status": status_final,
231
+ "erro": it.erro,
232
+ "sent_item_id": it.sent_item_id,
233
+ "internet_message_id": it.internet_message_id,
234
+ "conversation_id": it.conversation_id,
235
+ }
236
+ )
237
+
238
+ return {
239
+ "modo": modo,
240
+ "total": len(itens_evento),
241
+ "enviados": enviados,
242
+ "simulados": simulados,
243
+ "pulados_ja_enviados": pulados,
244
+ "erros": erros,
245
+ "log_path": str(log_efetivo),
246
+ "preview_index": preview_index,
247
+ "itens": itens_evento,
248
+ }
249
+
250
+
251
+ def sincronizar_inbox(
252
+ *,
253
+ caixas: list[str] | None = None,
254
+ dias: int | None = None,
255
+ limite: int = 300,
256
+ exportar: Path | None = None,
257
+ ) -> dict[str, Any]:
258
+ """Sincroniza caixas monitoradas via ``audcom.sync_inbox``."""
259
+ _require_audcom()
260
+ import json
261
+
262
+ from sqlalchemy import select
263
+
264
+ from audcom.database import SessionLocal, init_db
265
+ from audcom.models import EmailRecebido
266
+ from audcom.sync_inbox import executar_sync
267
+
268
+ init_db()
269
+ resumo = executar_sync(caixas=caixas, dias=dias, limite=limite)
270
+ if "erro" in resumo:
271
+ raise ArgosError(f"Falha ao sincronizar inbox: {resumo['erro']}")
272
+
273
+ exportadas = 0
274
+ if exportar is not None:
275
+ exportar.parent.mkdir(parents=True, exist_ok=True)
276
+ db = SessionLocal()
277
+ try:
278
+ stmt = select(EmailRecebido).order_by(EmailRecebido.recebido_em.desc())
279
+ if caixas:
280
+ stmt = stmt.where(EmailRecebido.caixa.in_([c.lower() for c in caixas]))
281
+ rows = db.scalars(stmt).all()
282
+ with exportar.open("w", encoding="utf-8") as fh:
283
+ for row in rows:
284
+ fh.write(
285
+ json.dumps(
286
+ {
287
+ "id": row.id,
288
+ "caixa": row.caixa,
289
+ "de_nome": row.de_nome,
290
+ "de_email": row.de_email,
291
+ "para": row.para,
292
+ "cc": row.cc,
293
+ "assunto": row.assunto,
294
+ "recebido_em": row.recebido_em.isoformat() if row.recebido_em else None,
295
+ "tipo": row.tipo,
296
+ "tem_anexos": row.tem_anexos,
297
+ "anexos": row.anexos or [],
298
+ },
299
+ ensure_ascii=False,
300
+ )
301
+ + "\n"
302
+ )
303
+ exportadas = len(rows)
304
+ finally:
305
+ db.close()
306
+
307
+ return {
308
+ **resumo,
309
+ "exportar": str(exportar) if exportar else None,
310
+ "exportadas": exportadas,
311
+ }