argos-cli 0.3.1__py3-none-any.whl

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 (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/matrix_widths.py ADDED
@@ -0,0 +1,280 @@
1
+ """Contrato decimal e valores de largura comuns às matrizes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from decimal import Decimal, InvalidOperation
7
+ from fractions import Fraction
8
+ from typing import Any, Mapping
9
+
10
+ from .core import InputValidationError
11
+
12
+ PLANNING_COLUMN_KEYS = (
13
+ "fontes_de_informacao",
14
+ "informacoes_requeridas",
15
+ "criterios",
16
+ "procedimentos",
17
+ "evidencias",
18
+ "possiveis_achados",
19
+ )
20
+
21
+ FINDINGS_COLUMN_KEYS = (
22
+ "situacao_encontrada",
23
+ "criterios",
24
+ "evidencias",
25
+ "causas",
26
+ "efeitos",
27
+ "encaminhamentos",
28
+ )
29
+
30
+ COLUMN_KEYS_BY_KIND = {
31
+ "planejamento": PLANNING_COLUMN_KEYS,
32
+ "achados": FINDINGS_COLUMN_KEYS,
33
+ }
34
+
35
+ _WORD_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
36
+ _W = f"{{{_WORD_NS}}}"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ColumnWidths:
41
+ """Seis percentuais válidos ordenados conforme as colunas visuais."""
42
+
43
+ kind: str
44
+ percentages: tuple[Decimal, ...]
45
+
46
+ @property
47
+ def keys(self) -> tuple[str, ...]:
48
+ return COLUMN_KEYS_BY_KIND[self.kind]
49
+
50
+ def as_mapping(self) -> dict[str, Decimal]:
51
+ return dict(zip(self.keys, self.percentages, strict=True))
52
+
53
+ def as_json_mapping(self) -> dict[str, str]:
54
+ """Representação exata e serializável em JSON para resumos de execução."""
55
+ return {key: format(value, "f") for key, value in zip(self.keys, self.percentages, strict=True)}
56
+
57
+
58
+ def _error(path: str, message: str) -> InputValidationError:
59
+ return InputValidationError(f"{path}: {message}")
60
+
61
+
62
+ def _fraction_decimal_text(value: Fraction) -> str:
63
+ """Formata exatamente uma fração cujo denominador vem de decimais finitos."""
64
+ denominator = value.denominator
65
+ twos = fives = 0
66
+ while denominator % 2 == 0:
67
+ denominator //= 2
68
+ twos += 1
69
+ while denominator % 5 == 0:
70
+ denominator //= 5
71
+ fives += 1
72
+ if denominator != 1:
73
+ return f"{value.numerator}/{value.denominator}"
74
+ scale = max(twos, fives)
75
+ scaled = value.numerator * (2 ** (scale - twos)) * (5 ** (scale - fives))
76
+ sign = "-" if scaled < 0 else ""
77
+ digits = str(abs(scaled))
78
+ if scale == 0:
79
+ return sign + digits
80
+ digits = digits.rjust(scale + 1, "0")
81
+ whole, fraction = digits[:-scale], digits[-scale:].rstrip("0")
82
+ return sign + whole + ("." + fraction if fraction else "")
83
+
84
+
85
+ def _decimal_value(value: Any, *, path: str) -> Decimal:
86
+ if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
87
+ raise _error(path, "deve ser um número YAML decimal sem aspas")
88
+ if isinstance(value, Decimal):
89
+ result = value
90
+ elif isinstance(value, int):
91
+ result = Decimal(value)
92
+ else:
93
+ # Este ramo atende apenas chamadas Python diretas. O loader Markdown mantém
94
+ # o léxico decimal antes de chegar aqui e nunca converte primeiro para float.
95
+ try:
96
+ result = Decimal(str(value))
97
+ except InvalidOperation as exc:
98
+ raise _error(path, "deve ser um número decimal finito") from exc
99
+ if not result.is_finite():
100
+ raise _error(path, "deve ser finito; NaN e infinito não são permitidos")
101
+ return result
102
+
103
+
104
+ def validate_column_widths(value: Any, *, kind: str, path: str) -> ColumnWidths:
105
+ """Valida o mapa completo, sem soma aproximada ou preenchimento de defaults."""
106
+ keys = COLUMN_KEYS_BY_KIND.get(kind)
107
+ if keys is None:
108
+ raise _error(path, f"tipo de matriz desconhecido: {kind!r}")
109
+ if not isinstance(value, Mapping):
110
+ raise _error(path, "deve ser um mapa YAML com os seis percentuais")
111
+ if any(not isinstance(key, str) for key in value):
112
+ raise _error(path, "as seis chaves devem ser textos")
113
+ unknown = [key for key in value if key not in keys]
114
+ if unknown:
115
+ raise _error(path, f"chave desconhecida para {kind}: {unknown[0]!r}")
116
+ missing = [key for key in keys if key not in value]
117
+ if missing:
118
+ raise _error(path, f"chave obrigatória ausente: {missing[0]}")
119
+
120
+ percentages: list[Decimal] = []
121
+ for key in keys:
122
+ item_path = f"{path}.{key}"
123
+ raw = value[key]
124
+ if isinstance(raw, Mapping) or isinstance(raw, (list, tuple)):
125
+ raise _error(item_path, "deve ser um número, não um mapa ou uma lista")
126
+ number = _decimal_value(raw, path=item_path)
127
+ if number <= 0 or number >= 100:
128
+ raise _error(item_path, "deve ser maior que 0 e menor que 100")
129
+ percentages.append(number)
130
+
131
+ # Fraction(Decimal) usa a representação decimal exata e não o contexto de
132
+ # precisão corrente do módulo decimal.
133
+ total = sum((Fraction(item) for item in percentages), Fraction(0))
134
+ if total != 100:
135
+ total_text = _fraction_decimal_text(total)
136
+ raise _error(path, f"a soma decimal deve ser exatamente 100; soma recebida: {total_text}")
137
+ return ColumnWidths(kind=kind, percentages=tuple(percentages))
138
+
139
+
140
+ def allocate_column_widths(total_twips: int, widths: ColumnWidths) -> tuple[int, ...]:
141
+ """Converte percentuais validados em twips por maiores restos estáveis."""
142
+ if isinstance(total_twips, bool) or not isinstance(total_twips, int) or total_twips <= 0:
143
+ raise _error("larguras_colunas_percentuais", "a largura total da tabela deve ser inteira e positiva")
144
+ if len(widths.percentages) != 6 or len(widths.keys) != 6:
145
+ raise _error("larguras_colunas_percentuais", "são necessárias exatamente seis colunas")
146
+
147
+ ideals = tuple(Fraction(value) * total_twips / 100 for value in widths.percentages)
148
+ allocated = [ideal.numerator // ideal.denominator for ideal in ideals]
149
+ remainder = total_twips - sum(allocated)
150
+ order = sorted(
151
+ range(len(ideals)),
152
+ key=lambda index: (-(ideals[index] - allocated[index]), index),
153
+ )
154
+ if remainder < 0 or remainder > len(order):
155
+ raise _error("larguras_colunas_percentuais", "não foi possível distribuir a largura total em twips")
156
+ for index in order[:remainder]:
157
+ allocated[index] += 1
158
+
159
+ for key, width in zip(widths.keys, allocated, strict=True):
160
+ if width <= 0:
161
+ raise _error(
162
+ f"larguras_colunas_percentuais.{key}",
163
+ f"a largura informada resulta em zero twip na tabela de {total_twips} twips",
164
+ )
165
+ if sum(allocated) != total_twips:
166
+ raise _error("larguras_colunas_percentuais", "a soma das larguras alocadas não preservou a tabela")
167
+ return tuple(allocated)
168
+
169
+
170
+ def _element(parent: Any, name: str) -> Any | None:
171
+ return parent.find(_W + name)
172
+
173
+
174
+ def _new_child(parent: Any, name: str, *, index: int | None = None) -> Any:
175
+ child = parent.makeelement(_W + name, {})
176
+ if index is None:
177
+ parent.append(child)
178
+ else:
179
+ parent.insert(index, child)
180
+ return child
181
+
182
+
183
+ def _cell_width(cell: Any) -> int | None:
184
+ properties = _element(cell, "tcPr")
185
+ width = _element(properties, "tcW") if properties is not None else None
186
+ if width is None or width.get(_W + "type") != "dxa":
187
+ return None
188
+ try:
189
+ result = int(width.get(_W + "w", ""))
190
+ except (TypeError, ValueError):
191
+ return None
192
+ return result if result > 0 else None
193
+
194
+
195
+ def table_column_widths(table: Any) -> tuple[int, ...]:
196
+ """Lê a grade de seis colunas ou larguras dxa coerentes de uma linha detalhada."""
197
+ grid = _element(table, "tblGrid")
198
+ if grid is not None:
199
+ columns = grid.findall(_W + "gridCol")
200
+ try:
201
+ widths = tuple(int(column.get(_W + "w", "")) for column in columns)
202
+ except (TypeError, ValueError):
203
+ widths = ()
204
+ if len(widths) == 6 and all(width > 0 for width in widths):
205
+ return widths
206
+
207
+ for row in table.findall(f".//{_W}tr"):
208
+ cells = row.findall(_W + "tc")
209
+ if len(cells) != 6 or any(_element(cell, "tcPr") is not None and _element(_element(cell, "tcPr"), "gridSpan") is not None for cell in cells):
210
+ continue
211
+ widths = tuple(_cell_width(cell) for cell in cells)
212
+ if all(width is not None for width in widths):
213
+ return tuple(int(width) for width in widths if width is not None)
214
+ raise _error(
215
+ "modelo DOCX",
216
+ "a tabela precisa declarar uma grade de seis colunas ou larguras dxa positivas em uma linha detalhada",
217
+ )
218
+
219
+
220
+ def apply_column_widths_to_table(
221
+ table: Any,
222
+ widths: ColumnWidths,
223
+ *,
224
+ total_twips: int | None = None,
225
+ ) -> tuple[int, ...]:
226
+ """Aplica o mapa à grade, largura declarada e células (incluindo células mescladas)."""
227
+ if total_twips is None:
228
+ total_twips = sum(table_column_widths(table))
229
+ allocated = allocate_column_widths(total_twips, widths)
230
+
231
+ grid = _element(table, "tblGrid")
232
+ if grid is None:
233
+ properties = _element(table, "tblPr")
234
+ grid = _new_child(table, "tblGrid", index=1 if properties is not None else 0)
235
+ for column in list(grid):
236
+ grid.remove(column)
237
+ for value in allocated:
238
+ column = _new_child(grid, "gridCol")
239
+ column.set(_W + "w", str(value))
240
+
241
+ properties = _element(table, "tblPr")
242
+ if properties is None:
243
+ properties = _new_child(table, "tblPr", index=0)
244
+ table_width = _element(properties, "tblW")
245
+ if table_width is None:
246
+ table_width = _new_child(properties, "tblW", index=0)
247
+ table_width.set(_W + "w", str(total_twips))
248
+ table_width.set(_W + "type", "dxa")
249
+ layout = _element(properties, "tblLayout")
250
+ if layout is None:
251
+ layout = _new_child(properties, "tblLayout")
252
+ layout.set(_W + "type", "fixed")
253
+
254
+ for row_index, row in enumerate(table.findall(f".//{_W}tr"), start=1):
255
+ cursor = 0
256
+ cells = row.findall(_W + "tc")
257
+ for cell_index, cell in enumerate(cells, start=1):
258
+ cell_properties = _element(cell, "tcPr")
259
+ span_node = _element(cell_properties, "gridSpan") if cell_properties is not None else None
260
+ try:
261
+ span = int(span_node.get(_W + "val", "1")) if span_node is not None else 1
262
+ except (TypeError, ValueError) as exc:
263
+ raise _error("modelo DOCX", f"gridSpan inválido na linha {row_index}, célula {cell_index}") from exc
264
+ if span <= 0 or cursor + span > 6:
265
+ raise _error("modelo DOCX", f"mesclagem inválida na linha {row_index}, célula {cell_index}")
266
+ cell_width = sum(allocated[cursor : cursor + span])
267
+ if cell_properties is None:
268
+ cell_properties = _new_child(cell, "tcPr", index=0)
269
+ width = _element(cell_properties, "tcW")
270
+ if width is None:
271
+ width = _new_child(cell_properties, "tcW", index=0)
272
+ width.set(_W + "w", str(cell_width))
273
+ width.set(_W + "type", "dxa")
274
+ cursor += span
275
+ if cursor != 6:
276
+ raise _error(
277
+ "modelo DOCX",
278
+ f"linha {row_index} cobre {cursor} das seis colunas da matriz",
279
+ )
280
+ return allocated