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/engines/index.py ADDED
@@ -0,0 +1,1683 @@
1
+ """Cálculo de índices e contexto estatístico/comparativo por auditado."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ import csv
7
+ import io
8
+ import json
9
+ import math
10
+ import re
11
+ import statistics
12
+ import unicodedata
13
+ from dataclasses import replace
14
+ from decimal import Decimal, ROUND_HALF_UP
15
+ from pathlib import Path
16
+ from typing import Any, Iterable, Mapping
17
+
18
+ from ..contracts import canonical_json, sha256_bytes
19
+ from ..core import OperationContext, OperationResult, ProductDraft, ResourceProfile, ScheduledUnit, sha256_file
20
+ from ..errors import InputValidationError, MissingInputError
21
+ from ..adapters.xlsx import (
22
+ TabularRecord,
23
+ TabularTable,
24
+ audit_table_bytes,
25
+ load_json_list,
26
+ read_tabular_table,
27
+ require_file,
28
+ )
29
+ from ..index_dsl import (
30
+ ComponentTrace,
31
+ INDEX_EVALUATOR_REVISION,
32
+ IndexDslError,
33
+ NodeTrace,
34
+ OperationResult as DslOperationResult,
35
+ evaluate_index_row,
36
+ load_index_yaml,
37
+ prepare_input,
38
+ validate_external_score,
39
+ )
40
+ from ..report_config import load_report_config
41
+
42
+ REPORT_CONTEXT_FORMAT = "argos.report-context.v2"
43
+ def _dense_ranking(rows: list[dict[str, Any]]) -> None:
44
+ valid_scores = sorted(
45
+ {
46
+ float(row["indice_principal"])
47
+ for row in rows
48
+ if isinstance(row.get("indice_principal"), (int, float))
49
+ },
50
+ reverse=True,
51
+ )
52
+ if not valid_scores:
53
+ return
54
+ positions = {score: index + 1 for index, score in enumerate(valid_scores)}
55
+ for row in rows:
56
+ score = row.get("indice_principal")
57
+ if isinstance(score, (int, float)):
58
+ row["posicao"] = positions[float(score)]
59
+
60
+
61
+ INDEX_RESULT_FORMAT = "argos.index-result.v1"
62
+ INDEX_TRACE_FORMAT = "argos.index-trace.v1"
63
+
64
+
65
+ def _operation_trace_payload(result: DslOperationResult | None) -> dict[str, Any] | None:
66
+ if result is None:
67
+ return None
68
+ return {
69
+ "value": result.value,
70
+ "before_range": result.before_range,
71
+ "applied_range": list(result.applied_range) if result.applied_range is not None else None,
72
+ "diagnostics": _trace_json_value(result.diagnostics),
73
+ }
74
+
75
+
76
+ def _trace_json_value(value: Any) -> Any:
77
+ if isinstance(value, Mapping):
78
+ return {str(key): _trace_json_value(item) for key, item in value.items()}
79
+ if isinstance(value, (tuple, list)):
80
+ return [_trace_json_value(item) for item in value]
81
+ if isinstance(value, (str, int, float, bool)) or value is None:
82
+ return value
83
+ return str(value)
84
+
85
+
86
+ def _component_trace_payload(component: ComponentTrace) -> dict[str, Any]:
87
+ reference = component.reference
88
+ selector = reference.selector.source if reference.selector is not None else None
89
+ return {
90
+ "reference": {
91
+ "raw": reference.raw_text,
92
+ "kind": reference.kind,
93
+ "target_node": reference.target_node,
94
+ "question": reference.question,
95
+ "selector": selector,
96
+ },
97
+ "input_column": component.input_column,
98
+ "detail_columns": dict(component.detail_columns),
99
+ "value": component.value,
100
+ "code": component.canonical_code,
101
+ "origin": component.origin,
102
+ "weight": component.weight,
103
+ "rule_result": _operation_trace_payload(component.rule_result),
104
+ }
105
+
106
+
107
+ def _node_trace_payload(node: NodeTrace) -> dict[str, Any]:
108
+ return {
109
+ "operation": node.operation,
110
+ "rule": node.rule_name,
111
+ "component_rule": node.component_rule_name,
112
+ "components": [_component_trace_payload(component) for component in node.components],
113
+ "exclusive_negative": (
114
+ _component_trace_payload(node.exclusive_negative) if node.exclusive_negative is not None else None
115
+ ),
116
+ "result": _operation_trace_payload(node.result),
117
+ }
118
+
119
+
120
+ def _node_statistics(rows: list[Mapping[str, Any]], node_ids: Iterable[str]) -> dict[str, Any]:
121
+ output: dict[str, Any] = {}
122
+ for node_id in node_ids:
123
+ values = [float(row["indices"][node_id]) for row in rows]
124
+ output[node_id] = {
125
+ "count": len(values),
126
+ "media": statistics.fmean(values) if values else None,
127
+ "mediana": float(statistics.median(values)) if values else None,
128
+ "minimo": min(values) if values else None,
129
+ "maximo": max(values) if values else None,
130
+ }
131
+ return output
132
+
133
+
134
+ def _calculate_index_payload(
135
+ memory_path: Path,
136
+ responses_path: Path,
137
+ *,
138
+ compiled: Any,
139
+ table: Any,
140
+ trace_requested: bool = False,
141
+ ) -> dict[str, Any]:
142
+ try:
143
+ prepared = prepare_input(compiled, table)
144
+ root_identifier = str(compiled.metadata["raiz"])
145
+ output_rows: list[dict[str, Any]] = []
146
+ trace_rows: list[dict[str, Any]] = []
147
+ for record in prepared.records:
148
+ evaluation = evaluate_index_row(compiled, prepared, record)
149
+ scores = dict(evaluation.scores)
150
+ output: dict[str, Any] = {"auditado": evaluation.organization, "indices": scores}
151
+ output["indice_principal"] = scores[root_identifier]
152
+ if evaluation.classification is not None:
153
+ output["nivel_maturidade"] = evaluation.classification
154
+ output_rows.append(output)
155
+ if trace_requested:
156
+ trace_rows.append(
157
+ {
158
+ "auditado": evaluation.organization,
159
+ "row_number": record.row_number,
160
+ "nodes": {node_id: _node_trace_payload(trace) for node_id, trace in evaluation.traces.items()},
161
+ }
162
+ )
163
+ except IndexDslError as exc:
164
+ raise InputValidationError(str(exc)) from exc
165
+
166
+ _dense_ranking(output_rows)
167
+ root_scores = [float(row["indice_principal"]) for row in output_rows]
168
+ root_statistics: dict[str, Any] = {}
169
+ if root_scores:
170
+ root_statistics = {
171
+ "nome": root_identifier,
172
+ "media": statistics.fmean(root_scores),
173
+ "mediana": float(statistics.median(root_scores)),
174
+ "minimo": min(root_scores),
175
+ "maximo": max(root_scores),
176
+ "distribuicao_maturidade": dict(
177
+ sorted(
178
+ Counter(
179
+ str(row["nivel_maturidade"])
180
+ for row in output_rows
181
+ if row.get("nivel_maturidade")
182
+ ).items()
183
+ )
184
+ ),
185
+ }
186
+ node_ids = tuple(compiled.evaluation_order)
187
+ statistics_payload = {
188
+ **root_statistics,
189
+ **dict(prepared.statistics),
190
+ "root": root_identifier,
191
+ "node_count": len(node_ids),
192
+ "node_ids": list(node_ids),
193
+ "nodes": _node_statistics(output_rows, node_ids),
194
+ }
195
+ payload: dict[str, Any] = {
196
+ "format": INDEX_RESULT_FORMAT,
197
+ "evaluator_revision": INDEX_EVALUATOR_REVISION,
198
+ "memory": dict(compiled.metadata),
199
+ "memory_path": str(memory_path),
200
+ "memory_sha256": sha256_file(memory_path),
201
+ "responses_path": str(responses_path),
202
+ "responses_sha256": sha256_file(responses_path),
203
+ "statistics": statistics_payload,
204
+ "rows": output_rows,
205
+ }
206
+ if trace_requested:
207
+ payload["_trace"] = {
208
+ "format": INDEX_TRACE_FORMAT,
209
+ "evaluator_revision": INDEX_EVALUATOR_REVISION,
210
+ "memory_path": str(memory_path),
211
+ "memory_sha256": payload["memory_sha256"],
212
+ "responses_path": str(responses_path),
213
+ "responses_sha256": payload["responses_sha256"],
214
+ "statistics": dict(prepared.statistics),
215
+ "rows": trace_rows,
216
+ }
217
+ return payload
218
+
219
+
220
+ def _public_index_payload(payload: Mapping[str, Any]) -> dict[str, Any]:
221
+ return {key: value for key, value in payload.items() if not str(key).startswith("_")}
222
+
223
+
224
+ def _index_csv_bytes(payload: Mapping[str, Any]) -> bytes:
225
+ rows = _index_rows_for_workbook(payload)
226
+ if not rows:
227
+ return b""
228
+ fieldnames = list(rows[0].keys())
229
+ buffer = io.StringIO()
230
+ writer = csv.DictWriter(buffer, fieldnames=fieldnames, lineterminator="\n")
231
+ writer.writeheader()
232
+ for row in rows:
233
+ writer.writerow(row)
234
+ return buffer.getvalue().encode("utf-8")
235
+
236
+
237
+ def calculate_index_payload(context: OperationContext) -> dict[str, Any]:
238
+ """Calcula o payload canônico do índice sem criar nem publicar produtos."""
239
+ params = context.params
240
+ memory_path = require_file(context, params["memoria"], "memória de cálculo")
241
+ responses_path = require_file(context, params["respostas"], "respostas")
242
+ try:
243
+ compiled = load_index_yaml(memory_path)
244
+ except IndexDslError as exc:
245
+ raise InputValidationError(str(exc)) from exc
246
+ requested_root = params.get("raiz")
247
+ if requested_root is not None and str(requested_root) != compiled.metadata["raiz"]:
248
+ raise InputValidationError(
249
+ f"raiz informada ({requested_root!r}) diverge da raiz declarada em metadata.raiz "
250
+ f"({compiled.metadata['raiz']!r})"
251
+ )
252
+ table = read_tabular_table(responses_path)
253
+ return _calculate_index_payload(
254
+ memory_path,
255
+ responses_path,
256
+ compiled=compiled,
257
+ table=table,
258
+ trace_requested=bool(params.get("rastreio_output")),
259
+ )
260
+
261
+
262
+ def index_result_from_payload(
263
+ context: OperationContext,
264
+ payload: Mapping[str, Any],
265
+ *,
266
+ output_value: str | Path | None = None,
267
+ ) -> OperationResult:
268
+ """Cria os produtos individuais a partir do payload já calculado."""
269
+ output = context.optional_path(output_value)
270
+ trace_output = context.optional_path(context.params.get("rastreio_output"))
271
+ if output is not None and trace_output is not None and output == trace_output:
272
+ raise InputValidationError("output e rastreio_output devem apontar para arquivos diferentes")
273
+ products: list[ProductDraft] = []
274
+ if output:
275
+ products.append(_index_product_draft(payload, output, kind="index-result"))
276
+ trace_payload = payload.get("_trace")
277
+ if trace_output is not None:
278
+ if not isinstance(trace_payload, Mapping):
279
+ raise InputValidationError("rastreio_output requer que a rastreabilidade seja calculada")
280
+ products.append(
281
+ ProductDraft(
282
+ kind="index-trace",
283
+ path=trace_output,
284
+ content=trace_payload,
285
+ media_type="application/json",
286
+ metadata={
287
+ "memory_sha256": payload["memory_sha256"],
288
+ "responses_sha256": payload["responses_sha256"],
289
+ "evaluator_revision": payload["evaluator_revision"],
290
+ },
291
+ )
292
+ )
293
+ return OperationResult(
294
+ summary={
295
+ "row_count": len(payload["rows"]),
296
+ "node_count": payload["statistics"]["node_count"],
297
+ "root": payload["statistics"]["root"],
298
+ "memory": payload.get("memory", {}),
299
+ "statistics": payload.get("statistics", {}),
300
+ "results_payload_sha256": sha256_bytes(
301
+ canonical_json(_public_index_payload(payload)).encode("utf-8")
302
+ ),
303
+ "output_requested": bool(output),
304
+ "rastreio_output_requested": bool(trace_output),
305
+ },
306
+ products=tuple(products),
307
+ )
308
+
309
+
310
+ def _index_rows_for_workbook(payload: Mapping[str, Any]) -> list[dict[str, Any]]:
311
+ rows: list[dict[str, Any]] = []
312
+ for item in payload.get("rows", []):
313
+ output = {"auditado": item.get("auditado")}
314
+ output.update(item.get("indices") or {})
315
+ if "indice_principal" in item:
316
+ output["indice_principal"] = item["indice_principal"]
317
+ if "nivel_maturidade" in item:
318
+ output["nivel_maturidade"] = item["nivel_maturidade"]
319
+ if "posicao" in item:
320
+ output["posicao"] = item["posicao"]
321
+ rows.append(output)
322
+ return rows
323
+
324
+
325
+ def _index_product_draft(
326
+ payload: Mapping[str, Any],
327
+ output: Path,
328
+ *,
329
+ kind: str,
330
+ metadata: Mapping[str, Any] | None = None,
331
+ ) -> ProductDraft:
332
+ product_metadata = {
333
+ "memory_sha256": payload["memory_sha256"],
334
+ "evaluator_revision": payload["evaluator_revision"],
335
+ **dict(metadata or {}),
336
+ }
337
+ if output.suffix.casefold() == ".xlsx":
338
+ return ProductDraft(
339
+ kind=kind,
340
+ path=output,
341
+ content=audit_table_bytes({"Resultados": _index_rows_for_workbook(payload)}),
342
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
343
+ metadata=product_metadata,
344
+ )
345
+ if output.suffix.casefold() == ".csv":
346
+ return ProductDraft(
347
+ kind=kind,
348
+ path=output,
349
+ content=_index_csv_bytes(payload),
350
+ media_type="text/csv",
351
+ metadata=product_metadata,
352
+ )
353
+ return ProductDraft(
354
+ kind=kind,
355
+ path=output,
356
+ content=_public_index_payload(payload),
357
+ metadata=product_metadata,
358
+ )
359
+
360
+
361
+ def calculate_indices_batch(context: OperationContext) -> OperationResult:
362
+ """Calcula várias memórias sobre a mesma base, lendo a planilha uma vez."""
363
+ params = context.params
364
+ responses_path = require_file(context, params["respostas"], "respostas")
365
+ seen: set[str] = set()
366
+
367
+ def index_spec(item: Any, position: int) -> dict[str, Any]:
368
+ if isinstance(item, (str, Path)):
369
+ item = {"memory": str(item)}
370
+ if not isinstance(item, Mapping) or not item.get("memory"):
371
+ raise InputValidationError(f"memória {position} requer memory")
372
+ normalized = dict(item)
373
+ unknown = sorted(set(normalized) - {"id", "memory", "root", "output", "trace_output"})
374
+ if unknown:
375
+ raise InputValidationError(
376
+ f"campos desconhecidos na memória {position}: {', '.join(str(name) for name in unknown)}"
377
+ )
378
+ if not isinstance(normalized["memory"], (str, Path)):
379
+ raise InputValidationError(f"memory da definição {position} deve ser um caminho")
380
+ identifier = str(normalized.get("id") or Path(str(normalized["memory"])).stem).strip()
381
+ if not identifier or identifier in seen:
382
+ raise InputValidationError(f"id de memória repetido ou vazio: {identifier or position}")
383
+ seen.add(identifier)
384
+ normalized["id"] = identifier
385
+ return normalized
386
+
387
+ raw_memories = params["memorias"]
388
+ if isinstance(raw_memories, (str, Path)):
389
+ raw_memories = [raw_memories]
390
+ specs: list[dict[str, Any]] = []
391
+ for item in raw_memories:
392
+ caminho = context.path(item)
393
+ if str(caminho).lower().endswith((".yaml", ".yml")):
394
+ specs.append({"memory": str(item), "id": Path(str(item)).stem})
395
+ else:
396
+ specs.extend(
397
+ load_json_list(
398
+ context,
399
+ item,
400
+ label="memórias de cálculo",
401
+ keys=("indices", "memories", "memórias"),
402
+ item_fn=index_spec,
403
+ )
404
+ )
405
+ vistos_ids: set[str] = set()
406
+ normalizados: list[dict[str, Any]] = []
407
+ for spec in specs:
408
+ identifier = str(spec.get("id") or Path(str(spec["memory"])).stem).strip()
409
+ if not identifier or identifier in vistos_ids:
410
+ raise InputValidationError(f"id de memória repetido ou vazio: {identifier or len(specs)}")
411
+ vistos_ids.add(identifier)
412
+ normalizados.append(spec)
413
+ specs = normalizados
414
+
415
+ output_owners: dict[Path, str] = {}
416
+ output_specs = [
417
+ ("output", params.get("output")),
418
+ ("xlsx_output", params.get("xlsx_output")),
419
+ *[
420
+ (f"{spec['id']}.{name}", spec.get(name))
421
+ for spec in specs
422
+ for name in ("output", "trace_output")
423
+ ],
424
+ ]
425
+ for owner, value in output_specs:
426
+ if value in (None, ""):
427
+ continue
428
+ destination = context.path(value)
429
+ prior_owner = output_owners.get(destination)
430
+ if prior_owner:
431
+ raise InputValidationError(
432
+ f"destino de produto repetido entre {prior_owner} e {owner}: {destination}"
433
+ )
434
+ output_owners[destination] = owner
435
+
436
+ table = read_tabular_table(responses_path)
437
+ loaded: list[tuple[dict[str, Any], Path]] = []
438
+ for spec in specs:
439
+ loaded.append((spec, context.path(spec["memory"])))
440
+
441
+ def run_one(item: tuple[dict[str, Any], Path]) -> dict[str, Any]:
442
+ spec, memory_path = item
443
+ require_file(context, memory_path, f"memória {spec['id']}")
444
+ try:
445
+ compiled = load_index_yaml(memory_path)
446
+ except IndexDslError as exc:
447
+ raise InputValidationError(str(exc)) from exc
448
+ requested_root = spec.get("root")
449
+ if requested_root is not None and str(requested_root) != compiled.metadata["raiz"]:
450
+ raise InputValidationError(
451
+ f"root informado para {spec['id']} ({requested_root!r}) diverge da raiz declarada "
452
+ f"({compiled.metadata['raiz']!r})"
453
+ )
454
+ payload = _calculate_index_payload(
455
+ memory_path,
456
+ responses_path,
457
+ compiled=compiled,
458
+ table=table,
459
+ trace_requested=bool(spec.get("trace_output")),
460
+ )
461
+ return {
462
+ "id": spec["id"],
463
+ "spec": spec,
464
+ "payload": payload,
465
+ "node_count": len(compiled.nodes),
466
+ }
467
+
468
+ units = [
469
+ ScheduledUnit(
470
+ str(spec["id"]),
471
+ lambda item=item: run_one(item),
472
+ ResourceProfile(cpu=1, memory_mb=128),
473
+ event_meta={"memory_id": spec["id"]},
474
+ )
475
+ for item in loaded
476
+ for spec in [item[0]]
477
+ ]
478
+ outcome = context.run_batch(units, jobs=params.get("jobs"))
479
+ products: list[ProductDraft] = []
480
+ summaries: list[dict[str, Any]] = []
481
+ warnings: list[str] = []
482
+ combined: dict[str, Any] = {
483
+ "responses_path": str(responses_path),
484
+ "responses_sha256": sha256_file(responses_path),
485
+ "indices": {},
486
+ }
487
+ workbook_tables: dict[str, list[dict[str, Any]]] = {}
488
+ for spec, item in zip(specs, outcome.units, strict=False):
489
+ identifier = str(spec["id"])
490
+ if item.get("status") != "completed":
491
+ warnings.append(f"memória {identifier}: {item.get('error')}")
492
+ continue
493
+ payload = item["result"]["payload"]
494
+ combined["indices"][identifier] = _public_index_payload(payload)
495
+ workbook_tables[identifier] = _index_rows_for_workbook(payload)
496
+ summary = {
497
+ "id": identifier,
498
+ "row_count": len(payload["rows"]),
499
+ "node_count": item["result"]["node_count"],
500
+ "root": payload["statistics"]["root"],
501
+ "memory": payload["memory"],
502
+ "statistics": payload.get("statistics", {}),
503
+ }
504
+ summaries.append(summary)
505
+ item_output = context.optional_path(spec.get("output"))
506
+ trace_output = context.optional_path(spec.get("trace_output"))
507
+ if item_output is not None and trace_output is not None and item_output == trace_output:
508
+ raise InputValidationError(f"output e trace_output da memória {identifier} devem ser diferentes")
509
+ if item_output:
510
+ products.append(
511
+ _index_product_draft(
512
+ payload,
513
+ item_output,
514
+ kind=f"index-result:{identifier}",
515
+ metadata={"index_id": identifier},
516
+ )
517
+ )
518
+ trace_payload = payload.get("_trace")
519
+ if trace_output is not None:
520
+ if not isinstance(trace_payload, Mapping):
521
+ raise InputValidationError(f"trace_output ausente no cálculo da memória {identifier}")
522
+ products.append(
523
+ ProductDraft(
524
+ kind="index-trace",
525
+ path=trace_output,
526
+ content=trace_payload,
527
+ media_type="application/json",
528
+ metadata={
529
+ "memory_sha256": payload["memory_sha256"],
530
+ "responses_sha256": payload["responses_sha256"],
531
+ "evaluator_revision": payload["evaluator_revision"],
532
+ "index_id": identifier,
533
+ },
534
+ )
535
+ )
536
+ output = context.optional_path(params.get("output"))
537
+ if output:
538
+ products.append(ProductDraft(kind="indices-batch", path=output, content=combined))
539
+ xlsx_output = context.optional_path(params.get("xlsx_output"))
540
+ if xlsx_output:
541
+ products.append(
542
+ ProductDraft(
543
+ kind="indices-workbook",
544
+ path=xlsx_output,
545
+ content=audit_table_bytes(workbook_tables),
546
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
547
+ metadata={"index_ids": list(workbook_tables)},
548
+ )
549
+ )
550
+ return OperationResult(
551
+ summary={
552
+ "index_count": len(summaries),
553
+ "failed": len(outcome.failed),
554
+ "row_count": len(table.rows),
555
+ "indices": summaries,
556
+ "output_requested": bool(
557
+ output or xlsx_output or any(item.get("output") or item.get("trace_output") for item in specs)
558
+ ),
559
+ },
560
+ products=tuple(products),
561
+ warnings=tuple(warnings),
562
+ )
563
+
564
+
565
+ def join_index_scores(
566
+ table: TabularTable,
567
+ index_payload: Mapping[str, Any],
568
+ *,
569
+ key_column: str,
570
+ columns: Iterable[str],
571
+ ) -> TabularTable:
572
+ """Join selected node scores onto tabular input with strict one-to-one keys.
573
+
574
+ The input table's ``key_column`` is matched to ``auditado`` in an index
575
+ result payload. Only explicitly named node columns are appended.
576
+ """
577
+ if isinstance(columns, str):
578
+ raise InputValidationError("columns deve ser uma lista explícita de nomes de nós")
579
+ requested_columns = tuple(str(column) for column in columns)
580
+ if not requested_columns or any(not column.strip() for column in requested_columns):
581
+ raise InputValidationError("a junção exige uma lista explícita de colunas de índice")
582
+ if not str(key_column).strip():
583
+ raise InputValidationError("a junção exige uma coluna-chave explícita")
584
+ normalized_columns = [unicodedata.normalize("NFC", column).strip() for column in requested_columns]
585
+ if len(set(normalized_columns)) != len(normalized_columns):
586
+ raise InputValidationError("a junção contém colunas de índice repetidas")
587
+
588
+ normalized_headers = [unicodedata.normalize("NFC", str(header)).strip() for header in table.headers]
589
+ header_positions: dict[str, int] = {}
590
+ for index, header in enumerate(normalized_headers):
591
+ if header in header_positions:
592
+ raise InputValidationError(f"cabeçalhos de entrada ambíguos para junção: {header!r}")
593
+ header_positions[header] = index
594
+ key_name = unicodedata.normalize("NFC", str(key_column)).strip()
595
+ if key_name not in header_positions:
596
+ raise InputValidationError(f"coluna-chave ausente na entrada da junção: {key_column!r}")
597
+ collisions = set(normalized_columns).intersection(normalized_headers)
598
+ if collisions:
599
+ raise InputValidationError(
600
+ "colunas da junção já existem na entrada: " + ", ".join(sorted(collisions))
601
+ )
602
+
603
+ def key_value(value: Any, *, location: str) -> str:
604
+ if value is None or isinstance(value, bool):
605
+ raise InputValidationError(f"chave vazia ou inválida na junção ({location})")
606
+ key = unicodedata.normalize("NFC", str(value)).strip()
607
+ if not key:
608
+ raise InputValidationError(f"chave vazia ou inválida na junção ({location})")
609
+ return key
610
+
611
+ base_by_key: dict[str, TabularRecord] = {}
612
+ position = header_positions[key_name]
613
+ for record in table.rows:
614
+ if len(record.values) != len(table.headers):
615
+ raise InputValidationError(f"linha {record.row_number} tem estrutura inválida para junção")
616
+ key = key_value(record.values[position], location=f"linha {record.row_number}")
617
+ if key in base_by_key:
618
+ raise InputValidationError(f"chave duplicada na entrada da junção: {key!r}")
619
+ base_by_key[key] = record
620
+
621
+ result_rows = index_payload.get("rows")
622
+ if not isinstance(result_rows, list):
623
+ raise InputValidationError("resultado de índice inválido para junção: rows deve ser uma lista")
624
+ scores_by_key: dict[str, dict[str, float]] = {}
625
+ for index, result_row in enumerate(result_rows, start=1):
626
+ if not isinstance(result_row, Mapping):
627
+ raise InputValidationError(f"linha {index} do resultado de índice é inválida para junção")
628
+ key = key_value(result_row.get("auditado"), location=f"resultado {index}")
629
+ if key in scores_by_key:
630
+ raise InputValidationError(f"chave duplicada no resultado de índice: {key!r}")
631
+ raw_scores = result_row.get("indices")
632
+ if not isinstance(raw_scores, Mapping):
633
+ raise InputValidationError(f"resultado {key!r} não contém o mapa indices")
634
+ selected: dict[str, float] = {}
635
+ for column in requested_columns:
636
+ if column not in raw_scores:
637
+ raise InputValidationError(f"resultado {key!r} não contém o nó solicitado {column!r}")
638
+ try:
639
+ selected[column] = validate_external_score(
640
+ raw_scores[column], column=column, path=f"junção.{key}.{column}"
641
+ )
642
+ except IndexDslError as exc:
643
+ raise InputValidationError(str(exc)) from exc
644
+ scores_by_key[key] = selected
645
+
646
+ missing_results = sorted(set(base_by_key) - set(scores_by_key))
647
+ missing_inputs = sorted(set(scores_by_key) - set(base_by_key))
648
+ if missing_results or missing_inputs:
649
+ fragments = []
650
+ if missing_results:
651
+ fragments.append("sem resultado: " + ", ".join(missing_results[:5]))
652
+ if missing_inputs:
653
+ fragments.append("sem linha de entrada: " + ", ".join(missing_inputs[:5]))
654
+ raise InputValidationError("junção não é 1:1; " + "; ".join(fragments))
655
+
656
+ joined_records = tuple(
657
+ TabularRecord(
658
+ record.row_number,
659
+ record.values + tuple(scores_by_key[key_value(record.values[position], location=f"linha {record.row_number}")][column] for column in requested_columns),
660
+ )
661
+ for record in table.rows
662
+ )
663
+ return TabularTable(tuple(table.headers) + requested_columns, joined_records)
664
+
665
+
666
+ _TOLERANCIA = 1e-12
667
+
668
+
669
+ def slugify(value: Any) -> str:
670
+ texto = unicodedata.normalize("NFKD", str(value or ""))
671
+ texto = texto.encode("ascii", "ignore").decode()
672
+ texto = texto.lower()
673
+ return re.sub(r"[^a-z0-9]+", "", texto)
674
+
675
+
676
+ def comparison_cycle_keys(config: Mapping[str, Any]) -> tuple[str, str]:
677
+ """Devolve as chaves estáveis dos ciclos anterior e atual.
678
+
679
+ Os nomes são dados da memória da auditoria. Sem declaração explícita,
680
+ usamos rótulos neutros; o núcleo não presume anos ou uma fiscalização.
681
+ """
682
+ comparison = config.get("comparacao") or {}
683
+ labels = comparison.get("rotulos_ciclos") or []
684
+ previous = comparison.get("ciclo_anterior") or (labels[0] if len(labels) > 0 else "anterior")
685
+ current = comparison.get("ciclo_atual") or (labels[1] if len(labels) > 1 else "atual")
686
+ return slugify(previous) or "anterior", slugify(current) or "atual"
687
+
688
+
689
+ def normalizar_chave(value: Any, *, modo: str) -> str:
690
+ texto = unicodedata.normalize("NFKD", str(value or ""))
691
+ texto = texto.encode("ascii", "ignore").decode().upper().strip()
692
+ return re.sub(r"[^A-Z0-9]", "", texto)
693
+
694
+
695
+ def _quantile(values: list[float], q: float) -> float:
696
+ """Quantil com interpolação linear, equivalente ao default do pandas."""
697
+ ordenados = sorted(values)
698
+ if not ordenados:
699
+ return 0.0
700
+ pos = (len(ordenados) - 1) * q
701
+ base = int(math.floor(pos))
702
+ frac = pos - base
703
+ if base + 1 >= len(ordenados):
704
+ return ordenados[-1]
705
+ return ordenados[base] + frac * (ordenados[base + 1] - ordenados[base])
706
+
707
+
708
+ def _isclose(a: float, b: float, *, rtol: float, atol: float) -> bool:
709
+ return abs(a - b) <= atol + rtol * abs(b)
710
+
711
+
712
+ def serie_stats(values: Iterable[Any], limiar: float) -> dict[str, float | int]:
713
+ """Estatísticas da série com nomes derivados do limiar (abaixo_040 etc.)."""
714
+ numericos = [float(value) for value in values]
715
+ if not numericos:
716
+ raise InputValidationError("série sem valores numéricos para estatísticas")
717
+ limiar_label = f"{int(round(limiar * 100)):03d}"
718
+ abaixo = sum(1 for value in numericos if value < limiar)
719
+ return {
720
+ "media": sum(numericos) / len(numericos),
721
+ "q1": _quantile(numericos, 0.25),
722
+ "mediana": _quantile(numericos, 0.50),
723
+ "q3": _quantile(numericos, 0.75),
724
+ "minimo": min(numericos),
725
+ "maximo": max(numericos),
726
+ "zeros_n": sum(1 for value in numericos if _isclose(value, 0.0, rtol=1e-5, atol=1e-8)),
727
+ f"abaixo_{limiar_label}_n": abaixo,
728
+ f"a_partir_{limiar_label}_n": len(numericos) - abaixo,
729
+ }
730
+
731
+
732
+ def percentual(quantidade: int, total: int) -> float:
733
+ return 100.0 * quantidade / total if total else 0.0
734
+
735
+
736
+ def classify_level(value: Any, levels: Iterable[Mapping[str, Any]]) -> str:
737
+ """Classifica o valor no primeiro nível da memória que o contém."""
738
+ try:
739
+ valor = float(value)
740
+ except (TypeError, ValueError):
741
+ return ""
742
+ for nivel in levels:
743
+ minimo = float(nivel.get("min", 0.0))
744
+ maximo = float(nivel.get("max", 1.0))
745
+ inclui_min = bool(nivel.get("inclui_min", True))
746
+ inclui_max = bool(nivel.get("inclui_max", True))
747
+ acima_min = valor >= minimo if inclui_min else valor > minimo
748
+ abaixo_max = valor <= maximo if inclui_max else valor < maximo
749
+ if acima_min and abaixo_max:
750
+ return str(nivel.get("nome") or "")
751
+ return ""
752
+
753
+
754
+ def _yaml() -> Any:
755
+ try:
756
+ import yaml
757
+ except ImportError as exc: # pragma: no cover - opcional no pacote base
758
+ raise InputValidationError("a memória YAML requer PyYAML; instale argos-cli[workbooks]") from exc
759
+ return yaml
760
+
761
+
762
+ def load_memory(path: Path) -> dict[str, Any]:
763
+ try:
764
+ return dict(load_index_yaml(path).document)
765
+ except IndexDslError as exc:
766
+ raise InputValidationError(str(exc)) from exc
767
+
768
+
769
+ def load_aliases(path: Path | None) -> dict[str, str]:
770
+ if path is None:
771
+ return {}
772
+ yaml = _yaml()
773
+ try:
774
+ payload = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
775
+ except Exception as exc: # noqa: BLE001
776
+ raise InputValidationError(f"aliases inválidos: {exc}") from exc
777
+ if not isinstance(payload, dict):
778
+ raise InputValidationError("aliases deve ser um mapeamento chave_anterior: chave_atual")
779
+ return {str(key): str(value) for key, value in payload.items()}
780
+
781
+
782
+ def context_config(report_config: Mapping[str, Any], index_definition: Mapping[str, Any]) -> dict[str, Any]:
783
+ """Normalize a separately validated report configuration for consumers."""
784
+ config = dict(report_config)
785
+ config.setdefault("limiar", 0.40)
786
+ config.setdefault("coluna_maturidade", "nivel_maturidade")
787
+ config.setdefault("universo_prefixo", "universo")
788
+ indice_coluna = config.get("indice_coluna") or (index_definition.get("metadata") or {}).get("raiz") or ""
789
+ config["indice_coluna"] = str(indice_coluna)
790
+ config.setdefault("indice_prefixo", slugify(indice_coluna) or "indice")
791
+ config.setdefault("indicadores", {})
792
+ config.setdefault("dimensoes", {})
793
+ config.setdefault("projecoes", {})
794
+ config.setdefault("componentes_comparar", [])
795
+ config.setdefault("comparacao", {})
796
+ comparacao = dict(config["comparacao"])
797
+ comparacao.setdefault("ativo", False)
798
+ comparacao.setdefault("indicadores", {})
799
+ comparacao.setdefault("agregados", {})
800
+ comparacao.setdefault("grupos", [])
801
+ comparacao.setdefault("aliases", {})
802
+ comparacao.setdefault("cobertura_sufixo", "")
803
+ comparacao.setdefault("direcao_coluna", config["indice_coluna"])
804
+ comparacao.setdefault("ciclo_anterior", "anterior")
805
+ comparacao.setdefault("ciclo_atual", "atual")
806
+ config["comparacao"] = comparacao
807
+ return config
808
+
809
+
810
+ def read_index_payload(payload: Mapping[str, Any], config: Mapping[str, Any]) -> list[dict[str, Any]]:
811
+ """Normaliza em memória o payload canônico produzido pelo motor de índice."""
812
+ coluna_auditado = str(config.get("coluna_auditado") or "sigla")
813
+ coluna_maturidade = str(config.get("coluna_maturidade") or "nivel_maturidade")
814
+ rows = payload.get("rows")
815
+ if not isinstance(rows, list):
816
+ indices = payload.get("indices")
817
+ if isinstance(indices, Mapping):
818
+ for indice in indices.values():
819
+ if isinstance(indice, Mapping) and isinstance(indice.get("rows"), list):
820
+ rows = indice["rows"]
821
+ break
822
+ if not isinstance(rows, list):
823
+ raise InputValidationError("o JSON de resultados deve conter a lista rows")
824
+ linhas: list[dict[str, Any]] = []
825
+ for item in rows:
826
+ if not isinstance(item, dict):
827
+ continue
828
+ linha = dict(item)
829
+ indices = linha.pop("indices", None)
830
+ if isinstance(indices, dict):
831
+ linha.update(indices)
832
+ auditado = linha.pop("auditado", None)
833
+ linha[coluna_auditado] = auditado
834
+ nivel = linha.pop("nivel_maturidade", None)
835
+ linha[coluna_maturidade] = nivel
836
+ linhas.append(linha)
837
+ if not linhas:
838
+ raise InputValidationError("o JSON de resultados não contém linhas de auditados")
839
+ return linhas
840
+
841
+
842
+ def read_results(path: Path, config: Mapping[str, Any]) -> list[dict[str, Any]]:
843
+ """Lê os resultados do cálculo: JSON do calcular-indices ou XLSX 'resultados'."""
844
+ coluna_auditado = str(config.get("coluna_auditado") or "sigla")
845
+ coluna_maturidade = str(config.get("coluna_maturidade") or "nivel_maturidade")
846
+ if path.suffix.lower() == ".json":
847
+ try:
848
+ payload = json.loads(path.read_text(encoding="utf-8"))
849
+ except Exception as exc: # noqa: BLE001
850
+ raise InputValidationError(f"JSON de resultados inválido: {exc}") from exc
851
+ if not isinstance(payload, Mapping):
852
+ raise InputValidationError("JSON de resultados deve ser um objeto")
853
+ return read_index_payload(payload, config)
854
+
855
+ from ..adapters.xlsx import openpyxl_workbook, sheet_records
856
+
857
+ load_workbook = openpyxl_workbook()
858
+ workbook = load_workbook(path, read_only=True, data_only=True)
859
+ try:
860
+ worksheets = {str(sheet.title).casefold(): sheet for sheet in workbook.worksheets}
861
+ worksheet = worksheets.get("resultados")
862
+ if worksheet is None:
863
+ raise InputValidationError(f"aba 'resultados' ausente em {path}")
864
+ _, headers, rows = sheet_records(worksheet)
865
+ finally:
866
+ workbook.close()
867
+ linhas = []
868
+ for row in rows:
869
+ linha: dict[str, Any] = {}
870
+ for name in headers:
871
+ if not name:
872
+ continue
873
+ if name in {"id", "auditado"} and coluna_auditado not in linha:
874
+ linha[coluna_auditado] = row.get(name)
875
+ elif name == "nivel_maturidade" and coluna_maturidade not in linha:
876
+ linha[coluna_maturidade] = row.get(name)
877
+ else:
878
+ linha[name] = row.get(name)
879
+ linhas.append(linha)
880
+ return linhas
881
+
882
+
883
+ def _validar_chaves_unicas(linhas: list[dict[str, Any]], config: Mapping[str, Any], *, modo: str) -> None:
884
+ coluna_auditado = str(config.get("coluna_auditado") or "sigla")
885
+ chaves: dict[str, str] = {}
886
+ duplicadas: list[str] = []
887
+ sem_chave: list[str] = []
888
+ for linha in linhas:
889
+ valor = linha.get(coluna_auditado)
890
+ if valor in (None, ""):
891
+ sem_chave.append(str(valor))
892
+ continue
893
+ chave = normalizar_chave(valor, modo=modo)
894
+ if chave in chaves:
895
+ duplicadas.append(chaves[chave])
896
+ else:
897
+ chaves[chave] = str(valor)
898
+ if sem_chave:
899
+ raise InputValidationError("linhas sem identificador de auditado nos resultados")
900
+ if duplicadas:
901
+ raise InputValidationError(f"identificadores duplicados após normalização: {sorted(set(duplicadas))}")
902
+
903
+
904
+ def _colunas_numericas(linhas: list[dict[str, Any]], coluna: str) -> list[float]:
905
+ valores: list[float] = []
906
+ for linha in linhas:
907
+ valor = linha.get(coluna)
908
+ if valor in (None, ""):
909
+ continue
910
+ try:
911
+ valores.append(float(valor))
912
+ except (TypeError, ValueError):
913
+ continue
914
+ return valores
915
+
916
+
917
+ def _coluna_por_linha(linhas: list[dict[str, Any]], coluna: str) -> list[float | None]:
918
+ """Valores da coluna alinhados às linhas (None quando não numérico/ausente)."""
919
+ valores: list[float | None] = []
920
+ for linha in linhas:
921
+ valor = linha.get(coluna)
922
+ if valor in (None, ""):
923
+ valores.append(None)
924
+ continue
925
+ try:
926
+ valores.append(float(valor))
927
+ except (TypeError, ValueError):
928
+ valores.append(None)
929
+ return valores
930
+
931
+
932
+ def global_stats(
933
+ linhas: list[dict[str, Any]],
934
+ memory: Mapping[str, Any],
935
+ config: Mapping[str, Any],
936
+ ) -> dict[str, Any]:
937
+ """Porto genérico de ``calcular_estatisticas_globais``."""
938
+ total = len(linhas)
939
+ limiar = float(config.get("limiar", 0.40))
940
+ limiar_label = f"{int(round(limiar * 100)):03d}"
941
+ coluna_indice = str(config.get("indice_coluna") or "")
942
+ coluna_maturidade = str(config.get("coluna_maturidade") or "nivel_maturidade")
943
+ universo_prefixo = str(config.get("universo_prefixo") or "universo")
944
+ indice_prefixo = str(config.get("indice_prefixo") or "indice")
945
+
946
+ estatisticas: dict[str, Any] = {f"{universo_prefixo}_n": total}
947
+
948
+ niveis = list(memory.get("maturidade") or [])
949
+ contagem_niveis: dict[str, int] = {}
950
+ for linha in linhas:
951
+ nivel = str(linha.get(coluna_maturidade) or "")
952
+ if nivel:
953
+ contagem_niveis[nivel] = contagem_niveis.get(nivel, 0) + 1
954
+ for nivel in niveis:
955
+ nome = str(nivel.get("nome") or "")
956
+ if not nome:
957
+ continue
958
+ prefixo = f"maturidade_{slugify(nome)}"
959
+ quantidade = contagem_niveis.get(nome, 0)
960
+ estatisticas[f"{prefixo}_n"] = quantidade
961
+ estatisticas[f"{prefixo}_pct"] = percentual(quantidade, total)
962
+
963
+ if coluna_indice:
964
+ abaixo = sum(1 for valor in _colunas_numericas(linhas, coluna_indice) if valor < limiar)
965
+ estatisticas[f"{indice_prefixo}_abaixo_{limiar_label}_n"] = abaixo
966
+ estatisticas[f"{indice_prefixo}_abaixo_{limiar_label}_pct"] = percentual(abaixo, total)
967
+
968
+ for coluna, prefixo in (config.get("indicadores") or {}).items():
969
+ resumo = serie_stats(_colunas_numericas(linhas, str(coluna)), limiar)
970
+ for nome, valor in resumo.items():
971
+ estatisticas[f"{prefixo}_{nome}"] = valor
972
+ for nome in ("zeros", f"abaixo_{limiar_label}", f"a_partir_{limiar_label}"):
973
+ estatisticas[f"{prefixo}_{nome}_pct"] = percentual(
974
+ int(resumo[f"{nome}_n"]), total
975
+ )
976
+
977
+ componentes = config.get("componentes_comparar") or {}
978
+ if len(componentes) == 2:
979
+ coluna_a, coluna_b = list(componentes)
980
+ prefixo_a = str(componentes[coluna_a].get("prefixo") or slugify(coluna_a))
981
+ prefixo_b = str(componentes[coluna_b].get("prefixo") or slugify(coluna_b))
982
+ valores_a = _colunas_numericas(linhas, coluna_a)
983
+ valores_b = _colunas_numericas(linhas, coluna_b)
984
+ maior_b = sum(1 for a, b in zip(valores_a, valores_b) if b - a > _TOLERANCIA)
985
+ maior_a = sum(1 for a, b in zip(valores_a, valores_b) if a - b > _TOLERANCIA)
986
+ iguais = sum(1 for a, b in zip(valores_a, valores_b) if abs(a - b) <= _TOLERANCIA)
987
+ for nome, quantidade in {
988
+ f"{prefixo_b}_maior_{prefixo_a}": maior_b,
989
+ f"{prefixo_a}_maior_{prefixo_b}": maior_a,
990
+ f"{prefixo_a}_{prefixo_b}_iguais": iguais,
991
+ }.items():
992
+ estatisticas[f"{nome}_n"] = quantidade
993
+ estatisticas[f"{nome}_pct"] = percentual(quantidade, total)
994
+
995
+ dimensoes = config.get("dimensoes") or {}
996
+ colunas_dimensoes = list(dimensoes)
997
+ valores_por_coluna = {
998
+ coluna: _coluna_por_linha(linhas, coluna) for coluna in colunas_dimensoes
999
+ }
1000
+ maximos_linha = [
1001
+ max((valores_por_coluna[coluna][i] for coluna in colunas_dimensoes if valores_por_coluna[coluna][i] is not None), default=0.0)
1002
+ for i in range(total)
1003
+ ]
1004
+ minimos_linha = [
1005
+ min((valores_por_coluna[coluna][i] for coluna in colunas_dimensoes if valores_por_coluna[coluna][i] is not None), default=0.0)
1006
+ for i in range(total)
1007
+ ]
1008
+ for indice, coluna in enumerate(colunas_dimensoes):
1009
+ prefixo = str(dimensoes[coluna].get("prefixo") or slugify(coluna))
1010
+ resumo = serie_stats([v for v in valores_por_coluna[coluna] if v is not None], limiar)
1011
+ for nome, valor in resumo.items():
1012
+ estatisticas[f"{prefixo}_geral_{nome}"] = valor
1013
+ estatisticas[f"{prefixo}_geral_zeros_pct"] = percentual(int(resumo["zeros_n"]), total)
1014
+ estatisticas[f"{prefixo}_geral_abaixo_{limiar_label}_pct"] = percentual(
1015
+ int(resumo[f"abaixo_{limiar_label}_n"]), total
1016
+ )
1017
+ maior = sum(
1018
+ 1
1019
+ for i, valor in enumerate(valores_por_coluna[coluna])
1020
+ if valor is not None and _isclose(valor, maximos_linha[i], rtol=0.0, atol=1e-12)
1021
+ )
1022
+ menor = sum(
1023
+ 1
1024
+ for i, valor in enumerate(valores_por_coluna[coluna])
1025
+ if valor is not None and _isclose(valor, minimos_linha[i], rtol=0.0, atol=1e-12)
1026
+ )
1027
+ estatisticas[f"{prefixo}_maior_resultado_n"] = maior
1028
+ estatisticas[f"{prefixo}_maior_resultado_pct"] = percentual(maior, total)
1029
+ estatisticas[f"{prefixo}_menor_resultado_n"] = menor
1030
+ estatisticas[f"{prefixo}_menor_resultado_pct"] = percentual(menor, total)
1031
+
1032
+ medias = sorted(
1033
+ (
1034
+ (coluna, sum(v for v in valores_por_coluna[coluna] if v is not None) / max(1, sum(1 for v in valores_por_coluna[coluna] if v is not None)))
1035
+ for coluna in colunas_dimensoes
1036
+ ),
1037
+ key=lambda item: item[1],
1038
+ reverse=True,
1039
+ )
1040
+ medianas = sorted(
1041
+ (
1042
+ (coluna, _quantile([v for v in valores_por_coluna[coluna] if v is not None], 0.50))
1043
+ for coluna in colunas_dimensoes
1044
+ ),
1045
+ key=lambda item: item[1],
1046
+ reverse=True,
1047
+ )
1048
+ rotulos = {coluna: str((espec or {}).get("rotulo") or coluna) for coluna, espec in dimensoes.items()}
1049
+ if medias:
1050
+ maior_media_coluna = medias[0][0]
1051
+ estatisticas["dimensao_maior_media_nome"] = rotulos[maior_media_coluna]
1052
+ estatisticas["dimensao_maior_media_valor"] = medias[0][1]
1053
+ estatisticas["dimensao_maior_media_mediana"] = _quantile(
1054
+ [v for v in valores_por_coluna[maior_media_coluna] if v is not None], 0.50
1055
+ )
1056
+ prefixo_media = str(dimensoes[maior_media_coluna].get("prefixo") or slugify(maior_media_coluna))
1057
+ estatisticas["dimensao_maior_media_maior_resultado_n"] = estatisticas[f"{prefixo_media}_maior_resultado_n"]
1058
+ estatisticas["dimensao_maior_media_maior_resultado_pct"] = estatisticas[f"{prefixo_media}_maior_resultado_pct"]
1059
+ if medianas:
1060
+ estatisticas["dimensao_maior_mediana_nome"] = rotulos[medianas[0][0]]
1061
+ estatisticas["dimensao_maior_mediana_valor"] = medianas[0][1]
1062
+ for indice, (coluna, _media) in enumerate(medias[-2:][::-1], start=1):
1063
+ prefixo = str(dimensoes[coluna].get("prefixo") or slugify(coluna))
1064
+ estatisticas[f"dimensao_fragil_{indice}_nome"] = rotulos[coluna]
1065
+ estatisticas[f"dimensao_fragil_{indice}_media"] = sum(v for v in valores_por_coluna[coluna] if v is not None) / max(
1066
+ 1, sum(1 for v in valores_por_coluna[coluna] if v is not None)
1067
+ )
1068
+ estatisticas[f"dimensao_fragil_{indice}_abaixo_{limiar_label}_n"] = estatisticas[f"{prefixo}_geral_abaixo_{limiar_label}_n"]
1069
+ estatisticas[f"dimensao_fragil_{indice}_abaixo_{limiar_label}_pct"] = estatisticas[f"{prefixo}_geral_abaixo_{limiar_label}_pct"]
1070
+ estatisticas[f"dimensao_fragil_{indice}_menor_resultado_n"] = estatisticas[f"{prefixo}_menor_resultado_n"]
1071
+ estatisticas[f"dimensao_fragil_{indice}_menor_resultado_pct"] = estatisticas[f"{prefixo}_menor_resultado_pct"]
1072
+ return estatisticas
1073
+
1074
+
1075
+ def read_comparavel(path: Path, config: Mapping[str, Any]) -> list[dict[str, Any]]:
1076
+ from ..adapters.xlsx import openpyxl_workbook, sheet_records
1077
+
1078
+ colunas_comparacao = list((config.get("comparacao") or {}).get("indicadores") or {}) + list(
1079
+ (config.get("comparacao") or {}).get("agregados") or {}
1080
+ )
1081
+ load_workbook = openpyxl_workbook()
1082
+ workbook = load_workbook(path, read_only=True, data_only=True)
1083
+ try:
1084
+ worksheet = next(
1085
+ (sheet for sheet in workbook.worksheets if sheet.title.strip().casefold() == "resultados"),
1086
+ None,
1087
+ )
1088
+ if worksheet is None:
1089
+ raise InputValidationError(f"aba 'resultados' ausente em {path}")
1090
+ _, headers, rows = sheet_records(worksheet)
1091
+ finally:
1092
+ workbook.close()
1093
+ obrigatorias = {"id", "nivel_maturidade", *colunas_comparacao}
1094
+ presentes = {str(header).strip() for header in headers if header}
1095
+ if "id" not in presentes and "auditado" in presentes:
1096
+ presentes.add("id")
1097
+ faltantes = sorted(obrigatorias - presentes)
1098
+ if faltantes:
1099
+ raise InputValidationError(f"Colunas ausentes em {path}: {faltantes}")
1100
+ comparaveis = []
1101
+ for row in rows:
1102
+ comparavel = {name: row.get(name) for name in headers if name}
1103
+ if "id" not in comparavel and "auditado" in comparavel:
1104
+ comparavel["id"] = comparavel["auditado"]
1105
+ comparaveis.append(comparavel)
1106
+ return comparaveis
1107
+
1108
+
1109
+ def parear_ciclos(
1110
+ atual: list[dict[str, Any]],
1111
+ anteriores_por_grupo: Mapping[str, list[dict[str, Any]]],
1112
+ *,
1113
+ aliases: Mapping[str, str],
1114
+ modo: str,
1115
+ config: Mapping[str, Any],
1116
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
1117
+ """Porto genérico de ``consolidar_pareamentos``."""
1118
+ colunas_comparacao = list((config.get("comparacao") or {}).get("indicadores") or {}) + list(
1119
+ (config.get("comparacao") or {}).get("agregados") or {}
1120
+ )
1121
+ ciclo_anterior, ciclo_atual = comparison_cycle_keys(config)
1122
+ antigo_sigla = f"sigla_{ciclo_anterior}"
1123
+ antigo_chave = f"chave_{ciclo_anterior}"
1124
+ atual_sigla = f"sigla_{ciclo_atual}"
1125
+ atual_chave = f"chave_{ciclo_atual}"
1126
+ por_chave_atual = {normalizar_chave(row.get("id"), modo=modo): row for row in atual}
1127
+ linhas: list[dict[str, Any]] = []
1128
+ usados_atual: set[str] = set()
1129
+
1130
+ for grupo, antigos in anteriores_por_grupo.items():
1131
+ for antigo in antigos:
1132
+ chave_anterior = normalizar_chave(antigo.get("id"), modo=modo)
1133
+ if chave_anterior in por_chave_atual:
1134
+ chave_atual = chave_anterior
1135
+ tipo = "normalizado"
1136
+ else:
1137
+ chave_atual = aliases.get(chave_anterior)
1138
+ tipo = "alias validado" if chave_atual in por_chave_atual else "sem correspondência"
1139
+
1140
+ registro: dict[str, Any] = {
1141
+ "grupo": grupo,
1142
+ antigo_sigla: antigo.get("id"),
1143
+ antigo_chave: chave_anterior,
1144
+ atual_sigla: None,
1145
+ atual_chave: chave_atual,
1146
+ "tipo_pareamento": tipo,
1147
+ "pareado": tipo != "sem correspondência",
1148
+ }
1149
+ if registro["pareado"]:
1150
+ if chave_atual in usados_atual:
1151
+ raise InputValidationError(f"Mais de uma organização de ciclo anterior foi associada a {chave_atual}.")
1152
+ usados_atual.add(chave_atual)
1153
+ novo = por_chave_atual[chave_atual]
1154
+ registro[atual_sigla] = novo.get("id")
1155
+ registro[f"nivel_maturidade_{ciclo_anterior}"] = antigo.get("nivel_maturidade")
1156
+ registro[f"nivel_maturidade_{ciclo_atual}"] = novo.get("nivel_maturidade")
1157
+ for indicador in colunas_comparacao:
1158
+ registro[f"{indicador}_{ciclo_anterior}"] = float(antigo.get(indicador) or 0.0)
1159
+ registro[f"{indicador}_{ciclo_atual}"] = float(novo.get(indicador) or 0.0)
1160
+ registro[f"delta_{indicador}"] = registro[f"{indicador}_{ciclo_atual}"] - registro[f"{indicador}_{ciclo_anterior}"]
1161
+ linhas.append(registro)
1162
+
1163
+ pareados = [registro for registro in linhas if registro["pareado"]]
1164
+ nao_pareados = [
1165
+ {atual_sigla: row.get("id"), atual_chave: chave}
1166
+ for chave, row in por_chave_atual.items()
1167
+ if chave not in usados_atual
1168
+ ]
1169
+ return linhas, pareados, nao_pareados
1170
+
1171
+
1172
+ def direcao_variacao(delta: float, tolerancia: float = 1e-12) -> str:
1173
+ if delta > tolerancia:
1174
+ return "avanço"
1175
+ if delta < -tolerancia:
1176
+ return "regressão"
1177
+ return "estabilidade"
1178
+
1179
+
1180
+ def formatar_variacoes(
1181
+ par: Mapping[str, Any],
1182
+ positivas: bool,
1183
+ config: Mapping[str, Any],
1184
+ limite: int = 3,
1185
+ ) -> str:
1186
+ agregados = (config.get("comparacao") or {}).get("agregados") or {}
1187
+ variacoes = [
1188
+ (float(par.get(f"delta_{campo}") or 0.0), str(espec.get("rotulo") or campo))
1189
+ for campo, espec in agregados.items()
1190
+ ]
1191
+ if positivas:
1192
+ selecionadas = sorted((item for item in variacoes if item[0] > 1e-12), reverse=True)[:limite]
1193
+ else:
1194
+ selecionadas = sorted(item for item in variacoes if item[0] < -1e-12)[:limite]
1195
+ return "; ".join(
1196
+ f"{rotulo} ({Decimal(str(delta)).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP):+.4f})"
1197
+ for delta, rotulo in selecionadas
1198
+ )
1199
+
1200
+
1201
+ def comparacao_fields(par: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:
1202
+ """Campos ``comparacao_*`` por auditado (porto de ``adicionar_comparacao``)."""
1203
+ comparacao = config.get("comparacao") or {}
1204
+ ciclo_anterior, ciclo_atual = comparison_cycle_keys(config)
1205
+ direcao_coluna = str(comparacao.get("direcao_coluna") or "")
1206
+ campos: dict[str, Any] = {
1207
+ f"tem_comparacao_{ciclo_anterior}": True,
1208
+ f"comparacao_sigla_{ciclo_anterior}": par.get(f"sigla_{ciclo_anterior}"),
1209
+ "comparacao_tipo_pareamento": par.get("tipo_pareamento"),
1210
+ "comparacao_grupo": par.get("grupo"),
1211
+ f"comparacao_nivel_{ciclo_anterior}": par.get(f"nivel_maturidade_{ciclo_anterior}"),
1212
+ f"comparacao_nivel_{ciclo_atual}": par.get(f"nivel_maturidade_{ciclo_atual}"),
1213
+ }
1214
+ for indicador, espec in (comparacao.get("indicadores") or {}).items():
1215
+ prefixo = str(espec.get("prefixo") or slugify(indicador))
1216
+ campos[f"comparacao_{prefixo}_{ciclo_anterior}"] = par.get(f"{indicador}_{ciclo_anterior}")
1217
+ campos[f"comparacao_{prefixo}_{ciclo_atual}"] = par.get(f"{indicador}_{ciclo_atual}")
1218
+ campos[f"comparacao_delta_{prefixo}"] = par.get(f"delta_{indicador}")
1219
+ if indicador == direcao_coluna:
1220
+ campos[f"comparacao_direcao_{prefixo}"] = direcao_variacao(float(par.get(f"delta_{indicador}") or 0.0))
1221
+ campos["comparacao_principais_avancos"] = formatar_variacoes(par, positivas=True, config=config)
1222
+ campos["comparacao_principais_regressoes"] = formatar_variacoes(par, positivas=False, config=config)
1223
+ return campos
1224
+
1225
+
1226
+ def _apply_report_projections(
1227
+ rows: list[dict[str, Any]],
1228
+ statistics_payload: dict[str, Any],
1229
+ memory: Mapping[str, Any],
1230
+ config: Mapping[str, Any],
1231
+ ) -> None:
1232
+ """Apply declarative aliases, graph weights, and rankings to report context."""
1233
+ projections = config.get("projecoes") or {}
1234
+ for alias, node_id in (projections.get("campos_por_auditado") or {}).items():
1235
+ for row in rows:
1236
+ if node_id not in row:
1237
+ raise InputValidationError(
1238
+ f"fonte de projeção {node_id!r} ausente na linha de {row.get(config.get('coluna_auditado') or 'sigla')!r}"
1239
+ )
1240
+ value = row[node_id]
1241
+ if alias in row and row[alias] != value:
1242
+ raise InputValidationError(f"campo projetado {alias!r} conflita com valor já existente")
1243
+ row[alias] = value
1244
+
1245
+ for name, value in (projections.get("constantes") or {}).items():
1246
+ if name in statistics_payload and statistics_payload[name] != value:
1247
+ raise InputValidationError(f"constante projetada {name!r} conflita com estatística calculada")
1248
+ statistics_payload[name] = value
1249
+
1250
+ nodes = memory.get("calculo") or {}
1251
+ for output_name, reference in (projections.get("pesos") or {}).items():
1252
+ node = nodes.get(reference["no"])
1253
+ components = node.get("componentes") if isinstance(node, Mapping) else None
1254
+ component = reference["componente"]
1255
+ if isinstance(components, Mapping):
1256
+ weight = components.get(component)
1257
+ elif isinstance(components, list) and component in components:
1258
+ weight = 1.0
1259
+ else:
1260
+ weight = None
1261
+ if weight is None:
1262
+ raise InputValidationError(
1263
+ f"peso de {component!r} no nó {reference['no']!r} não está disponível na definição do índice"
1264
+ )
1265
+ statistics_payload[output_name] = weight
1266
+
1267
+ for prefix, ranking in (projections.get("rankings") or {}).items():
1268
+ means: list[tuple[str, str, float]] = []
1269
+ for node_id, label in ranking["nos"].items():
1270
+ values = _colunas_numericas(rows, str(node_id))
1271
+ if not values:
1272
+ raise InputValidationError(f"ranking {prefix!r} não tem valores numéricos para o nó {node_id!r}")
1273
+ means.append((str(node_id), str(label), statistics.fmean(values)))
1274
+ highest = max(means, key=lambda item: item[2])
1275
+ lowest = min(means, key=lambda item: item[2])
1276
+ statistics_payload[f"{prefix}_maior_media_nome"] = highest[1]
1277
+ statistics_payload[f"{prefix}_maior_media_valor"] = highest[2]
1278
+ statistics_payload[f"{prefix}_menor_media_nome"] = lowest[1]
1279
+ statistics_payload[f"{prefix}_menor_media_valor"] = lowest[2]
1280
+
1281
+
1282
+ def render_context(
1283
+ linhas: list[dict[str, Any]],
1284
+ memory: Mapping[str, Any],
1285
+ config: Mapping[str, Any],
1286
+ *,
1287
+ comparavel_atual: list[dict[str, Any]] | None = None,
1288
+ anteriores_por_grupo: Mapping[str, list[dict[str, Any]]] | None = None,
1289
+ aliases: Mapping[str, str] | None = None,
1290
+ modo: str = "simples",
1291
+ ) -> tuple[list[dict[str, Any]], dict[str, Any], list[dict[str, Any]]]:
1292
+ """Porto genérico de ``gerar_contexto``: linhas do contexto + estatísticas + pareados."""
1293
+ estatisticas = global_stats(linhas, memory, config)
1294
+ _apply_report_projections(linhas, estatisticas, memory, config)
1295
+ pareados: list[dict[str, Any]] = []
1296
+ if comparavel_atual is not None and anteriores_por_grupo is not None:
1297
+ aliases_config = dict((config.get("comparacao") or {}).get("aliases") or {})
1298
+ aliases_config.update(aliases or {})
1299
+ _, pareados, _ = parear_ciclos(
1300
+ comparavel_atual,
1301
+ anteriores_por_grupo,
1302
+ aliases=aliases_config,
1303
+ modo=modo,
1304
+ config=config,
1305
+ )
1306
+ estatisticas["comparacao_pareados_n"] = len(pareados)
1307
+ cobertura_sufixo = str((config.get("comparacao") or {}).get("cobertura_sufixo") or "")
1308
+ sufixo = f"_{cobertura_sufixo}" if cobertura_sufixo else ""
1309
+ estatisticas[f"comparacao_cobertura{sufixo}_pct"] = percentual(len(pareados), len(linhas))
1310
+
1311
+ coluna_auditado = str(config.get("coluna_auditado") or "sigla")
1312
+ comparacao_ativa = comparavel_atual is not None and anteriores_por_grupo is not None
1313
+ campos_comparacao: list[str] = []
1314
+ if comparacao_ativa:
1315
+ comparacao = config.get("comparacao") or {}
1316
+ ciclo_anterior, ciclo_atual = comparison_cycle_keys(config)
1317
+ indicadores = comparacao.get("indicadores") or {}
1318
+ direcao_coluna = str(comparacao.get("direcao_coluna") or "")
1319
+ campos_comparacao = [
1320
+ f"comparacao_sigla_{ciclo_anterior}",
1321
+ "comparacao_tipo_pareamento",
1322
+ "comparacao_grupo",
1323
+ f"comparacao_nivel_{ciclo_anterior}",
1324
+ f"comparacao_nivel_{ciclo_atual}",
1325
+ ]
1326
+ for indicador, espec in indicadores.items():
1327
+ prefixo = str(espec.get("prefixo") or slugify(indicador))
1328
+ campos_comparacao.extend(
1329
+ [
1330
+ f"comparacao_{prefixo}_{ciclo_anterior}",
1331
+ f"comparacao_{prefixo}_{ciclo_atual}",
1332
+ f"comparacao_delta_{prefixo}",
1333
+ ]
1334
+ )
1335
+ if indicador == direcao_coluna:
1336
+ campos_comparacao.append(f"comparacao_direcao_{prefixo}")
1337
+ campos_comparacao.extend(
1338
+ ["comparacao_principais_avancos", "comparacao_principais_regressoes"]
1339
+ )
1340
+
1341
+ contexto: list[dict[str, Any]] = []
1342
+ for linha in linhas:
1343
+ registro = dict(linha)
1344
+ for nome, valor in estatisticas.items():
1345
+ registro[nome] = valor
1346
+ if comparacao_ativa:
1347
+ ciclo_anterior, _ = comparison_cycle_keys(config)
1348
+ registro[f"tem_comparacao_{ciclo_anterior}"] = False
1349
+ for campo in campos_comparacao:
1350
+ registro[campo] = None
1351
+ contexto.append(registro)
1352
+
1353
+ if pareados:
1354
+ chave_por_sigla = {
1355
+ normalizar_chave(linha.get(coluna_auditado), modo=modo): linha
1356
+ for linha in contexto
1357
+ }
1358
+ for par in pareados:
1359
+ _, ciclo_atual = comparison_cycle_keys(config)
1360
+ chave = par.get(f"chave_{ciclo_atual}")
1361
+ if chave not in chave_por_sigla:
1362
+ continue
1363
+ registro = chave_por_sigla[chave]
1364
+ registro.update(comparacao_fields(par, config))
1365
+ return contexto, estatisticas, pareados
1366
+
1367
+
1368
+ def context_workbook_bytes(
1369
+ linhas: Iterable[Mapping[str, Any]],
1370
+ config: Mapping[str, Any],
1371
+ ) -> bytes:
1372
+ """XLSX largo do contexto, indexado pela coluna de auditado."""
1373
+ try:
1374
+ from openpyxl import Workbook
1375
+ except ImportError as exc: # pragma: no cover - opcional no pacote base
1376
+ raise InputValidationError("a geração do contexto XLSX requer openpyxl") from exc
1377
+ linhas = list(linhas)
1378
+ colunas: list[str] = []
1379
+ for linha in linhas:
1380
+ for coluna in linha:
1381
+ if coluna not in colunas:
1382
+ colunas.append(coluna)
1383
+
1384
+ workbook = Workbook()
1385
+ worksheet = workbook.active
1386
+ worksheet.title = "contexto"
1387
+ worksheet.append(colunas)
1388
+ for linha in linhas:
1389
+ valores: list[Any] = []
1390
+ for coluna in colunas:
1391
+ valor = linha.get(coluna)
1392
+ if isinstance(valor, (dict, list, tuple)):
1393
+ valor = json.dumps(valor, ensure_ascii=False)
1394
+ valores.append(valor)
1395
+ worksheet.append(valores)
1396
+ worksheet.freeze_panes = "A2"
1397
+ buffer = io.BytesIO()
1398
+ workbook.save(buffer)
1399
+ return buffer.getvalue()
1400
+
1401
+
1402
+ def context_json_payload(
1403
+ linhas: Iterable[Mapping[str, Any]],
1404
+ estatisticas: Mapping[str, Any],
1405
+ fontes: Mapping[str, Any],
1406
+ config: Mapping[str, Any],
1407
+ ) -> dict[str, Any]:
1408
+ """JSON consumível por ``gerar-relatorios-auditoria`` (globais repetidas por auditado)."""
1409
+ coluna_auditado = str(config.get("coluna_auditado") or "sigla")
1410
+ auditados: dict[str, Any] = {}
1411
+ for linha in linhas:
1412
+ chave = str(linha.get(coluna_auditado) or "")
1413
+ if chave:
1414
+ auditados[chave] = dict(linha)
1415
+ payload = {
1416
+ **dict(estatisticas),
1417
+ "fontes": dict(fontes),
1418
+ "estatisticas": dict(estatisticas),
1419
+ "auditados": auditados,
1420
+ }
1421
+ if config.get("layout_documento") is not None:
1422
+ payload["layout_documento"] = config["layout_documento"]
1423
+ return payload
1424
+
1425
+
1426
+ def _validate_registered_index_source(context, path: Path, *, scenario: str, label: str) -> dict[str, Any] | None:
1427
+ """Valida o produto de índice quando o arquivo já foi registrado no controle."""
1428
+ rows = context.store._execute(
1429
+ "SELECT p.id, e.scenario_id, p.sha256, e.status FROM product p "
1430
+ "JOIN execution e ON e.id=p.execution_id "
1431
+ "WHERE e.fiscalizacao_id=? AND p.path=? "
1432
+ "AND p.kind IN ('index-result', 'indices-batch', 'indices-workbook') "
1433
+ "ORDER BY p.created_at DESC, p.id DESC",
1434
+ (context.store.fiscalizacao_id, str(path)),
1435
+ ).fetchall()
1436
+ if not rows:
1437
+ return {"status": "unregistered", "path": str(path)}
1438
+ digest = sha256_file(path)
1439
+ matching = [row for row in rows if row["sha256"] == digest]
1440
+ if not matching:
1441
+ raise InputValidationError(f"{label} diverge da versão registrada como produto")
1442
+ matching_scenario = [row for row in matching if row["scenario_id"] == scenario]
1443
+ if not matching_scenario:
1444
+ raise InputValidationError(f"{label} pertence a outro cenário")
1445
+ completed = next((row for row in matching_scenario if row["status"] == "completed"), None)
1446
+ if completed is None:
1447
+ raise InputValidationError(f"{label} não possui execução produtora concluída")
1448
+ return {"status": "current", "path": str(path), "artifact_id": completed["id"]}
1449
+
1450
+
1451
+ def generate_report_context(context: OperationContext) -> OperationResult:
1452
+ """Gera o contexto por auditado (resultados + estatísticas + comparação)."""
1453
+ results_path = require_file(context, context.params["results"], "resultados do cálculo")
1454
+ scenario = context.params.get("scenario") or "base"
1455
+ results_provenance = _validate_registered_index_source(
1456
+ context, results_path, scenario=scenario, label="resultados do cálculo"
1457
+ )
1458
+ return _generate_report_context(
1459
+ context,
1460
+ results_path=results_path,
1461
+ results_payload=None,
1462
+ results_provenance=results_provenance,
1463
+ )
1464
+
1465
+
1466
+ def generate_report_context_from_payload(
1467
+ context: OperationContext,
1468
+ payload: Mapping[str, Any],
1469
+ params: Mapping[str, Any],
1470
+ ) -> OperationResult:
1471
+ """Gera contexto ligado à execução registrada do cálculo recém-realizado."""
1472
+ inner = replace(context, params=dict(params))
1473
+ public_payload = _public_index_payload(payload)
1474
+ execution = context.store.get_execution(context.execution_id)
1475
+ provenance = {
1476
+ "kind": "execution-result",
1477
+ "execution_id": context.execution_id,
1478
+ "input_hash": execution.get("input_hash") if execution else None,
1479
+ "sha256": sha256_bytes(canonical_json(public_payload).encode("utf-8")),
1480
+ }
1481
+ return _generate_report_context(
1482
+ inner,
1483
+ results_path=None,
1484
+ results_payload=public_payload,
1485
+ results_provenance=provenance,
1486
+ )
1487
+
1488
+
1489
+ def _generate_report_context(
1490
+ context: OperationContext,
1491
+ *,
1492
+ results_path: Path | None,
1493
+ results_payload: Mapping[str, Any] | None,
1494
+ results_provenance: Mapping[str, Any] | None,
1495
+ ) -> OperationResult:
1496
+ params = context.params
1497
+ if results_path is None and results_payload is None:
1498
+ raise MissingInputError("informe resultados do cálculo")
1499
+ memory_path = require_file(context, params["memoria"], "memória de cálculo")
1500
+ report_config_path = require_file(context, params["config_estatisticas"], "config_estatisticas de relatórios")
1501
+ scenario = params.get("scenario") or "base"
1502
+ if context.store.get_scenario(scenario) is None:
1503
+ raise InputValidationError(f"cenário do contexto inexistente: {scenario}")
1504
+
1505
+ memory = load_memory(memory_path)
1506
+ report_config = load_report_config(report_config_path, memory)
1507
+ config = context_config(report_config, memory)
1508
+ key_mode = str(params.get("modo_chave") or "simples")
1509
+ if key_mode != "simples":
1510
+ raise InputValidationError("modo_chave deve ser 'simples'")
1511
+ linhas = (
1512
+ read_results(results_path, config)
1513
+ if results_path is not None
1514
+ else read_index_payload(results_payload or {}, config)
1515
+ )
1516
+ _validar_chaves_unicas(linhas, config, modo=key_mode)
1517
+
1518
+ context_output = context.optional_path(params.get("contexto_output"))
1519
+ json_output = context.optional_path(params.get("contexto_json_output"))
1520
+ if context_output is None and json_output is None:
1521
+ raise MissingInputError("informe contexto_output ou contexto_json_output")
1522
+
1523
+ comparavel_atual_path = context.optional_path(params.get("comparavel_atual"))
1524
+ anteriores_values = params.get("anteriores") or []
1525
+ if isinstance(anteriores_values, (str, Path)):
1526
+ anteriores_values = [anteriores_values]
1527
+ anteriores_paths = [context.path(value) for value in anteriores_values]
1528
+ if (comparavel_atual_path is None) != (not anteriores_paths):
1529
+ raise InputValidationError(
1530
+ "informe comparavel_atual e anteriores juntos para habilitar a comparação com o ciclo anterior"
1531
+ )
1532
+ aliases = load_aliases(context.optional_path(params.get("aliases")))
1533
+
1534
+ comparavel_atual = None
1535
+ anteriores_por_grupo = None
1536
+ if comparavel_atual_path is not None:
1537
+ require_file(context, comparavel_atual_path, "comparável do ciclo atual")
1538
+ comparavel_atual = read_comparavel(comparavel_atual_path, config)
1539
+ grupos = list((config.get("comparacao") or {}).get("grupos") or [])
1540
+ grupos_value = params.get("grupos_anteriores") or []
1541
+ if isinstance(grupos_value, (str, Path)):
1542
+ grupos_value = [grupos_value]
1543
+ if grupos_value:
1544
+ grupos = [str(grupo) for grupo in grupos_value]
1545
+ if len(grupos) != len(anteriores_paths):
1546
+ raise InputValidationError("grupos_anteriores deve ter um rótulo por arquivo anterior")
1547
+ anteriores_por_grupo = {}
1548
+ for grupo, path in zip(grupos, anteriores_paths):
1549
+ require_file(context, path, f"ciclo anterior ({grupo})")
1550
+ anteriores_por_grupo[grupo] = read_comparavel(path, config)
1551
+
1552
+ contexto, estatisticas, pareados = render_context(
1553
+ linhas,
1554
+ memory,
1555
+ config,
1556
+ comparavel_atual=comparavel_atual,
1557
+ anteriores_por_grupo=anteriores_por_grupo,
1558
+ aliases=aliases,
1559
+ modo=key_mode,
1560
+ )
1561
+
1562
+ results_sha256 = sha256_file(results_path) if results_path is not None else str((results_provenance or {}).get("sha256") or "")
1563
+ if not results_sha256:
1564
+ results_sha256 = sha256_bytes(canonical_json(dict(results_payload or {})).encode("utf-8"))
1565
+ results_source: Any = str(results_path) if results_path is not None else dict(results_provenance or {})
1566
+ fontes = {
1567
+ "results": results_source,
1568
+ "memory": str(memory_path),
1569
+ "report_config": str(report_config_path),
1570
+ "comparavel_atual": str(comparavel_atual_path) if comparavel_atual_path else None,
1571
+ "anteriores": [str(path) for path in anteriores_paths],
1572
+ "aliases": str(context.optional_path(params.get("aliases"))) if params.get("aliases") else None,
1573
+ }
1574
+ fontes_sha256 = {}
1575
+ fontes_sha256["results"] = results_sha256
1576
+ for name, value in fontes.items():
1577
+ if isinstance(value, Mapping):
1578
+ continue
1579
+ paths = value if isinstance(value, list) else [value]
1580
+ hashes = [sha256_file(Path(item)) for item in paths if isinstance(item, str) and Path(item).is_file()]
1581
+ if hashes:
1582
+ fontes_sha256[name] = hashes if isinstance(value, list) else hashes[0]
1583
+ fontes_provenance = {
1584
+ "results": (
1585
+ "execution_reference"
1586
+ if results_path is None
1587
+ else (results_provenance or {}).get("status", "unregistered")
1588
+ ),
1589
+ "memory": "input_hash_recorded",
1590
+ "report_config": "input_hash_recorded",
1591
+ }
1592
+ for name in ("comparavel_atual", "aliases"):
1593
+ if name in fontes_sha256:
1594
+ fontes_provenance[name] = "input_hash_recorded"
1595
+ if "anteriores" in fontes_sha256:
1596
+ fontes_provenance["anteriores"] = ["input_hash_recorded"] * len(anteriores_paths)
1597
+
1598
+ products: list[ProductDraft] = []
1599
+ if context_output is not None:
1600
+ products.append(
1601
+ ProductDraft(
1602
+ kind="contexto-relatorios-xlsx",
1603
+ path=context_output,
1604
+ content=context_workbook_bytes(contexto, config),
1605
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1606
+ metadata={
1607
+ "scenario": scenario,
1608
+ "sources_sha256": fontes_sha256,
1609
+ "sources_validation": fontes_provenance,
1610
+ },
1611
+ )
1612
+ )
1613
+ if json_output is not None:
1614
+ payload = context_json_payload(contexto, estatisticas, fontes, config)
1615
+ payload.update(
1616
+ {
1617
+ "format": REPORT_CONTEXT_FORMAT,
1618
+ "scenario": scenario,
1619
+ "sources_sha256": fontes_sha256,
1620
+ "sources_validation": fontes_provenance,
1621
+ }
1622
+ )
1623
+ products.append(
1624
+ ProductDraft(
1625
+ kind="contexto-relatorios-json",
1626
+ path=json_output,
1627
+ content=json.dumps(payload, ensure_ascii=False, indent=2),
1628
+ media_type="application/json",
1629
+ metadata={
1630
+ "scenario": scenario,
1631
+ "sources_sha256": fontes_sha256,
1632
+ "sources_validation": fontes_provenance,
1633
+ },
1634
+ )
1635
+ )
1636
+
1637
+ return OperationResult(
1638
+ summary={
1639
+ "results": results_source,
1640
+ "results_sha256": results_sha256,
1641
+ "memory": str(memory_path),
1642
+ "memory_sha256": sha256_file(memory_path),
1643
+ "report_config": str(report_config_path),
1644
+ "report_config_sha256": sha256_file(report_config_path),
1645
+ "scenario": scenario,
1646
+ "key_mode": key_mode,
1647
+ "auditados": len(contexto),
1648
+ "pareados": len(pareados),
1649
+ "context_output": str(context_output) if context_output else None,
1650
+ "json_output": str(json_output) if json_output else None,
1651
+ },
1652
+ products=tuple(products),
1653
+ )
1654
+
1655
+
1656
+ def calculate_index(context: OperationContext) -> OperationResult:
1657
+ """Calcula uma memória e, com `config_estatisticas`, também o contexto estatístico dos relatórios."""
1658
+ params = context.params
1659
+ context_requested = bool(params.get("contexto_output") or params.get("contexto_json_output"))
1660
+ if context_requested and not params.get("config_estatisticas"):
1661
+ raise MissingInputError("informe config_estatisticas para gerar o contexto de relatórios")
1662
+ if params.get("config_estatisticas") and not context_requested:
1663
+ raise InputValidationError("config_estatisticas requer contexto_output ou contexto_json_output")
1664
+ payload = calculate_index_payload(context)
1665
+ res = index_result_from_payload(context, payload, output_value=params.get("output"))
1666
+ if not context_requested:
1667
+ return res
1668
+ ctx_params = {
1669
+ "memoria": params["memoria"],
1670
+ "config_estatisticas": params["config_estatisticas"],
1671
+ "scenario": params.get("scenario") or "base",
1672
+ }
1673
+ for k in ("comparavel_atual", "anteriores", "grupos_anteriores", "aliases", "modo_chave", "contexto_output", "contexto_json_output"):
1674
+ if params.get(k) is not None:
1675
+ ctx_params[k] = params[k]
1676
+ ctx_res = generate_report_context_from_payload(context, payload, ctx_params)
1677
+ return context.merge_composed(
1678
+ res,
1679
+ summary={"report_context": dict(ctx_res.summary)},
1680
+ products=ctx_res.products,
1681
+ warnings=ctx_res.warnings,
1682
+ pending=ctx_res.pending,
1683
+ )