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/pipeline.py
ADDED
|
@@ -0,0 +1,1745 @@
|
|
|
1
|
+
"""Execução declarativa de pipelines por etapas com retomada por hash.
|
|
2
|
+
|
|
3
|
+
Uma etapa é um objeto com ``operation`` (ou ``id``), ``unit_id`` opcional e
|
|
4
|
+
``params``. As etapas são lidas de ``--plan-file`` (``.json``, ``.yml`` ou
|
|
5
|
+
``.yaml``) ou da chave ``pipeline:`` de ``fiscalizacao.yml`` e executadas em
|
|
6
|
+
ordem, reutilizando o cache semântico de cada operação do catálogo.
|
|
7
|
+
|
|
8
|
+
Referências simples entre etapas usam ``{"$stage": "<unit_id>", "kind": ...}``
|
|
9
|
+
e são resolvidas para o caminho do produto publicado pela etapa anterior, o
|
|
10
|
+
que permite encadear comandos sem repetir caminhos no arquivo do pipeline.
|
|
11
|
+
Quando um insumo obrigatório de uma etapa futura ainda não existe, o motor
|
|
12
|
+
pausa a execução com status ``awaiting_input`` em vez de falhar.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import tempfile
|
|
24
|
+
import uuid
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any, Mapping, Sequence
|
|
28
|
+
|
|
29
|
+
from .assets import AssetEntry, AssetManifest, load_manifest, manifest_product, sanitized_env, validate_manifest
|
|
30
|
+
from .contracts import OperationResult, ProductDraft, canonical_json, sha256_bytes, sha256_file
|
|
31
|
+
from .core import InputValidationError, MissingInputError, OperationContext
|
|
32
|
+
from .adapters.xlsx import require_file
|
|
33
|
+
from .project import read_project
|
|
34
|
+
from .project import yaml_module
|
|
35
|
+
|
|
36
|
+
STAGE_REFERENCE_KEYS = frozenset({"$stage", "kind", "index"})
|
|
37
|
+
DEFAULT_SCRIPT_TIMEOUT_SECONDS = 300
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class ScriptRun:
|
|
42
|
+
"""Resultado transitório do script; o chamador copia e limpa o staging."""
|
|
43
|
+
|
|
44
|
+
products: tuple[ProductDraft, ...]
|
|
45
|
+
staging: Path
|
|
46
|
+
manifest: Any
|
|
47
|
+
|
|
48
|
+
def cleanup(self) -> None:
|
|
49
|
+
shutil.rmtree(self.staging, ignore_errors=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class ScriptOutput:
|
|
54
|
+
"""Declaração de um arquivo produzido por um script externo."""
|
|
55
|
+
|
|
56
|
+
path: str | None
|
|
57
|
+
glob: str | None
|
|
58
|
+
required: bool
|
|
59
|
+
slot_id: str | None
|
|
60
|
+
kind: str
|
|
61
|
+
media_type: str
|
|
62
|
+
caption: str
|
|
63
|
+
scope: str
|
|
64
|
+
auditee: str | None
|
|
65
|
+
metadata: Mapping[str, Any]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class ScriptStep:
|
|
70
|
+
"""Etapa declarativa que executa um script externo no projeto."""
|
|
71
|
+
|
|
72
|
+
unit_id: str
|
|
73
|
+
script: str
|
|
74
|
+
args: tuple[str, ...]
|
|
75
|
+
inputs: Mapping[str, Any]
|
|
76
|
+
deps: tuple[str, ...]
|
|
77
|
+
output_dir: str
|
|
78
|
+
manifest: str | None
|
|
79
|
+
timeout_seconds: int
|
|
80
|
+
outputs: tuple[ScriptOutput, ...] = ()
|
|
81
|
+
output_arg: str | None = None
|
|
82
|
+
cwd: str | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def stage_reference(value: Any) -> Mapping[str, Any] | None:
|
|
86
|
+
"""Reconhece ``{"$stage": ...}`` estrito, rejeitando chaves desconhecidas."""
|
|
87
|
+
if not isinstance(value, Mapping) or "$stage" not in value:
|
|
88
|
+
return None
|
|
89
|
+
unknown = set(value) - STAGE_REFERENCE_KEYS
|
|
90
|
+
producer = value["$stage"]
|
|
91
|
+
if unknown or not isinstance(producer, str) or not producer.strip():
|
|
92
|
+
raise InputValidationError("referência de etapa inválida; use {'$stage': unit_id, 'kind': ...}")
|
|
93
|
+
if "kind" in value and not isinstance(value["kind"], str):
|
|
94
|
+
raise InputValidationError("filtro de produto por kind deve ser texto")
|
|
95
|
+
if "index" in value and (
|
|
96
|
+
isinstance(value["index"], bool) or not isinstance(value["index"], int) or value["index"] < 0
|
|
97
|
+
):
|
|
98
|
+
raise InputValidationError("índice de produto da etapa deve ser inteiro não negativo")
|
|
99
|
+
return value
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _resolve_stage_path(reference: Mapping[str, Any], published: Mapping[str, Sequence[Mapping[str, Any]]]) -> str:
|
|
103
|
+
producer = str(reference["$stage"])
|
|
104
|
+
products = list(published.get(producer) or ())
|
|
105
|
+
if not products:
|
|
106
|
+
raise MissingInputError(f"etapa {producer} ainda não publicou produtos para resolver {'$stage'}")
|
|
107
|
+
kind = reference.get("kind")
|
|
108
|
+
if kind:
|
|
109
|
+
products = [item for item in products if str(item.get("kind") or "") == str(kind)]
|
|
110
|
+
if not products:
|
|
111
|
+
raise MissingInputError(f"etapa {producer} não publicou produto do tipo {kind}")
|
|
112
|
+
index = reference.get("index")
|
|
113
|
+
if index is None and len(products) != 1:
|
|
114
|
+
raise MissingInputError(
|
|
115
|
+
f"referência exige produto único da etapa {producer}; encontrados {len(products)}"
|
|
116
|
+
)
|
|
117
|
+
selected = products[int(index or 0)] if index is not None else products[0]
|
|
118
|
+
path = str(selected.get("path") or "")
|
|
119
|
+
if not path:
|
|
120
|
+
raise MissingInputError(f"produto referenciado da etapa {producer} não informa caminho")
|
|
121
|
+
return path
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def resolve_stage_references(value: Any, published: Mapping[str, Sequence[Mapping[str, Any]]]) -> Any:
|
|
125
|
+
"""Substitui referências ``$stage`` pelos caminhos de produtos já publicados."""
|
|
126
|
+
if isinstance(value, Mapping):
|
|
127
|
+
reference = stage_reference(value)
|
|
128
|
+
if reference is not None:
|
|
129
|
+
return _resolve_stage_path(reference, published)
|
|
130
|
+
return {key: resolve_stage_references(item, published) for key, item in value.items()}
|
|
131
|
+
if isinstance(value, (list, tuple)):
|
|
132
|
+
return [resolve_stage_references(item, published) for item in value]
|
|
133
|
+
return value
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def pending_stage_references(value: Any, published: Mapping[str, Sequence[Mapping[str, Any]]]) -> list[str]:
|
|
137
|
+
"""Lista etapas referenciadas por ``$stage`` que ainda não publicaram produtos."""
|
|
138
|
+
missing: list[str] = []
|
|
139
|
+
if isinstance(value, Mapping):
|
|
140
|
+
reference = stage_reference(value)
|
|
141
|
+
if reference is not None:
|
|
142
|
+
producer = str(reference["$stage"])
|
|
143
|
+
if not published.get(producer):
|
|
144
|
+
missing.append(producer)
|
|
145
|
+
return missing
|
|
146
|
+
for item in value.values():
|
|
147
|
+
missing.extend(pending_stage_references(item, published))
|
|
148
|
+
elif isinstance(value, (list, tuple)):
|
|
149
|
+
for item in value:
|
|
150
|
+
missing.extend(pending_stage_references(item, published))
|
|
151
|
+
return missing
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def load_pipeline_spec(
|
|
155
|
+
context: OperationContext,
|
|
156
|
+
source: Any,
|
|
157
|
+
) -> Mapping[str, Any]:
|
|
158
|
+
"""Lê o pipeline de um arquivo JSON/YAML ou da seção ``pipeline`` do projeto."""
|
|
159
|
+
if source in (None, ""):
|
|
160
|
+
project_cfg = read_project(context.project_root) or {}
|
|
161
|
+
spec = project_cfg.get("pipeline")
|
|
162
|
+
if not spec:
|
|
163
|
+
raise MissingInputError("informe plan_file ou declare a seção pipeline em fiscalizacao.yml")
|
|
164
|
+
payload: Any = {"operations": spec}
|
|
165
|
+
else:
|
|
166
|
+
plan_path = require_file(context, source, "arquivo de pipeline")
|
|
167
|
+
text = plan_path.read_text(encoding="utf-8")
|
|
168
|
+
if plan_path.suffix.casefold() in {".yml", ".yaml"}:
|
|
169
|
+
payload = yaml_module().safe_load(text)
|
|
170
|
+
else:
|
|
171
|
+
payload = json.loads(text)
|
|
172
|
+
if isinstance(payload, list):
|
|
173
|
+
payload = {"operations": payload}
|
|
174
|
+
if not isinstance(payload, Mapping) or not payload.get("operations"):
|
|
175
|
+
raise InputValidationError("pipeline deve declarar uma lista não vazia em operations")
|
|
176
|
+
return payload
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _is_script_step(step: Mapping[str, Any]) -> bool:
|
|
180
|
+
return "script" in step
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _stage_identifier(step: Mapping[str, Any], index: int) -> str:
|
|
184
|
+
if _is_script_step(step):
|
|
185
|
+
script = str(step.get("script") or "").strip()
|
|
186
|
+
if not script:
|
|
187
|
+
raise InputValidationError(f"etapa {index} do pipeline declara script vazio")
|
|
188
|
+
default = f"{index:02d}-script-{Path(script).stem or 'etapa'}"
|
|
189
|
+
return str(step.get("unit_id") or default)
|
|
190
|
+
operation_id = str(step.get("operation") or step.get("id") or "").strip()
|
|
191
|
+
if not operation_id:
|
|
192
|
+
raise InputValidationError(f"etapa {index} do pipeline não declara operation")
|
|
193
|
+
return str(step.get("unit_id") or f"{index:02d}-{operation_id}")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _filter_stages(
|
|
197
|
+
operations: Sequence[Any],
|
|
198
|
+
*,
|
|
199
|
+
until_stage: Any,
|
|
200
|
+
from_stage: Any,
|
|
201
|
+
) -> list[tuple[str, Mapping[str, Any]]]:
|
|
202
|
+
stages: list[tuple[str, Mapping[str, Any]]] = []
|
|
203
|
+
for index, step in enumerate(operations, start=1):
|
|
204
|
+
if not isinstance(step, Mapping):
|
|
205
|
+
raise InputValidationError(f"etapa {index} do pipeline deve ser um objeto")
|
|
206
|
+
stages.append((_stage_identifier(step, index), step))
|
|
207
|
+
identifiers = [unit_id for unit_id, _ in stages]
|
|
208
|
+
if len(set(identifiers)) != len(identifiers):
|
|
209
|
+
raise InputValidationError("unit_id repetido no pipeline")
|
|
210
|
+
if from_stage:
|
|
211
|
+
if str(from_stage) not in identifiers:
|
|
212
|
+
raise InputValidationError(f"etapa from_stage não encontrada no pipeline: {from_stage}")
|
|
213
|
+
stages = stages[identifiers.index(str(from_stage)) :]
|
|
214
|
+
if until_stage:
|
|
215
|
+
selected = [unit_id for unit_id, _ in stages]
|
|
216
|
+
if str(until_stage) not in selected:
|
|
217
|
+
raise InputValidationError(f"etapa until_stage não encontrada no pipeline: {until_stage}")
|
|
218
|
+
stages = stages[: selected.index(str(until_stage)) + 1]
|
|
219
|
+
return stages
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _stage_references(value: Any) -> list[str]:
|
|
223
|
+
"""Lista as referências declaradas, mantendo erro estrito para sintaxe inválida."""
|
|
224
|
+
if isinstance(value, Mapping):
|
|
225
|
+
reference = stage_reference(value)
|
|
226
|
+
if reference is not None:
|
|
227
|
+
return [str(reference["$stage"])]
|
|
228
|
+
return [unit_id for item in value.values() for unit_id in _stage_references(item)]
|
|
229
|
+
if isinstance(value, (list, tuple)):
|
|
230
|
+
return [unit_id for item in value for unit_id in _stage_references(item)]
|
|
231
|
+
return []
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _replace_stage_references(value: Any, replacement: str) -> Any:
|
|
235
|
+
"""Substitui referências por caminho sentinela durante validação do contrato."""
|
|
236
|
+
if isinstance(value, Mapping):
|
|
237
|
+
if stage_reference(value) is not None:
|
|
238
|
+
return replacement
|
|
239
|
+
return {key: _replace_stage_references(item, replacement) for key, item in value.items()}
|
|
240
|
+
if isinstance(value, (list, tuple)):
|
|
241
|
+
return [_replace_stage_references(item, replacement) for item in value]
|
|
242
|
+
return value
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _operation_id(step: Mapping[str, Any]) -> str | None:
|
|
246
|
+
if _is_script_step(step):
|
|
247
|
+
return None
|
|
248
|
+
operation_id = str(step.get("operation") or step.get("id") or "").strip()
|
|
249
|
+
if not operation_id:
|
|
250
|
+
raise InputValidationError("etapa do pipeline não declara operation")
|
|
251
|
+
return operation_id
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _step_params(step: Mapping[str, Any], default_scenario: Any) -> dict[str, Any]:
|
|
255
|
+
operation_id = _operation_id(step)
|
|
256
|
+
if operation_id is None:
|
|
257
|
+
raise InputValidationError("etapa script não aceita params; use args/inputs")
|
|
258
|
+
raw = step.get("params", {})
|
|
259
|
+
if raw is None:
|
|
260
|
+
raw = {}
|
|
261
|
+
if not isinstance(raw, Mapping):
|
|
262
|
+
raise InputValidationError(f"params da etapa {operation_id} deve ser um objeto")
|
|
263
|
+
resolved = dict(raw)
|
|
264
|
+
if default_scenario and "scenario" not in resolved:
|
|
265
|
+
resolved["scenario"] = default_scenario
|
|
266
|
+
return resolved
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
OUTPUT_SCOPE_VALUES = frozenset({"consolidated", "auditee"})
|
|
270
|
+
OUTPUT_SLOT_TOKENS = frozenset({"stem", "name", "relpath"})
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _relative_project_path(
|
|
274
|
+
raw: str,
|
|
275
|
+
*,
|
|
276
|
+
project_root: Path,
|
|
277
|
+
label: str,
|
|
278
|
+
unit_id: str,
|
|
279
|
+
must_exist: bool,
|
|
280
|
+
directory: bool = False,
|
|
281
|
+
) -> Path:
|
|
282
|
+
path = Path(raw)
|
|
283
|
+
if path.is_absolute() or ".." in path.parts:
|
|
284
|
+
raise InputValidationError(f"{label} da etapa {unit_id} deve ser relativo ao projeto")
|
|
285
|
+
candidate = project_root / path
|
|
286
|
+
if candidate.is_symlink():
|
|
287
|
+
raise InputValidationError(f"{label} da etapa {unit_id} não pode ser symlink")
|
|
288
|
+
resolved = candidate.resolve()
|
|
289
|
+
root = project_root.resolve()
|
|
290
|
+
if resolved != root and root not in resolved.parents:
|
|
291
|
+
raise InputValidationError(f"{label} da etapa {unit_id} escapa do projeto")
|
|
292
|
+
if must_exist:
|
|
293
|
+
if directory and not resolved.is_dir():
|
|
294
|
+
raise InputValidationError(f"{label} da etapa {unit_id} não é diretório: {raw}")
|
|
295
|
+
if not directory and not resolved.is_file():
|
|
296
|
+
raise InputValidationError(f"{label} da etapa {unit_id} não existe: {raw}")
|
|
297
|
+
return resolved
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _slot_template(value: str, *, label: str, unit_id: str) -> str:
|
|
301
|
+
if not value.strip():
|
|
302
|
+
raise InputValidationError(f"{label} da etapa {unit_id} não pode ser vazio")
|
|
303
|
+
for match in re.finditer(r"\{([^{}]+)\}", value):
|
|
304
|
+
token = match.group(1)
|
|
305
|
+
if token not in OUTPUT_SLOT_TOKENS:
|
|
306
|
+
raise InputValidationError(
|
|
307
|
+
f"{label} da etapa {unit_id} usa placeholder desconhecido: {{{token}}}"
|
|
308
|
+
)
|
|
309
|
+
return value
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _parse_output_spec(raw: Any, *, index: int, unit_id: str) -> ScriptOutput:
|
|
313
|
+
if not isinstance(raw, Mapping):
|
|
314
|
+
raise InputValidationError(f"outputs[{index}] da etapa {unit_id} deve ser um objeto")
|
|
315
|
+
allowed = {"path", "glob", "required", "slot_id", "kind", "media_type", "caption", "scope", "auditee", "metadata"}
|
|
316
|
+
unknown = sorted(set(raw) - allowed)
|
|
317
|
+
if unknown:
|
|
318
|
+
raise InputValidationError(
|
|
319
|
+
f"outputs[{index}] da etapa {unit_id} tem chaves desconhecidas: {', '.join(unknown)}"
|
|
320
|
+
)
|
|
321
|
+
has_path = raw.get("path") not in (None, "")
|
|
322
|
+
has_glob = raw.get("glob") not in (None, "")
|
|
323
|
+
if has_path == has_glob:
|
|
324
|
+
raise InputValidationError(
|
|
325
|
+
f"outputs[{index}] da etapa {unit_id} exige path ou glob, nunca ambos"
|
|
326
|
+
)
|
|
327
|
+
path = str(raw["path"]) if has_path else None
|
|
328
|
+
glob = str(raw["glob"]) if has_glob else None
|
|
329
|
+
for label, value in (("path", path), ("glob", glob)):
|
|
330
|
+
if value is None:
|
|
331
|
+
continue
|
|
332
|
+
parsed = Path(value)
|
|
333
|
+
if parsed.is_absolute() or ".." in parsed.parts:
|
|
334
|
+
raise InputValidationError(
|
|
335
|
+
f"{label} de outputs[{index}] da etapa {unit_id} deve ser relativo ao run directory"
|
|
336
|
+
)
|
|
337
|
+
required = raw.get("required", True)
|
|
338
|
+
if not isinstance(required, bool):
|
|
339
|
+
raise InputValidationError(f"required de outputs[{index}] da etapa {unit_id} deve ser bool")
|
|
340
|
+
slot_id = raw.get("slot_id")
|
|
341
|
+
if slot_id is not None:
|
|
342
|
+
if not isinstance(slot_id, str):
|
|
343
|
+
raise InputValidationError(f"slot_id de outputs[{index}] da etapa {unit_id} deve ser texto")
|
|
344
|
+
slot_id = _slot_template(slot_id, label=f"slot_id de outputs[{index}]", unit_id=unit_id)
|
|
345
|
+
kind = str(raw.get("kind") or "").strip()
|
|
346
|
+
if not kind.startswith("asset:") or kind == "asset:":
|
|
347
|
+
raise InputValidationError(f"kind de outputs[{index}] da etapa {unit_id} deve começar com asset:")
|
|
348
|
+
media_type = str(raw.get("media_type") or "").strip()
|
|
349
|
+
if not media_type:
|
|
350
|
+
raise InputValidationError(f"media_type de outputs[{index}] da etapa {unit_id} é obrigatório")
|
|
351
|
+
caption = str(raw.get("caption") or "")
|
|
352
|
+
scope = str(raw.get("scope") or "consolidated")
|
|
353
|
+
if scope not in OUTPUT_SCOPE_VALUES:
|
|
354
|
+
raise InputValidationError(f"scope de outputs[{index}] da etapa {unit_id} inválido: {scope}")
|
|
355
|
+
auditee_raw = raw.get("auditee")
|
|
356
|
+
auditee = str(auditee_raw) if auditee_raw not in (None, "") else None
|
|
357
|
+
if scope == "auditee" and not auditee:
|
|
358
|
+
raise InputValidationError(f"scope=auditee exige auditee em outputs[{index}] da etapa {unit_id}")
|
|
359
|
+
if scope == "consolidated" and auditee is not None:
|
|
360
|
+
raise InputValidationError(f"auditee só é permitido com scope=auditee em outputs[{index}] da etapa {unit_id}")
|
|
361
|
+
metadata = raw.get("metadata") or {}
|
|
362
|
+
if not isinstance(metadata, Mapping):
|
|
363
|
+
raise InputValidationError(f"metadata de outputs[{index}] da etapa {unit_id} deve ser um objeto")
|
|
364
|
+
return ScriptOutput(
|
|
365
|
+
path=path,
|
|
366
|
+
glob=glob,
|
|
367
|
+
required=required,
|
|
368
|
+
slot_id=slot_id,
|
|
369
|
+
kind=kind,
|
|
370
|
+
media_type=media_type,
|
|
371
|
+
caption=caption,
|
|
372
|
+
scope=scope,
|
|
373
|
+
auditee=auditee,
|
|
374
|
+
metadata=dict(metadata),
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
def _parse_script_step(
|
|
378
|
+
step: Mapping[str, Any],
|
|
379
|
+
*,
|
|
380
|
+
project_root: Path,
|
|
381
|
+
unit_id: str,
|
|
382
|
+
) -> ScriptStep:
|
|
383
|
+
"""Valida e normaliza uma etapa script sem executar o processo."""
|
|
384
|
+
if "operation" in step or "id" in step:
|
|
385
|
+
raise InputValidationError(f"etapa {unit_id} não pode declarar operation e script juntos")
|
|
386
|
+
raw_script = str(step.get("script") or "").strip()
|
|
387
|
+
if not raw_script:
|
|
388
|
+
raise InputValidationError(f"etapa {unit_id} declara script vazio")
|
|
389
|
+
script_relative = Path(raw_script)
|
|
390
|
+
if script_relative.is_absolute() or ".." in script_relative.parts:
|
|
391
|
+
raise InputValidationError(f"script da etapa {unit_id} deve ser relativo ao projeto")
|
|
392
|
+
candidate = project_root / script_relative
|
|
393
|
+
if candidate.is_symlink():
|
|
394
|
+
raise InputValidationError(f"script da etapa {unit_id} não pode ser symlink")
|
|
395
|
+
script_path = candidate.resolve()
|
|
396
|
+
if project_root.resolve() not in script_path.parents:
|
|
397
|
+
raise InputValidationError(f"script da etapa {unit_id} escapa do projeto")
|
|
398
|
+
if not script_path.is_file():
|
|
399
|
+
raise InputValidationError(f"script da etapa {unit_id} não existe: {raw_script}")
|
|
400
|
+
|
|
401
|
+
raw_args = step.get("args", ())
|
|
402
|
+
if raw_args is None:
|
|
403
|
+
raw_args = ()
|
|
404
|
+
if not isinstance(raw_args, (list, tuple)) or not all(isinstance(item, str) for item in raw_args):
|
|
405
|
+
raise InputValidationError(f"args da etapa {unit_id} deve ser uma lista de textos")
|
|
406
|
+
|
|
407
|
+
raw_inputs = step.get("inputs", {})
|
|
408
|
+
if raw_inputs is None:
|
|
409
|
+
raw_inputs = {}
|
|
410
|
+
if not isinstance(raw_inputs, Mapping):
|
|
411
|
+
raise InputValidationError(f"inputs da etapa {unit_id} deve ser um objeto")
|
|
412
|
+
inputs: dict[str, Any] = {}
|
|
413
|
+
for name, value in raw_inputs.items():
|
|
414
|
+
if not isinstance(name, str) or not name.strip():
|
|
415
|
+
raise InputValidationError(f"inputs da etapa {unit_id} tem nome inválido")
|
|
416
|
+
if stage_reference(value) is not None:
|
|
417
|
+
inputs[name] = value
|
|
418
|
+
continue
|
|
419
|
+
if not isinstance(value, (str, Path)) or not str(value).strip():
|
|
420
|
+
raise InputValidationError(f"input {name!r} da etapa {unit_id} deve ser caminho ou referência de etapa")
|
|
421
|
+
raw_path = Path(str(value))
|
|
422
|
+
if raw_path.is_absolute() or ".." in raw_path.parts:
|
|
423
|
+
raise InputValidationError(f"input {name!r} da etapa {unit_id} deve ser relativo ao projeto")
|
|
424
|
+
candidate_input = project_root / raw_path
|
|
425
|
+
if candidate_input.is_symlink():
|
|
426
|
+
raise InputValidationError(f"input {name!r} da etapa {unit_id} não pode ser symlink")
|
|
427
|
+
resolved_input = candidate_input.resolve()
|
|
428
|
+
root_resolved = project_root.resolve()
|
|
429
|
+
if resolved_input != root_resolved and root_resolved not in resolved_input.parents:
|
|
430
|
+
raise InputValidationError(f"input {name!r} da etapa {unit_id} escapa do projeto")
|
|
431
|
+
if not resolved_input.is_file():
|
|
432
|
+
raise InputValidationError(f"input {name!r} da etapa {unit_id} não existe: {value}")
|
|
433
|
+
inputs[name] = str(value)
|
|
434
|
+
|
|
435
|
+
raw_deps = step.get("deps", ())
|
|
436
|
+
if raw_deps is None:
|
|
437
|
+
raw_deps = ()
|
|
438
|
+
if not isinstance(raw_deps, (list, tuple)) or not all(isinstance(item, str) for item in raw_deps):
|
|
439
|
+
raise InputValidationError(f"deps da etapa {unit_id} deve ser uma lista de textos")
|
|
440
|
+
deps: list[str] = []
|
|
441
|
+
for raw_dep in raw_deps:
|
|
442
|
+
dep_path = Path(raw_dep)
|
|
443
|
+
if dep_path.is_absolute() or ".." in dep_path.parts:
|
|
444
|
+
raise InputValidationError(f"dep {raw_dep!r} da etapa {unit_id} deve ser relativo ao projeto")
|
|
445
|
+
candidate_dep = project_root / dep_path
|
|
446
|
+
if candidate_dep.is_symlink():
|
|
447
|
+
raise InputValidationError(f"dep {raw_dep!r} da etapa {unit_id} não pode ser symlink")
|
|
448
|
+
resolved_dep = candidate_dep.resolve()
|
|
449
|
+
root_resolved = project_root.resolve()
|
|
450
|
+
if resolved_dep != root_resolved and root_resolved not in resolved_dep.parents:
|
|
451
|
+
raise InputValidationError(f"dep {raw_dep!r} da etapa {unit_id} escapa do projeto")
|
|
452
|
+
if not resolved_dep.is_file():
|
|
453
|
+
raise InputValidationError(f"dep {raw_dep!r} da etapa {unit_id} não existe")
|
|
454
|
+
deps.append(raw_dep)
|
|
455
|
+
|
|
456
|
+
raw_output_dir = str(step.get("output_dir") or "").strip()
|
|
457
|
+
if not raw_output_dir:
|
|
458
|
+
raise InputValidationError(f"etapa {unit_id} exige output_dir")
|
|
459
|
+
output_root = _relative_project_path(
|
|
460
|
+
raw_output_dir,
|
|
461
|
+
project_root=project_root,
|
|
462
|
+
label="output_dir",
|
|
463
|
+
unit_id=unit_id,
|
|
464
|
+
must_exist=False,
|
|
465
|
+
)
|
|
466
|
+
if output_root.exists() and not output_root.is_dir():
|
|
467
|
+
raise InputValidationError(f"output_dir da etapa {unit_id} não é diretório: {raw_output_dir}")
|
|
468
|
+
|
|
469
|
+
raw_outputs = step.get("outputs")
|
|
470
|
+
outputs: tuple[ScriptOutput, ...] = ()
|
|
471
|
+
output_arg_raw = step.get("output_arg")
|
|
472
|
+
cwd_raw = step.get("cwd")
|
|
473
|
+
if raw_outputs is None:
|
|
474
|
+
if output_arg_raw not in (None, ""):
|
|
475
|
+
raise InputValidationError(f"output_arg só é permitido com outputs na etapa {unit_id}")
|
|
476
|
+
raw_manifest = str(step.get("manifest") or "").strip()
|
|
477
|
+
if not raw_manifest:
|
|
478
|
+
raise InputValidationError(f"etapa {unit_id} exige manifest no modo nativo")
|
|
479
|
+
manifest_path = (project_root / raw_manifest).resolve()
|
|
480
|
+
if manifest_path.parent != output_root:
|
|
481
|
+
raise InputValidationError(f"manifest da etapa {unit_id} deve ficar diretamente em output_dir")
|
|
482
|
+
manifest_value: str | None = raw_manifest
|
|
483
|
+
else:
|
|
484
|
+
if not isinstance(raw_outputs, (list, tuple)) or not raw_outputs:
|
|
485
|
+
raise InputValidationError(f"outputs da etapa {unit_id} deve ser uma lista não vazia")
|
|
486
|
+
outputs = tuple(
|
|
487
|
+
_parse_output_spec(item, index=index, unit_id=unit_id)
|
|
488
|
+
for index, item in enumerate(raw_outputs)
|
|
489
|
+
)
|
|
490
|
+
raw_manifest = str(step.get("manifest") or "manifest.json").strip()
|
|
491
|
+
manifest_relative = Path(raw_manifest)
|
|
492
|
+
if (
|
|
493
|
+
not raw_manifest
|
|
494
|
+
or manifest_relative.is_absolute()
|
|
495
|
+
or ".." in manifest_relative.parts
|
|
496
|
+
or len(manifest_relative.parts) != 1
|
|
497
|
+
):
|
|
498
|
+
raise InputValidationError(
|
|
499
|
+
f"manifest da etapa {unit_id} deve ser um nome direto dentro do run directory"
|
|
500
|
+
)
|
|
501
|
+
manifest_path = output_root / manifest_relative
|
|
502
|
+
manifest_value = raw_manifest
|
|
503
|
+
output_arg = None
|
|
504
|
+
if output_arg_raw not in (None, ""):
|
|
505
|
+
if not isinstance(output_arg_raw, str) or not output_arg_raw.strip():
|
|
506
|
+
raise InputValidationError(f"output_arg da etapa {unit_id} deve ser texto não vazio")
|
|
507
|
+
output_arg = output_arg_raw
|
|
508
|
+
if output_arg in raw_args:
|
|
509
|
+
raise InputValidationError(
|
|
510
|
+
f"output_arg {output_arg!r} não pode aparecer também em args na etapa {unit_id}"
|
|
511
|
+
)
|
|
512
|
+
if any("{output_dir}" in item for item in raw_args):
|
|
513
|
+
raise InputValidationError(
|
|
514
|
+
f"etapa {unit_id} não pode usar output_arg e {{output_dir}} em args ao mesmo tempo"
|
|
515
|
+
)
|
|
516
|
+
for spec in outputs:
|
|
517
|
+
if spec.path is not None and spec.path == manifest_value:
|
|
518
|
+
raise InputValidationError(
|
|
519
|
+
f"manifest da etapa {unit_id} não pode ser declarado como output"
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
if cwd_raw not in (None, ""):
|
|
523
|
+
if not isinstance(cwd_raw, str):
|
|
524
|
+
raise InputValidationError(f"cwd da etapa {unit_id} deve ser texto")
|
|
525
|
+
cwd_value: str | None = str(cwd_raw)
|
|
526
|
+
_relative_project_path(
|
|
527
|
+
cwd_value,
|
|
528
|
+
project_root=project_root,
|
|
529
|
+
label="cwd",
|
|
530
|
+
unit_id=unit_id,
|
|
531
|
+
must_exist=True,
|
|
532
|
+
directory=True,
|
|
533
|
+
)
|
|
534
|
+
else:
|
|
535
|
+
cwd_value = None
|
|
536
|
+
|
|
537
|
+
raw_timeout = step.get("timeout_seconds", DEFAULT_SCRIPT_TIMEOUT_SECONDS)
|
|
538
|
+
if isinstance(raw_timeout, bool) or not isinstance(raw_timeout, int) or raw_timeout <= 0:
|
|
539
|
+
raise InputValidationError(f"timeout_seconds da etapa {unit_id} deve ser inteiro positivo")
|
|
540
|
+
|
|
541
|
+
return ScriptStep(
|
|
542
|
+
unit_id=unit_id,
|
|
543
|
+
script=raw_script,
|
|
544
|
+
args=tuple(raw_args),
|
|
545
|
+
inputs=inputs,
|
|
546
|
+
deps=tuple(deps),
|
|
547
|
+
output_dir=raw_output_dir,
|
|
548
|
+
manifest=manifest_value,
|
|
549
|
+
timeout_seconds=raw_timeout,
|
|
550
|
+
outputs=outputs,
|
|
551
|
+
output_arg=output_arg if raw_outputs is not None else None,
|
|
552
|
+
cwd=cwd_value,
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
_ARG_PLACEHOLDER = re.compile(r"\{([^{}]+)\}")
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def _render_script_args(
|
|
560
|
+
args: Sequence[str],
|
|
561
|
+
*,
|
|
562
|
+
input_paths: Mapping[str, str],
|
|
563
|
+
run_dir: Path,
|
|
564
|
+
context: OperationContext,
|
|
565
|
+
unit_id: str,
|
|
566
|
+
) -> tuple[str, ...]:
|
|
567
|
+
"""Renderiza placeholders declarativos sem shell e sem interpolação livre."""
|
|
568
|
+
def replace(match: re.Match[str]) -> str:
|
|
569
|
+
token = match.group(1)
|
|
570
|
+
if token.startswith("input:"):
|
|
571
|
+
name = token[6:]
|
|
572
|
+
if not name or name not in input_paths:
|
|
573
|
+
raise InputValidationError(
|
|
574
|
+
f"placeholder {token!r} da etapa {unit_id} referencia input ausente"
|
|
575
|
+
)
|
|
576
|
+
return input_paths[name]
|
|
577
|
+
if token == "output_dir":
|
|
578
|
+
return str(run_dir)
|
|
579
|
+
if token == "project_root":
|
|
580
|
+
return str(context.project_root)
|
|
581
|
+
if token == "scenario":
|
|
582
|
+
return str(context.params.get("scenario") or "base")
|
|
583
|
+
if token == "unit_id":
|
|
584
|
+
return unit_id
|
|
585
|
+
raise InputValidationError(
|
|
586
|
+
f"placeholder desconhecido em args da etapa {unit_id}: {{{token}}}"
|
|
587
|
+
)
|
|
588
|
+
|
|
589
|
+
rendered: list[str] = []
|
|
590
|
+
for raw in args:
|
|
591
|
+
value = str(raw).replace("{{", "\x00ARGOS_OPEN\x00").replace("}}", "\x00ARGOS_CLOSE\x00")
|
|
592
|
+
value = _ARG_PLACEHOLDER.sub(replace, value)
|
|
593
|
+
rendered.append(
|
|
594
|
+
value.replace("\x00ARGOS_OPEN\x00", "{").replace("\x00ARGOS_CLOSE\x00", "}")
|
|
595
|
+
)
|
|
596
|
+
return tuple(rendered)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _safe_run_label(unit_id: str) -> str:
|
|
600
|
+
value = re.sub(r"[^A-Za-z0-9._-]+", "-", unit_id).strip("-._")
|
|
601
|
+
return value or "script"
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _outputs_cache_path(context: OperationContext, step: ScriptStep) -> Path | None:
|
|
605
|
+
base = context.path(step.output_dir)
|
|
606
|
+
if not base.is_dir():
|
|
607
|
+
return None
|
|
608
|
+
key = sha256_bytes(step.unit_id.encode("utf-8"))[:12]
|
|
609
|
+
return base / f".argos-script-cache-{key}.json"
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _output_fingerprint(step: ScriptStep) -> list[dict[str, Any]]:
|
|
613
|
+
return [
|
|
614
|
+
{
|
|
615
|
+
"path": spec.path,
|
|
616
|
+
"glob": spec.glob,
|
|
617
|
+
"required": spec.required,
|
|
618
|
+
"slot_id": spec.slot_id,
|
|
619
|
+
"kind": spec.kind,
|
|
620
|
+
"media_type": spec.media_type,
|
|
621
|
+
"caption": spec.caption,
|
|
622
|
+
"scope": spec.scope,
|
|
623
|
+
"auditee": spec.auditee,
|
|
624
|
+
"metadata": dict(spec.metadata),
|
|
625
|
+
}
|
|
626
|
+
for spec in step.outputs
|
|
627
|
+
]
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _render_output_template(value: str, *, stem: str, name: str, relpath: str, unit_id: str) -> str:
|
|
631
|
+
def replace(match: re.Match[str]) -> str:
|
|
632
|
+
token = match.group(1)
|
|
633
|
+
if token == "stem":
|
|
634
|
+
return stem
|
|
635
|
+
if token == "name":
|
|
636
|
+
return name
|
|
637
|
+
if token == "relpath":
|
|
638
|
+
return relpath
|
|
639
|
+
raise InputValidationError(
|
|
640
|
+
f"placeholder desconhecido em output da etapa {unit_id}: {{{token}}}"
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
return _ARG_PLACEHOLDER.sub(replace, value)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def _slug_slot(value: str) -> str:
|
|
647
|
+
slug = re.sub(r"[^a-z0-9_-]+", "-", value.casefold()).strip("-_")
|
|
648
|
+
if not slug:
|
|
649
|
+
raise InputValidationError("slot_id calculado ficou vazio")
|
|
650
|
+
return slug
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _collect_output_manifest(
|
|
654
|
+
context: OperationContext,
|
|
655
|
+
step: ScriptStep,
|
|
656
|
+
run_dir: Path,
|
|
657
|
+
) -> tuple[AssetManifest, Path, list[str]]:
|
|
658
|
+
manifest_name = step.manifest or "manifest.json"
|
|
659
|
+
manifest_path = run_dir / manifest_name
|
|
660
|
+
warnings: list[str] = []
|
|
661
|
+
entries: list[AssetEntry] = []
|
|
662
|
+
seen_paths: set[Path] = set()
|
|
663
|
+
seen_slots: set[str] = set()
|
|
664
|
+
|
|
665
|
+
def add_entry(spec: Any, matched: Path) -> None:
|
|
666
|
+
if matched.is_symlink() or not matched.is_file():
|
|
667
|
+
raise InputValidationError(f"output {matched} da etapa {step.unit_id} não é arquivo regular")
|
|
668
|
+
resolved = matched.resolve()
|
|
669
|
+
if run_dir not in resolved.parents:
|
|
670
|
+
raise InputValidationError(f"output {matched} da etapa {step.unit_id} escapa do run directory")
|
|
671
|
+
if resolved == manifest_path.resolve():
|
|
672
|
+
raise InputValidationError(f"manifest da etapa {step.unit_id} não pode ser output")
|
|
673
|
+
if resolved in seen_paths:
|
|
674
|
+
raise InputValidationError(f"output repetido da etapa {step.unit_id}: {matched}")
|
|
675
|
+
seen_paths.add(resolved)
|
|
676
|
+
relpath = resolved.relative_to(run_dir).as_posix()
|
|
677
|
+
stem = resolved.stem
|
|
678
|
+
name = resolved.name
|
|
679
|
+
slot_source = spec.slot_id or "{stem}"
|
|
680
|
+
slot = _slug_slot(
|
|
681
|
+
_render_output_template(
|
|
682
|
+
slot_source,
|
|
683
|
+
stem=stem,
|
|
684
|
+
name=name,
|
|
685
|
+
relpath=relpath,
|
|
686
|
+
unit_id=step.unit_id,
|
|
687
|
+
)
|
|
688
|
+
)
|
|
689
|
+
if slot in seen_slots:
|
|
690
|
+
raise InputValidationError(f"slot_id repetido da etapa {step.unit_id}: {slot}")
|
|
691
|
+
seen_slots.add(slot)
|
|
692
|
+
auditee = None
|
|
693
|
+
if spec.auditee is not None:
|
|
694
|
+
auditee = _render_output_template(
|
|
695
|
+
spec.auditee,
|
|
696
|
+
stem=stem,
|
|
697
|
+
name=name,
|
|
698
|
+
relpath=relpath,
|
|
699
|
+
unit_id=step.unit_id,
|
|
700
|
+
)
|
|
701
|
+
if not auditee.strip():
|
|
702
|
+
raise InputValidationError(f"auditee vazio em output {relpath} da etapa {step.unit_id}")
|
|
703
|
+
entries.append(
|
|
704
|
+
AssetEntry(
|
|
705
|
+
slot_id=slot,
|
|
706
|
+
kind=spec.kind,
|
|
707
|
+
path=relpath,
|
|
708
|
+
media_type=spec.media_type,
|
|
709
|
+
sha256=sha256_file(resolved),
|
|
710
|
+
caption=spec.caption,
|
|
711
|
+
scope=spec.scope,
|
|
712
|
+
auditee=auditee,
|
|
713
|
+
metadata=dict(spec.metadata),
|
|
714
|
+
)
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
for spec in step.outputs:
|
|
718
|
+
if spec.path is not None:
|
|
719
|
+
matched = run_dir / spec.path
|
|
720
|
+
if not matched.is_file() or matched.is_symlink():
|
|
721
|
+
if spec.required:
|
|
722
|
+
raise InputValidationError(
|
|
723
|
+
f"output obrigatório ausente da etapa {step.unit_id}: {spec.path}"
|
|
724
|
+
)
|
|
725
|
+
warnings.append(
|
|
726
|
+
f"output opcional ausente na etapa {step.unit_id}: {spec.path}"
|
|
727
|
+
)
|
|
728
|
+
continue
|
|
729
|
+
add_entry(spec, matched)
|
|
730
|
+
continue
|
|
731
|
+
pattern = spec.glob or ""
|
|
732
|
+
matches = sorted(
|
|
733
|
+
(
|
|
734
|
+
item for item in run_dir.glob(pattern)
|
|
735
|
+
if item.is_file()
|
|
736
|
+
and not item.is_symlink()
|
|
737
|
+
and not item.name.startswith(".argos-")
|
|
738
|
+
),
|
|
739
|
+
key=lambda item: item.relative_to(run_dir).as_posix(),
|
|
740
|
+
)
|
|
741
|
+
if not matches:
|
|
742
|
+
if spec.required:
|
|
743
|
+
raise InputValidationError(
|
|
744
|
+
f"glob obrigatório sem arquivos na etapa {step.unit_id}: {pattern}"
|
|
745
|
+
)
|
|
746
|
+
warnings.append(f"glob opcional sem arquivos na etapa {step.unit_id}: {pattern}")
|
|
747
|
+
continue
|
|
748
|
+
for matched in matches:
|
|
749
|
+
add_entry(spec, matched)
|
|
750
|
+
|
|
751
|
+
if not entries:
|
|
752
|
+
raise InputValidationError(f"nenhum output declarado foi produzido pela etapa {step.unit_id}")
|
|
753
|
+
entries.sort(key=lambda item: item.slot_id)
|
|
754
|
+
manifest = AssetManifest(schema_version="argos.asset-manifest/v1", assets=tuple(entries))
|
|
755
|
+
temporary = manifest_path.with_name(f".{manifest_path.name}.{uuid.uuid4().hex}.tmp")
|
|
756
|
+
try:
|
|
757
|
+
temporary.write_text(
|
|
758
|
+
canonical_json(manifest.as_dict()) + "\n",
|
|
759
|
+
encoding="utf-8",
|
|
760
|
+
)
|
|
761
|
+
os.replace(temporary, manifest_path)
|
|
762
|
+
finally:
|
|
763
|
+
temporary.unlink(missing_ok=True)
|
|
764
|
+
validate_manifest(manifest, output_root=run_dir)
|
|
765
|
+
return manifest, manifest_path, warnings
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def _allocate_run_dir(context: OperationContext, step: ScriptStep, fingerprint: str) -> Path:
|
|
769
|
+
base = context.path(step.output_dir)
|
|
770
|
+
if base.exists() and not base.is_dir():
|
|
771
|
+
raise InputValidationError(f"output_dir da etapa {step.unit_id} não é diretório: {base}")
|
|
772
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
773
|
+
label = _safe_run_label(step.unit_id)
|
|
774
|
+
for _ in range(20):
|
|
775
|
+
suffix = "" if _ == 0 else f"-{uuid.uuid4().hex[:8]}"
|
|
776
|
+
candidate = base / f"{label}-{fingerprint[:12]}{suffix}"
|
|
777
|
+
try:
|
|
778
|
+
candidate.mkdir(parents=True, exist_ok=False)
|
|
779
|
+
return candidate
|
|
780
|
+
except FileExistsError:
|
|
781
|
+
continue
|
|
782
|
+
raise InputValidationError(f"não foi possível reservar run directory para a etapa {step.unit_id}")
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def _outputs_cache_hit(
|
|
786
|
+
context: OperationContext,
|
|
787
|
+
step: ScriptStep,
|
|
788
|
+
fingerprint: str,
|
|
789
|
+
) -> tuple[list[dict[str, Any]], tuple[ProductDraft, ...], dict[str, Any]] | None:
|
|
790
|
+
cache_path = _outputs_cache_path(context, step)
|
|
791
|
+
if cache_path is None or cache_path.is_symlink() or not cache_path.is_file():
|
|
792
|
+
return None
|
|
793
|
+
try:
|
|
794
|
+
cache = json.loads(cache_path.read_text(encoding="utf-8"))
|
|
795
|
+
except (OSError, UnicodeError, json.JSONDecodeError):
|
|
796
|
+
return None
|
|
797
|
+
if not isinstance(cache, Mapping) or cache.get("schema_version") != 1:
|
|
798
|
+
return None
|
|
799
|
+
if str(cache.get("fingerprint") or "") != fingerprint:
|
|
800
|
+
return None
|
|
801
|
+
base = context.path(step.output_dir)
|
|
802
|
+
run_dir = Path(str(cache.get("run_dir") or "")).resolve()
|
|
803
|
+
if run_dir == base or base not in run_dir.parents:
|
|
804
|
+
return None
|
|
805
|
+
raw_products = cache.get("products")
|
|
806
|
+
if not isinstance(raw_products, list) or not raw_products:
|
|
807
|
+
return None
|
|
808
|
+
products: list[ProductDraft] = []
|
|
809
|
+
stage_products: list[dict[str, Any]] = []
|
|
810
|
+
for item in raw_products:
|
|
811
|
+
if not isinstance(item, Mapping):
|
|
812
|
+
return None
|
|
813
|
+
path = Path(str(item.get("path") or ""))
|
|
814
|
+
kind = str(item.get("kind") or "")
|
|
815
|
+
digest = str(item.get("sha256") or "")
|
|
816
|
+
resolved = path.resolve()
|
|
817
|
+
if resolved != run_dir and run_dir not in resolved.parents:
|
|
818
|
+
return None
|
|
819
|
+
if not path.is_file() or path.is_symlink() or sha256_file(path) != digest:
|
|
820
|
+
return None
|
|
821
|
+
if not kind:
|
|
822
|
+
return None
|
|
823
|
+
metadata = dict(item.get("metadata") or {})
|
|
824
|
+
products.append(
|
|
825
|
+
ProductDraft(
|
|
826
|
+
kind=kind,
|
|
827
|
+
path=path,
|
|
828
|
+
content=path,
|
|
829
|
+
media_type=str(item.get("media_type") or "application/json"),
|
|
830
|
+
metadata=metadata,
|
|
831
|
+
)
|
|
832
|
+
)
|
|
833
|
+
stage_products.append(
|
|
834
|
+
{
|
|
835
|
+
"kind": kind,
|
|
836
|
+
"path": str(path),
|
|
837
|
+
"media_type": str(item.get("media_type") or "application/json"),
|
|
838
|
+
"metadata": metadata,
|
|
839
|
+
}
|
|
840
|
+
)
|
|
841
|
+
manifest = next((item for item in products if item.kind == "asset-manifest"), None)
|
|
842
|
+
if manifest is None:
|
|
843
|
+
return None
|
|
844
|
+
record = {
|
|
845
|
+
"unit_id": step.unit_id,
|
|
846
|
+
"operation": None,
|
|
847
|
+
"kind": "script",
|
|
848
|
+
"script": step.script,
|
|
849
|
+
"execution_id": context.execution_id,
|
|
850
|
+
"status": "completed",
|
|
851
|
+
"reused": True,
|
|
852
|
+
"summary": {
|
|
853
|
+
"run_dir": str(run_dir),
|
|
854
|
+
"manifest": str(manifest.path),
|
|
855
|
+
"assets": [item.metadata.get("slot_id") for item in products if item.kind != "asset-manifest"],
|
|
856
|
+
},
|
|
857
|
+
"warnings": [str(item) for item in cache.get("warnings") or ()],
|
|
858
|
+
"products": [dict(item) for item in stage_products],
|
|
859
|
+
}
|
|
860
|
+
return stage_products, tuple(products), record
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def _write_outputs_cache(
|
|
864
|
+
context: OperationContext,
|
|
865
|
+
step: ScriptStep,
|
|
866
|
+
fingerprint: str,
|
|
867
|
+
run_dir: Path,
|
|
868
|
+
stage_products: Sequence[Mapping[str, Any]],
|
|
869
|
+
warnings: Sequence[str] = (),
|
|
870
|
+
) -> None:
|
|
871
|
+
cache_path = _outputs_cache_path(context, step)
|
|
872
|
+
if cache_path is None or cache_path.is_symlink():
|
|
873
|
+
return
|
|
874
|
+
payload = {
|
|
875
|
+
"schema_version": 1,
|
|
876
|
+
"fingerprint": fingerprint,
|
|
877
|
+
"run_dir": str(run_dir),
|
|
878
|
+
"warnings": [str(item) for item in warnings],
|
|
879
|
+
"products": [
|
|
880
|
+
{
|
|
881
|
+
"kind": str(item.get("kind") or ""),
|
|
882
|
+
"path": str(item.get("path") or ""),
|
|
883
|
+
"media_type": str(item.get("media_type") or "application/json"),
|
|
884
|
+
"metadata": dict(item.get("metadata") or {}),
|
|
885
|
+
"sha256": sha256_file(Path(str(item.get("path") or ""))),
|
|
886
|
+
}
|
|
887
|
+
for item in stage_products
|
|
888
|
+
],
|
|
889
|
+
}
|
|
890
|
+
temporary = cache_path.with_name(f".{cache_path.name}.{uuid.uuid4().hex}.tmp")
|
|
891
|
+
try:
|
|
892
|
+
temporary.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True), encoding="utf-8")
|
|
893
|
+
os.replace(temporary, cache_path)
|
|
894
|
+
finally:
|
|
895
|
+
temporary.unlink(missing_ok=True)
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _execute_outputs_script_stage(
|
|
899
|
+
context: OperationContext,
|
|
900
|
+
step: ScriptStep,
|
|
901
|
+
published: Mapping[str, Sequence[Mapping[str, Any]]],
|
|
902
|
+
batch: dict[str, Any],
|
|
903
|
+
) -> tuple[list[dict[str, Any]], tuple[ProductDraft, ...], dict[str, Any]]:
|
|
904
|
+
input_paths = _resolved_script_inputs(context, step, published)
|
|
905
|
+
fingerprint = _script_fingerprint(context, step, published)
|
|
906
|
+
cached = _outputs_cache_hit(context, step, fingerprint)
|
|
907
|
+
if cached is not None:
|
|
908
|
+
return cached
|
|
909
|
+
cache_path = _outputs_cache_path(context, step)
|
|
910
|
+
if cache_path is not None and not cache_path.is_symlink():
|
|
911
|
+
cache_path.unlink(missing_ok=True)
|
|
912
|
+
|
|
913
|
+
run_dir = _allocate_run_dir(context, step, fingerprint)
|
|
914
|
+
try:
|
|
915
|
+
inputs_path = run_dir / ".argos-inputs.json"
|
|
916
|
+
inputs_path.write_text(
|
|
917
|
+
json.dumps(input_paths, ensure_ascii=False, sort_keys=True),
|
|
918
|
+
encoding="utf-8",
|
|
919
|
+
)
|
|
920
|
+
mplconfig = run_dir / ".mplconfig"
|
|
921
|
+
mplconfig.mkdir(parents=True, exist_ok=True)
|
|
922
|
+
manifest_path = run_dir / (step.manifest or "manifest.json")
|
|
923
|
+
env = sanitized_env(
|
|
924
|
+
{
|
|
925
|
+
"ARGOS_PROJECT_ROOT": str(context.project_root),
|
|
926
|
+
"ARGOS_INPUTS": str(inputs_path),
|
|
927
|
+
"ARGOS_OUTPUT_DIR": str(run_dir),
|
|
928
|
+
"ARGOS_MANIFEST": str(manifest_path),
|
|
929
|
+
"ARGOS_SCENARIO": str(context.params.get("scenario") or "base"),
|
|
930
|
+
"ARGOS_UNIT_ID": step.unit_id,
|
|
931
|
+
"MPLCONFIGDIR": str(mplconfig),
|
|
932
|
+
}
|
|
933
|
+
)
|
|
934
|
+
rendered_args = _render_script_args(
|
|
935
|
+
step.args,
|
|
936
|
+
input_paths=input_paths,
|
|
937
|
+
run_dir=run_dir,
|
|
938
|
+
context=context,
|
|
939
|
+
unit_id=step.unit_id,
|
|
940
|
+
)
|
|
941
|
+
if step.output_arg:
|
|
942
|
+
rendered_args = (*rendered_args, step.output_arg, str(run_dir))
|
|
943
|
+
script_path = context.path(step.script)
|
|
944
|
+
argv = ([sys.executable, str(script_path)] if script_path.suffix.casefold() == ".py" else [str(script_path)])
|
|
945
|
+
argv.extend(rendered_args)
|
|
946
|
+
cwd = context.path(step.cwd) if step.cwd else context.project_root
|
|
947
|
+
try:
|
|
948
|
+
completed = subprocess.run(
|
|
949
|
+
argv,
|
|
950
|
+
cwd=str(cwd),
|
|
951
|
+
env=env,
|
|
952
|
+
timeout=step.timeout_seconds,
|
|
953
|
+
capture_output=True,
|
|
954
|
+
text=True,
|
|
955
|
+
encoding="utf-8",
|
|
956
|
+
shell=False,
|
|
957
|
+
check=False,
|
|
958
|
+
)
|
|
959
|
+
except subprocess.TimeoutExpired as exc:
|
|
960
|
+
stdout = exc.stdout if isinstance(exc.stdout, str) else ""
|
|
961
|
+
stderr = exc.stderr if isinstance(exc.stderr, str) else ""
|
|
962
|
+
raise _script_error(
|
|
963
|
+
step,
|
|
964
|
+
f"timeout de {step.timeout_seconds}s; stdout={stdout[-2000:]!r}; stderr={stderr[-2000:]!r}",
|
|
965
|
+
) from exc
|
|
966
|
+
except OSError as exc:
|
|
967
|
+
raise _script_error(step, f"não foi possível executar {script_path}: {exc}") from exc
|
|
968
|
+
if completed.returncode != 0:
|
|
969
|
+
raise _script_error(
|
|
970
|
+
step,
|
|
971
|
+
f"código {completed.returncode}; stdout={completed.stdout[-2000:]!r}; "
|
|
972
|
+
f"stderr={completed.stderr[-2000:]!r}",
|
|
973
|
+
)
|
|
974
|
+
manifest, manifest_path, script_warnings = _collect_output_manifest(context, step, run_dir)
|
|
975
|
+
drafts: list[ProductDraft] = []
|
|
976
|
+
stage_products: list[dict[str, Any]] = []
|
|
977
|
+
for entry in manifest.assets:
|
|
978
|
+
path = run_dir / entry.path
|
|
979
|
+
metadata = {
|
|
980
|
+
"slot_id": entry.slot_id,
|
|
981
|
+
"caption": entry.caption,
|
|
982
|
+
"scope": entry.scope,
|
|
983
|
+
"auditee": entry.auditee,
|
|
984
|
+
}
|
|
985
|
+
draft = ProductDraft(
|
|
986
|
+
kind=entry.kind,
|
|
987
|
+
path=path,
|
|
988
|
+
content=path,
|
|
989
|
+
media_type=entry.media_type,
|
|
990
|
+
metadata=metadata,
|
|
991
|
+
)
|
|
992
|
+
drafts.append(draft)
|
|
993
|
+
stage_products.append(
|
|
994
|
+
{
|
|
995
|
+
"kind": draft.kind,
|
|
996
|
+
"path": str(path),
|
|
997
|
+
"media_type": draft.media_type,
|
|
998
|
+
"metadata": metadata,
|
|
999
|
+
}
|
|
1000
|
+
)
|
|
1001
|
+
manifest_draft = manifest_product(manifest, manifest_path)
|
|
1002
|
+
drafts.append(manifest_draft)
|
|
1003
|
+
stage_products.append(
|
|
1004
|
+
{
|
|
1005
|
+
"kind": manifest_draft.kind,
|
|
1006
|
+
"path": str(manifest_path),
|
|
1007
|
+
"media_type": manifest_draft.media_type,
|
|
1008
|
+
"metadata": dict(manifest_draft.metadata),
|
|
1009
|
+
}
|
|
1010
|
+
)
|
|
1011
|
+
_write_outputs_cache(context, step, fingerprint, run_dir, stage_products, script_warnings)
|
|
1012
|
+
record = {
|
|
1013
|
+
"unit_id": step.unit_id,
|
|
1014
|
+
"operation": None,
|
|
1015
|
+
"kind": "script",
|
|
1016
|
+
"script": step.script,
|
|
1017
|
+
"execution_id": context.execution_id,
|
|
1018
|
+
"status": "completed",
|
|
1019
|
+
"reused": False,
|
|
1020
|
+
"summary": {
|
|
1021
|
+
"run_dir": str(run_dir),
|
|
1022
|
+
"manifest": str(manifest_path),
|
|
1023
|
+
"assets": [entry.slot_id for entry in manifest.assets],
|
|
1024
|
+
},
|
|
1025
|
+
"warnings": script_warnings,
|
|
1026
|
+
"products": [dict(item) for item in stage_products],
|
|
1027
|
+
}
|
|
1028
|
+
return stage_products, tuple(drafts), record
|
|
1029
|
+
except Exception:
|
|
1030
|
+
shutil.rmtree(run_dir, ignore_errors=True)
|
|
1031
|
+
raise
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
def _script_argv(step: ScriptStep, script_path: Path) -> list[str]:
|
|
1035
|
+
if script_path.suffix.casefold() == ".py":
|
|
1036
|
+
return [sys.executable, str(script_path), *step.args]
|
|
1037
|
+
return [str(script_path), *step.args]
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
def _script_error(step: ScriptStep, detail: str) -> InputValidationError:
|
|
1041
|
+
from .telemetry import redact_error
|
|
1042
|
+
|
|
1043
|
+
return InputValidationError(
|
|
1044
|
+
f"script da etapa {step.unit_id} falhou: {redact_error(detail)}"
|
|
1045
|
+
)
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def _resolved_script_inputs(
|
|
1049
|
+
context: OperationContext,
|
|
1050
|
+
step: ScriptStep,
|
|
1051
|
+
published: Mapping[str, Sequence[Mapping[str, Any]]],
|
|
1052
|
+
) -> dict[str, str]:
|
|
1053
|
+
resolved_inputs = resolve_stage_references(dict(step.inputs), published)
|
|
1054
|
+
input_paths: dict[str, str] = {}
|
|
1055
|
+
for name, value in resolved_inputs.items():
|
|
1056
|
+
path = context.path(str(value))
|
|
1057
|
+
if not path.is_file():
|
|
1058
|
+
raise InputValidationError(f"input {name!r} da etapa {step.unit_id} não existe: {path}")
|
|
1059
|
+
input_paths[name] = str(path)
|
|
1060
|
+
return input_paths
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
def _script_fingerprint(
|
|
1064
|
+
context: OperationContext,
|
|
1065
|
+
step: ScriptStep,
|
|
1066
|
+
published: Mapping[str, Sequence[Mapping[str, Any]]],
|
|
1067
|
+
) -> str:
|
|
1068
|
+
input_paths = _resolved_script_inputs(context, step, published)
|
|
1069
|
+
script_path = context.path(step.script)
|
|
1070
|
+
payload = {
|
|
1071
|
+
"unit_id": step.unit_id,
|
|
1072
|
+
"script": {"path": step.script, "sha256": sha256_file(script_path)},
|
|
1073
|
+
"args": list(step.args),
|
|
1074
|
+
"deps": [
|
|
1075
|
+
{"path": dep, "sha256": sha256_file(context.path(dep))}
|
|
1076
|
+
for dep in step.deps
|
|
1077
|
+
],
|
|
1078
|
+
"inputs": {
|
|
1079
|
+
name: {"path": path, "sha256": sha256_file(Path(path))}
|
|
1080
|
+
for name, path in sorted(input_paths.items())
|
|
1081
|
+
},
|
|
1082
|
+
"output_dir": step.output_dir,
|
|
1083
|
+
"manifest": step.manifest,
|
|
1084
|
+
"mode": "outputs" if step.outputs else "manifest",
|
|
1085
|
+
"outputs": _output_fingerprint(step),
|
|
1086
|
+
"output_arg": step.output_arg,
|
|
1087
|
+
"cwd": step.cwd,
|
|
1088
|
+
}
|
|
1089
|
+
return sha256_bytes(canonical_json(payload).encode("utf-8"))
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def _script_cache_path(context: OperationContext, step: ScriptStep) -> Path | None:
|
|
1093
|
+
output_root = context.path(step.output_dir)
|
|
1094
|
+
if not output_root.is_dir():
|
|
1095
|
+
return None
|
|
1096
|
+
key = sha256_bytes(step.unit_id.encode("utf-8"))[:12]
|
|
1097
|
+
return output_root / f".argos-script-cache-{key}.json"
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
def _cached_script_stage(
|
|
1101
|
+
context: OperationContext,
|
|
1102
|
+
step: ScriptStep,
|
|
1103
|
+
fingerprint: str,
|
|
1104
|
+
) -> tuple[list[dict[str, Any]], tuple[ProductDraft, ...], dict[str, Any]] | None:
|
|
1105
|
+
cache_path = _script_cache_path(context, step)
|
|
1106
|
+
if cache_path is None or cache_path.is_symlink() or not cache_path.is_file():
|
|
1107
|
+
return None
|
|
1108
|
+
try:
|
|
1109
|
+
cache = json.loads(cache_path.read_text(encoding="utf-8"))
|
|
1110
|
+
except (OSError, UnicodeError, json.JSONDecodeError):
|
|
1111
|
+
return None
|
|
1112
|
+
if not isinstance(cache, Mapping) or cache.get("schema_version") != 1:
|
|
1113
|
+
return None
|
|
1114
|
+
if str(cache.get("fingerprint") or "") != fingerprint:
|
|
1115
|
+
return None
|
|
1116
|
+
raw_products = cache.get("products")
|
|
1117
|
+
if not isinstance(raw_products, list) or not raw_products:
|
|
1118
|
+
return None
|
|
1119
|
+
products: list[ProductDraft] = []
|
|
1120
|
+
stage_products: list[dict[str, Any]] = []
|
|
1121
|
+
for item in raw_products:
|
|
1122
|
+
if not isinstance(item, Mapping):
|
|
1123
|
+
return None
|
|
1124
|
+
path = Path(str(item.get("path") or ""))
|
|
1125
|
+
kind = str(item.get("kind") or "")
|
|
1126
|
+
digest = str(item.get("sha256") or "")
|
|
1127
|
+
output_root = context.path(step.output_dir)
|
|
1128
|
+
resolved = path.resolve()
|
|
1129
|
+
if output_root not in resolved.parents:
|
|
1130
|
+
return None
|
|
1131
|
+
if not path.is_file() or path.is_symlink() or sha256_file(path) != digest:
|
|
1132
|
+
return None
|
|
1133
|
+
if not kind:
|
|
1134
|
+
return None
|
|
1135
|
+
metadata = dict(item.get("metadata") or {})
|
|
1136
|
+
products.append(
|
|
1137
|
+
ProductDraft(
|
|
1138
|
+
kind=kind,
|
|
1139
|
+
path=path,
|
|
1140
|
+
content=path,
|
|
1141
|
+
media_type=str(item.get("media_type") or "application/json"),
|
|
1142
|
+
metadata=metadata,
|
|
1143
|
+
)
|
|
1144
|
+
)
|
|
1145
|
+
stage_products.append(
|
|
1146
|
+
{
|
|
1147
|
+
"kind": kind,
|
|
1148
|
+
"path": str(path),
|
|
1149
|
+
"media_type": str(item.get("media_type") or "application/json"),
|
|
1150
|
+
"metadata": metadata,
|
|
1151
|
+
}
|
|
1152
|
+
)
|
|
1153
|
+
manifest = next((item for item in products if item.kind == "asset-manifest"), None)
|
|
1154
|
+
if manifest is None:
|
|
1155
|
+
return None
|
|
1156
|
+
assets = [
|
|
1157
|
+
str(item.metadata.get("slot_id") or "")
|
|
1158
|
+
for item in products
|
|
1159
|
+
if item.kind != "asset-manifest"
|
|
1160
|
+
]
|
|
1161
|
+
record = {
|
|
1162
|
+
"unit_id": step.unit_id,
|
|
1163
|
+
"operation": None,
|
|
1164
|
+
"kind": "script",
|
|
1165
|
+
"script": step.script,
|
|
1166
|
+
"execution_id": context.execution_id,
|
|
1167
|
+
"status": "completed",
|
|
1168
|
+
"reused": True,
|
|
1169
|
+
"summary": {"manifest": str(manifest.path), "assets": assets},
|
|
1170
|
+
"products": [dict(item) for item in stage_products],
|
|
1171
|
+
}
|
|
1172
|
+
return stage_products, tuple(products), record
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
def _write_script_cache(
|
|
1176
|
+
context: OperationContext,
|
|
1177
|
+
step: ScriptStep,
|
|
1178
|
+
fingerprint: str,
|
|
1179
|
+
stage_products: Sequence[Mapping[str, Any]],
|
|
1180
|
+
) -> None:
|
|
1181
|
+
cache_path = _script_cache_path(context, step)
|
|
1182
|
+
if cache_path is None or cache_path.is_symlink():
|
|
1183
|
+
return
|
|
1184
|
+
payload = {
|
|
1185
|
+
"schema_version": 1,
|
|
1186
|
+
"fingerprint": fingerprint,
|
|
1187
|
+
"products": [
|
|
1188
|
+
{
|
|
1189
|
+
"kind": str(item.get("kind") or ""),
|
|
1190
|
+
"path": str(item.get("path") or ""),
|
|
1191
|
+
"media_type": str(item.get("media_type") or "application/json"),
|
|
1192
|
+
"metadata": dict(item.get("metadata") or {}),
|
|
1193
|
+
"sha256": sha256_file(Path(str(item.get("path") or ""))),
|
|
1194
|
+
}
|
|
1195
|
+
for item in stage_products
|
|
1196
|
+
],
|
|
1197
|
+
}
|
|
1198
|
+
temporary = cache_path.with_name(f".{cache_path.name}.{uuid.uuid4().hex}.tmp")
|
|
1199
|
+
try:
|
|
1200
|
+
temporary.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True), encoding="utf-8")
|
|
1201
|
+
os.replace(temporary, cache_path)
|
|
1202
|
+
finally:
|
|
1203
|
+
temporary.unlink(missing_ok=True)
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def _run_script(
|
|
1207
|
+
context: OperationContext,
|
|
1208
|
+
step: ScriptStep,
|
|
1209
|
+
published: Mapping[str, Sequence[Mapping[str, Any]]],
|
|
1210
|
+
) -> ScriptRun:
|
|
1211
|
+
"""Executa o script em staging e devolve drafts; não publica nada."""
|
|
1212
|
+
input_paths = _resolved_script_inputs(context, step, published)
|
|
1213
|
+
script_path = context.path(step.script)
|
|
1214
|
+
if not script_path.is_file():
|
|
1215
|
+
raise InputValidationError(f"script da etapa {step.unit_id} não existe: {script_path}")
|
|
1216
|
+
final_output = context.path(step.output_dir)
|
|
1217
|
+
final_manifest = context.path(step.manifest)
|
|
1218
|
+
if final_output.exists() and not final_output.is_dir():
|
|
1219
|
+
raise InputValidationError(f"output_dir da etapa {step.unit_id} não é diretório: {final_output}")
|
|
1220
|
+
|
|
1221
|
+
staging = Path(tempfile.mkdtemp(prefix=".argos-script-", dir=context.project_root))
|
|
1222
|
+
try:
|
|
1223
|
+
inputs_path = staging / "inputs.json"
|
|
1224
|
+
inputs_path.write_text(json.dumps(input_paths, ensure_ascii=False, sort_keys=True), encoding="utf-8")
|
|
1225
|
+
manifest_path = staging / "manifest.json"
|
|
1226
|
+
mplconfig = staging / ".mplconfig"
|
|
1227
|
+
mplconfig.mkdir(parents=True, exist_ok=True)
|
|
1228
|
+
env = sanitized_env(
|
|
1229
|
+
{
|
|
1230
|
+
"ARGOS_PROJECT_ROOT": str(context.project_root),
|
|
1231
|
+
"ARGOS_INPUTS": str(inputs_path),
|
|
1232
|
+
"ARGOS_OUTPUT_DIR": str(staging),
|
|
1233
|
+
"ARGOS_MANIFEST": str(manifest_path),
|
|
1234
|
+
"ARGOS_SCENARIO": str(context.params.get("scenario") or "base"),
|
|
1235
|
+
"ARGOS_UNIT_ID": step.unit_id,
|
|
1236
|
+
"MPLCONFIGDIR": str(mplconfig),
|
|
1237
|
+
}
|
|
1238
|
+
)
|
|
1239
|
+
argv = _script_argv(step, script_path)
|
|
1240
|
+
try:
|
|
1241
|
+
completed = subprocess.run(
|
|
1242
|
+
argv,
|
|
1243
|
+
cwd=str(context.project_root),
|
|
1244
|
+
env=env,
|
|
1245
|
+
timeout=step.timeout_seconds,
|
|
1246
|
+
capture_output=True,
|
|
1247
|
+
text=True,
|
|
1248
|
+
encoding="utf-8",
|
|
1249
|
+
shell=False,
|
|
1250
|
+
check=False,
|
|
1251
|
+
)
|
|
1252
|
+
except subprocess.TimeoutExpired as exc:
|
|
1253
|
+
stdout = exc.stdout if isinstance(exc.stdout, str) else ""
|
|
1254
|
+
stderr = exc.stderr if isinstance(exc.stderr, str) else ""
|
|
1255
|
+
raise _script_error(
|
|
1256
|
+
step,
|
|
1257
|
+
f"timeout de {step.timeout_seconds}s; stdout={stdout[-2000:]!r}; stderr={stderr[-2000:]!r}",
|
|
1258
|
+
) from exc
|
|
1259
|
+
except OSError as exc:
|
|
1260
|
+
raise _script_error(step, f"não foi possível executar {script_path}: {exc}") from exc
|
|
1261
|
+
if completed.returncode != 0:
|
|
1262
|
+
raise _script_error(
|
|
1263
|
+
step,
|
|
1264
|
+
f"código {completed.returncode}; stdout={completed.stdout[-2000:]!r}; "
|
|
1265
|
+
f"stderr={completed.stderr[-2000:]!r}",
|
|
1266
|
+
)
|
|
1267
|
+
if not manifest_path.is_file():
|
|
1268
|
+
raise _script_error(step, f"manifesto não foi escrito em {manifest_path}")
|
|
1269
|
+
manifest = load_manifest(manifest_path)
|
|
1270
|
+
entries = validate_manifest(manifest, output_root=staging)
|
|
1271
|
+
for entry in entries:
|
|
1272
|
+
source = staging / entry.path
|
|
1273
|
+
actual = sha256_file(source)
|
|
1274
|
+
if actual != entry.sha256:
|
|
1275
|
+
raise _script_error(
|
|
1276
|
+
step,
|
|
1277
|
+
f"hash divergente para {entry.path}: declarado {entry.sha256}, calculado {actual}",
|
|
1278
|
+
)
|
|
1279
|
+
assets = tuple(
|
|
1280
|
+
ProductDraft(
|
|
1281
|
+
kind=entry.kind,
|
|
1282
|
+
path=final_output / entry.path,
|
|
1283
|
+
content=staging / entry.path,
|
|
1284
|
+
media_type=entry.media_type,
|
|
1285
|
+
metadata={
|
|
1286
|
+
"slot_id": entry.slot_id,
|
|
1287
|
+
"caption": entry.caption,
|
|
1288
|
+
"scope": entry.scope,
|
|
1289
|
+
"auditee": entry.auditee,
|
|
1290
|
+
},
|
|
1291
|
+
)
|
|
1292
|
+
for entry in entries
|
|
1293
|
+
)
|
|
1294
|
+
return ScriptRun(
|
|
1295
|
+
products=(*assets, manifest_product(manifest, final_manifest)),
|
|
1296
|
+
staging=staging,
|
|
1297
|
+
manifest=manifest,
|
|
1298
|
+
)
|
|
1299
|
+
except Exception:
|
|
1300
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
1301
|
+
raise
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def _copy_script_file(source: Path, requested: Path, digest: str) -> tuple[Path, bool]:
|
|
1305
|
+
"""Copia para o destino sem sobrescrever produto divergente.
|
|
1306
|
+
|
|
1307
|
+
O mesmo destino com o mesmo hash é reutilizado. Um destino divergente gera
|
|
1308
|
+
um caminho derivado ``.argos-<hash>``, como o ProductLifecycle faz para os
|
|
1309
|
+
demais produtos; nunca há sobrescrita silenciosa.
|
|
1310
|
+
"""
|
|
1311
|
+
requested = Path(requested)
|
|
1312
|
+
if requested.is_symlink():
|
|
1313
|
+
raise InputValidationError(f"destino de ativo não pode ser symlink: {requested}")
|
|
1314
|
+
|
|
1315
|
+
def matches(path: Path) -> bool:
|
|
1316
|
+
return path.is_file() and not path.is_symlink() and sha256_file(path) == digest
|
|
1317
|
+
|
|
1318
|
+
if requested.exists():
|
|
1319
|
+
if not requested.is_file():
|
|
1320
|
+
raise InputValidationError(f"destino de ativo não é arquivo: {requested}")
|
|
1321
|
+
if matches(requested):
|
|
1322
|
+
return requested, False
|
|
1323
|
+
target = requested.with_name(f"{requested.stem}.argos-{digest[:12]}{requested.suffix}")
|
|
1324
|
+
if target.exists():
|
|
1325
|
+
if not target.is_file() or target.is_symlink():
|
|
1326
|
+
raise InputValidationError(f"destino derivado de ativo não é arquivo: {target}")
|
|
1327
|
+
if matches(target):
|
|
1328
|
+
return target, False
|
|
1329
|
+
raise InputValidationError(
|
|
1330
|
+
f"destino derivado já ocupado por conteúdo divergente: {target}"
|
|
1331
|
+
)
|
|
1332
|
+
else:
|
|
1333
|
+
target = requested
|
|
1334
|
+
|
|
1335
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
1336
|
+
temporary = target.with_name(f".argos-{uuid.uuid4().hex}.tmp")
|
|
1337
|
+
try:
|
|
1338
|
+
shutil.copyfile(source, temporary)
|
|
1339
|
+
# "r+b": no Windows o fsync exige descritor com escrita (um arquivo aberto só para leitura dá EBADF).
|
|
1340
|
+
with temporary.open("r+b") as stream:
|
|
1341
|
+
os.fsync(stream.fileno())
|
|
1342
|
+
try:
|
|
1343
|
+
os.link(temporary, target)
|
|
1344
|
+
created = True
|
|
1345
|
+
except FileExistsError:
|
|
1346
|
+
if not matches(target):
|
|
1347
|
+
raise InputValidationError(
|
|
1348
|
+
f"destino de ativo ocupado por conteúdo divergente: {target}"
|
|
1349
|
+
)
|
|
1350
|
+
created = False
|
|
1351
|
+
finally:
|
|
1352
|
+
temporary.unlink(missing_ok=True)
|
|
1353
|
+
return target, created
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def _manifest_payload(manifest: Any, actual_paths: list[Path], output_root: Path) -> dict[str, Any]:
|
|
1357
|
+
assets = []
|
|
1358
|
+
for entry, actual in zip(manifest.assets, actual_paths):
|
|
1359
|
+
try:
|
|
1360
|
+
relative = actual.relative_to(output_root)
|
|
1361
|
+
except ValueError as exc:
|
|
1362
|
+
raise InputValidationError(f"ativo {entry.slot_id!r} ficou fora de output_dir") from exc
|
|
1363
|
+
assets.append(
|
|
1364
|
+
{
|
|
1365
|
+
"slot_id": entry.slot_id,
|
|
1366
|
+
"kind": entry.kind,
|
|
1367
|
+
"path": relative.as_posix(),
|
|
1368
|
+
"media_type": entry.media_type,
|
|
1369
|
+
"sha256": entry.sha256,
|
|
1370
|
+
"caption": entry.caption,
|
|
1371
|
+
"scope": entry.scope,
|
|
1372
|
+
"auditee": entry.auditee,
|
|
1373
|
+
"metadata": dict(entry.metadata),
|
|
1374
|
+
}
|
|
1375
|
+
)
|
|
1376
|
+
return {"schema_version": manifest.schema_version, "assets": assets}
|
|
1377
|
+
|
|
1378
|
+
|
|
1379
|
+
def _execute_script_stage(
|
|
1380
|
+
context: OperationContext,
|
|
1381
|
+
step: ScriptStep,
|
|
1382
|
+
published: Mapping[str, Sequence[Mapping[str, Any]]],
|
|
1383
|
+
batch: dict[str, Any],
|
|
1384
|
+
) -> tuple[list[dict[str, Any]], tuple[ProductDraft, ...], dict[str, Any]]:
|
|
1385
|
+
if step.outputs:
|
|
1386
|
+
return _execute_outputs_script_stage(context, step, published, batch)
|
|
1387
|
+
fingerprint = _script_fingerprint(context, step, published)
|
|
1388
|
+
cached = _cached_script_stage(context, step, fingerprint)
|
|
1389
|
+
if cached is not None:
|
|
1390
|
+
return cached
|
|
1391
|
+
cache_path = _script_cache_path(context, step)
|
|
1392
|
+
if cache_path is not None:
|
|
1393
|
+
cache_path.unlink(missing_ok=True)
|
|
1394
|
+
|
|
1395
|
+
run = _run_script(context, step, published)
|
|
1396
|
+
try:
|
|
1397
|
+
output_root = context.path(step.output_dir)
|
|
1398
|
+
drafts: list[ProductDraft] = []
|
|
1399
|
+
actual_paths: list[Path] = []
|
|
1400
|
+
stage_products: list[dict[str, Any]] = []
|
|
1401
|
+
for entry in run.manifest.assets:
|
|
1402
|
+
source = run.staging / entry.path
|
|
1403
|
+
requested = output_root / entry.path
|
|
1404
|
+
actual, created = _copy_script_file(source, requested, entry.sha256)
|
|
1405
|
+
if created:
|
|
1406
|
+
batch["paths"].append(actual)
|
|
1407
|
+
actual_paths.append(actual)
|
|
1408
|
+
metadata = {
|
|
1409
|
+
"slot_id": entry.slot_id,
|
|
1410
|
+
"caption": entry.caption,
|
|
1411
|
+
"scope": entry.scope,
|
|
1412
|
+
"auditee": entry.auditee,
|
|
1413
|
+
}
|
|
1414
|
+
draft = ProductDraft(
|
|
1415
|
+
kind=entry.kind,
|
|
1416
|
+
path=actual,
|
|
1417
|
+
content=actual,
|
|
1418
|
+
media_type=entry.media_type,
|
|
1419
|
+
metadata=metadata,
|
|
1420
|
+
)
|
|
1421
|
+
drafts.append(draft)
|
|
1422
|
+
stage_products.append(
|
|
1423
|
+
{
|
|
1424
|
+
"kind": draft.kind,
|
|
1425
|
+
"path": str(actual),
|
|
1426
|
+
"media_type": draft.media_type,
|
|
1427
|
+
"metadata": metadata,
|
|
1428
|
+
}
|
|
1429
|
+
)
|
|
1430
|
+
|
|
1431
|
+
payload = _manifest_payload(run.manifest, actual_paths, output_root)
|
|
1432
|
+
manifest_bytes = (canonical_json(payload) + "\n").encode("utf-8")
|
|
1433
|
+
manifest_source = run.staging / "manifest-final.json"
|
|
1434
|
+
manifest_source.write_bytes(manifest_bytes)
|
|
1435
|
+
actual_manifest, created = _copy_script_file(
|
|
1436
|
+
manifest_source,
|
|
1437
|
+
context.path(step.manifest),
|
|
1438
|
+
sha256_bytes(manifest_bytes),
|
|
1439
|
+
)
|
|
1440
|
+
if created:
|
|
1441
|
+
batch["paths"].append(actual_manifest)
|
|
1442
|
+
manifest_draft = ProductDraft(
|
|
1443
|
+
kind="asset-manifest",
|
|
1444
|
+
path=actual_manifest,
|
|
1445
|
+
content=payload,
|
|
1446
|
+
media_type="application/json",
|
|
1447
|
+
metadata={"assets": len(payload["assets"])},
|
|
1448
|
+
)
|
|
1449
|
+
drafts.append(manifest_draft)
|
|
1450
|
+
stage_products.append(
|
|
1451
|
+
{
|
|
1452
|
+
"kind": manifest_draft.kind,
|
|
1453
|
+
"path": str(actual_manifest),
|
|
1454
|
+
"media_type": manifest_draft.media_type,
|
|
1455
|
+
"metadata": dict(manifest_draft.metadata),
|
|
1456
|
+
}
|
|
1457
|
+
)
|
|
1458
|
+
record = {
|
|
1459
|
+
"unit_id": step.unit_id,
|
|
1460
|
+
"operation": None,
|
|
1461
|
+
"kind": "script",
|
|
1462
|
+
"script": step.script,
|
|
1463
|
+
"execution_id": context.execution_id,
|
|
1464
|
+
"status": "completed",
|
|
1465
|
+
"reused": False,
|
|
1466
|
+
"summary": {
|
|
1467
|
+
"manifest": str(actual_manifest),
|
|
1468
|
+
"assets": [entry.slot_id for entry in run.manifest.assets],
|
|
1469
|
+
},
|
|
1470
|
+
"products": [dict(item) for item in stage_products],
|
|
1471
|
+
}
|
|
1472
|
+
_write_script_cache(context, step, fingerprint, stage_products)
|
|
1473
|
+
return stage_products, tuple(drafts), record
|
|
1474
|
+
finally:
|
|
1475
|
+
run.cleanup()
|
|
1476
|
+
|
|
1477
|
+
|
|
1478
|
+
def _cleanup_script_batches(batches: Sequence[dict[str, Any]]) -> None:
|
|
1479
|
+
for batch in batches:
|
|
1480
|
+
if batch.get("consumed"):
|
|
1481
|
+
continue
|
|
1482
|
+
for path in reversed(batch.get("paths") or ()):
|
|
1483
|
+
try:
|
|
1484
|
+
Path(path).unlink()
|
|
1485
|
+
except FileNotFoundError:
|
|
1486
|
+
continue
|
|
1487
|
+
except OSError:
|
|
1488
|
+
continue
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def _stage_descriptor(step: Mapping[str, Any]) -> dict[str, Any]:
|
|
1492
|
+
if _is_script_step(step):
|
|
1493
|
+
return {
|
|
1494
|
+
"kind": "script",
|
|
1495
|
+
"script": str(step.get("script") or ""),
|
|
1496
|
+
"outputs": list(step.get("outputs") or ()),
|
|
1497
|
+
}
|
|
1498
|
+
return {"operation": str(_operation_id(step) or "")}
|
|
1499
|
+
|
|
1500
|
+
|
|
1501
|
+
def _validate_pipeline(
|
|
1502
|
+
context: OperationContext,
|
|
1503
|
+
all_stages: Sequence[tuple[str, Mapping[str, Any]]],
|
|
1504
|
+
default_scenario: Any,
|
|
1505
|
+
) -> dict[str, int]:
|
|
1506
|
+
"""Valida catálogo, referências e parâmetros conhecidos antes de executar etapas."""
|
|
1507
|
+
if context.catalog is None:
|
|
1508
|
+
raise InputValidationError("pipeline requer catálogo público no contexto de execução")
|
|
1509
|
+
positions = {unit_id: index for index, (unit_id, _) in enumerate(all_stages)}
|
|
1510
|
+
placeholder = str((context.project_root / ".argos-stage-reference-validation").resolve())
|
|
1511
|
+
|
|
1512
|
+
def validate_references(unit_id: str, index: int, references: Sequence[str]) -> None:
|
|
1513
|
+
for producer in references:
|
|
1514
|
+
if producer not in positions:
|
|
1515
|
+
raise InputValidationError(
|
|
1516
|
+
f"etapa {unit_id} referencia etapa inexistente: {producer}"
|
|
1517
|
+
)
|
|
1518
|
+
if positions[producer] >= index:
|
|
1519
|
+
raise InputValidationError(
|
|
1520
|
+
f"etapa {unit_id} referencia {producer}, que não é uma etapa anterior"
|
|
1521
|
+
)
|
|
1522
|
+
|
|
1523
|
+
for index, (unit_id, step) in enumerate(all_stages):
|
|
1524
|
+
if _is_script_step(step):
|
|
1525
|
+
parsed = _parse_script_step(step, project_root=context.project_root, unit_id=unit_id)
|
|
1526
|
+
validate_references(unit_id, index, _stage_references(parsed.inputs))
|
|
1527
|
+
continue
|
|
1528
|
+
operation_id = _operation_id(step)
|
|
1529
|
+
if operation_id is None:
|
|
1530
|
+
raise InputValidationError(f"etapa {unit_id} não declara operation nem script")
|
|
1531
|
+
if operation_id == "pipeline":
|
|
1532
|
+
raise InputValidationError(f"etapa {unit_id} não pode executar pipeline recursivamente")
|
|
1533
|
+
operation = context.catalog.get(operation_id)
|
|
1534
|
+
stage_params = _step_params(step, default_scenario)
|
|
1535
|
+
validate_references(unit_id, index, _stage_references(stage_params))
|
|
1536
|
+
validation_params = _replace_stage_references(stage_params, placeholder)
|
|
1537
|
+
operation.resolve(
|
|
1538
|
+
validation_params,
|
|
1539
|
+
project_root=context.project_root,
|
|
1540
|
+
project_overrides=context.project_overrides,
|
|
1541
|
+
)
|
|
1542
|
+
return positions
|
|
1543
|
+
|
|
1544
|
+
def _envelope_products(envelope: Mapping[str, Any]) -> list[dict[str, Any]]:
|
|
1545
|
+
result = envelope.get("result")
|
|
1546
|
+
if not isinstance(result, Mapping):
|
|
1547
|
+
return []
|
|
1548
|
+
raw_products = result.get("products") or ()
|
|
1549
|
+
return [dict(item) for item in raw_products if isinstance(item, Mapping)]
|
|
1550
|
+
|
|
1551
|
+
|
|
1552
|
+
def run_pipeline(context: OperationContext) -> OperationResult:
|
|
1553
|
+
"""Executa cada etapa pelo ciclo público completo do motor."""
|
|
1554
|
+
params = context.params
|
|
1555
|
+
source_spec = load_pipeline_spec(context, params.get("plan_file"))
|
|
1556
|
+
operations = list(source_spec["operations"])
|
|
1557
|
+
all_stages = _filter_stages(operations, until_stage=None, from_stage=None)
|
|
1558
|
+
positions = _validate_pipeline(context, all_stages, params.get("scenario"))
|
|
1559
|
+
stages = _filter_stages(
|
|
1560
|
+
operations,
|
|
1561
|
+
until_stage=params.get("until_stage"),
|
|
1562
|
+
from_stage=params.get("from_stage"),
|
|
1563
|
+
)
|
|
1564
|
+
|
|
1565
|
+
if params.get("dry_run"):
|
|
1566
|
+
return OperationResult(
|
|
1567
|
+
summary={
|
|
1568
|
+
"dry_run": True,
|
|
1569
|
+
"count": len(stages),
|
|
1570
|
+
"stages": [
|
|
1571
|
+
{"unit_id": unit_id, **_stage_descriptor(step)}
|
|
1572
|
+
for unit_id, step in stages
|
|
1573
|
+
],
|
|
1574
|
+
}
|
|
1575
|
+
)
|
|
1576
|
+
|
|
1577
|
+
if context.run_operation is None or context.reuse_operation is None:
|
|
1578
|
+
raise InputValidationError("pipeline requer o ciclo completo de execução do motor")
|
|
1579
|
+
|
|
1580
|
+
by_id = {unit_id: step for unit_id, step in all_stages}
|
|
1581
|
+
published: dict[str, list[dict[str, Any]]] = {}
|
|
1582
|
+
executed_stages: list[dict[str, Any]] = []
|
|
1583
|
+
warnings: list[str] = []
|
|
1584
|
+
pending: list[Mapping[str, Any]] = []
|
|
1585
|
+
|
|
1586
|
+
def prior_products(unit_id: str, before_index: int, consumer: str) -> list[dict[str, Any]]:
|
|
1587
|
+
"""Busca somente cache íntegro de pré-requisitos excluídos por from_stage."""
|
|
1588
|
+
if published.get(unit_id):
|
|
1589
|
+
return published[unit_id]
|
|
1590
|
+
producer_index = positions[unit_id]
|
|
1591
|
+
if producer_index >= before_index:
|
|
1592
|
+
raise InputValidationError(
|
|
1593
|
+
f"etapa {consumer} não pode consumir {unit_id} antes da execução"
|
|
1594
|
+
)
|
|
1595
|
+
producer = by_id[unit_id]
|
|
1596
|
+
if _is_script_step(producer):
|
|
1597
|
+
raise InputValidationError(
|
|
1598
|
+
f"etapa {consumer} não pode retomar de {unit_id}: from_stage não reutiliza saídas de script"
|
|
1599
|
+
)
|
|
1600
|
+
producer_operation = _operation_id(producer)
|
|
1601
|
+
if producer_operation is None:
|
|
1602
|
+
raise InputValidationError(f"etapa {unit_id} não declara operation")
|
|
1603
|
+
producer_params = _step_params(producer, params.get("scenario"))
|
|
1604
|
+
for dependency in _stage_references(producer_params):
|
|
1605
|
+
prior_products(dependency, producer_index, unit_id)
|
|
1606
|
+
resolved_params = resolve_stage_references(producer_params, published)
|
|
1607
|
+
envelope = context.reuse_operation(producer_operation, resolved_params)
|
|
1608
|
+
if envelope is None or str(envelope.get("status")) != "completed":
|
|
1609
|
+
raise MissingInputError(
|
|
1610
|
+
f"etapa {consumer} depende do resultado atual e íntegro da etapa {unit_id}; "
|
|
1611
|
+
f"execute o pipeline até {unit_id} antes de retomar com from_stage"
|
|
1612
|
+
)
|
|
1613
|
+
products = _envelope_products(envelope)
|
|
1614
|
+
if not products:
|
|
1615
|
+
raise MissingInputError(
|
|
1616
|
+
f"etapa {consumer} depende de produtos da etapa {unit_id}, mas não há produto reutilizável"
|
|
1617
|
+
)
|
|
1618
|
+
published[unit_id] = products
|
|
1619
|
+
return products
|
|
1620
|
+
|
|
1621
|
+
cleanup_batches: list[dict[str, Any]] = []
|
|
1622
|
+
all_products: list[ProductDraft] = []
|
|
1623
|
+
try:
|
|
1624
|
+
for unit_id, step in stages:
|
|
1625
|
+
# A etapa seguinte pode consumir os ativos publicados pelo script
|
|
1626
|
+
# anterior; a partir daqui uma falha não deve removê-los.
|
|
1627
|
+
for batch in cleanup_batches:
|
|
1628
|
+
batch["consumed"] = True
|
|
1629
|
+
|
|
1630
|
+
if _is_script_step(step):
|
|
1631
|
+
parsed = _parse_script_step(step, project_root=context.project_root, unit_id=unit_id)
|
|
1632
|
+
for producer in _stage_references(parsed.inputs):
|
|
1633
|
+
if not published.get(producer):
|
|
1634
|
+
prior_products(producer, positions[unit_id], unit_id)
|
|
1635
|
+
batch: dict[str, Any] = {"paths": [], "consumed": False}
|
|
1636
|
+
cleanup_batches.append(batch)
|
|
1637
|
+
stage_products, stage_drafts, stage_record = _execute_script_stage(
|
|
1638
|
+
context, parsed, published, batch
|
|
1639
|
+
)
|
|
1640
|
+
all_products.extend(stage_drafts)
|
|
1641
|
+
published[unit_id] = stage_products
|
|
1642
|
+
executed_stages.append(stage_record)
|
|
1643
|
+
warnings.extend(str(item) for item in stage_record.get("warnings") or ())
|
|
1644
|
+
continue
|
|
1645
|
+
|
|
1646
|
+
operation_id = _operation_id(step)
|
|
1647
|
+
if operation_id is None:
|
|
1648
|
+
raise InputValidationError(f"etapa {unit_id} não declara operation")
|
|
1649
|
+
step_params = _step_params(step, params.get("scenario"))
|
|
1650
|
+
for producer in _stage_references(step_params):
|
|
1651
|
+
if not published.get(producer):
|
|
1652
|
+
prior_products(producer, positions[unit_id], unit_id)
|
|
1653
|
+
resolved_params = resolve_stage_references(step_params, published)
|
|
1654
|
+
try:
|
|
1655
|
+
envelope = context.run_operation(operation_id, resolved_params)
|
|
1656
|
+
except MissingInputError as exc:
|
|
1657
|
+
context.event(
|
|
1658
|
+
"pipeline_stage_awaiting_input",
|
|
1659
|
+
payload={"unit_id": unit_id, "operation_id": operation_id, "error": str(exc)},
|
|
1660
|
+
)
|
|
1661
|
+
raise MissingInputError(f"etapa {unit_id} ({operation_id}) aguarda insumos: {exc}") from exc
|
|
1662
|
+
|
|
1663
|
+
status = str(envelope.get("status") or "unknown")
|
|
1664
|
+
result = envelope.get("result")
|
|
1665
|
+
if status == "awaiting_input":
|
|
1666
|
+
detail = str(envelope.get("error") or "insumos pendentes")
|
|
1667
|
+
if isinstance(result, Mapping) and result.get("pending"):
|
|
1668
|
+
detail = json.dumps(result["pending"], ensure_ascii=False)
|
|
1669
|
+
context.event(
|
|
1670
|
+
"pipeline_stage_awaiting_input",
|
|
1671
|
+
payload={"unit_id": unit_id, "operation_id": operation_id, "execution_id": envelope.get("id"), "error": detail},
|
|
1672
|
+
)
|
|
1673
|
+
raise MissingInputError(f"etapa {unit_id} ({operation_id}) aguarda insumos: {detail}")
|
|
1674
|
+
if status == "failed":
|
|
1675
|
+
raise InputValidationError(
|
|
1676
|
+
f"etapa {unit_id} ({operation_id}) falhou: {envelope.get('error') or 'erro sem detalhe'}"
|
|
1677
|
+
)
|
|
1678
|
+
if status not in {"completed", "unknown"}:
|
|
1679
|
+
raise InputValidationError(f"etapa {unit_id} terminou em estado inesperado: {status}")
|
|
1680
|
+
if not isinstance(result, Mapping) and status == "unknown":
|
|
1681
|
+
result = {}
|
|
1682
|
+
if not isinstance(result, Mapping):
|
|
1683
|
+
raise InputValidationError(f"etapa {unit_id} não retornou resultado persistido")
|
|
1684
|
+
|
|
1685
|
+
stage_products = _envelope_products(envelope)
|
|
1686
|
+
if status == "completed":
|
|
1687
|
+
published[unit_id] = stage_products
|
|
1688
|
+
stage_summary = dict(result.get("summary") or {})
|
|
1689
|
+
stage_record = {
|
|
1690
|
+
"unit_id": unit_id,
|
|
1691
|
+
"operation": operation_id,
|
|
1692
|
+
"execution_id": str(envelope.get("id") or ""),
|
|
1693
|
+
"status": status,
|
|
1694
|
+
"reused": bool(envelope.get("reused")),
|
|
1695
|
+
"summary": stage_summary,
|
|
1696
|
+
"products": stage_products,
|
|
1697
|
+
}
|
|
1698
|
+
executed_stages.append(stage_record)
|
|
1699
|
+
warnings.extend(str(item) for item in result.get("warnings") or ())
|
|
1700
|
+
if status == "unknown":
|
|
1701
|
+
pending.append(
|
|
1702
|
+
{
|
|
1703
|
+
"type": "pipeline_stage_unknown",
|
|
1704
|
+
"unit_id": unit_id,
|
|
1705
|
+
"operation_id": operation_id,
|
|
1706
|
+
"execution_id": envelope.get("id"),
|
|
1707
|
+
"cause": "unknown",
|
|
1708
|
+
"error": envelope.get("error"),
|
|
1709
|
+
}
|
|
1710
|
+
)
|
|
1711
|
+
break
|
|
1712
|
+
if result.get("pending"):
|
|
1713
|
+
pending.extend(dict(item) for item in result["pending"] if isinstance(item, Mapping))
|
|
1714
|
+
break
|
|
1715
|
+
except Exception:
|
|
1716
|
+
_cleanup_script_batches(cleanup_batches)
|
|
1717
|
+
raise
|
|
1718
|
+
|
|
1719
|
+
summary = {
|
|
1720
|
+
"stages_executed": len(executed_stages),
|
|
1721
|
+
"stages": executed_stages,
|
|
1722
|
+
"pipeline_stages": {
|
|
1723
|
+
unit_id: [dict(item) for item in stage_products]
|
|
1724
|
+
for unit_id, stage_products in published.items()
|
|
1725
|
+
},
|
|
1726
|
+
}
|
|
1727
|
+
products: list[ProductDraft] = list(all_products)
|
|
1728
|
+
output = context.optional_path(params.get("output"))
|
|
1729
|
+
if output:
|
|
1730
|
+
products.append(ProductDraft("pipeline-result", output, summary))
|
|
1731
|
+
return OperationResult(
|
|
1732
|
+
summary=summary,
|
|
1733
|
+
products=tuple(products),
|
|
1734
|
+
warnings=tuple(warnings),
|
|
1735
|
+
pending=tuple(pending),
|
|
1736
|
+
)
|
|
1737
|
+
|
|
1738
|
+
|
|
1739
|
+
__all__ = [
|
|
1740
|
+
"load_pipeline_spec",
|
|
1741
|
+
"pending_stage_references",
|
|
1742
|
+
"resolve_stage_references",
|
|
1743
|
+
"run_pipeline",
|
|
1744
|
+
"stage_reference",
|
|
1745
|
+
]
|