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.
- argos/__init__.py +5 -0
- argos/__main__.py +4 -0
- argos/adapters/__init__.py +9 -0
- argos/adapters/_libreoffice_worker.py +111 -0
- argos/adapters/ai.py +1506 -0
- argos/adapters/ai_remote.py +654 -0
- argos/adapters/attachment_conversion.py +132 -0
- argos/adapters/capabilities.py +31 -0
- argos/adapters/chart_render.py +72 -0
- argos/adapters/docx_pdf.py +2953 -0
- argos/adapters/limesurvey.py +1079 -0
- argos/adapters/model_call.py +274 -0
- argos/adapters/report_publication.py +1530 -0
- argos/adapters/url_fetch.py +146 -0
- argos/adapters/xlsx.py +454 -0
- argos/analytics.py +731 -0
- argos/assets.py +257 -0
- argos/audit_result.py +369 -0
- argos/booleans.py +105 -0
- argos/catalog.py +1205 -0
- argos/cli.py +606 -0
- argos/contracts.py +532 -0
- argos/core.py +325 -0
- argos/default_skills/README.md +23 -0
- argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
- argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
- argos/default_skills/operar-argos/SKILL.md +74 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
- argos/engines/__init__.py +3 -0
- argos/engines/adjustments.py +571 -0
- argos/engines/analytics.py +195 -0
- argos/engines/audit.py +2730 -0
- argos/engines/evaluation.py +6088 -0
- argos/engines/index.py +1683 -0
- argos/engines/matrix.py +5736 -0
- argos/engines/matrix_html.py +698 -0
- argos/engines/model_request.py +201 -0
- argos/engines/report_document.py +137 -0
- argos/engines/reports.py +1200 -0
- argos/engines/survey.py +4445 -0
- argos/envfile.py +53 -0
- argos/errors.py +29 -0
- argos/evidence_staging.py +293 -0
- argos/executions.py +565 -0
- argos/findings_matrix.py +2549 -0
- argos/fingerprints.py +487 -0
- argos/index_dsl.py +2100 -0
- argos/matrix_markdown.py +475 -0
- argos/matrix_widths.py +280 -0
- argos/pipeline.py +1745 -0
- argos/products.py +220 -0
- argos/progress.py +221 -0
- argos/project.py +608 -0
- argos/report_config.py +158 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
- argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
- argos/resources/anexo-evidencias-base.docx +0 -0
- argos/resources/argos-index-dsl-v1.schema.json +539 -0
- argos/resources/argos-report-config-v1.schema.json +113 -0
- argos/resources/diretrizes-projeto.md +476 -0
- argos/resources/env.example +37 -0
- argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
- argos/resources/exemplos/matriz_achados_draft.md +106 -0
- argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
- argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
- argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
- argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
- argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
- argos/resources/template-base-estilos-sigiloso.docx +0 -0
- argos/resources/template-base-estilos.docx +0 -0
- argos/resources/template-matriz-planejamento.docx +0 -0
- argos/resources/template-relatorio-consolidado-comum.docx +0 -0
- argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
- argos/response_profiles.py +856 -0
- argos/scheduler.py +142 -0
- argos/status.py +367 -0
- argos/store.py +1228 -0
- argos/survey_collection.py +832 -0
- argos/telemetry.py +84 -0
- argos/tui.py +1262 -0
- argos/tui.tcss +827 -0
- argos/tui_models.py +466 -0
- argos/tui_path.py +155 -0
- argos/tui_widgets.py +482 -0
- argos/version.py +3 -0
- argos_cli-0.3.1.dist-info/METADATA +570 -0
- argos_cli-0.3.1.dist-info/RECORD +96 -0
- argos_cli-0.3.1.dist-info/WHEEL +5 -0
- argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
- argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/engines/reports.py
ADDED
|
@@ -0,0 +1,1200 @@
|
|
|
1
|
+
"""Documentos, ativos e composição de relatórios de auditoria."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import gc
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import threading
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Iterable, Mapping
|
|
13
|
+
|
|
14
|
+
from ..booleans import normalize
|
|
15
|
+
from ..assets import AssetEntry, load_manifest, validate_manifest
|
|
16
|
+
from ..contracts import OperationResult, canonical_json, sha256_bytes, sha256_file
|
|
17
|
+
from ..core import InputValidationError, MissingInputError, OperationContext, ProductDraft, ResourceProfile, ScheduledUnit
|
|
18
|
+
from ..adapters.docx_pdf import validate_markdown_pipe_tables
|
|
19
|
+
from ..adapters.report_publication import resolve_report_layout
|
|
20
|
+
from ..adapters.xlsx import load_json_list, load_json_object, require_file
|
|
21
|
+
from .report_document import ReportDocumentRequest, publish_document
|
|
22
|
+
from .audit import (
|
|
23
|
+
anexar_ajustes,
|
|
24
|
+
anexar_funcoes,
|
|
25
|
+
audit_rows_from_result,
|
|
26
|
+
carregar_ajustes_respostas,
|
|
27
|
+
evidence_annex_context,
|
|
28
|
+
)
|
|
29
|
+
from .index import REPORT_CONTEXT_FORMAT
|
|
30
|
+
|
|
31
|
+
FORMAT = REPORT_CONTEXT_FORMAT
|
|
32
|
+
_DOCX_CYCLE_COLLECTION_INTERVAL = 4
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_SKIP = object()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _json_safe(value: Any) -> Any:
|
|
39
|
+
if callable(value):
|
|
40
|
+
return _SKIP
|
|
41
|
+
if isinstance(value, Mapping):
|
|
42
|
+
return {str(key): cleaned for key, item in value.items() if (cleaned := _json_safe(item)) is not _SKIP}
|
|
43
|
+
if isinstance(value, (list, tuple)):
|
|
44
|
+
return [cleaned for item in value if (cleaned := _json_safe(item)) is not _SKIP]
|
|
45
|
+
if isinstance(value, Path):
|
|
46
|
+
return str(value)
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def normalize_report_date(value: Any) -> tuple[str | None, str | None]:
|
|
51
|
+
"""Valida data ISO explícita e devolve valor canônico e apresentação pt-BR."""
|
|
52
|
+
if value in (None, ""):
|
|
53
|
+
return None, None
|
|
54
|
+
try:
|
|
55
|
+
text = str(value).strip()
|
|
56
|
+
parsed = datetime.date.fromisoformat(text)
|
|
57
|
+
if parsed.isoformat() != text:
|
|
58
|
+
raise ValueError(text)
|
|
59
|
+
except ValueError as exc:
|
|
60
|
+
raise InputValidationError("data_relatorio deve estar no formato AAAA-MM-DD") from exc
|
|
61
|
+
canonical = parsed.isoformat()
|
|
62
|
+
return canonical, parsed.strftime("%d/%m/%Y")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def source_reference(value: Any, root: Path, *, label: str) -> dict[str, str] | None:
|
|
66
|
+
if value in (None, ""):
|
|
67
|
+
return None
|
|
68
|
+
if isinstance(value, Mapping):
|
|
69
|
+
digest = sha256_bytes(canonical_json(_json_safe(value)).encode("utf-8"))
|
|
70
|
+
return {"label": label, "kind": "inline", "sha256": digest}
|
|
71
|
+
path = Path(value).expanduser()
|
|
72
|
+
if not path.is_absolute():
|
|
73
|
+
path = root / path
|
|
74
|
+
path = path.resolve()
|
|
75
|
+
try:
|
|
76
|
+
digest = sha256_file(path)
|
|
77
|
+
except OSError as exc:
|
|
78
|
+
raise InputValidationError(f"fonte do relatório indisponível ({label}): {path}") from exc
|
|
79
|
+
return {"label": label, "path": str(path), "sha256": digest}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
IDENTIDADE = ("numero", "titulo", "objetivo", "numero_processo", "jurisdicionados")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def fiscalizacao_values(params, store) -> dict[str, str]:
|
|
86
|
+
"""Metadados efetivos já resolvidos e registrados no snapshot da execução.
|
|
87
|
+
|
|
88
|
+
``params`` usa os nomes da identidade do catálogo (``IDENTIDADE``).
|
|
89
|
+
"""
|
|
90
|
+
return {
|
|
91
|
+
"numero": str(params.get("numero") or store.numero),
|
|
92
|
+
"nome": str(params.get("titulo") or store.nome),
|
|
93
|
+
"titulo": str(params.get("titulo") or store.nome),
|
|
94
|
+
"objetivo": str(params.get("objetivo") or ""),
|
|
95
|
+
"numero_processo": str(params.get("numero_processo") or ""),
|
|
96
|
+
"jurisdicionados": str(params.get("jurisdicionados") or ""),
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _identidade(params: Mapping[str, Any]) -> dict[str, Any]:
|
|
101
|
+
"""Campos de identidade informados, para repassar a outro handler."""
|
|
102
|
+
return {key: params[key] for key in IDENTIDADE if params.get(key) is not None}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def with_project_fields(context: OperationContext, values: dict[str, Any]) -> dict[str, Any]:
|
|
106
|
+
"""Seções de fiscalizacao.yml (orgao, fiscalizacao, relatorio) sob o contexto do relatório."""
|
|
107
|
+
from ..project import project_template_values
|
|
108
|
+
|
|
109
|
+
for section, configured in project_template_values(context.project_root).items():
|
|
110
|
+
values[section] = {**dict(configured), **dict(values.get(section) or {})}
|
|
111
|
+
return values
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def normalized_context(
|
|
115
|
+
*,
|
|
116
|
+
scenario: str,
|
|
117
|
+
report_date: str | None,
|
|
118
|
+
sources: Mapping[str, Any],
|
|
119
|
+
common: Mapping[str, Any],
|
|
120
|
+
auditees: Mapping[str, Mapping[str, Any]],
|
|
121
|
+
) -> dict[str, Any]:
|
|
122
|
+
return {
|
|
123
|
+
"format": FORMAT,
|
|
124
|
+
"scenario": scenario,
|
|
125
|
+
"report_date": report_date,
|
|
126
|
+
"sources": dict(sources),
|
|
127
|
+
"common": dict(common),
|
|
128
|
+
"auditados": {str(key): dict(value) for key, value in auditees.items()},
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _report_resource_base(context: OperationContext, raw_context: Any) -> Path:
|
|
133
|
+
if raw_context and not isinstance(raw_context, Mapping):
|
|
134
|
+
return context.path(raw_context).parent
|
|
135
|
+
return context.project_root
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _merge_report_context_sources(
|
|
139
|
+
context: OperationContext,
|
|
140
|
+
values: Mapping[str, Any],
|
|
141
|
+
raw_sources: Any,
|
|
142
|
+
) -> tuple[dict[str, Any], list[Path]]:
|
|
143
|
+
"""Merge explicit JSON context sources while rejecting conflicting values."""
|
|
144
|
+
sources = raw_sources or []
|
|
145
|
+
if isinstance(sources, (str, Path)):
|
|
146
|
+
sources = [sources]
|
|
147
|
+
merged = dict(values)
|
|
148
|
+
paths: list[Path] = []
|
|
149
|
+
|
|
150
|
+
def merge_mapping(target: dict[str, Any], incoming: Mapping[str, Any], label: str, prefix: str = "") -> None:
|
|
151
|
+
for raw_key, value in incoming.items():
|
|
152
|
+
key = str(raw_key)
|
|
153
|
+
location = f"{prefix}.{key}" if prefix else key
|
|
154
|
+
if key not in target:
|
|
155
|
+
target[key] = value
|
|
156
|
+
elif isinstance(target[key], Mapping) and isinstance(value, Mapping):
|
|
157
|
+
nested = dict(target[key])
|
|
158
|
+
merge_mapping(nested, value, label, location)
|
|
159
|
+
target[key] = nested
|
|
160
|
+
elif target[key] != value:
|
|
161
|
+
raise InputValidationError(
|
|
162
|
+
f"conflito entre contexto principal e fonte complementar {label!r} no campo {location!r}"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
for raw_path in sources:
|
|
166
|
+
path = require_file(context, raw_path, "fonte complementar de contexto")
|
|
167
|
+
payload = load_json_object(context, path, label="fonte complementar de contexto")
|
|
168
|
+
merge_mapping(merged, payload, path.name)
|
|
169
|
+
paths.append(path)
|
|
170
|
+
return merged, paths
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _report_resource_aliases(values: Mapping[str, Any], base: Path) -> dict[str, Path]:
|
|
174
|
+
aliases = values.get("recursos") or {}
|
|
175
|
+
if not isinstance(aliases, Mapping):
|
|
176
|
+
raise InputValidationError("recursos do relatório deve ser um mapeamento alias: caminho")
|
|
177
|
+
resolved: dict[str, Path] = {}
|
|
178
|
+
for alias, value in aliases.items():
|
|
179
|
+
if not isinstance(alias, str) or not alias.strip() or not isinstance(value, str) or not value.strip():
|
|
180
|
+
raise InputValidationError("cada recurso exige alias e caminho não vazios")
|
|
181
|
+
path = Path(value).expanduser()
|
|
182
|
+
path = (path if path.is_absolute() else base / path).resolve()
|
|
183
|
+
if not path.is_file():
|
|
184
|
+
raise InputValidationError(f"recurso explícito do relatório não encontrado: {alias}: {path}")
|
|
185
|
+
resolved[alias] = path
|
|
186
|
+
return resolved
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _render_report_markdown(template_path: Path, values: Mapping[str, Any]) -> str:
|
|
190
|
+
"""Renderiza template Jinja uma vez, com suporte aos marcadores de recursos."""
|
|
191
|
+
try:
|
|
192
|
+
from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape
|
|
193
|
+
except ImportError as exc: # pragma: no cover
|
|
194
|
+
raise InputValidationError("relatórios Jinja requerem jinja2; instale argos-cli[reports]") from exc
|
|
195
|
+
|
|
196
|
+
class ReportEnvironment(Environment):
|
|
197
|
+
def preprocess(self, source, name=None, filename=None):
|
|
198
|
+
# Lexing distinguishes actual comments from raw blocks and quoted
|
|
199
|
+
# expressions. Every loaded template/partial uses this environment.
|
|
200
|
+
tokens = list(self.lex(source, name, filename))
|
|
201
|
+
output: list[str] = []
|
|
202
|
+
position = 0
|
|
203
|
+
while position < len(tokens):
|
|
204
|
+
_, kind, value = tokens[position]
|
|
205
|
+
if (
|
|
206
|
+
kind == "comment_begin"
|
|
207
|
+
and value == "{#"
|
|
208
|
+
and position + 2 < len(tokens)
|
|
209
|
+
and tokens[position + 1][1] == "comment"
|
|
210
|
+
and tokens[position + 2][1:] == ("comment_end", "#}")
|
|
211
|
+
and re.fullmatch(r"(?:fig|tbl):[^#\r\n]+", tokens[position + 1][2])
|
|
212
|
+
):
|
|
213
|
+
declaration = "".join(item[2] for item in tokens[position : position + 3])
|
|
214
|
+
output.append("{{ " + repr(declaration) + " }}")
|
|
215
|
+
position += 3
|
|
216
|
+
else:
|
|
217
|
+
output.append(value)
|
|
218
|
+
position += 1
|
|
219
|
+
return super().preprocess("".join(output), name, filename)
|
|
220
|
+
|
|
221
|
+
environment = ReportEnvironment(
|
|
222
|
+
loader=FileSystemLoader(str(template_path.parent)),
|
|
223
|
+
undefined=StrictUndefined,
|
|
224
|
+
autoescape=select_autoescape(
|
|
225
|
+
enabled_extensions=("html", "xml"),
|
|
226
|
+
default_for_string=False,
|
|
227
|
+
default=False,
|
|
228
|
+
),
|
|
229
|
+
keep_trailing_newline=True,
|
|
230
|
+
)
|
|
231
|
+
try:
|
|
232
|
+
return environment.get_template(template_path.name).render(**dict(values))
|
|
233
|
+
except Exception as exc: # noqa: BLE001 - preserva o erro do template no evento da execução
|
|
234
|
+
raise InputValidationError(f"falha ao renderizar template {template_path}: {exc}") from exc
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def render_report(context: OperationContext) -> OperationResult:
|
|
238
|
+
"""Renderiza Markdown como template Jinja e publica em DOCX, sem arquivo intermediário.
|
|
239
|
+
|
|
240
|
+
É o núcleo de `documento` e dos relatórios da auditoria. Sem `contexto`, o
|
|
241
|
+
contexto é vazio e um Markdown sem `{{ }}` sai como está.
|
|
242
|
+
"""
|
|
243
|
+
params = context.params
|
|
244
|
+
template_path = require_file(context, params["input"], "Markdown")
|
|
245
|
+
output_path = context.path(params["output"])
|
|
246
|
+
raw_context = params.get("contexto")
|
|
247
|
+
values, context_source_paths = _merge_report_context_sources(
|
|
248
|
+
context,
|
|
249
|
+
load_json_object(context, raw_context, label="contexto de relatórios"),
|
|
250
|
+
params.get("fontes_contexto"),
|
|
251
|
+
)
|
|
252
|
+
with_project_fields(context, values)
|
|
253
|
+
values["fiscalizacao"] = {**dict(values.get("fiscalizacao") or {}), **fiscalizacao_values(params, context.store)}
|
|
254
|
+
report_date, report_date_br = normalize_report_date(
|
|
255
|
+
params.get("data_relatorio") or values.get("report_date") or values.get("data_relatorio")
|
|
256
|
+
)
|
|
257
|
+
scenario = str(params.get("scenario") or "base")
|
|
258
|
+
if context.store.get_scenario(scenario) is None:
|
|
259
|
+
raise InputValidationError(f"cenário do relatório inexistente: {scenario}")
|
|
260
|
+
if not isinstance(raw_context, Mapping):
|
|
261
|
+
|
|
262
|
+
context_validation = _validate_report_context(context, raw_context, values, scenario)
|
|
263
|
+
else:
|
|
264
|
+
context_validation = {"status": "inline"}
|
|
265
|
+
if report_date:
|
|
266
|
+
values["report_date"] = report_date
|
|
267
|
+
values["data_relatorio"] = report_date
|
|
268
|
+
values["data_hoje"] = report_date_br
|
|
269
|
+
context_path = None if isinstance(raw_context, Mapping) else context.optional_path(raw_context)
|
|
270
|
+
markdown = params.get("rendered_markdown")
|
|
271
|
+
if not isinstance(markdown, str):
|
|
272
|
+
markdown = _render_report_markdown(template_path, values)
|
|
273
|
+
publication_config = context.optional_path(params.get("config_publicacao"))
|
|
274
|
+
if publication_config is not None:
|
|
275
|
+
publication_config = require_file(context, publication_config, "configuração de publicação")
|
|
276
|
+
layout = resolve_report_layout(publication_config, values.get("layout_documento"))
|
|
277
|
+
reference = (
|
|
278
|
+
require_file(context, params["estilos"], "modelo DOCX")
|
|
279
|
+
if params.get("estilos")
|
|
280
|
+
else None
|
|
281
|
+
)
|
|
282
|
+
aliases = _report_resource_aliases(
|
|
283
|
+
values, Path(params["resource_base"]) if params.get("resource_base") else _report_resource_base(context, raw_context)
|
|
284
|
+
)
|
|
285
|
+
resources: dict[str, Path] = {}
|
|
286
|
+
outcome = publish_document(
|
|
287
|
+
ReportDocumentRequest(
|
|
288
|
+
markdown=markdown,
|
|
289
|
+
output=output_path,
|
|
290
|
+
resource_root=template_path.parent,
|
|
291
|
+
resource_overrides={**aliases, **context.resource_overrides},
|
|
292
|
+
reference=reference,
|
|
293
|
+
publication_config=publication_config,
|
|
294
|
+
layout=layout,
|
|
295
|
+
values=values,
|
|
296
|
+
document_label=(f"relatório do auditado {values.get('sigla')}" if values.get("sigla") else "relatório"),
|
|
297
|
+
resolve_path=context.path,
|
|
298
|
+
resolved_resources=resources,
|
|
299
|
+
)
|
|
300
|
+
)
|
|
301
|
+
content, pending = outcome.content, outcome.pending
|
|
302
|
+
publication, docx_fields = outcome.publication, outcome.docx_fields
|
|
303
|
+
return OperationResult(
|
|
304
|
+
summary={
|
|
305
|
+
"template": str(template_path),
|
|
306
|
+
"context": str(context_path) if context_path else None,
|
|
307
|
+
"output": str(output_path),
|
|
308
|
+
"bytes": len(content),
|
|
309
|
+
"pending_resources": len(pending),
|
|
310
|
+
"scenario": scenario,
|
|
311
|
+
"report_date": report_date,
|
|
312
|
+
"publication_config": str(publication_config) if publication_config else None,
|
|
313
|
+
"publication": publication,
|
|
314
|
+
"docx_fields": docx_fields,
|
|
315
|
+
},
|
|
316
|
+
products=(
|
|
317
|
+
ProductDraft(
|
|
318
|
+
kind="report-docx",
|
|
319
|
+
path=output_path,
|
|
320
|
+
content=content,
|
|
321
|
+
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
322
|
+
metadata={
|
|
323
|
+
"template": str(template_path),
|
|
324
|
+
"context": str(context_path) if context_path else None,
|
|
325
|
+
"scenario": scenario,
|
|
326
|
+
"report_date": report_date,
|
|
327
|
+
"context_validation": context_validation,
|
|
328
|
+
"resources": {alias: source_reference(path, context.project_root, label=alias)
|
|
329
|
+
for alias, path in resources.items()},
|
|
330
|
+
"sources": {
|
|
331
|
+
"template": source_reference(template_path, context.project_root, label="template"),
|
|
332
|
+
"context": source_reference(raw_context, context.project_root, label="contexto"),
|
|
333
|
+
"reference": source_reference(params.get("estilos"), context.project_root, label="modelo DOCX"),
|
|
334
|
+
"publication_config": source_reference(
|
|
335
|
+
publication_config, context.project_root, label="configuração de publicação"
|
|
336
|
+
),
|
|
337
|
+
"context_sources": [
|
|
338
|
+
source_reference(path, context.project_root, label="fonte complementar de contexto")
|
|
339
|
+
for path in context_source_paths
|
|
340
|
+
],
|
|
341
|
+
},
|
|
342
|
+
"publication": publication,
|
|
343
|
+
"docx_fields": docx_fields,
|
|
344
|
+
},
|
|
345
|
+
),
|
|
346
|
+
),
|
|
347
|
+
pending=pending,
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _carregar_ativos(context: OperationContext, raw_manifests: Any, *, include_auditee: bool) -> list[dict[str, Any]]:
|
|
352
|
+
"""Valida os manifestos de `ativos` e os expõe aos recursos do documento."""
|
|
353
|
+
bindings = _load_asset_bindings(context, raw_manifests)
|
|
354
|
+
if bindings:
|
|
355
|
+
context.resource_overrides.update(_asset_aliases(bindings, include_auditee=include_auditee))
|
|
356
|
+
return bindings
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _com_resumo_ativos(result: OperationResult, bindings: list[dict[str, Any]]) -> OperationResult:
|
|
360
|
+
if not bindings:
|
|
361
|
+
return result
|
|
362
|
+
return replace(
|
|
363
|
+
result,
|
|
364
|
+
summary={
|
|
365
|
+
**dict(result.summary),
|
|
366
|
+
"ativos": sorted({str(item["manifest"]) for item in bindings}),
|
|
367
|
+
"ativos_count": len(bindings),
|
|
368
|
+
},
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def render_documento(context: OperationContext) -> OperationResult:
|
|
373
|
+
"""`documento`: Markdown (template Jinja + contexto) em DOCX e, com --pdf, em PDF."""
|
|
374
|
+
params = context.params
|
|
375
|
+
bindings = _carregar_ativos(context, params.get("ativos"), include_auditee=True)
|
|
376
|
+
result = _com_resumo_ativos(render_report(context), bindings)
|
|
377
|
+
if not (params.get("pdf") or params.get("pdf_output")):
|
|
378
|
+
return result
|
|
379
|
+
from ..adapters.docx_pdf import docx_bytes_to_pdf
|
|
380
|
+
|
|
381
|
+
docx = next(product for product in result.products if product.kind == "report-docx")
|
|
382
|
+
output_path = Path(docx.path)
|
|
383
|
+
pdf_output = context.path(params.get("pdf_output") or output_path.with_suffix(".pdf"))
|
|
384
|
+
if context.staging_root is None:
|
|
385
|
+
raise InputValidationError("geração de PDF requer staging do motor")
|
|
386
|
+
staged_pdf = docx_bytes_to_pdf(docx.content, workdir=context.staging_root, stem=output_path.stem)
|
|
387
|
+
pdf = ProductDraft(
|
|
388
|
+
kind="report-pdf",
|
|
389
|
+
path=pdf_output,
|
|
390
|
+
content=staged_pdf,
|
|
391
|
+
media_type="application/pdf",
|
|
392
|
+
metadata={"docx": str(output_path)},
|
|
393
|
+
)
|
|
394
|
+
return replace(
|
|
395
|
+
result,
|
|
396
|
+
summary={**dict(result.summary), "pdf_output": str(pdf_output)},
|
|
397
|
+
products=(*result.products, pdf),
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def render_documents_batch(context: OperationContext) -> OperationResult:
|
|
402
|
+
"""Renderiza documentos independentes e publica somente os DOCX pedidos."""
|
|
403
|
+
outputs: set[Path] = set()
|
|
404
|
+
completed_documents = 0
|
|
405
|
+
completion_lock = threading.Lock()
|
|
406
|
+
cycle_collection_lock = threading.Lock()
|
|
407
|
+
|
|
408
|
+
def document_case(item: Any, position: int) -> dict[str, Any]:
|
|
409
|
+
if not isinstance(item, Mapping) or not item.get("output") or not item.get("input"):
|
|
410
|
+
raise InputValidationError(f"documento {position} requer input e output")
|
|
411
|
+
normalized = dict(item)
|
|
412
|
+
output_path = context.path(str(normalized["output"]))
|
|
413
|
+
if output_path in outputs:
|
|
414
|
+
raise InputValidationError(f"output repetido no documento {position}: {output_path}")
|
|
415
|
+
outputs.add(output_path)
|
|
416
|
+
return normalized
|
|
417
|
+
|
|
418
|
+
documents = load_json_list(
|
|
419
|
+
context,
|
|
420
|
+
context.params["documents"],
|
|
421
|
+
label="documentos",
|
|
422
|
+
keys=("documents", "documentos"),
|
|
423
|
+
item_fn=document_case,
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
def make_unit(item: Mapping[str, Any], position: int) -> ScheduledUnit:
|
|
427
|
+
output_path = item["output"]
|
|
428
|
+
doc_params = {
|
|
429
|
+
**_identidade(context.params),
|
|
430
|
+
"input": item["input"],
|
|
431
|
+
"contexto": item.get("contexto"),
|
|
432
|
+
"data_relatorio": item.get("data_relatorio", context.params.get("data_relatorio")),
|
|
433
|
+
"scenario": item.get("scenario", context.params.get("scenario", "base")),
|
|
434
|
+
"output": output_path,
|
|
435
|
+
"estilos": item.get("estilos"),
|
|
436
|
+
"resource_base": item.get("resource_base"),
|
|
437
|
+
"config_publicacao": item.get("config_publicacao"),
|
|
438
|
+
"rendered_markdown": item.get("rendered_markdown"),
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
def run_document() -> dict[str, Any]:
|
|
442
|
+
nonlocal completed_documents
|
|
443
|
+
try:
|
|
444
|
+
document_overrides = dict(item.get("resource_overrides") or {})
|
|
445
|
+
inner = render_report(
|
|
446
|
+
replace(
|
|
447
|
+
context,
|
|
448
|
+
params=doc_params,
|
|
449
|
+
resource_overrides={**context.resource_overrides, **document_overrides},
|
|
450
|
+
)
|
|
451
|
+
)
|
|
452
|
+
products = []
|
|
453
|
+
for product in inner.products:
|
|
454
|
+
if (
|
|
455
|
+
product.path is not None
|
|
456
|
+
and isinstance(product.content, bytes)
|
|
457
|
+
and product.media_type.startswith(
|
|
458
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
|
459
|
+
)
|
|
460
|
+
):
|
|
461
|
+
# O scheduler conserva resultados concluídos até o lote
|
|
462
|
+
# inteiro terminar. Colocar os DOCX em staging impede
|
|
463
|
+
# que os bytes de todos os documentos fiquem na memória
|
|
464
|
+
# ao mesmo tempo; o checkpoint os copia em blocos.
|
|
465
|
+
staged = context.stage_file(product.path.suffix or ".docx")
|
|
466
|
+
staged.write_bytes(product.content)
|
|
467
|
+
product = replace(product, content=staged)
|
|
468
|
+
products.append(product)
|
|
469
|
+
return {
|
|
470
|
+
"products": tuple(products),
|
|
471
|
+
"pending": tuple(inner.pending),
|
|
472
|
+
"output": str(output_path),
|
|
473
|
+
}
|
|
474
|
+
finally:
|
|
475
|
+
with completion_lock:
|
|
476
|
+
completed_documents += 1
|
|
477
|
+
collect_cycles = completed_documents % _DOCX_CYCLE_COLLECTION_INTERVAL == 0
|
|
478
|
+
if collect_cycles:
|
|
479
|
+
# python-docx leaves cyclic XML objects after each render;
|
|
480
|
+
# collect them in bounded intervals while the scheduler
|
|
481
|
+
# limits the number of simultaneously active renderers.
|
|
482
|
+
with cycle_collection_lock:
|
|
483
|
+
gc.collect()
|
|
484
|
+
|
|
485
|
+
return ScheduledUnit(
|
|
486
|
+
str(output_path),
|
|
487
|
+
run_document,
|
|
488
|
+
ResourceProfile(cpu=1, memory_mb=128, network_slots=0, estimated_tokens=0),
|
|
489
|
+
event_meta={"position": position},
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
units = [make_unit(item, position) for position, item in enumerate(documents, start=1)]
|
|
493
|
+
outcome = context.run_batch(units, jobs=context.params.get("jobs"))
|
|
494
|
+
products: list[ProductDraft] = []
|
|
495
|
+
pending: list[dict[str, Any]] = []
|
|
496
|
+
for item in outcome.completed:
|
|
497
|
+
result = item["result"]
|
|
498
|
+
products.extend(result["products"])
|
|
499
|
+
pending.extend({**dict(issue), "document_output": result["output"]} for issue in result.get("pending", ()))
|
|
500
|
+
summary = {
|
|
501
|
+
"total_documents": outcome.total,
|
|
502
|
+
"completed": len(outcome.completed),
|
|
503
|
+
"failed": len(outcome.failed),
|
|
504
|
+
"documents": [
|
|
505
|
+
{
|
|
506
|
+
"output": document["output"],
|
|
507
|
+
"status": item.get("status"),
|
|
508
|
+
"error": item.get("error") if item.get("status") == "failed" else None,
|
|
509
|
+
}
|
|
510
|
+
for document, item in zip(documents, outcome.units, strict=False)
|
|
511
|
+
],
|
|
512
|
+
}
|
|
513
|
+
return OperationResult(
|
|
514
|
+
summary=summary,
|
|
515
|
+
products=tuple(products),
|
|
516
|
+
warnings=outcome.errors,
|
|
517
|
+
pending=tuple(pending),
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _validate_registered_source(context, value, *, kinds, scenario, label):
|
|
522
|
+
"""Confere cenário e integridade se a fonte já foi registrada como produto."""
|
|
523
|
+
path = context.optional_path(value)
|
|
524
|
+
if path is None:
|
|
525
|
+
return None
|
|
526
|
+
placeholders = ",".join("?" for _ in kinds)
|
|
527
|
+
rows = context.store._execute(
|
|
528
|
+
f"SELECT p.id, e.scenario_id, p.sha256, e.status FROM product p JOIN execution e ON e.id=p.execution_id WHERE e.fiscalizacao_id=? AND p.path=? AND p.kind IN ({placeholders}) ORDER BY p.created_at DESC, p.id DESC", # nosec B608 - apenas a quantidade de placeholders é interpolada
|
|
529
|
+
(context.store.fiscalizacao_id, str(path), *kinds),
|
|
530
|
+
).fetchall()
|
|
531
|
+
if not rows:
|
|
532
|
+
return {"status": "unregistered", "path": str(path)}
|
|
533
|
+
digest = sha256_file(path)
|
|
534
|
+
matching = [row for row in rows if row["sha256"] == digest]
|
|
535
|
+
if not matching:
|
|
536
|
+
raise InputValidationError(f"{label} diverge da versão registrada como produto")
|
|
537
|
+
matching_scenario = [row for row in matching if scenario is None or row["scenario_id"] == scenario]
|
|
538
|
+
if not matching_scenario:
|
|
539
|
+
raise InputValidationError(f"{label} pertence a outro cenário")
|
|
540
|
+
completed = next((row for row in matching_scenario if row["status"] == "completed"), None)
|
|
541
|
+
if completed is None:
|
|
542
|
+
raise InputValidationError(f"{label} não possui execução produtora concluída")
|
|
543
|
+
return {"status": "current", "path": str(path), "artifact_id": completed["id"]}
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _validate_index_execution_reference(context, reference, expected_hash, scenario):
|
|
547
|
+
if reference.get("kind") != "execution-result":
|
|
548
|
+
raise InputValidationError("referência de resultados do contexto tem tipo desconhecido")
|
|
549
|
+
execution_id = str(reference.get("execution_id") or "")
|
|
550
|
+
execution = context.store.get_execution(execution_id) if execution_id else None
|
|
551
|
+
if execution is None or execution.get("operation_id") != "indice":
|
|
552
|
+
raise InputValidationError("execução de índice referenciada pelo contexto não existe")
|
|
553
|
+
if execution.get("status") != "completed":
|
|
554
|
+
raise InputValidationError("execução de índice referenciada pelo contexto não foi concluída")
|
|
555
|
+
if execution.get("scenario_id") != scenario:
|
|
556
|
+
raise InputValidationError("execução de índice referenciada pelo contexto pertence a outro cenário")
|
|
557
|
+
if execution.get("input_hash") != reference.get("input_hash"):
|
|
558
|
+
raise InputValidationError("fingerprint da execução de índice diverge do contexto")
|
|
559
|
+
if not expected_hash or reference.get("sha256") != expected_hash:
|
|
560
|
+
raise InputValidationError("hash dos resultados diverge da referência da execução")
|
|
561
|
+
|
|
562
|
+
result_json = execution.get("result_json")
|
|
563
|
+
if isinstance(result_json, str):
|
|
564
|
+
try:
|
|
565
|
+
result_json = json.loads(result_json)
|
|
566
|
+
except json.JSONDecodeError as exc:
|
|
567
|
+
raise InputValidationError("resultado registrado da execução de índice é inválido") from exc
|
|
568
|
+
summary = result_json.get("summary") if isinstance(result_json, Mapping) else None
|
|
569
|
+
if not isinstance(summary, Mapping) or summary.get("results_payload_sha256") != expected_hash:
|
|
570
|
+
raise InputValidationError("resultado registrado da execução de índice diverge do contexto")
|
|
571
|
+
|
|
572
|
+
from ..fingerprints import execution_fingerprint, products_intact
|
|
573
|
+
|
|
574
|
+
if not products_intact(execution):
|
|
575
|
+
raise InputValidationError("produto da execução de índice mudou desde a publicação")
|
|
576
|
+
catalog = context.catalog
|
|
577
|
+
if catalog is None:
|
|
578
|
+
from ..catalog import build_catalog
|
|
579
|
+
|
|
580
|
+
catalog = build_catalog()
|
|
581
|
+
current_hash = execution_fingerprint(
|
|
582
|
+
catalog.get("indice"),
|
|
583
|
+
json.loads(str(execution.get("params_json") or "{}")),
|
|
584
|
+
context.project_root,
|
|
585
|
+
context.store,
|
|
586
|
+
)
|
|
587
|
+
if current_hash != execution.get("input_hash"):
|
|
588
|
+
raise InputValidationError("insumos da execução de índice mudaram desde o cálculo")
|
|
589
|
+
return {"status": "execution_reference", "execution_id": execution_id, "input_hash": current_hash}
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _validate_report_context(context, raw_context, payload, scenario):
|
|
593
|
+
if payload.get("format") == REPORT_CONTEXT_FORMAT:
|
|
594
|
+
if payload.get("scenario") != scenario:
|
|
595
|
+
raise InputValidationError("contexto de relatórios pertence a outro cenário")
|
|
596
|
+
source_paths = payload.get("fontes")
|
|
597
|
+
source_hashes = payload.get("sources_sha256")
|
|
598
|
+
source_validation = payload.get("sources_validation")
|
|
599
|
+
if (
|
|
600
|
+
not isinstance(source_paths, Mapping)
|
|
601
|
+
or not isinstance(source_hashes, Mapping)
|
|
602
|
+
or not isinstance(source_validation, Mapping)
|
|
603
|
+
):
|
|
604
|
+
raise InputValidationError("contexto de relatórios não contém proveniência de fontes")
|
|
605
|
+
result_reference = source_paths.get("results")
|
|
606
|
+
if isinstance(result_reference, Mapping):
|
|
607
|
+
_validate_index_execution_reference(
|
|
608
|
+
context,
|
|
609
|
+
result_reference,
|
|
610
|
+
source_hashes.get("results"),
|
|
611
|
+
scenario,
|
|
612
|
+
)
|
|
613
|
+
for name, expected in source_hashes.items():
|
|
614
|
+
if name == "results" and isinstance(result_reference, Mapping):
|
|
615
|
+
if source_validation.get(name) != "execution_reference":
|
|
616
|
+
raise InputValidationError("contexto de relatórios possui validação inválida dos resultados")
|
|
617
|
+
continue
|
|
618
|
+
source = source_paths.get(name)
|
|
619
|
+
if not source or name not in source_validation:
|
|
620
|
+
raise InputValidationError(f"contexto de relatórios perdeu a fonte: {name}")
|
|
621
|
+
source_values = source if isinstance(source, list) else [source]
|
|
622
|
+
expected_values = expected if isinstance(expected, list) else [expected]
|
|
623
|
+
if len(source_values) != len(expected_values):
|
|
624
|
+
raise InputValidationError(f"contexto de relatórios perdeu referências da fonte: {name}")
|
|
625
|
+
for position, (source_value, expected_hash) in enumerate(zip(source_values, expected_values), start=1):
|
|
626
|
+
source_path = context.path(source_value)
|
|
627
|
+
if not source_path.is_file() or sha256_file(source_path) != expected_hash:
|
|
628
|
+
label = f"{name}[{position}]" if len(source_values) > 1 else name
|
|
629
|
+
raise InputValidationError(f"fonte do contexto de relatórios mudou: {label}")
|
|
630
|
+
return _validate_registered_source(
|
|
631
|
+
context,
|
|
632
|
+
raw_context,
|
|
633
|
+
kinds=("contexto-relatorios-json",),
|
|
634
|
+
scenario=scenario,
|
|
635
|
+
label="contexto de relatórios",
|
|
636
|
+
)
|
|
637
|
+
elif payload.get("format") == "argos.manager-report-context.v1":
|
|
638
|
+
return _validate_registered_source(
|
|
639
|
+
context,
|
|
640
|
+
raw_context,
|
|
641
|
+
kinds=("manager-report-context",),
|
|
642
|
+
scenario=payload.get("applied_scenario") or payload.get("scenario") or scenario,
|
|
643
|
+
label="contexto de comentários do gestor",
|
|
644
|
+
)
|
|
645
|
+
if raw_context not in (None, ""):
|
|
646
|
+
return {"status": "unregistered", "reason": "contexto legado sem proveniência declarada"}
|
|
647
|
+
return {"status": "not_applicable"}
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _load_current_impact_product(context, value, result_path, scenario):
|
|
651
|
+
impacts_path = context.optional_path(value)
|
|
652
|
+
if impacts_path is None:
|
|
653
|
+
return None
|
|
654
|
+
impact_payload = load_json_object(context, impacts_path, label="impactos de auditoria")
|
|
655
|
+
registered = _validate_registered_source(
|
|
656
|
+
context,
|
|
657
|
+
impacts_path,
|
|
658
|
+
kinds=("audit-impact",),
|
|
659
|
+
scenario=None,
|
|
660
|
+
label="impactos",
|
|
661
|
+
)
|
|
662
|
+
if registered["status"] != "current":
|
|
663
|
+
raise InputValidationError("impactos precisam estar registrados e atuais no grafo de artefatos")
|
|
664
|
+
if impact_payload.get("format") != "argos.audit-impact.v1":
|
|
665
|
+
raise InputValidationError("arquivo de impactos sem vínculo de cenário")
|
|
666
|
+
if impact_payload.get("scenario_after") != scenario:
|
|
667
|
+
raise InputValidationError("impactos pertencem a outro cenário do relatório")
|
|
668
|
+
result_payload = load_json_object(context, result_path, label="resultado da auditoria")
|
|
669
|
+
from ..audit_result import expandir
|
|
670
|
+
|
|
671
|
+
# Os impactos registram o hash da visão expandida (v1), que é a mesma para o arquivo v1 ou v2.
|
|
672
|
+
result_digest = sha256_bytes(canonical_json(dict(expandir(result_payload))).encode("utf-8"))
|
|
673
|
+
if impact_payload.get("audit_after_sha256") != result_digest:
|
|
674
|
+
raise InputValidationError("impactos foram calculados com outro resultado de auditoria")
|
|
675
|
+
return impact_payload
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _source_references(context, params, common_context):
|
|
679
|
+
# Os rótulos são o contrato do `contexto_relatorio.sources` e não seguem os nomes dos parâmetros.
|
|
680
|
+
sources = {}
|
|
681
|
+
for label, name in (
|
|
682
|
+
("audit_result", "resultado_auditoria"),
|
|
683
|
+
("template", "template"),
|
|
684
|
+
("context", "contexto"),
|
|
685
|
+
("adjustments", "ajustes"),
|
|
686
|
+
("impacts", "impactos"),
|
|
687
|
+
("reference", "estilos"),
|
|
688
|
+
("publication_config", "config_publicacao"),
|
|
689
|
+
):
|
|
690
|
+
reference = source_reference(params.get(name), context.project_root, label=label)
|
|
691
|
+
if reference is not None:
|
|
692
|
+
sources[label] = reference
|
|
693
|
+
context_sources = params.get("fontes_contexto") or []
|
|
694
|
+
if isinstance(context_sources, (str, Path)):
|
|
695
|
+
context_sources = [context_sources]
|
|
696
|
+
if context_sources:
|
|
697
|
+
sources["context_sources"] = [
|
|
698
|
+
source_reference(value, context.project_root, label="fonte complementar de contexto")
|
|
699
|
+
for value in context_sources
|
|
700
|
+
]
|
|
701
|
+
if not params.get("data_relatorio"):
|
|
702
|
+
date_value = common_context.get("report_date") or common_context.get("data_relatorio")
|
|
703
|
+
if date_value:
|
|
704
|
+
sources["report_date_context"] = {
|
|
705
|
+
"label": "report_date_context",
|
|
706
|
+
"kind": "inline",
|
|
707
|
+
"sha256": source_reference({"report_date": date_value}, context.project_root, label="data")["sha256"],
|
|
708
|
+
}
|
|
709
|
+
return sources
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _build_report_contexts(
|
|
713
|
+
context,
|
|
714
|
+
*,
|
|
715
|
+
rows,
|
|
716
|
+
common_context,
|
|
717
|
+
adjustments,
|
|
718
|
+
impact_payload,
|
|
719
|
+
scenario,
|
|
720
|
+
report_date,
|
|
721
|
+
sources,
|
|
722
|
+
):
|
|
723
|
+
from .evaluation import scoped_report_context
|
|
724
|
+
|
|
725
|
+
keyed = common_context.get("auditados") or common_context.get("by_auditado")
|
|
726
|
+
if not isinstance(keyed, Mapping):
|
|
727
|
+
keyed = {}
|
|
728
|
+
if common_context.get("format") == "argos.manager-report-context.v1":
|
|
729
|
+
shared = {"runs": common_context.get("runs") or {}}
|
|
730
|
+
else:
|
|
731
|
+
shared = {
|
|
732
|
+
key: value
|
|
733
|
+
for key, value in common_context.items()
|
|
734
|
+
if key not in {"auditados", "by_auditado"}
|
|
735
|
+
}
|
|
736
|
+
fiscalizacao = fiscalizacao_values(context.params, context.store)
|
|
737
|
+
normalized_auditees = {}
|
|
738
|
+
local_contexts = {}
|
|
739
|
+
comparisons = impact_payload.get("auditados") or {} if impact_payload else {}
|
|
740
|
+
for organization, row in rows.items():
|
|
741
|
+
if common_context.get("format") == "argos.manager-report-context.v1":
|
|
742
|
+
local = scoped_report_context(common_context, organization, scenario, context.store)
|
|
743
|
+
else:
|
|
744
|
+
local = dict(shared)
|
|
745
|
+
specific = keyed.get(organization)
|
|
746
|
+
if isinstance(specific, Mapping):
|
|
747
|
+
local.update(dict(specific))
|
|
748
|
+
local = anexar_ajustes(local, adjustments.get(organization, []))
|
|
749
|
+
local.update(
|
|
750
|
+
{
|
|
751
|
+
"auditado": anexar_funcoes(row),
|
|
752
|
+
"sigla": organization,
|
|
753
|
+
"resultado_auditoria": row,
|
|
754
|
+
"fiscalizacao": fiscalizacao,
|
|
755
|
+
}
|
|
756
|
+
)
|
|
757
|
+
comparison = None
|
|
758
|
+
if impact_payload is not None:
|
|
759
|
+
identifier = str(organization).strip().upper()
|
|
760
|
+
comparison = comparisons.get(identifier)
|
|
761
|
+
if comparison is None:
|
|
762
|
+
raise InputValidationError(f"impactos não contêm o auditado do relatório: {organization}")
|
|
763
|
+
local["impactos"] = {
|
|
764
|
+
"cenario_anterior": impact_payload.get("scenario_before"),
|
|
765
|
+
"cenario_atual": impact_payload.get("scenario_after"),
|
|
766
|
+
"auditados": {identifier: comparison},
|
|
767
|
+
"pendencias": [
|
|
768
|
+
item
|
|
769
|
+
for item in impact_payload.get("pending") or []
|
|
770
|
+
if str(item.get("auditado") or "").strip().upper() == identifier
|
|
771
|
+
],
|
|
772
|
+
}
|
|
773
|
+
if report_date:
|
|
774
|
+
local["report_date"] = report_date
|
|
775
|
+
local["data_relatorio"] = report_date
|
|
776
|
+
normalized_auditees[organization] = {
|
|
777
|
+
"resultado_auditoria": dict(row),
|
|
778
|
+
"indicadores": dict(specific) if isinstance(specific, Mapping) else {},
|
|
779
|
+
"ajustes_respostas": list(local.get("ajustes_respostas") or []),
|
|
780
|
+
"comentarios_gestor": local.get("comentarios_gestor"),
|
|
781
|
+
"impactos": local.get("impactos"),
|
|
782
|
+
}
|
|
783
|
+
local_contexts[organization] = local
|
|
784
|
+
normalized = normalized_context(
|
|
785
|
+
scenario=scenario,
|
|
786
|
+
report_date=report_date,
|
|
787
|
+
sources=sources,
|
|
788
|
+
common=shared,
|
|
789
|
+
auditees=normalized_auditees,
|
|
790
|
+
)
|
|
791
|
+
for organization, local in local_contexts.items():
|
|
792
|
+
local["contexto_relatorio"] = normalized_context(
|
|
793
|
+
scenario=scenario,
|
|
794
|
+
report_date=report_date,
|
|
795
|
+
sources=sources,
|
|
796
|
+
common=shared,
|
|
797
|
+
auditees={organization: normalized_auditees[organization]},
|
|
798
|
+
)
|
|
799
|
+
return local_contexts, normalized
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _audit_result_warnings(context: OperationContext, payload: Any) -> list[str]:
|
|
803
|
+
"""Avisa quando o resultado v2 não corresponde mais ao mapa, à matriz ou às fontes atuais."""
|
|
804
|
+
from ..audit_result import verificar
|
|
805
|
+
|
|
806
|
+
return [f"resultado da auditoria: {item}" for item in verificar(payload, context.project_root)]
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def render_audit_reports(context: OperationContext) -> OperationResult:
|
|
810
|
+
"""Renderiza relatórios individuais de uma auditoria em paralelo.
|
|
811
|
+
|
|
812
|
+
A operação aceita o resultado da auditoria, um template
|
|
813
|
+
Jinja/Markdown e um diretório de destino. O contexto de cada auditado é
|
|
814
|
+
criado na memória e encaminhado ao renderer DOCX; não é materializado um
|
|
815
|
+
JSON por auditado.
|
|
816
|
+
"""
|
|
817
|
+
params = context.params
|
|
818
|
+
result_path = require_file(context, params["resultado_auditoria"], "resultado da auditoria")
|
|
819
|
+
report_scenario = params.get("scenario") or "base"
|
|
820
|
+
if context.store.get_scenario(report_scenario) is None:
|
|
821
|
+
raise InputValidationError(f"cenário do relatório inexistente: {report_scenario}")
|
|
822
|
+
audit_provenance = _validate_registered_source(
|
|
823
|
+
context,
|
|
824
|
+
result_path,
|
|
825
|
+
kinds=("audit-result",),
|
|
826
|
+
scenario=report_scenario,
|
|
827
|
+
label="resultado de auditoria",
|
|
828
|
+
)
|
|
829
|
+
template_path = require_file(context, params["template"], "template de relatório")
|
|
830
|
+
output_dir = context.path(params["output_dir"])
|
|
831
|
+
raw_result = load_json_object(context, result_path, label="resultado da auditoria")
|
|
832
|
+
audit_rows = audit_rows_from_result(raw_result)
|
|
833
|
+
provenance_warnings = _audit_result_warnings(context, raw_result)
|
|
834
|
+
|
|
835
|
+
bindings = _carregar_ativos(context, params.get("ativos"), include_auditee=False)
|
|
836
|
+
common_context, _ = _merge_report_context_sources(
|
|
837
|
+
context,
|
|
838
|
+
load_json_object(context, params.get("contexto"), label="contexto de relatórios"),
|
|
839
|
+
params.get("fontes_contexto"),
|
|
840
|
+
)
|
|
841
|
+
context_provenance = _validate_report_context(
|
|
842
|
+
context, params.get("contexto"), common_context, report_scenario
|
|
843
|
+
)
|
|
844
|
+
impact_payload = _load_current_impact_product(context, params.get("impactos"), result_path, report_scenario)
|
|
845
|
+
ajustes_path = context.optional_path(params.get("ajustes"))
|
|
846
|
+
ajustes_por_auditado = carregar_ajustes_respostas(ajustes_path) if ajustes_path is not None else {}
|
|
847
|
+
report_date, report_date_br = normalize_report_date(
|
|
848
|
+
params.get("data_relatorio")
|
|
849
|
+
or common_context.get("report_date")
|
|
850
|
+
or common_context.get("data_relatorio")
|
|
851
|
+
)
|
|
852
|
+
sources = _source_references(context, params, common_context)
|
|
853
|
+
sources["audit_result"]["validation"] = audit_provenance["status"]
|
|
854
|
+
if "context" in sources:
|
|
855
|
+
sources["context"]["validation"] = context_provenance["status"]
|
|
856
|
+
if "impacts" in sources:
|
|
857
|
+
sources["impacts"]["validation"] = "current"
|
|
858
|
+
local_contexts, normalized = _build_report_contexts(
|
|
859
|
+
context,
|
|
860
|
+
rows=audit_rows,
|
|
861
|
+
common_context=common_context,
|
|
862
|
+
adjustments=ajustes_por_auditado,
|
|
863
|
+
impact_payload=impact_payload,
|
|
864
|
+
scenario=report_scenario,
|
|
865
|
+
report_date=report_date,
|
|
866
|
+
sources=sources,
|
|
867
|
+
)
|
|
868
|
+
filters = params.get("auditados") or []
|
|
869
|
+
if isinstance(filters, (str, Path)):
|
|
870
|
+
filters = [filters]
|
|
871
|
+
selected = {normalize(item) for item in filters if str(item).strip()}
|
|
872
|
+
filename_pattern = str(params.get("padrao_nome") or "{auditado}.docx")
|
|
873
|
+
documents: list[dict[str, Any]] = []
|
|
874
|
+
used_outputs: set[Path] = set()
|
|
875
|
+
for auditado, row in audit_rows.items():
|
|
876
|
+
if selected and normalize(auditado) not in selected:
|
|
877
|
+
continue
|
|
878
|
+
local_context = dict(local_contexts[auditado])
|
|
879
|
+
if report_date:
|
|
880
|
+
local_context["data_hoje"] = report_date_br
|
|
881
|
+
local_context["data_relatorio"] = report_date
|
|
882
|
+
try:
|
|
883
|
+
filename = filename_pattern.format(auditado=auditado, sigla=auditado)
|
|
884
|
+
except (KeyError, ValueError) as exc:
|
|
885
|
+
raise InputValidationError(f"padrao_nome inválido: {filename_pattern}") from exc
|
|
886
|
+
filename = Path(filename).name
|
|
887
|
+
filename = re.sub(r"[^A-Za-z0-9._-]+", "_", filename)
|
|
888
|
+
if not filename.lower().endswith(".docx"):
|
|
889
|
+
filename += ".docx"
|
|
890
|
+
output = (output_dir / filename).resolve()
|
|
891
|
+
if output in used_outputs:
|
|
892
|
+
raise InputValidationError(f"saída de relatório repetida: {output}")
|
|
893
|
+
used_outputs.add(output)
|
|
894
|
+
rendered_markdown = _render_report_markdown(template_path, local_context)
|
|
895
|
+
validate_markdown_pipe_tables(
|
|
896
|
+
rendered_markdown,
|
|
897
|
+
document_label=f"relatório individual do auditado {auditado}",
|
|
898
|
+
)
|
|
899
|
+
documents.append(
|
|
900
|
+
{
|
|
901
|
+
"input": str(template_path),
|
|
902
|
+
"rendered_markdown": rendered_markdown,
|
|
903
|
+
"contexto": local_context,
|
|
904
|
+
"resource_base": str(_report_resource_base(context, params.get("contexto"))),
|
|
905
|
+
"output": str(output),
|
|
906
|
+
"estilos": params.get("estilos"),
|
|
907
|
+
"data_relatorio": report_date,
|
|
908
|
+
"scenario": report_scenario,
|
|
909
|
+
"config_publicacao": params.get("config_publicacao"),
|
|
910
|
+
"resource_overrides": _asset_aliases(
|
|
911
|
+
bindings,
|
|
912
|
+
auditee=str(auditado),
|
|
913
|
+
),
|
|
914
|
+
}
|
|
915
|
+
)
|
|
916
|
+
if not documents:
|
|
917
|
+
raise MissingInputError("nenhum auditado selecionado para gerar relatórios")
|
|
918
|
+
|
|
919
|
+
batch_result = render_documents_batch(
|
|
920
|
+
replace(
|
|
921
|
+
context,
|
|
922
|
+
params={**_identidade(params), "documents": documents, "jobs": params.get("jobs") or 4},
|
|
923
|
+
)
|
|
924
|
+
)
|
|
925
|
+
return context.merge_composed(
|
|
926
|
+
_com_resumo_ativos(batch_result, bindings),
|
|
927
|
+
summary={
|
|
928
|
+
"resultado_auditoria": str(result_path),
|
|
929
|
+
"resultado_auditoria_sha256": sha256_file(result_path),
|
|
930
|
+
"template": str(template_path),
|
|
931
|
+
"output_dir": str(output_dir),
|
|
932
|
+
"selected_count": len(documents),
|
|
933
|
+
"scenario": report_scenario,
|
|
934
|
+
"report_date": report_date,
|
|
935
|
+
"context_format": REPORT_CONTEXT_FORMAT,
|
|
936
|
+
"context_sources": normalized["sources"],
|
|
937
|
+
},
|
|
938
|
+
warnings=provenance_warnings,
|
|
939
|
+
)
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
def render_consolidated_report(context: OperationContext) -> OperationResult:
|
|
943
|
+
"""Renderiza um único relatório consolidado a partir do resultado da auditoria."""
|
|
944
|
+
params = context.params
|
|
945
|
+
result_path = require_file(context, params["resultado_auditoria"], "resultado da auditoria")
|
|
946
|
+
template_path = require_file(context, params["template"], "template de relatório")
|
|
947
|
+
raw_result = load_json_object(context, result_path, label="resultado da auditoria")
|
|
948
|
+
rows = audit_rows_from_result(raw_result)
|
|
949
|
+
provenance_warnings = _audit_result_warnings(context, raw_result)
|
|
950
|
+
scenario = params.get("scenario") or "base"
|
|
951
|
+
if context.store.get_scenario(scenario) is None:
|
|
952
|
+
raise InputValidationError(f"cenário do relatório inexistente: {scenario}")
|
|
953
|
+
audit_provenance = _validate_registered_source(
|
|
954
|
+
context,
|
|
955
|
+
result_path,
|
|
956
|
+
kinds=("audit-result",),
|
|
957
|
+
scenario=scenario,
|
|
958
|
+
label="resultado de auditoria",
|
|
959
|
+
)
|
|
960
|
+
bindings = _carregar_ativos(context, params.get("ativos"), include_auditee=True)
|
|
961
|
+
common_context, _ = _merge_report_context_sources(
|
|
962
|
+
context,
|
|
963
|
+
load_json_object(context, params.get("contexto"), label="contexto de relatórios"),
|
|
964
|
+
params.get("fontes_contexto"),
|
|
965
|
+
)
|
|
966
|
+
context_provenance = _validate_report_context(context, params.get("contexto"), common_context, scenario)
|
|
967
|
+
impact_payload = _load_current_impact_product(context, params.get("impactos"), result_path, scenario)
|
|
968
|
+
|
|
969
|
+
adjustments_path = context.optional_path(params.get("ajustes"))
|
|
970
|
+
adjustments = carregar_ajustes_respostas(adjustments_path) if adjustments_path is not None else {}
|
|
971
|
+
report_date, report_date_br = normalize_report_date(
|
|
972
|
+
params.get("data_relatorio")
|
|
973
|
+
or common_context.get("report_date")
|
|
974
|
+
or common_context.get("data_relatorio")
|
|
975
|
+
)
|
|
976
|
+
sources = _source_references(context, params, common_context)
|
|
977
|
+
sources["audit_result"]["validation"] = audit_provenance["status"]
|
|
978
|
+
if "context" in sources:
|
|
979
|
+
sources["context"]["validation"] = context_provenance["status"]
|
|
980
|
+
if "impacts" in sources:
|
|
981
|
+
sources["impacts"]["validation"] = "current"
|
|
982
|
+
local_contexts, normalized = _build_report_contexts(
|
|
983
|
+
context,
|
|
984
|
+
rows=rows,
|
|
985
|
+
common_context=common_context,
|
|
986
|
+
adjustments=adjustments,
|
|
987
|
+
impact_payload=impact_payload,
|
|
988
|
+
scenario=scenario,
|
|
989
|
+
report_date=report_date,
|
|
990
|
+
sources=sources,
|
|
991
|
+
)
|
|
992
|
+
values = dict(common_context)
|
|
993
|
+
values["auditados"] = {
|
|
994
|
+
organization: dict(local["auditado"], **{
|
|
995
|
+
"ajustes_respostas": local.get("ajustes_respostas") or [],
|
|
996
|
+
"comentarios_gestor": local.get("comentarios_gestor"),
|
|
997
|
+
"impactos": local.get("impactos"),
|
|
998
|
+
})
|
|
999
|
+
for organization, local in local_contexts.items()
|
|
1000
|
+
}
|
|
1001
|
+
if impact_payload is not None:
|
|
1002
|
+
values["impactos"] = {
|
|
1003
|
+
"cenario_anterior": impact_payload.get("scenario_before"),
|
|
1004
|
+
"cenario_atual": impact_payload.get("scenario_after"),
|
|
1005
|
+
"auditados": impact_payload.get("auditados") or {},
|
|
1006
|
+
"pendencias": impact_payload.get("pending") or [],
|
|
1007
|
+
}
|
|
1008
|
+
values["contexto_relatorio"] = normalized
|
|
1009
|
+
values["resultado_auditoria"] = raw_result
|
|
1010
|
+
with_project_fields(context, values)
|
|
1011
|
+
values["fiscalizacao"] = {**dict(values.get("fiscalizacao") or {}), **fiscalizacao_values(params, context.store)}
|
|
1012
|
+
if report_date:
|
|
1013
|
+
values["report_date"] = report_date
|
|
1014
|
+
values["data_relatorio"] = report_date
|
|
1015
|
+
values["data_hoje"] = report_date_br
|
|
1016
|
+
output = context.path(params["output"])
|
|
1017
|
+
|
|
1018
|
+
result = render_report(
|
|
1019
|
+
replace(
|
|
1020
|
+
context,
|
|
1021
|
+
params={
|
|
1022
|
+
**_identidade(params),
|
|
1023
|
+
"input": str(template_path),
|
|
1024
|
+
"contexto": values,
|
|
1025
|
+
"resource_base": str(_report_resource_base(context, params.get("contexto"))),
|
|
1026
|
+
"data_relatorio": report_date,
|
|
1027
|
+
"scenario": scenario,
|
|
1028
|
+
"output": str(output),
|
|
1029
|
+
"estilos": params.get("estilos"),
|
|
1030
|
+
"config_publicacao": params.get("config_publicacao"),
|
|
1031
|
+
},
|
|
1032
|
+
)
|
|
1033
|
+
)
|
|
1034
|
+
return context.merge_composed(
|
|
1035
|
+
_com_resumo_ativos(result, bindings),
|
|
1036
|
+
summary={
|
|
1037
|
+
"resultado_auditoria": str(result_path),
|
|
1038
|
+
"resultado_auditoria_sha256": sha256_file(result_path),
|
|
1039
|
+
"template": str(template_path),
|
|
1040
|
+
"audited_count": len(rows),
|
|
1041
|
+
"scenario": scenario,
|
|
1042
|
+
"report_date": report_date,
|
|
1043
|
+
"context_format": REPORT_CONTEXT_FORMAT,
|
|
1044
|
+
"context_sources": normalized["sources"],
|
|
1045
|
+
},
|
|
1046
|
+
warnings=provenance_warnings,
|
|
1047
|
+
)
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
def render_anexo_evidencias(context: OperationContext) -> OperationResult:
|
|
1051
|
+
"""Anexo de evidências dos achados por auditado, no template DOCX do projeto."""
|
|
1052
|
+
from ..adapters.docx_pdf import mark_update_fields, render_docx_template
|
|
1053
|
+
from ..adapters.report_publication import fill_template_fields
|
|
1054
|
+
from ..project import project_template_values
|
|
1055
|
+
|
|
1056
|
+
params = context.params
|
|
1057
|
+
result_path = require_file(context, params["resultado_auditoria"], "resultado da auditoria")
|
|
1058
|
+
template = require_file(context, params["template"], "template do anexo de evidências")
|
|
1059
|
+
output = context.path(params["output"])
|
|
1060
|
+
scenario = params.get("scenario") or "base"
|
|
1061
|
+
if context.store.get_scenario(scenario) is None:
|
|
1062
|
+
raise InputValidationError(f"cenário do relatório inexistente: {scenario}")
|
|
1063
|
+
_validate_registered_source(
|
|
1064
|
+
context, result_path, kinds=("audit-result",), scenario=scenario, label="resultado de auditoria"
|
|
1065
|
+
)
|
|
1066
|
+
raw_result = load_json_object(context, result_path, label="resultado da auditoria")
|
|
1067
|
+
dados = evidence_annex_context(raw_result)
|
|
1068
|
+
if not dados:
|
|
1069
|
+
raise InputValidationError("nenhum auditado com achados para o anexo de evidências")
|
|
1070
|
+
rendered = render_docx_template(template, {"dados": dados})
|
|
1071
|
+
content = mark_update_fields(fill_template_fields(rendered, project_template_values(context.project_root)))
|
|
1072
|
+
return OperationResult(
|
|
1073
|
+
summary={
|
|
1074
|
+
"resultado_auditoria": str(result_path),
|
|
1075
|
+
"resultado_auditoria_sha256": sha256_file(result_path),
|
|
1076
|
+
"template": str(template),
|
|
1077
|
+
"output": str(output),
|
|
1078
|
+
"auditados": len(dados),
|
|
1079
|
+
"scenario": scenario,
|
|
1080
|
+
"bytes": len(content),
|
|
1081
|
+
},
|
|
1082
|
+
products=(
|
|
1083
|
+
ProductDraft(
|
|
1084
|
+
kind="evidence-annex-docx",
|
|
1085
|
+
path=output,
|
|
1086
|
+
content=content,
|
|
1087
|
+
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
1088
|
+
metadata={"template": str(template), "template_sha256": sha256_file(template), "auditados": len(dados)},
|
|
1089
|
+
),
|
|
1090
|
+
),
|
|
1091
|
+
warnings=tuple(_audit_result_warnings(context, raw_result)),
|
|
1092
|
+
)
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def mesclar_contextos_relatorios_op(context: OperationContext) -> OperationResult:
|
|
1096
|
+
"""Mescla contextos JSON por auditado."""
|
|
1097
|
+
params = context.params
|
|
1098
|
+
contexts = params.get("contexts") or []
|
|
1099
|
+
if isinstance(contexts, (str, Path)):
|
|
1100
|
+
contexts = [contexts]
|
|
1101
|
+
if not contexts:
|
|
1102
|
+
raise MissingInputError("informe ao menos um contexto JSON (contexts)")
|
|
1103
|
+
final: dict[str, Any] = {"auditados": {}}
|
|
1104
|
+
fontes: dict[str, str] = {}
|
|
1105
|
+
for raw in contexts:
|
|
1106
|
+
caminho = require_file(context, raw, "contexto de relatórios")
|
|
1107
|
+
payload = json.loads(caminho.read_text(encoding="utf-8"))
|
|
1108
|
+
por_auditado = payload.get("auditados")
|
|
1109
|
+
if not isinstance(por_auditado, Mapping):
|
|
1110
|
+
por_auditado = payload
|
|
1111
|
+
for sigla, dados in (por_auditado or {}).items():
|
|
1112
|
+
if not isinstance(dados, Mapping):
|
|
1113
|
+
continue
|
|
1114
|
+
existente = final["auditados"].setdefault(str(sigla), {})
|
|
1115
|
+
for chave, valor in dados.items():
|
|
1116
|
+
if isinstance(valor, Mapping) and isinstance(existente.get(chave), Mapping):
|
|
1117
|
+
existente[chave] = {**existente[chave], **valor}
|
|
1118
|
+
else:
|
|
1119
|
+
existente[chave] = valor
|
|
1120
|
+
fontes[str(sigla)] = fontes.get(str(sigla), "") + f"{caminho.name} "
|
|
1121
|
+
output = context.optional_path(params.get("output"))
|
|
1122
|
+
products: tuple[ProductDraft, ...] = ()
|
|
1123
|
+
if output is not None:
|
|
1124
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
1125
|
+
output.write_text(json.dumps(final, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1126
|
+
products = (ProductDraft(kind="report-context-merged", path=output, content=final),)
|
|
1127
|
+
return OperationResult(
|
|
1128
|
+
summary={
|
|
1129
|
+
"auditados": len(final["auditados"]),
|
|
1130
|
+
"fontes": len(contexts),
|
|
1131
|
+
"output": str(output) if output else "",
|
|
1132
|
+
},
|
|
1133
|
+
products=products,
|
|
1134
|
+
)
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def _load_asset_bindings(
|
|
1138
|
+
context: OperationContext,
|
|
1139
|
+
raw_manifests: Any,
|
|
1140
|
+
) -> list[dict[str, Any]]:
|
|
1141
|
+
"""Carrega manifestos, confere hashes e devolve ativos com sua origem."""
|
|
1142
|
+
if raw_manifests in (None, "", []):
|
|
1143
|
+
return []
|
|
1144
|
+
values = raw_manifests if isinstance(raw_manifests, (list, tuple)) else [raw_manifests]
|
|
1145
|
+
bindings: list[dict[str, Any]] = []
|
|
1146
|
+
seen_slots: dict[str, Path] = {}
|
|
1147
|
+
seen_names: dict[str, Path] = {}
|
|
1148
|
+
for raw in values:
|
|
1149
|
+
manifest_path = require_file(context, raw, "manifesto de ativos")
|
|
1150
|
+
manifest = load_manifest(manifest_path)
|
|
1151
|
+
entries = validate_manifest(manifest, output_root=manifest_path.parent)
|
|
1152
|
+
for entry in entries:
|
|
1153
|
+
asset_path = (manifest_path.parent / entry.path).resolve()
|
|
1154
|
+
actual = sha256_file(asset_path)
|
|
1155
|
+
if actual != entry.sha256:
|
|
1156
|
+
raise InputValidationError(
|
|
1157
|
+
f"hash divergente no ativo {entry.slot_id!r}: declarado {entry.sha256}, calculado {actual}"
|
|
1158
|
+
)
|
|
1159
|
+
if entry.slot_id in seen_slots:
|
|
1160
|
+
raise InputValidationError(
|
|
1161
|
+
f"slot_id repetido em manifestos distintos: {entry.slot_id}"
|
|
1162
|
+
)
|
|
1163
|
+
seen_slots[entry.slot_id] = asset_path
|
|
1164
|
+
previous_name = seen_names.get(asset_path.name)
|
|
1165
|
+
if previous_name is not None and previous_name != asset_path:
|
|
1166
|
+
raise InputValidationError(
|
|
1167
|
+
f"nome de ativo ambíguo entre manifestos: {asset_path.name}"
|
|
1168
|
+
)
|
|
1169
|
+
seen_names[asset_path.name] = asset_path
|
|
1170
|
+
bindings.append(
|
|
1171
|
+
{
|
|
1172
|
+
"entry": entry,
|
|
1173
|
+
"path": asset_path,
|
|
1174
|
+
"manifest": manifest_path,
|
|
1175
|
+
}
|
|
1176
|
+
)
|
|
1177
|
+
return bindings
|
|
1178
|
+
|
|
1179
|
+
|
|
1180
|
+
def _asset_aliases(
|
|
1181
|
+
bindings: Iterable[Mapping[str, Any]],
|
|
1182
|
+
*,
|
|
1183
|
+
auditee: str | None = None,
|
|
1184
|
+
include_auditee: bool = True,
|
|
1185
|
+
) -> dict[str, Path]:
|
|
1186
|
+
aliases: dict[str, Path] = {}
|
|
1187
|
+
for binding in bindings:
|
|
1188
|
+
entry = binding.get("entry")
|
|
1189
|
+
if not isinstance(entry, AssetEntry):
|
|
1190
|
+
continue
|
|
1191
|
+
if entry.scope == "auditee":
|
|
1192
|
+
if not include_auditee or (auditee is not None and entry.auditee != auditee):
|
|
1193
|
+
continue
|
|
1194
|
+
path = Path(binding["path"])
|
|
1195
|
+
for alias in (entry.slot_id, path.name):
|
|
1196
|
+
existing = aliases.get(alias)
|
|
1197
|
+
if existing is not None and existing != path:
|
|
1198
|
+
raise InputValidationError(f"alias de ativo ambíguo: {alias}")
|
|
1199
|
+
aliases[alias] = path
|
|
1200
|
+
return aliases
|