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/fingerprints.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Identidade material das entradas e conferência dos produtos reutilizados."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
import glob
|
|
7
|
+
import importlib.metadata
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import sqlite3
|
|
11
|
+
import sys
|
|
12
|
+
from types import CodeType
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Mapping
|
|
15
|
+
|
|
16
|
+
from .contracts import OperationSpec, canonical_json, sha256_bytes, sha256_file
|
|
17
|
+
from .errors import InputValidationError
|
|
18
|
+
from .adapters.docx_pdf import document_resources
|
|
19
|
+
from .version import __version__ as ARGOS_VERSION
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@lru_cache(maxsize=1)
|
|
23
|
+
def _package_implementation() -> dict[str, str]:
|
|
24
|
+
package = Path(__file__).parent
|
|
25
|
+
return {
|
|
26
|
+
str(path.relative_to(package)): sha256_file(path)
|
|
27
|
+
for path in sorted(package.rglob("*"))
|
|
28
|
+
if path.is_file() and path.suffix in {".py", ".md", ".tcss", ".yml", ".yaml"}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@lru_cache(maxsize=1)
|
|
33
|
+
def _environment_versions() -> dict[str, Any]:
|
|
34
|
+
environment: dict[str, Any] = {
|
|
35
|
+
"python": list(sys.version_info[:3]),
|
|
36
|
+
"sqlite": sqlite3.sqlite_version,
|
|
37
|
+
}
|
|
38
|
+
for name in (
|
|
39
|
+
"openpyxl", "PyYAML", "python-docx", "docxcompose", "lxml", "Jinja2",
|
|
40
|
+
"markdown-it-py", "matplotlib", "requests", "google-genai",
|
|
41
|
+
"pypdf", "PyMuPDF",
|
|
42
|
+
):
|
|
43
|
+
try:
|
|
44
|
+
environment[name] = importlib.metadata.version(name)
|
|
45
|
+
except importlib.metadata.PackageNotFoundError:
|
|
46
|
+
environment[name] = None
|
|
47
|
+
return environment
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _values(value: Any):
|
|
51
|
+
if isinstance(value, (str, Path)):
|
|
52
|
+
yield value
|
|
53
|
+
elif isinstance(value, (tuple, list)):
|
|
54
|
+
for item in value:
|
|
55
|
+
yield from _values(item)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _pipeline_plan_snapshot(
|
|
59
|
+
value: str | Path,
|
|
60
|
+
root: Path,
|
|
61
|
+
excluded: list[Path],
|
|
62
|
+
catalog: Any,
|
|
63
|
+
) -> dict[str, Any]:
|
|
64
|
+
"""Hash the pipeline declaration and its external inputs, excluding stage outputs.
|
|
65
|
+
|
|
66
|
+
A pipeline's ``mapa_fontes`` may point at a file produced by an earlier stage.
|
|
67
|
+
The child operation fingerprints that file when it consumes it; including it
|
|
68
|
+
as an external input of the parent would make the parent's snapshot change
|
|
69
|
+
when the producer publishes the file during the same execution.
|
|
70
|
+
"""
|
|
71
|
+
path = _path(value, root)
|
|
72
|
+
snapshot = _snapshot(path, root, excluded, follow_resources=False)
|
|
73
|
+
if catalog is None or not path.is_file() or path.suffix.casefold() not in {".json", ".yml", ".yaml"}:
|
|
74
|
+
return snapshot
|
|
75
|
+
try:
|
|
76
|
+
if path.suffix.casefold() == ".json":
|
|
77
|
+
payload = json.loads(_readable_text(path))
|
|
78
|
+
else:
|
|
79
|
+
import yaml
|
|
80
|
+
|
|
81
|
+
payload = yaml.safe_load(_readable_text(path))
|
|
82
|
+
except (ImportError, UnicodeError, ValueError):
|
|
83
|
+
return snapshot
|
|
84
|
+
except yaml.YAMLError:
|
|
85
|
+
return snapshot
|
|
86
|
+
operations = payload.get("operations") if isinstance(payload, Mapping) else None
|
|
87
|
+
if not isinstance(operations, list):
|
|
88
|
+
return snapshot
|
|
89
|
+
|
|
90
|
+
product_paths: list[Path] = []
|
|
91
|
+
for step in operations:
|
|
92
|
+
if not isinstance(step, Mapping):
|
|
93
|
+
continue
|
|
94
|
+
operation_id = str(step.get("operation") or step.get("id") or "").strip()
|
|
95
|
+
raw_params = step.get("params") or {}
|
|
96
|
+
if not operation_id or not isinstance(raw_params, Mapping):
|
|
97
|
+
continue
|
|
98
|
+
try:
|
|
99
|
+
operation = catalog.get(operation_id)
|
|
100
|
+
except Exception: # noqa: BLE001 - normal contract validation reports unknown operations
|
|
101
|
+
continue
|
|
102
|
+
for parameter_name in operation.products.path_parameters:
|
|
103
|
+
for output in _values(raw_params.get(parameter_name)):
|
|
104
|
+
if isinstance(output, (str, Path)) and str(output).strip():
|
|
105
|
+
product_paths.append(_path(output, root))
|
|
106
|
+
|
|
107
|
+
def is_stage_product(candidate: Path) -> bool:
|
|
108
|
+
return any(candidate == output or output in candidate.parents for output in product_paths)
|
|
109
|
+
|
|
110
|
+
references: list[str] = []
|
|
111
|
+
script_steps: list[dict[str, Any]] = []
|
|
112
|
+
for step in operations:
|
|
113
|
+
if not isinstance(step, Mapping) or "script" not in step:
|
|
114
|
+
continue
|
|
115
|
+
raw_script = str(step.get("script") or "").strip()
|
|
116
|
+
if not raw_script:
|
|
117
|
+
continue
|
|
118
|
+
raw_args = step.get("args") or ()
|
|
119
|
+
raw_deps = step.get("deps") or ()
|
|
120
|
+
raw_inputs = step.get("inputs") or {}
|
|
121
|
+
entry: dict[str, Any] = {
|
|
122
|
+
"unit_id": str(step.get("unit_id") or ""),
|
|
123
|
+
"script": raw_script,
|
|
124
|
+
"args": list(raw_args) if isinstance(raw_args, (list, tuple)) else str(raw_args),
|
|
125
|
+
"deps": list(raw_deps) if isinstance(raw_deps, (list, tuple)) else str(raw_deps),
|
|
126
|
+
"inputs": {},
|
|
127
|
+
"outputs": step.get("outputs") or [],
|
|
128
|
+
"output_arg": step.get("output_arg"),
|
|
129
|
+
"cwd": step.get("cwd"),
|
|
130
|
+
}
|
|
131
|
+
if isinstance(raw_deps, (list, tuple)):
|
|
132
|
+
references.extend(str(dep) for dep in raw_deps if str(dep).strip())
|
|
133
|
+
if isinstance(raw_inputs, Mapping):
|
|
134
|
+
for name, value in raw_inputs.items():
|
|
135
|
+
if isinstance(value, Mapping) and "$stage" in value:
|
|
136
|
+
entry["inputs"][str(name)] = {
|
|
137
|
+
"$stage": value.get("$stage"),
|
|
138
|
+
"kind": value.get("kind"),
|
|
139
|
+
}
|
|
140
|
+
elif isinstance(value, (str, Path)):
|
|
141
|
+
entry["inputs"][str(name)] = str(value)
|
|
142
|
+
if str(value).strip():
|
|
143
|
+
references.append(str(value))
|
|
144
|
+
else:
|
|
145
|
+
entry["inputs"][str(name)] = repr(value)
|
|
146
|
+
references.append(raw_script)
|
|
147
|
+
script_steps.append(entry)
|
|
148
|
+
if script_steps:
|
|
149
|
+
snapshot["script_steps"] = script_steps
|
|
150
|
+
|
|
151
|
+
references.extend(_resource_references(payload))
|
|
152
|
+
filtered_references: list[str] = []
|
|
153
|
+
for reference in references:
|
|
154
|
+
root_candidate = _path(reference, root)
|
|
155
|
+
plan_candidate = _path(reference, path.parent)
|
|
156
|
+
if is_stage_product(root_candidate) or is_stage_product(plan_candidate):
|
|
157
|
+
continue
|
|
158
|
+
filtered_references.append(reference)
|
|
159
|
+
resources = _snapshot_references(path, filtered_references, root, excluded, frozenset({path}))
|
|
160
|
+
if resources:
|
|
161
|
+
snapshot["resources"] = resources
|
|
162
|
+
return snapshot
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def execution_snapshot(
|
|
166
|
+
spec: OperationSpec,
|
|
167
|
+
params: Mapping[str, Any],
|
|
168
|
+
root: Path,
|
|
169
|
+
store: Any = None,
|
|
170
|
+
catalog: Any = None,
|
|
171
|
+
) -> dict[str, Any]:
|
|
172
|
+
"""Inclui bytes das entradas declaradas, sem incluir arquivos de saída.
|
|
173
|
+
|
|
174
|
+
Diretórios usam ordem estável e links para diretórios não são percorridos.
|
|
175
|
+
Identidade material conservadora; a deduplicação semântica de avaliações
|
|
176
|
+
continua pertencendo a EvaluationLifecycle.
|
|
177
|
+
"""
|
|
178
|
+
inputs: dict[str, Any] = {}
|
|
179
|
+
configuration = root / "fiscalizacao.yml"
|
|
180
|
+
if configuration.is_file():
|
|
181
|
+
inputs["project_configuration"] = {"sha256": _readable_sha256(configuration)}
|
|
182
|
+
output_parameters = set(spec.products.path_parameters)
|
|
183
|
+
excluded = [
|
|
184
|
+
_path(value, root)
|
|
185
|
+
for name in output_parameters
|
|
186
|
+
for value in _values(params.get(name))
|
|
187
|
+
]
|
|
188
|
+
for parameter in spec.parameters:
|
|
189
|
+
if not parameter.path or parameter.name in output_parameters or parameter.name == "mapa_fontes":
|
|
190
|
+
continue
|
|
191
|
+
inputs[parameter.name] = [
|
|
192
|
+
snapshot
|
|
193
|
+
for value in _values(params.get(parameter.name))
|
|
194
|
+
if (
|
|
195
|
+
snapshot := (
|
|
196
|
+
_pipeline_plan_snapshot(value, root, excluded, catalog)
|
|
197
|
+
if spec.id == "pipeline" and parameter.name == "plan_file"
|
|
198
|
+
else _snapshot_input(value, root, excluded)
|
|
199
|
+
)
|
|
200
|
+
) is not None
|
|
201
|
+
]
|
|
202
|
+
# O contrato do mapa aceita id=caminho; estes são inputs, não texto livre.
|
|
203
|
+
mappings = {}
|
|
204
|
+
for value in _values(params.get("mapa_fontes")):
|
|
205
|
+
name, separator, path = str(value).partition("=")
|
|
206
|
+
if separator:
|
|
207
|
+
mappings[name.strip()] = _snapshot(path.strip(), root, excluded)
|
|
208
|
+
if mappings:
|
|
209
|
+
inputs["mapa_fontes"] = mappings
|
|
210
|
+
implementation = _package_implementation()
|
|
211
|
+
code = getattr(spec.handler, "__code__", None)
|
|
212
|
+
handler = {"module": getattr(spec.handler, "__module__", type(spec.handler).__module__), "name": getattr(spec.handler, "__qualname__", type(spec.handler).__qualname__)}
|
|
213
|
+
if isinstance(code, CodeType):
|
|
214
|
+
handler["code_sha256"] = sha256_bytes(canonical_json(_code_identity(code)).encode("utf-8"))
|
|
215
|
+
# O catálogo captura apenas o nome do handler. Estado mutável de
|
|
216
|
+
# callbacks (tentativas/contadores) não é configuração de domínio.
|
|
217
|
+
if handler["module"] == "argos.catalog":
|
|
218
|
+
handler["closure"] = [cell.cell_contents for cell in (spec.handler.__closure__ or ())
|
|
219
|
+
if isinstance(cell.cell_contents, str)]
|
|
220
|
+
environment = _environment_versions()
|
|
221
|
+
state = None
|
|
222
|
+
if store is not None:
|
|
223
|
+
state = {
|
|
224
|
+
"fiscalizacao_id": str(store.fiscalizacao_id),
|
|
225
|
+
"numero": str(store.numero),
|
|
226
|
+
"nome": str(store.nome),
|
|
227
|
+
}
|
|
228
|
+
projection = None
|
|
229
|
+
if spec.state_projection is not None:
|
|
230
|
+
if store is None:
|
|
231
|
+
raise InputValidationError(
|
|
232
|
+
f"operação {spec.id} exige controle SQLite para calcular sua identidade"
|
|
233
|
+
)
|
|
234
|
+
projected = spec.state_projection(store, params, root.resolve())
|
|
235
|
+
if not isinstance(projected, Mapping):
|
|
236
|
+
raise InputValidationError(
|
|
237
|
+
f"projeção de estado de {spec.id} deve retornar um objeto"
|
|
238
|
+
)
|
|
239
|
+
try:
|
|
240
|
+
projection_digest = sha256_bytes(canonical_json(dict(projected)).encode("utf-8"))
|
|
241
|
+
except (TypeError, ValueError) as exc:
|
|
242
|
+
raise InputValidationError(
|
|
243
|
+
f"projeção de estado de {spec.id} não é serializável"
|
|
244
|
+
) from exc
|
|
245
|
+
projection = {
|
|
246
|
+
"id": f"{spec.state_projection.__module__}.{spec.state_projection.__qualname__}",
|
|
247
|
+
"version": spec.state_projection_version,
|
|
248
|
+
"sha256": projection_digest,
|
|
249
|
+
}
|
|
250
|
+
snapshot = {
|
|
251
|
+
"operation": spec.id,
|
|
252
|
+
"version": spec.version,
|
|
253
|
+
"argos_version": ARGOS_VERSION,
|
|
254
|
+
"params": {key: value for key, value in params.items() if key not in {"retry_failed", "retry_unknown"}},
|
|
255
|
+
"inputs": inputs,
|
|
256
|
+
"fingerprint_version": 6,
|
|
257
|
+
"implementation": implementation,
|
|
258
|
+
"handler": handler,
|
|
259
|
+
"environment": environment,
|
|
260
|
+
"workspace_state": state,
|
|
261
|
+
"state_projection": projection,
|
|
262
|
+
"dependency_scope": "conservative-package: módulos/recursos do Argos e dependências diretas de execução",
|
|
263
|
+
}
|
|
264
|
+
if spec.id in {"indice", "indice.lote"}:
|
|
265
|
+
from .index_dsl import INDEX_EVALUATOR_REVISION
|
|
266
|
+
|
|
267
|
+
snapshot["semantic_revision"] = {"index_evaluator": INDEX_EVALUATOR_REVISION}
|
|
268
|
+
return snapshot
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def snapshot_hash(snapshot: Mapping[str, Any]) -> str:
|
|
272
|
+
return sha256_bytes(canonical_json(snapshot).encode("utf-8"))
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def execution_fingerprint(
|
|
276
|
+
spec: OperationSpec,
|
|
277
|
+
params: Mapping[str, Any],
|
|
278
|
+
root: Path,
|
|
279
|
+
store: Any = None,
|
|
280
|
+
catalog: Any = None,
|
|
281
|
+
) -> str:
|
|
282
|
+
return snapshot_hash(execution_snapshot(spec, params, root, store, catalog))
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _code_identity(code: CodeType) -> dict[str, Any]:
|
|
286
|
+
# O endereço do checkout, número da linha e tabelas de debugging não
|
|
287
|
+
# alteram a implementação semântica de uma função.
|
|
288
|
+
return {"bytecode": code.co_code.hex(), "constants": [_code_identity(item) if isinstance(item, CodeType) else repr(item) for item in code.co_consts],
|
|
289
|
+
"names": code.co_names, "variables": code.co_varnames, "freevars": code.co_freevars,
|
|
290
|
+
"args": code.co_argcount, "kwonly": code.co_kwonlyargcount, "flags": code.co_flags}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _path(value: str | Path, root: Path) -> Path:
|
|
294
|
+
candidate = Path(value).expanduser()
|
|
295
|
+
return (candidate if candidate.is_absolute() else root / candidate).resolve()
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _is_excluded(path: Path, excluded: list[Path]) -> bool:
|
|
299
|
+
resolved = path.resolve()
|
|
300
|
+
return any(resolved == output or output in resolved.parents for output in excluded)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _snapshot_input(value: str | Path, root: Path, excluded: list[Path]) -> dict[str, Any] | None:
|
|
304
|
+
"""Snapshot de entrada; ``None`` quando o caminho é um produto declarado.
|
|
305
|
+
|
|
306
|
+
Um caminho de saída aparece em ``params`` (e portanto em ``params`` do
|
|
307
|
+
snapshot), mas seu conteúdo nunca é entrada: incluí-lo tornaria a
|
|
308
|
+
identidade da execução dependente de o produto já existir, impedindo a
|
|
309
|
+
reutilização por hash entre execuções idênticas.
|
|
310
|
+
"""
|
|
311
|
+
path = _path(value, root)
|
|
312
|
+
if not glob.has_magic(str(path)) and path.resolve() in {output.resolve() for output in excluded}:
|
|
313
|
+
return None
|
|
314
|
+
return _snapshot(value, root, excluded)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _snapshot(
|
|
318
|
+
value: str | Path, root: Path, excluded: list[Path], seen: frozenset[Path] = frozenset(),
|
|
319
|
+
*, document_root: Path | None = None, follow_resources: bool = True,
|
|
320
|
+
) -> dict[str, Any]:
|
|
321
|
+
path = _path(value, root)
|
|
322
|
+
if glob.has_magic(str(path)):
|
|
323
|
+
matches = (
|
|
324
|
+
match
|
|
325
|
+
for match in sorted(glob.glob(str(path), recursive=True))
|
|
326
|
+
if not _is_excluded(Path(match), excluded)
|
|
327
|
+
)
|
|
328
|
+
return {"pattern": str(path), "matches": [_snapshot(match, root, excluded, seen) for match in matches]}
|
|
329
|
+
try:
|
|
330
|
+
path.stat()
|
|
331
|
+
except FileNotFoundError:
|
|
332
|
+
return {"path": str(path), "missing": True}
|
|
333
|
+
except OSError as exc:
|
|
334
|
+
raise InputValidationError(f"não foi possível inspecionar a entrada: {path}") from exc
|
|
335
|
+
if path.is_file():
|
|
336
|
+
result = {"path": str(path), "sha256": _readable_sha256(path)}
|
|
337
|
+
if path in seen or not follow_resources:
|
|
338
|
+
return result
|
|
339
|
+
if path.suffix.lower() in {".json", ".yml", ".yaml"}:
|
|
340
|
+
try:
|
|
341
|
+
if path.suffix.lower() == ".json":
|
|
342
|
+
config = json.loads(_readable_text(path))
|
|
343
|
+
else:
|
|
344
|
+
import yaml
|
|
345
|
+
|
|
346
|
+
config = yaml.safe_load(_readable_text(path))
|
|
347
|
+
except (ImportError, UnicodeError, ValueError):
|
|
348
|
+
config = None # A validação de formato permanece com a operação.
|
|
349
|
+
except yaml.YAMLError:
|
|
350
|
+
config = None
|
|
351
|
+
references = list(_resource_references(config))
|
|
352
|
+
if references:
|
|
353
|
+
result["resources"] = _snapshot_references(path, references, root, excluded, seen | {path})
|
|
354
|
+
elif path.suffix.lower() in {".md", ".markdown", ".j2"}:
|
|
355
|
+
references, dynamic = document_resources(_readable_text(path))
|
|
356
|
+
resources = _snapshot_references(
|
|
357
|
+
path, references, root, excluded, seen | {path}, document_root=document_root or path.parent
|
|
358
|
+
)
|
|
359
|
+
if dynamic:
|
|
360
|
+
resources["$template_directory"] = _snapshot(path.parent, root, excluded, seen | {path})
|
|
361
|
+
if resources:
|
|
362
|
+
result["resources"] = resources
|
|
363
|
+
return result
|
|
364
|
+
if path.is_dir():
|
|
365
|
+
entries = {}
|
|
366
|
+
def access_error(exc):
|
|
367
|
+
raise InputValidationError(f"não foi possível enumerar a entrada: {path}") from exc
|
|
368
|
+
|
|
369
|
+
for directory, folders, files in os.walk(path, onerror=access_error, followlinks=False):
|
|
370
|
+
folders[:] = sorted(
|
|
371
|
+
folder for folder in folders if not _is_excluded(Path(directory) / folder, excluded)
|
|
372
|
+
)
|
|
373
|
+
for name in sorted(files):
|
|
374
|
+
child = Path(directory) / name
|
|
375
|
+
if not _is_excluded(child, excluded):
|
|
376
|
+
entries[child.relative_to(path).as_posix()] = _readable_sha256(child)
|
|
377
|
+
return {"path": str(path), "files": entries}
|
|
378
|
+
return {"path": str(path), "missing": True}
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
# Chaves de formatos de arquivo que apontam para outros arquivos (mapa de fontes, manifesto de
|
|
382
|
+
# ativos, índice em lote, contexto, publicação, catálogo de prompts e passos de script do pipeline).
|
|
383
|
+
# Os nomes de parâmetros que são caminhos vêm do catálogo (`_path_parameter_names`).
|
|
384
|
+
_FILE_FORMAT_KEYS = frozenset({
|
|
385
|
+
"filepath", "path", "memory", "modelo_institucional", "arquivo", "arquivos", "files",
|
|
386
|
+
})
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
@lru_cache(maxsize=1)
|
|
390
|
+
def _path_parameter_names() -> frozenset[str]:
|
|
391
|
+
"""Nomes dos parâmetros de caminho de entrada do catálogo (os de saída não entram no hash)."""
|
|
392
|
+
from .catalog import build_catalog
|
|
393
|
+
|
|
394
|
+
names: set[str] = set()
|
|
395
|
+
for spec in build_catalog().all():
|
|
396
|
+
outputs = set(spec.products.path_parameters)
|
|
397
|
+
names.update(p.name for p in spec.parameters if p.path and p.name not in outputs)
|
|
398
|
+
return frozenset(names)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _resource_references(value: Any):
|
|
402
|
+
keys = _FILE_FORMAT_KEYS | _path_parameter_names()
|
|
403
|
+
if isinstance(value, Mapping):
|
|
404
|
+
for key, item in value.items():
|
|
405
|
+
if key == "recursos" and isinstance(item, Mapping):
|
|
406
|
+
for target in item.values():
|
|
407
|
+
yield from _values(target)
|
|
408
|
+
if key in keys:
|
|
409
|
+
for path in _values(item):
|
|
410
|
+
raw = str(path).partition("=")[2] if key == "mapa_fontes" and "=" in str(path) else str(path)
|
|
411
|
+
if key == "contexto" and not _context_path_like(raw):
|
|
412
|
+
continue
|
|
413
|
+
if raw and not raw.startswith(("http://", "https://")):
|
|
414
|
+
yield raw
|
|
415
|
+
if isinstance(item, (Mapping, list, tuple)):
|
|
416
|
+
yield from _resource_references(item)
|
|
417
|
+
elif isinstance(value, (list, tuple)):
|
|
418
|
+
for item in value:
|
|
419
|
+
yield from _resource_references(item)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _context_path_like(value: str) -> bool:
|
|
423
|
+
path = Path(value).expanduser()
|
|
424
|
+
return bool(path.suffix or "/" in value or "\\" in value)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _snapshot_references(
|
|
428
|
+
source: Path, references, root: Path, excluded: list[Path], seen: frozenset[Path],
|
|
429
|
+
*, document_root: Path | None = None,
|
|
430
|
+
):
|
|
431
|
+
resources = {}
|
|
432
|
+
for reference in references:
|
|
433
|
+
candidate = _path(reference, root)
|
|
434
|
+
resources[str(candidate)] = _snapshot(candidate, root, excluded, seen, document_root=document_root)
|
|
435
|
+
relative_candidate = _path(reference, source.parent)
|
|
436
|
+
if relative_candidate != candidate:
|
|
437
|
+
try:
|
|
438
|
+
relative_candidate.stat()
|
|
439
|
+
except FileNotFoundError:
|
|
440
|
+
pass
|
|
441
|
+
except OSError as exc:
|
|
442
|
+
raise InputValidationError(f"não foi possível inspecionar a referência: {relative_candidate}") from exc
|
|
443
|
+
else:
|
|
444
|
+
resources[str(relative_candidate)] = _snapshot(relative_candidate, root, excluded, seen, document_root=document_root)
|
|
445
|
+
if document_root is not None:
|
|
446
|
+
loader_candidate = _path(reference, document_root)
|
|
447
|
+
if str(loader_candidate) not in resources:
|
|
448
|
+
resources[str(loader_candidate)] = _snapshot(
|
|
449
|
+
loader_candidate, root, excluded, seen, document_root=document_root
|
|
450
|
+
)
|
|
451
|
+
return resources
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _readable_sha256(path: Path) -> str:
|
|
455
|
+
try:
|
|
456
|
+
return sha256_file(path)
|
|
457
|
+
except OSError as exc:
|
|
458
|
+
raise InputValidationError(f"não foi possível ler a entrada: {path}") from exc
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _readable_text(path: Path) -> str:
|
|
462
|
+
try:
|
|
463
|
+
return path.read_text(encoding="utf-8")
|
|
464
|
+
except UnicodeDecodeError:
|
|
465
|
+
try:
|
|
466
|
+
return path.read_text(encoding="latin-1")
|
|
467
|
+
except OSError as exc:
|
|
468
|
+
raise InputValidationError(f"não foi possível ler a entrada: {path}") from exc
|
|
469
|
+
except OSError as exc:
|
|
470
|
+
raise InputValidationError(f"não foi possível ler a entrada: {path}") from exc
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def products_intact(execution: Mapping[str, Any]) -> bool:
|
|
474
|
+
"""Um registro completed não basta quando seus arquivos foram perdidos."""
|
|
475
|
+
payload = execution.get("result_json")
|
|
476
|
+
if isinstance(payload, str):
|
|
477
|
+
payload = json.loads(payload)
|
|
478
|
+
if not isinstance(payload, Mapping):
|
|
479
|
+
return False
|
|
480
|
+
try:
|
|
481
|
+
for product in payload.get("products", ()):
|
|
482
|
+
path = Path(product["path"])
|
|
483
|
+
if not path.is_file() or sha256_file(path) != product["sha256"]:
|
|
484
|
+
return False
|
|
485
|
+
except OSError:
|
|
486
|
+
return False
|
|
487
|
+
return True
|