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/assets.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Contrato de ativos produzidos por scripts externos do pipeline.
|
|
2
|
+
|
|
3
|
+
O manifesto é a fronteira entre um script de extensão e o núcleo: o script
|
|
4
|
+
declara os arquivos que produziu e seus hashes; o pipeline valida, publica os
|
|
5
|
+
produtos e entrega os caminhos ao relatório. Nada aqui conhece um domínio
|
|
6
|
+
específico de fiscalização.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Mapping
|
|
17
|
+
|
|
18
|
+
from .contracts import ProductDraft
|
|
19
|
+
from .errors import InputValidationError
|
|
20
|
+
|
|
21
|
+
ASSET_MANIFEST_SCHEMA = "argos.asset-manifest/v1"
|
|
22
|
+
ASSET_KIND_PREFIX = "asset:"
|
|
23
|
+
ASSET_SCOPES = frozenset({"consolidated", "auditee"})
|
|
24
|
+
SLOT_ID_PATTERN = re.compile(r"^[a-z0-9_-]+$")
|
|
25
|
+
SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
|
|
26
|
+
_TOP_LEVEL_KEYS = frozenset({"schema_version", "assets"})
|
|
27
|
+
_ASSET_KEYS = frozenset(
|
|
28
|
+
{
|
|
29
|
+
"slot_id",
|
|
30
|
+
"kind",
|
|
31
|
+
"path",
|
|
32
|
+
"media_type",
|
|
33
|
+
"sha256",
|
|
34
|
+
"caption",
|
|
35
|
+
"scope",
|
|
36
|
+
"auditee",
|
|
37
|
+
"metadata",
|
|
38
|
+
}
|
|
39
|
+
)
|
|
40
|
+
_REQUIRED_ASSET_KEYS = frozenset({"slot_id", "kind", "path", "media_type", "sha256"})
|
|
41
|
+
_PATH_KEYS = frozenset(
|
|
42
|
+
{
|
|
43
|
+
"PATH",
|
|
44
|
+
"LANG",
|
|
45
|
+
"LC_ALL",
|
|
46
|
+
"TMPDIR",
|
|
47
|
+
"TEMP",
|
|
48
|
+
"TMP",
|
|
49
|
+
"SYSTEMROOT",
|
|
50
|
+
"WINDIR",
|
|
51
|
+
"COMSPEC",
|
|
52
|
+
"PATHEXT",
|
|
53
|
+
"HOME",
|
|
54
|
+
"USERPROFILE",
|
|
55
|
+
"MPLCONFIGDIR",
|
|
56
|
+
}
|
|
57
|
+
)
|
|
58
|
+
_SECRET_MARKERS = ("_API_KEY", "_TOKEN", "_PASSWORD", "_SECRET", "_COOKIE")
|
|
59
|
+
_SECRET_PREFIXES = ("GOOGLE_", "OPENAI_", "GEMINI_", "ARGOS_LIMESURVEY_")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class AssetEntry:
|
|
64
|
+
slot_id: str
|
|
65
|
+
kind: str
|
|
66
|
+
path: str
|
|
67
|
+
media_type: str
|
|
68
|
+
sha256: str
|
|
69
|
+
caption: str = ""
|
|
70
|
+
scope: str = "consolidated"
|
|
71
|
+
auditee: str | None = None
|
|
72
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class AssetManifest:
|
|
77
|
+
schema_version: str
|
|
78
|
+
assets: tuple[AssetEntry, ...]
|
|
79
|
+
|
|
80
|
+
def as_dict(self) -> dict[str, Any]:
|
|
81
|
+
return {
|
|
82
|
+
"schema_version": self.schema_version,
|
|
83
|
+
"assets": [
|
|
84
|
+
{
|
|
85
|
+
"slot_id": entry.slot_id,
|
|
86
|
+
"kind": entry.kind,
|
|
87
|
+
"path": entry.path,
|
|
88
|
+
"media_type": entry.media_type,
|
|
89
|
+
"sha256": entry.sha256,
|
|
90
|
+
"caption": entry.caption,
|
|
91
|
+
"scope": entry.scope,
|
|
92
|
+
"auditee": entry.auditee,
|
|
93
|
+
"metadata": dict(entry.metadata),
|
|
94
|
+
}
|
|
95
|
+
for entry in self.assets
|
|
96
|
+
],
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _error(path: Path, message: str) -> InputValidationError:
|
|
101
|
+
return InputValidationError(f"manifesto de ativos inválido em {path}: {message}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _mapping(value: Any, *, label: str, path: Path) -> Mapping[str, Any]:
|
|
105
|
+
if not isinstance(value, Mapping):
|
|
106
|
+
raise _error(path, f"{label} deve ser um objeto")
|
|
107
|
+
return value
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _asset_entry(raw: Any, *, index: int, path: Path) -> AssetEntry:
|
|
111
|
+
item = _mapping(raw, label=f"assets[{index}]", path=path)
|
|
112
|
+
unknown = sorted(set(item) - _ASSET_KEYS)
|
|
113
|
+
if unknown:
|
|
114
|
+
raise _error(path, f"assets[{index}] tem chaves desconhecidas: {', '.join(unknown)}")
|
|
115
|
+
missing = sorted(_REQUIRED_ASSET_KEYS - set(item))
|
|
116
|
+
if missing:
|
|
117
|
+
raise _error(path, f"assets[{index}] não declara: {', '.join(missing)}")
|
|
118
|
+
slot_id = str(item["slot_id"])
|
|
119
|
+
kind = str(item["kind"])
|
|
120
|
+
asset_path = str(item["path"])
|
|
121
|
+
media_type = str(item["media_type"])
|
|
122
|
+
digest = str(item["sha256"])
|
|
123
|
+
caption = str(item.get("caption") or "")
|
|
124
|
+
scope = str(item.get("scope") or "consolidated")
|
|
125
|
+
auditee_raw = item.get("auditee")
|
|
126
|
+
auditee = str(auditee_raw) if auditee_raw not in (None, "") else None
|
|
127
|
+
metadata = _mapping(item.get("metadata") or {}, label=f"assets[{index}].metadata", path=path)
|
|
128
|
+
if not SLOT_ID_PATTERN.fullmatch(slot_id):
|
|
129
|
+
raise _error(path, f"slot_id inválido em assets[{index}]: {slot_id!r}")
|
|
130
|
+
if not kind.startswith(ASSET_KIND_PREFIX) or kind == ASSET_KIND_PREFIX:
|
|
131
|
+
raise _error(path, f"kind inválido em assets[{index}]: {kind!r}")
|
|
132
|
+
if not media_type:
|
|
133
|
+
raise _error(path, f"media_type vazio em assets[{index}]")
|
|
134
|
+
if kind == "asset:chart" and media_type != "image/png":
|
|
135
|
+
raise _error(path, f"asset:chart exige image/png em assets[{index}]")
|
|
136
|
+
if not SHA256_PATTERN.fullmatch(digest):
|
|
137
|
+
raise _error(path, f"sha256 inválido em assets[{index}]")
|
|
138
|
+
if scope not in ASSET_SCOPES:
|
|
139
|
+
raise _error(path, f"scope inválido em assets[{index}]: {scope!r}")
|
|
140
|
+
if scope == "auditee" and not auditee:
|
|
141
|
+
raise _error(path, f"scope=auditee exige auditee em assets[{index}]")
|
|
142
|
+
if not asset_path or Path(asset_path).is_absolute():
|
|
143
|
+
raise _error(path, f"path deve ser relativo em assets[{index}]")
|
|
144
|
+
relative = Path(asset_path)
|
|
145
|
+
if ".." in relative.parts:
|
|
146
|
+
raise _error(path, f"path não pode conter '..' em assets[{index}]")
|
|
147
|
+
return AssetEntry(
|
|
148
|
+
slot_id=slot_id,
|
|
149
|
+
kind=kind,
|
|
150
|
+
path=asset_path,
|
|
151
|
+
media_type=media_type,
|
|
152
|
+
sha256=digest,
|
|
153
|
+
caption=caption,
|
|
154
|
+
scope=scope,
|
|
155
|
+
auditee=auditee,
|
|
156
|
+
metadata=metadata,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def load_manifest(path: Path) -> AssetManifest:
|
|
161
|
+
"""Lê o JSON do manifesto e valida a estrutura, sem exigir os arquivos."""
|
|
162
|
+
manifest_path = Path(path)
|
|
163
|
+
try:
|
|
164
|
+
raw = json.loads(manifest_path.read_text(encoding="utf-8"))
|
|
165
|
+
except FileNotFoundError as exc:
|
|
166
|
+
raise _error(manifest_path, "arquivo não encontrado") from exc
|
|
167
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
168
|
+
raise _error(manifest_path, f"JSON ilegível ({exc})") from exc
|
|
169
|
+
payload = _mapping(raw, label="manifesto", path=manifest_path)
|
|
170
|
+
unknown = sorted(set(payload) - _TOP_LEVEL_KEYS)
|
|
171
|
+
if unknown:
|
|
172
|
+
raise _error(manifest_path, f"chaves desconhecidas: {', '.join(unknown)}")
|
|
173
|
+
missing = sorted(_TOP_LEVEL_KEYS - set(payload))
|
|
174
|
+
if missing:
|
|
175
|
+
raise _error(manifest_path, f"não declara: {', '.join(missing)}")
|
|
176
|
+
if str(payload["schema_version"]) != ASSET_MANIFEST_SCHEMA:
|
|
177
|
+
raise _error(manifest_path, f"schema_version deve ser {ASSET_MANIFEST_SCHEMA}")
|
|
178
|
+
assets_raw = payload["assets"]
|
|
179
|
+
if not isinstance(assets_raw, list) or not assets_raw:
|
|
180
|
+
raise _error(manifest_path, "assets deve ser uma lista não vazia")
|
|
181
|
+
assets = tuple(
|
|
182
|
+
_asset_entry(item, index=index, path=manifest_path)
|
|
183
|
+
for index, item in enumerate(assets_raw)
|
|
184
|
+
)
|
|
185
|
+
seen: set[str] = set()
|
|
186
|
+
for entry in assets:
|
|
187
|
+
if entry.slot_id in seen:
|
|
188
|
+
raise _error(manifest_path, f"slot_id repetido: {entry.slot_id}")
|
|
189
|
+
seen.add(entry.slot_id)
|
|
190
|
+
return AssetManifest(schema_version=ASSET_MANIFEST_SCHEMA, assets=assets)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def validate_manifest(
|
|
194
|
+
manifest: AssetManifest,
|
|
195
|
+
*,
|
|
196
|
+
output_root: Path,
|
|
197
|
+
) -> tuple[AssetEntry, ...]:
|
|
198
|
+
"""Valida existência, contenção e symlinks dos ativos no diretório de saída."""
|
|
199
|
+
root = Path(output_root).expanduser().resolve()
|
|
200
|
+
if not root.is_dir():
|
|
201
|
+
raise InputValidationError(f"diretório de saída do manifesto não existe: {root}")
|
|
202
|
+
if manifest.schema_version != ASSET_MANIFEST_SCHEMA:
|
|
203
|
+
raise InputValidationError(f"schema de manifesto não suportado: {manifest.schema_version}")
|
|
204
|
+
if not manifest.assets:
|
|
205
|
+
raise InputValidationError("manifesto não declara ativos")
|
|
206
|
+
for entry in manifest.assets:
|
|
207
|
+
raw_target = root / entry.path
|
|
208
|
+
if raw_target.is_symlink():
|
|
209
|
+
raise InputValidationError(f"ativo {entry.slot_id!r} não pode ser symlink: {entry.path}")
|
|
210
|
+
target = raw_target.resolve()
|
|
211
|
+
if target != root and root not in target.parents:
|
|
212
|
+
raise InputValidationError(f"ativo {entry.slot_id!r} escapa do diretório de saída: {entry.path}")
|
|
213
|
+
if not target.is_file():
|
|
214
|
+
raise InputValidationError(f"ativo {entry.slot_id!r} não existe: {entry.path}")
|
|
215
|
+
return manifest.assets
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def manifest_product(manifest: AssetManifest, path: Path) -> ProductDraft:
|
|
219
|
+
return ProductDraft(
|
|
220
|
+
kind="asset-manifest",
|
|
221
|
+
path=Path(path),
|
|
222
|
+
content=manifest.as_dict(),
|
|
223
|
+
media_type="application/json",
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def sanitized_env(extra: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
228
|
+
"""Ambiente allowlist para scripts; nunca propaga credenciais do processo."""
|
|
229
|
+
env: dict[str, str] = {}
|
|
230
|
+
for name in _PATH_KEYS:
|
|
231
|
+
value = os.environ.get(name)
|
|
232
|
+
if value is not None:
|
|
233
|
+
env[name] = value
|
|
234
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
235
|
+
for name, value in (extra or {}).items():
|
|
236
|
+
key = str(name)
|
|
237
|
+
upper = key.upper()
|
|
238
|
+
if (
|
|
239
|
+
upper.startswith(_SECRET_PREFIXES)
|
|
240
|
+
or upper.endswith(_SECRET_MARKERS)
|
|
241
|
+
or upper in {"LIMESURVEY_PHPSESSID", "LIMESURVEY_COOKIE"}
|
|
242
|
+
):
|
|
243
|
+
continue
|
|
244
|
+
env[key] = str(value)
|
|
245
|
+
return env
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
__all__ = [
|
|
249
|
+
"ASSET_KIND_PREFIX",
|
|
250
|
+
"ASSET_MANIFEST_SCHEMA",
|
|
251
|
+
"AssetEntry",
|
|
252
|
+
"AssetManifest",
|
|
253
|
+
"load_manifest",
|
|
254
|
+
"manifest_product",
|
|
255
|
+
"sanitized_env",
|
|
256
|
+
"validate_manifest",
|
|
257
|
+
]
|
argos/audit_result.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Formato do resultado da auditoria: gravação ``argos.audit-result/v2`` e leitor único.
|
|
2
|
+
|
|
3
|
+
O motor monta o resultado na forma expandida (``argos.audit-result/v1``), que é a visão usada
|
|
4
|
+
por relatórios, matriz de achados, análises e comentários do gestor. Para gravar, ``compactar``
|
|
5
|
+
separa o que é texto do mapa e da matriz (``catalogo``, uma vez por arquivo) do que resultou da
|
|
6
|
+
execução para cada auditado. Os achados ocorridos continuam legíveis no próprio auditado: nome,
|
|
7
|
+
situações com descrição, critérios rotulados e encaminhamentos por extenso. As ações guardam só o
|
|
8
|
+
resultado, os valores encontrados e a evidência.
|
|
9
|
+
|
|
10
|
+
``expandir`` faz o caminho inverso e devolve exatamente a visão v1. ``compactar`` confere essa ida
|
|
11
|
+
e volta antes de entregar o v2; se não for idêntica, devolve ``None`` e o chamador grava o v1.
|
|
12
|
+
|
|
13
|
+
Uso avulso (leitura humana de um auditado, com tudo por extenso):
|
|
14
|
+
|
|
15
|
+
python -m argos.audit_result resultado.json --auditado "ANGRA DOS REIS"
|
|
16
|
+
python -m argos.audit_result resultado.json --verificar --raiz <projeto>
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import sys
|
|
25
|
+
from collections import Counter
|
|
26
|
+
from copy import deepcopy
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, Mapping
|
|
29
|
+
|
|
30
|
+
FORMATO_V1 = "argos.audit-result/v1"
|
|
31
|
+
FORMATO_V2 = "argos.audit-result/v2"
|
|
32
|
+
FORMATOS = (FORMATO_V1, FORMATO_V2)
|
|
33
|
+
|
|
34
|
+
# Campos da ação que dependem do auditado; os demais são metadados do mapa (catálogo).
|
|
35
|
+
_ACAO_EXECUCAO = (
|
|
36
|
+
"resultado",
|
|
37
|
+
"resultado_situacao",
|
|
38
|
+
"situacao_encontrada",
|
|
39
|
+
"situacoes_encontradas",
|
|
40
|
+
"descricao_evidencia",
|
|
41
|
+
"skipped",
|
|
42
|
+
)
|
|
43
|
+
# Campos da situação que dependem do auditado; os demais vêm da matriz.
|
|
44
|
+
_SITUACAO_EXECUCAO = ("id_situacao", "id_variante", "ativa", "motivos", "id_acoes")
|
|
45
|
+
# Campos que o motor repete nos motivos declarados na matriz.
|
|
46
|
+
_MOTIVO_DERIVADO = ("texto", "acoes_referencia", "id_situacao", "descricao_situacao_inconforme")
|
|
47
|
+
# Chaves da visão v1 de cada procedimento ocorrido derivadas de ``situacoes`` e ``evidencias``.
|
|
48
|
+
_PROCEDIMENTO_VAZIO = {
|
|
49
|
+
"situacoes_inconformes": [],
|
|
50
|
+
"situacoes_encontradas": [],
|
|
51
|
+
"situacoes_detalhadas": [],
|
|
52
|
+
"motivos_situacoes": {},
|
|
53
|
+
"evidencias": [],
|
|
54
|
+
"evidencias_detalhadas": [],
|
|
55
|
+
"encaminhamentos": [],
|
|
56
|
+
}
|
|
57
|
+
_CONTEXTO_MATRIZ = ("questoes", "achados", "situacoes", "criterios", "fontes")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def json_canonico(valor: Any) -> str:
|
|
61
|
+
return json.dumps(valor, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def sha256_texto(valor: str) -> str:
|
|
65
|
+
return hashlib.sha256(valor.encode("utf-8")).hexdigest()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def conteudo_sha256(payload: Mapping[str, Any]) -> str:
|
|
69
|
+
"""Hash do conteúdo de um v2 (catálogo e auditados), independente de indentação."""
|
|
70
|
+
return sha256_texto(json_canonico({"catalogo": payload.get("catalogo"), "auditados": payload.get("auditados")}))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def serializar(payload: Mapping[str, Any]) -> bytes:
|
|
74
|
+
"""JSON ordenado e indentado: determinístico e com diffs legíveis no Git."""
|
|
75
|
+
return (json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=1) + "\n").encode("utf-8")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _rotulo_criterio(criterio: Any) -> Any:
|
|
79
|
+
"""``{id, rotulo}`` para leitura: id de exibição e a norma até o travessão."""
|
|
80
|
+
if not isinstance(criterio, Mapping):
|
|
81
|
+
return criterio
|
|
82
|
+
texto = str(criterio.get("descricao") or "").split(" — ")[0].strip()
|
|
83
|
+
exibicao = criterio.get("id_exibicao") or criterio.get("id")
|
|
84
|
+
return {"id": criterio.get("id"), "rotulo": f"{exibicao} — {texto}" if texto else str(exibicao or "")}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _chave_livre(catalogo: dict[str, Any], base: str, valor: Any) -> str:
|
|
88
|
+
"""Chave legível (``S1.1``, ``S1.1/V2``) que só ganha sufixo se o conteúdo divergir."""
|
|
89
|
+
chave, n = base, 1
|
|
90
|
+
while chave in catalogo and json_canonico(catalogo[chave]) != json_canonico(valor):
|
|
91
|
+
n += 1
|
|
92
|
+
chave = f"{base}~{n}"
|
|
93
|
+
catalogo.setdefault(chave, valor)
|
|
94
|
+
return chave
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _catalogo_acoes(auditados: Mapping[str, Mapping[str, Any]]) -> dict[str, dict[str, Any]]:
|
|
98
|
+
"""Metadados de cada ação pelo valor mais frequente; o auditado guarda só o que difere."""
|
|
99
|
+
contagem: dict[str, dict[str, Counter]] = {}
|
|
100
|
+
for linha in auditados.values():
|
|
101
|
+
for identificador, acao in (linha.get("acoes") or {}).items():
|
|
102
|
+
for chave, valor in acao.items():
|
|
103
|
+
if chave in _ACAO_EXECUCAO or chave == "aplicacoes":
|
|
104
|
+
continue
|
|
105
|
+
contagem.setdefault(identificador, {}).setdefault(chave, Counter())[json_canonico(valor)] += 1
|
|
106
|
+
return {
|
|
107
|
+
identificador: {chave: json.loads(contador.most_common(1)[0][0]) for chave, contador in campos.items()}
|
|
108
|
+
for identificador, campos in contagem.items()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _compactar_v1(v1: Mapping[str, Any]) -> dict[str, Any]:
|
|
113
|
+
auditados = v1["auditados"]
|
|
114
|
+
acoes_catalogo = _catalogo_acoes(auditados)
|
|
115
|
+
procedimentos_catalogo: dict[str, dict[str, Any]] = {}
|
|
116
|
+
situacoes_catalogo: dict[str, Any] = {}
|
|
117
|
+
encaminhamentos_catalogo: dict[str, Any] = {}
|
|
118
|
+
linhas: dict[str, Any] = {}
|
|
119
|
+
for nome, linha in auditados.items():
|
|
120
|
+
nova = {k: deepcopy(v) for k, v in linha.items() if k not in ("acoes", "achados", "procedimentos_executados")}
|
|
121
|
+
acoes: dict[str, Any] = {}
|
|
122
|
+
for identificador, acao in (linha.get("acoes") or {}).items():
|
|
123
|
+
base = acoes_catalogo.get(identificador, {})
|
|
124
|
+
item = {k: deepcopy(acao[k]) for k in _ACAO_EXECUCAO if k in acao}
|
|
125
|
+
item.update({
|
|
126
|
+
k: deepcopy(v) for k, v in acao.items()
|
|
127
|
+
if k not in _ACAO_EXECUCAO and k != "aplicacoes" and (k not in base or json_canonico(base[k]) != json_canonico(v))
|
|
128
|
+
})
|
|
129
|
+
ausentes = sorted(k for k in base if k not in acao)
|
|
130
|
+
if ausentes:
|
|
131
|
+
item["_ausentes"] = ausentes
|
|
132
|
+
acoes[identificador] = item
|
|
133
|
+
nova["acoes"] = acoes
|
|
134
|
+
procedimentos = []
|
|
135
|
+
for procedimento in linha.get("procedimentos_executados") or []:
|
|
136
|
+
identificador = str(procedimento.get("id"))
|
|
137
|
+
procedimentos_catalogo.setdefault(identificador, {
|
|
138
|
+
k: deepcopy(v) for k, v in procedimento.items()
|
|
139
|
+
if k not in ("id", "achado", "achado_ocorreu", *_PROCEDIMENTO_VAZIO)
|
|
140
|
+
})
|
|
141
|
+
item = {"id": identificador, "achado_ocorreu": bool(procedimento.get("achado_ocorreu"))}
|
|
142
|
+
if procedimento.get("achado") != item["achado_ocorreu"]:
|
|
143
|
+
item["achado"] = deepcopy(procedimento.get("achado"))
|
|
144
|
+
if item["achado_ocorreu"]:
|
|
145
|
+
item["numero_achado"] = procedimento.get("numero_achado")
|
|
146
|
+
item["nome_achado"] = procedimento.get("nome_achado")
|
|
147
|
+
situacoes = []
|
|
148
|
+
for detalhe in procedimento.get("situacoes_detalhadas") or []:
|
|
149
|
+
fixo = {k: v for k, v in detalhe.items() if k not in _SITUACAO_EXECUCAO}
|
|
150
|
+
sid = str(detalhe.get("id_situacao") or "")
|
|
151
|
+
variante = detalhe.get("id_variante")
|
|
152
|
+
chave = _chave_livre(situacoes_catalogo, f"{sid}/{variante}" if variante else sid, deepcopy(fixo))
|
|
153
|
+
motivos = []
|
|
154
|
+
for motivo in detalhe.get("motivos") or []:
|
|
155
|
+
if isinstance(motivo, Mapping) and "id" in motivo and "id_acao" not in motivo:
|
|
156
|
+
motivo = {k: v for k, v in motivo.items() if k not in _MOTIVO_DERIVADO}
|
|
157
|
+
motivos.append(deepcopy(motivo))
|
|
158
|
+
situacoes.append({
|
|
159
|
+
"ref": chave,
|
|
160
|
+
"descricao": detalhe.get("descricao"),
|
|
161
|
+
"criterios": [_rotulo_criterio(c) for c in detalhe.get("criterios") or []],
|
|
162
|
+
**{k: deepcopy(detalhe[k]) for k in _SITUACAO_EXECUCAO if k in detalhe and k != "motivos"},
|
|
163
|
+
"motivos": motivos,
|
|
164
|
+
})
|
|
165
|
+
encaminhamentos = []
|
|
166
|
+
for referral in procedimento.get("encaminhamentos") or []:
|
|
167
|
+
fixo = {k: v for k, v in referral.items() if k != "id_acoes"}
|
|
168
|
+
base = "/".join(str(p) for p in (referral.get("id_situacao"), referral.get("id_variante") or "-", referral.get("tipo") or "-"))
|
|
169
|
+
chave = _chave_livre(encaminhamentos_catalogo, base, deepcopy(fixo))
|
|
170
|
+
encaminhamentos.append({
|
|
171
|
+
"ref": chave,
|
|
172
|
+
"id_situacao": referral.get("id_situacao"),
|
|
173
|
+
"id_variante": referral.get("id_variante"),
|
|
174
|
+
"tipo": referral.get("tipo"),
|
|
175
|
+
"encaminhamento": referral.get("encaminhamento"),
|
|
176
|
+
"fundamentacao_encaminhamento": referral.get("fundamentacao_encaminhamento"),
|
|
177
|
+
"criterios": [_rotulo_criterio(c) for c in referral.get("criterios") or []],
|
|
178
|
+
"id_acoes": deepcopy(referral.get("id_acoes") or []),
|
|
179
|
+
})
|
|
180
|
+
item.update(
|
|
181
|
+
situacoes=situacoes,
|
|
182
|
+
evidencias=deepcopy(procedimento.get("evidencias_detalhadas") or []),
|
|
183
|
+
encaminhamentos=encaminhamentos,
|
|
184
|
+
)
|
|
185
|
+
procedimentos.append(item)
|
|
186
|
+
nova["procedimentos"] = procedimentos
|
|
187
|
+
linhas[nome] = nova
|
|
188
|
+
contexto = v1.get("contexto_matriz") or {}
|
|
189
|
+
return {
|
|
190
|
+
"schema_version": FORMATO_V2,
|
|
191
|
+
"cenario": v1.get("cenario"),
|
|
192
|
+
"cobertura": deepcopy(v1.get("cobertura")),
|
|
193
|
+
"catalogo": {
|
|
194
|
+
**{k: deepcopy(contexto.get(k) or []) for k in _CONTEXTO_MATRIZ},
|
|
195
|
+
"acoes": acoes_catalogo,
|
|
196
|
+
"procedimentos": procedimentos_catalogo,
|
|
197
|
+
"situacoes_detalhadas": situacoes_catalogo,
|
|
198
|
+
"encaminhamentos": encaminhamentos_catalogo,
|
|
199
|
+
},
|
|
200
|
+
"auditados": linhas,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _expandir_auditado(linha: Mapping[str, Any], catalogo: Mapping[str, Any]) -> dict[str, Any]:
|
|
205
|
+
nova = {k: deepcopy(v) for k, v in linha.items() if k not in ("acoes", "procedimentos")}
|
|
206
|
+
acoes: dict[str, dict[str, Any]] = {}
|
|
207
|
+
for identificador, valores in (linha.get("acoes") or {}).items():
|
|
208
|
+
ausentes = set(valores.get("_ausentes") or ())
|
|
209
|
+
base = {k: deepcopy(v) for k, v in (catalogo["acoes"].get(identificador) or {}).items() if k not in ausentes}
|
|
210
|
+
acoes[identificador] = {**base, **{k: deepcopy(v) for k, v in valores.items() if k != "_ausentes"}, "aplicacoes": []}
|
|
211
|
+
procedimentos, achados = [], {}
|
|
212
|
+
for item in linha.get("procedimentos") or []:
|
|
213
|
+
meta = catalogo["procedimentos"].get(item["id"]) or {}
|
|
214
|
+
procedimento = {
|
|
215
|
+
**deepcopy(dict(meta)),
|
|
216
|
+
"id": item["id"],
|
|
217
|
+
"achado": deepcopy(item.get("achado", item["achado_ocorreu"])),
|
|
218
|
+
"achado_ocorreu": item["achado_ocorreu"],
|
|
219
|
+
**deepcopy(_PROCEDIMENTO_VAZIO),
|
|
220
|
+
}
|
|
221
|
+
if item["achado_ocorreu"]:
|
|
222
|
+
detalhes, motivos_por_situacao = [], {}
|
|
223
|
+
for situacao in item.get("situacoes") or []:
|
|
224
|
+
fixo = catalogo["situacoes_detalhadas"][situacao["ref"]]
|
|
225
|
+
motivos = []
|
|
226
|
+
for motivo in situacao.get("motivos") or []:
|
|
227
|
+
if isinstance(motivo, Mapping) and "id" in motivo and "id_acao" not in motivo:
|
|
228
|
+
motivo = {
|
|
229
|
+
**motivo,
|
|
230
|
+
"texto": motivo.get("descricao"),
|
|
231
|
+
"acoes_referencia": list(motivo.get("refs_acoes") or []),
|
|
232
|
+
"id_situacao": situacao.get("id_situacao"),
|
|
233
|
+
"descricao_situacao_inconforme": fixo.get("descricao"),
|
|
234
|
+
}
|
|
235
|
+
motivos.append(deepcopy(motivo))
|
|
236
|
+
detalhe = {
|
|
237
|
+
**deepcopy(fixo),
|
|
238
|
+
**{k: deepcopy(v) for k, v in situacao.items() if k in _SITUACAO_EXECUCAO and k != "motivos"},
|
|
239
|
+
"motivos": motivos,
|
|
240
|
+
}
|
|
241
|
+
detalhes.append(detalhe)
|
|
242
|
+
motivos_por_situacao[str(situacao.get("id_situacao"))] = deepcopy(motivos)
|
|
243
|
+
descricoes = [d.get("descricao") for d in detalhes]
|
|
244
|
+
evidencias = deepcopy(item.get("evidencias") or [])
|
|
245
|
+
procedimento.update(
|
|
246
|
+
situacoes_inconformes=descricoes,
|
|
247
|
+
situacoes_encontradas=list(descricoes),
|
|
248
|
+
situacoes_detalhadas=detalhes,
|
|
249
|
+
motivos_situacoes=motivos_por_situacao,
|
|
250
|
+
evidencias=[e.get("descricao") for e in evidencias if isinstance(e, Mapping)],
|
|
251
|
+
evidencias_detalhadas=evidencias,
|
|
252
|
+
encaminhamentos=[
|
|
253
|
+
{**deepcopy(catalogo["encaminhamentos"][e["ref"]]), "id_acoes": list(e.get("id_acoes") or [])}
|
|
254
|
+
for e in item.get("encaminhamentos") or []
|
|
255
|
+
],
|
|
256
|
+
)
|
|
257
|
+
achados[str(meta.get("numero_achado") or item["id"])] = procedimento
|
|
258
|
+
procedimentos.append(procedimento)
|
|
259
|
+
# ``aplicacoes``: as mesmas regras de VerificationMap._build_auditee_result.
|
|
260
|
+
por_id = {identificador.upper(): acao for identificador, acao in acoes.items()}
|
|
261
|
+
for procedimento in procedimentos:
|
|
262
|
+
for referral in procedimento["encaminhamentos"]:
|
|
263
|
+
aplicacao = {
|
|
264
|
+
"id_procedimento": procedimento["id"],
|
|
265
|
+
"id_situacao": referral.get("id_situacao"),
|
|
266
|
+
"tipo": deepcopy(referral.get("tipo")),
|
|
267
|
+
"encaminhamento": deepcopy(referral.get("encaminhamento")),
|
|
268
|
+
"fundamentacao_encaminhamento": deepcopy(referral.get("fundamentacao_encaminhamento")),
|
|
269
|
+
"criterios": deepcopy(referral.get("criterios") or []),
|
|
270
|
+
}
|
|
271
|
+
if referral.get("id_variante"):
|
|
272
|
+
aplicacao["id_variante"] = deepcopy(referral["id_variante"])
|
|
273
|
+
for identificador in referral.get("id_acoes") or []:
|
|
274
|
+
acao = por_id.get(str(identificador).upper())
|
|
275
|
+
if acao is not None and not any(json_canonico(x) == json_canonico(aplicacao) for x in acao["aplicacoes"]):
|
|
276
|
+
acao["aplicacoes"].append(deepcopy(aplicacao))
|
|
277
|
+
nova.update(acoes=acoes, procedimentos_executados=procedimentos, achados=achados)
|
|
278
|
+
return nova
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def expandir(payload: Any) -> Any:
|
|
282
|
+
"""Visão v1 de um resultado v2; v1, legado e dicionário sem envelope voltam como estão."""
|
|
283
|
+
if not isinstance(payload, Mapping) or payload.get("schema_version") != FORMATO_V2:
|
|
284
|
+
return payload
|
|
285
|
+
catalogo = payload.get("catalogo") or {}
|
|
286
|
+
for chave in ("acoes", "procedimentos", "situacoes_detalhadas", "encaminhamentos"):
|
|
287
|
+
if not isinstance(catalogo.get(chave), Mapping):
|
|
288
|
+
raise ValueError(f"resultado v2 sem catalogo.{chave}")
|
|
289
|
+
return {
|
|
290
|
+
"schema_version": FORMATO_V1,
|
|
291
|
+
"cenario": payload.get("cenario"),
|
|
292
|
+
"cobertura": deepcopy(payload.get("cobertura")),
|
|
293
|
+
"contexto_matriz": {k: deepcopy(catalogo.get(k) or []) for k in _CONTEXTO_MATRIZ},
|
|
294
|
+
"auditados": {nome: _expandir_auditado(linha, catalogo) for nome, linha in (payload.get("auditados") or {}).items()},
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def compactar(v1: Mapping[str, Any], proveniencia: Mapping[str, Any] | None = None) -> dict[str, Any] | None:
|
|
299
|
+
"""v2 do resultado expandido, ou ``None`` se a ida e volta não reproduzir o v1."""
|
|
300
|
+
v2 = _compactar_v1(v1)
|
|
301
|
+
if json_canonico(expandir(v2)) != json_canonico(dict(v1)):
|
|
302
|
+
return None
|
|
303
|
+
v2["proveniencia"] = {**dict(proveniencia or {}), "conteudo_sha256": conteudo_sha256(v2)}
|
|
304
|
+
return v2
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def verificar(payload: Mapping[str, Any], raiz: Path | None = None) -> list[str]:
|
|
308
|
+
"""Divergências entre a proveniência declarada e o conteúdo e os arquivos atuais."""
|
|
309
|
+
if not isinstance(payload, Mapping) or payload.get("schema_version") != FORMATO_V2:
|
|
310
|
+
return []
|
|
311
|
+
proveniencia = payload.get("proveniencia") or {}
|
|
312
|
+
problemas = []
|
|
313
|
+
declarado = proveniencia.get("conteudo_sha256")
|
|
314
|
+
if declarado and declarado != conteudo_sha256(payload):
|
|
315
|
+
problemas.append("conteúdo do resultado diverge de proveniencia.conteudo_sha256")
|
|
316
|
+
entradas = [(chave, proveniencia.get(chave)) for chave in ("auditados", "mapa", "matriz")]
|
|
317
|
+
entradas += [(f"fontes.{k}", v) for k, v in sorted((proveniencia.get("fontes") or {}).items())]
|
|
318
|
+
base = Path(raiz) if raiz is not None else Path.cwd()
|
|
319
|
+
for rotulo, entrada in entradas:
|
|
320
|
+
if not isinstance(entrada, Mapping) or not entrada.get("path"):
|
|
321
|
+
continue
|
|
322
|
+
caminho = Path(entrada["path"])
|
|
323
|
+
caminho = caminho if caminho.is_absolute() else base / caminho
|
|
324
|
+
if not caminho.is_file():
|
|
325
|
+
problemas.append(f"{rotulo}: arquivo ausente ({entrada['path']})")
|
|
326
|
+
elif hashlib.sha256(caminho.read_bytes()).hexdigest() != entrada.get("sha256"):
|
|
327
|
+
problemas.append(f"{rotulo}: arquivo alterado depois da auditoria ({entrada['path']})")
|
|
328
|
+
return problemas
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def carregar(origem: Any) -> Any:
|
|
332
|
+
"""Lê um resultado (caminho ou objeto) e devolve a visão expandida usada pelos consumidores."""
|
|
333
|
+
if isinstance(origem, (str, Path)):
|
|
334
|
+
origem = json.loads(Path(origem).read_text(encoding="utf-8"))
|
|
335
|
+
return expandir(origem)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def main(argv: list[str] | None = None) -> int:
|
|
339
|
+
parser = argparse.ArgumentParser(prog="python -m argos.audit_result", description=__doc__.split("\n\n")[0])
|
|
340
|
+
parser.add_argument("resultado", type=Path)
|
|
341
|
+
parser.add_argument("--auditado", help="imprime a visão expandida de um auditado")
|
|
342
|
+
parser.add_argument("--verificar", action="store_true", help="confere conteúdo e hashes das entradas")
|
|
343
|
+
parser.add_argument("--raiz", type=Path, help="raiz do projeto para resolver os caminhos da proveniência")
|
|
344
|
+
args = parser.parse_args(argv)
|
|
345
|
+
bruto = json.loads(args.resultado.read_text(encoding="utf-8"))
|
|
346
|
+
if args.verificar:
|
|
347
|
+
problemas = verificar(bruto, args.raiz)
|
|
348
|
+
print("\n".join(problemas) if problemas else "resultado íntegro e entradas inalteradas")
|
|
349
|
+
return 1 if problemas else 0
|
|
350
|
+
visao = expandir(bruto)
|
|
351
|
+
linhas = visao.get("auditados", visao) if isinstance(visao, Mapping) else {}
|
|
352
|
+
if args.auditado:
|
|
353
|
+
if args.auditado not in linhas:
|
|
354
|
+
parser.error(f"auditado ausente: {args.auditado}")
|
|
355
|
+
print(json.dumps(linhas[args.auditado], ensure_ascii=False, indent=1, sort_keys=True))
|
|
356
|
+
return 0
|
|
357
|
+
resumo = {
|
|
358
|
+
"schema_version": bruto.get("schema_version") if isinstance(bruto, Mapping) else None,
|
|
359
|
+
"cenario": bruto.get("cenario") if isinstance(bruto, Mapping) else None,
|
|
360
|
+
"cobertura": bruto.get("cobertura") if isinstance(bruto, Mapping) else None,
|
|
361
|
+
"proveniencia": bruto.get("proveniencia") if isinstance(bruto, Mapping) else None,
|
|
362
|
+
"auditados": len(linhas),
|
|
363
|
+
}
|
|
364
|
+
print(json.dumps(resumo, ensure_ascii=False, indent=1))
|
|
365
|
+
return 0
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
if __name__ == "__main__": # pragma: no cover
|
|
369
|
+
sys.exit(main())
|