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/executions.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
"""Ciclo de vida enxuto de Execuções."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import tempfile
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Callable, Mapping
|
|
10
|
+
|
|
11
|
+
from .core import ExecutionScheduler, InputValidationError, MissingInputError, OperationCatalog, OperationContext, OperationResult, OperationSpec, WorkspaceStore
|
|
12
|
+
from .fingerprints import execution_fingerprint, execution_snapshot, products_intact, snapshot_hash
|
|
13
|
+
from .status import AWAITING_INPUT, COMPLETED, EVENT_EXECUTION_RESUMED, EVENT_PRODUCT_PUBLISHED, EVENT_UNIT_COMPLETED, EVENT_UNIT_FAILED, EVENT_UNIT_INTERRUPTED, EVENT_UNIT_STARTED, EVENT_UNIT_UNKNOWN, FAILED, RUNNING, UNKNOWN, execution_completion_status, failure_status, is_resumable_execution, is_retryable_execution, is_reusable_execution
|
|
14
|
+
from .telemetry import redact_error
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ExecutionLifecycle:
|
|
18
|
+
"""Ciclo completo de uma Execução sem locks distribuídos ou journals."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
store: WorkspaceStore,
|
|
23
|
+
catalog: OperationCatalog,
|
|
24
|
+
*,
|
|
25
|
+
project_root: Path,
|
|
26
|
+
ai_services: Any = None,
|
|
27
|
+
attachment_service: Any = None,
|
|
28
|
+
evaluations: Any = None,
|
|
29
|
+
products: Any = None,
|
|
30
|
+
scheduler: ExecutionScheduler | None = None,
|
|
31
|
+
download_service: Any = None,
|
|
32
|
+
project_overrides: Mapping[str, Any] | None = None,
|
|
33
|
+
progress: Any = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
if ai_services is None or attachment_service is None:
|
|
36
|
+
from .adapters.ai import AIServiceRegistry, AttachmentProcessingService
|
|
37
|
+
|
|
38
|
+
self.store = store
|
|
39
|
+
self.catalog = catalog
|
|
40
|
+
self.project_root = project_root.resolve()
|
|
41
|
+
self.project_overrides = dict(project_overrides or {})
|
|
42
|
+
self.ai_services = ai_services or AIServiceRegistry()
|
|
43
|
+
self.attachment_service = attachment_service or AttachmentProcessingService()
|
|
44
|
+
self.download_service = download_service
|
|
45
|
+
self.progress = progress
|
|
46
|
+
if evaluations is None:
|
|
47
|
+
from .engines.evaluation import EvaluationLifecycle
|
|
48
|
+
|
|
49
|
+
evaluations = EvaluationLifecycle(
|
|
50
|
+
store,
|
|
51
|
+
ai_services=self.ai_services,
|
|
52
|
+
attachment_service=self.attachment_service,
|
|
53
|
+
scheduler=scheduler,
|
|
54
|
+
)
|
|
55
|
+
self.evaluations = evaluations
|
|
56
|
+
if products is None:
|
|
57
|
+
from .products import ProductLifecycle
|
|
58
|
+
|
|
59
|
+
products = ProductLifecycle(store)
|
|
60
|
+
self.products = products
|
|
61
|
+
self.scheduler = scheduler
|
|
62
|
+
|
|
63
|
+
def run(
|
|
64
|
+
self,
|
|
65
|
+
operation_id: str,
|
|
66
|
+
supplied_params: Mapping[str, Any],
|
|
67
|
+
*,
|
|
68
|
+
force: bool = False,
|
|
69
|
+
reuse_unknown: bool = False,
|
|
70
|
+
) -> dict[str, Any]:
|
|
71
|
+
spec = self.catalog.get(operation_id)
|
|
72
|
+
resolution = spec.resolve(
|
|
73
|
+
supplied_params,
|
|
74
|
+
project_root=self.project_root,
|
|
75
|
+
project_overrides=self.project_overrides,
|
|
76
|
+
)
|
|
77
|
+
if resolution.missing:
|
|
78
|
+
names = ", ".join(str(item["parameter"]) for item in resolution.missing)
|
|
79
|
+
raise MissingInputError(
|
|
80
|
+
f"parâmetros obrigatórios ausentes para {spec.id}: {names}"
|
|
81
|
+
)
|
|
82
|
+
params = dict(resolution.params)
|
|
83
|
+
scenario_id = self.store.ensure_session_scenario(
|
|
84
|
+
str(params.get("scenario") or "base")
|
|
85
|
+
)
|
|
86
|
+
snapshot = execution_snapshot(spec, params, self.project_root, self.store, self.catalog)
|
|
87
|
+
input_hash = snapshot_hash(snapshot)
|
|
88
|
+
cacheable = spec.cacheable(params) if callable(spec.cacheable) else spec.cacheable
|
|
89
|
+
if not force and cacheable:
|
|
90
|
+
existing = self.store.find_execution_by_input(
|
|
91
|
+
operation_id,
|
|
92
|
+
input_hash,
|
|
93
|
+
include_unknown=reuse_unknown,
|
|
94
|
+
)
|
|
95
|
+
if existing and (
|
|
96
|
+
str(existing.get("status")) == FAILED
|
|
97
|
+
or (reuse_unknown and str(existing.get("status")) == UNKNOWN)
|
|
98
|
+
or (
|
|
99
|
+
str(existing.get("status")) == COMPLETED
|
|
100
|
+
and products_intact(existing)
|
|
101
|
+
)
|
|
102
|
+
):
|
|
103
|
+
return self._envelope(existing, reused=True)
|
|
104
|
+
execution_id = self.store.create_execution(
|
|
105
|
+
spec.id,
|
|
106
|
+
params,
|
|
107
|
+
input_hash,
|
|
108
|
+
scenario_id=scenario_id,
|
|
109
|
+
)
|
|
110
|
+
return self._invoke(
|
|
111
|
+
execution_id,
|
|
112
|
+
spec,
|
|
113
|
+
params,
|
|
114
|
+
resources=resolution.resources.as_json(),
|
|
115
|
+
previous_status=None,
|
|
116
|
+
expected_input_hash=input_hash,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def reuse(
|
|
120
|
+
self,
|
|
121
|
+
operation_id: str,
|
|
122
|
+
supplied_params: Mapping[str, Any],
|
|
123
|
+
) -> dict[str, Any] | None:
|
|
124
|
+
"""Retorna somente uma execução concluída com produtos ainda íntegros.
|
|
125
|
+
|
|
126
|
+
Este caminho é deliberadamente somente leitura. Em particular, uma
|
|
127
|
+
tentativa de resolver uma etapa excluída por ``from_stage`` não cria
|
|
128
|
+
cenário nem dispara handler se o resultado anterior não existir.
|
|
129
|
+
"""
|
|
130
|
+
spec = self.catalog.get(operation_id)
|
|
131
|
+
resolution = spec.resolve(
|
|
132
|
+
supplied_params,
|
|
133
|
+
project_root=self.project_root,
|
|
134
|
+
project_overrides=self.project_overrides,
|
|
135
|
+
)
|
|
136
|
+
if resolution.missing:
|
|
137
|
+
return None
|
|
138
|
+
params = dict(resolution.params)
|
|
139
|
+
snapshot = execution_snapshot(spec, params, self.project_root, self.store, self.catalog)
|
|
140
|
+
existing = self.store.find_execution_by_input(
|
|
141
|
+
operation_id,
|
|
142
|
+
snapshot_hash(snapshot),
|
|
143
|
+
)
|
|
144
|
+
if (
|
|
145
|
+
existing is None
|
|
146
|
+
or str(existing.get("status")) != COMPLETED
|
|
147
|
+
or not products_intact(existing)
|
|
148
|
+
):
|
|
149
|
+
return None
|
|
150
|
+
return self._envelope(existing, reused=True)
|
|
151
|
+
|
|
152
|
+
def resume(self, execution_id: str) -> dict[str, Any]:
|
|
153
|
+
execution = self.store.get_execution(execution_id)
|
|
154
|
+
if execution is None:
|
|
155
|
+
raise InputValidationError(f"execução não encontrada: {execution_id}")
|
|
156
|
+
status = str(execution["status"])
|
|
157
|
+
if is_reusable_execution(status):
|
|
158
|
+
spec = self.catalog.get(str(execution["operation_id"]))
|
|
159
|
+
params = spec.resolve_parameters(
|
|
160
|
+
self._stored_params(execution),
|
|
161
|
+
project_root=self.project_root,
|
|
162
|
+
project_overrides=self.project_overrides,
|
|
163
|
+
)
|
|
164
|
+
if status == COMPLETED and (
|
|
165
|
+
execution_fingerprint(spec, params, self.project_root, self.store, self.catalog)
|
|
166
|
+
!= execution["input_hash"]
|
|
167
|
+
or not products_intact(execution)
|
|
168
|
+
):
|
|
169
|
+
return self.run(spec.id, params)
|
|
170
|
+
return self._envelope(execution, reused=True)
|
|
171
|
+
if not is_resumable_execution(status):
|
|
172
|
+
raise InputValidationError(
|
|
173
|
+
f"execução {execution_id} no estado {status!r} não pode ser retomada"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
spec = self.catalog.get(str(execution["operation_id"]))
|
|
177
|
+
params = self._stored_params(execution)
|
|
178
|
+
if is_retryable_execution(status) and self._declares_retry(spec):
|
|
179
|
+
params["retry_failed"] = True
|
|
180
|
+
resolution = spec.resolve(
|
|
181
|
+
params,
|
|
182
|
+
project_root=self.project_root,
|
|
183
|
+
project_overrides=self.project_overrides,
|
|
184
|
+
)
|
|
185
|
+
if resolution.missing:
|
|
186
|
+
names = ", ".join(str(item["parameter"]) for item in resolution.missing)
|
|
187
|
+
raise MissingInputError(
|
|
188
|
+
f"parâmetros obrigatórios ausentes para {spec.id}: {names}"
|
|
189
|
+
)
|
|
190
|
+
params = dict(resolution.params)
|
|
191
|
+
current_hash = execution_fingerprint(spec, params, self.project_root, self.store, self.catalog)
|
|
192
|
+
if current_hash != execution["input_hash"]:
|
|
193
|
+
return self.run(spec.id, params)
|
|
194
|
+
return self._invoke(
|
|
195
|
+
execution_id,
|
|
196
|
+
spec,
|
|
197
|
+
params,
|
|
198
|
+
resources=resolution.resources.as_json(),
|
|
199
|
+
previous_status=status,
|
|
200
|
+
expected_input_hash=current_hash,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def _declares_retry(spec: OperationSpec) -> bool:
|
|
205
|
+
return any(parameter.name == "retry_failed" for parameter in spec.parameters)
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
def _stored_params(execution: Mapping[str, Any]) -> dict[str, Any]:
|
|
209
|
+
try:
|
|
210
|
+
params = json.loads(str(execution["params_json"]))
|
|
211
|
+
except (KeyError, TypeError, json.JSONDecodeError) as exc:
|
|
212
|
+
raise InputValidationError("parâmetros persistidos da execução são inválidos") from exc
|
|
213
|
+
if not isinstance(params, Mapping):
|
|
214
|
+
raise InputValidationError("parâmetros persistidos da execução não são um objeto")
|
|
215
|
+
return dict(params)
|
|
216
|
+
|
|
217
|
+
def _invoke(
|
|
218
|
+
self,
|
|
219
|
+
execution_id: str,
|
|
220
|
+
spec: OperationSpec,
|
|
221
|
+
params: Mapping[str, Any],
|
|
222
|
+
*,
|
|
223
|
+
resources: Mapping[str, Any],
|
|
224
|
+
previous_status: str | None,
|
|
225
|
+
expected_input_hash: str,
|
|
226
|
+
) -> dict[str, Any]:
|
|
227
|
+
resumed = previous_status is not None
|
|
228
|
+
self.store.update_execution(
|
|
229
|
+
execution_id,
|
|
230
|
+
status=RUNNING,
|
|
231
|
+
clear_result=resumed,
|
|
232
|
+
clear_error=resumed,
|
|
233
|
+
clear_finished=resumed,
|
|
234
|
+
started=True,
|
|
235
|
+
)
|
|
236
|
+
if previous_status is not None:
|
|
237
|
+
self.store.record_event(
|
|
238
|
+
execution_id,
|
|
239
|
+
EVENT_EXECUTION_RESUMED,
|
|
240
|
+
status=RUNNING,
|
|
241
|
+
payload={"previous_status": previous_status},
|
|
242
|
+
)
|
|
243
|
+
self.store.record_event(
|
|
244
|
+
execution_id,
|
|
245
|
+
EVENT_UNIT_STARTED,
|
|
246
|
+
status=RUNNING,
|
|
247
|
+
payload={"resources": dict(resources), "resumed": resumed},
|
|
248
|
+
)
|
|
249
|
+
with tempfile.TemporaryDirectory(prefix="argos-stage-") as staging:
|
|
250
|
+
context = self._make_context(
|
|
251
|
+
execution_id,
|
|
252
|
+
spec,
|
|
253
|
+
params,
|
|
254
|
+
staging_root=Path(staging),
|
|
255
|
+
)
|
|
256
|
+
try:
|
|
257
|
+
result = spec.handler(context)
|
|
258
|
+
if context.batch_pending:
|
|
259
|
+
result = replace(
|
|
260
|
+
result,
|
|
261
|
+
pending=result.pending + tuple(context.batch_pending),
|
|
262
|
+
)
|
|
263
|
+
return self._complete(
|
|
264
|
+
execution_id,
|
|
265
|
+
spec,
|
|
266
|
+
params,
|
|
267
|
+
result,
|
|
268
|
+
expected_input_hash=expected_input_hash,
|
|
269
|
+
)
|
|
270
|
+
except MissingInputError as exc:
|
|
271
|
+
return self._await_input(execution_id, spec.id, exc)
|
|
272
|
+
except Exception as exc: # noqa: BLE001 - o ciclo registra a falha completa
|
|
273
|
+
return self._fail(execution_id, spec.id, exc)
|
|
274
|
+
|
|
275
|
+
def _make_context(
|
|
276
|
+
self,
|
|
277
|
+
execution_id: str,
|
|
278
|
+
spec: OperationSpec,
|
|
279
|
+
params: Mapping[str, Any],
|
|
280
|
+
*,
|
|
281
|
+
staging_root: Path | None = None,
|
|
282
|
+
batch_pending=None,
|
|
283
|
+
resource_overrides=None,
|
|
284
|
+
) -> OperationContext:
|
|
285
|
+
batch_pending = [] if batch_pending is None else batch_pending
|
|
286
|
+
resource_overrides = {} if resource_overrides is None else resource_overrides
|
|
287
|
+
return OperationContext(
|
|
288
|
+
store=self.store,
|
|
289
|
+
execution_id=execution_id,
|
|
290
|
+
operation=spec,
|
|
291
|
+
params=params,
|
|
292
|
+
project_root=self.project_root,
|
|
293
|
+
ai_services=self.ai_services,
|
|
294
|
+
attachment_service=self.attachment_service,
|
|
295
|
+
evaluations=self.evaluations,
|
|
296
|
+
scheduler=self.scheduler,
|
|
297
|
+
download_service=self.download_service,
|
|
298
|
+
sub_operation=self._sub_operation_for(
|
|
299
|
+
execution_id,
|
|
300
|
+
staging_root=staging_root,
|
|
301
|
+
batch_pending=batch_pending,
|
|
302
|
+
resource_overrides=resource_overrides,
|
|
303
|
+
),
|
|
304
|
+
run_operation=self._run_pipeline_stage,
|
|
305
|
+
reuse_operation=self.reuse,
|
|
306
|
+
catalog=self.catalog,
|
|
307
|
+
progress=self.progress,
|
|
308
|
+
project_overrides=dict(self.project_overrides),
|
|
309
|
+
staging_root=staging_root,
|
|
310
|
+
resource_overrides=resource_overrides,
|
|
311
|
+
batch_pending=batch_pending,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
def _run_pipeline_stage(
|
|
315
|
+
self,
|
|
316
|
+
operation_id: str,
|
|
317
|
+
supplied_params: Mapping[str, Any],
|
|
318
|
+
) -> dict[str, Any]:
|
|
319
|
+
"""Executa uma etapa e conserva resultados indeterminados no retry implícito."""
|
|
320
|
+
return self.run(operation_id, supplied_params, reuse_unknown=True)
|
|
321
|
+
|
|
322
|
+
def _sub_operation_for(
|
|
323
|
+
self,
|
|
324
|
+
execution_id: str,
|
|
325
|
+
*,
|
|
326
|
+
staging_root: Path | None = None,
|
|
327
|
+
batch_pending=None,
|
|
328
|
+
resource_overrides=None,
|
|
329
|
+
) -> Callable[[str, Mapping[str, Any]], OperationResult]:
|
|
330
|
+
def sub_operation(
|
|
331
|
+
operation_id: str,
|
|
332
|
+
supplied_params: Mapping[str, Any],
|
|
333
|
+
) -> OperationResult:
|
|
334
|
+
spec = self.catalog.get(operation_id)
|
|
335
|
+
params = spec.resolve_parameters(
|
|
336
|
+
supplied_params,
|
|
337
|
+
project_root=self.project_root,
|
|
338
|
+
project_overrides=self.project_overrides,
|
|
339
|
+
)
|
|
340
|
+
context = self._make_context(
|
|
341
|
+
execution_id,
|
|
342
|
+
spec,
|
|
343
|
+
params,
|
|
344
|
+
staging_root=staging_root,
|
|
345
|
+
batch_pending=batch_pending,
|
|
346
|
+
resource_overrides=resource_overrides,
|
|
347
|
+
)
|
|
348
|
+
result = spec.handler(context)
|
|
349
|
+
spec.validate_result(params, result, project_root=self.project_root)
|
|
350
|
+
return result
|
|
351
|
+
|
|
352
|
+
return sub_operation
|
|
353
|
+
|
|
354
|
+
@classmethod
|
|
355
|
+
def _result_from_envelope(cls, raw_result: Any) -> OperationResult:
|
|
356
|
+
"""Reconstrói o resultado persistido para composição idempotente."""
|
|
357
|
+
if isinstance(raw_result, Mapping):
|
|
358
|
+
result = dict(raw_result)
|
|
359
|
+
else:
|
|
360
|
+
try:
|
|
361
|
+
result = json.loads(str(raw_result or "{}"))
|
|
362
|
+
except (TypeError, ValueError):
|
|
363
|
+
result = {}
|
|
364
|
+
if not isinstance(result, Mapping):
|
|
365
|
+
result = {}
|
|
366
|
+
from .contracts import ProductDraft, ScenarioDraft
|
|
367
|
+
|
|
368
|
+
def _content(path: Any) -> Any:
|
|
369
|
+
return Path(str(path)) if path else None
|
|
370
|
+
|
|
371
|
+
return OperationResult(
|
|
372
|
+
summary=dict(result.get("summary") or {}),
|
|
373
|
+
products=tuple(
|
|
374
|
+
ProductDraft(
|
|
375
|
+
kind=str(item.get("kind") or ""),
|
|
376
|
+
path=Path(str(item["path"])) if item.get("path") else None,
|
|
377
|
+
content=_content(item.get("path")),
|
|
378
|
+
media_type=str(item.get("media_type") or "application/json"),
|
|
379
|
+
metadata=dict(item.get("metadata") or {}),
|
|
380
|
+
)
|
|
381
|
+
for item in result.get("products") or ()
|
|
382
|
+
if isinstance(item, Mapping)
|
|
383
|
+
),
|
|
384
|
+
scenarios=tuple(
|
|
385
|
+
ScenarioDraft(
|
|
386
|
+
id=str(item["id"]),
|
|
387
|
+
name=item.get("name"),
|
|
388
|
+
parent_id=item.get("parent_id"),
|
|
389
|
+
kind=item.get("kind"),
|
|
390
|
+
input_hash=item.get("input_hash"),
|
|
391
|
+
metadata=dict(item.get("metadata") or {}),
|
|
392
|
+
)
|
|
393
|
+
for item in result.get("scenarios") or ()
|
|
394
|
+
if isinstance(item, Mapping) and item.get("id")
|
|
395
|
+
),
|
|
396
|
+
warnings=tuple(str(item) for item in result.get("warnings") or ()),
|
|
397
|
+
pending=tuple(
|
|
398
|
+
dict(item) for item in result.get("pending") or () if isinstance(item, Mapping)
|
|
399
|
+
),
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
def _complete(
|
|
403
|
+
self,
|
|
404
|
+
execution_id: str,
|
|
405
|
+
spec: OperationSpec,
|
|
406
|
+
params: Mapping[str, Any],
|
|
407
|
+
result: OperationResult,
|
|
408
|
+
*,
|
|
409
|
+
expected_input_hash: str,
|
|
410
|
+
) -> dict[str, Any]:
|
|
411
|
+
spec.validate_result(params, result, project_root=self.project_root)
|
|
412
|
+
|
|
413
|
+
def validate_snapshot() -> None:
|
|
414
|
+
current_hash = execution_fingerprint(
|
|
415
|
+
spec, params, self.project_root, self.store, self.catalog
|
|
416
|
+
)
|
|
417
|
+
if current_hash != expected_input_hash:
|
|
418
|
+
raise InputValidationError(
|
|
419
|
+
"entradas ou implementação mudaram durante execução; produtos não foram promovidos"
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
products = self.products.publish(
|
|
423
|
+
execution_id,
|
|
424
|
+
spec.id,
|
|
425
|
+
result.products,
|
|
426
|
+
validate_snapshot=validate_snapshot,
|
|
427
|
+
)
|
|
428
|
+
with self.store._lock:
|
|
429
|
+
self.store.connection.execute("BEGIN IMMEDIATE")
|
|
430
|
+
try:
|
|
431
|
+
validate_snapshot()
|
|
432
|
+
envelope = self._finalize(execution_id, spec, result, products)
|
|
433
|
+
self.store.connection.commit()
|
|
434
|
+
return envelope
|
|
435
|
+
except Exception:
|
|
436
|
+
self.store.connection.rollback()
|
|
437
|
+
raise
|
|
438
|
+
|
|
439
|
+
def _finalize(
|
|
440
|
+
self,
|
|
441
|
+
execution_id: str,
|
|
442
|
+
spec: OperationSpec,
|
|
443
|
+
result: OperationResult,
|
|
444
|
+
products: list[dict[str, Any]],
|
|
445
|
+
) -> dict[str, Any]:
|
|
446
|
+
scenarios = [
|
|
447
|
+
self.store.publish_scenario(draft, execution_id=execution_id)
|
|
448
|
+
for draft in result.scenarios
|
|
449
|
+
]
|
|
450
|
+
for published in products:
|
|
451
|
+
self.store.record_event(
|
|
452
|
+
execution_id,
|
|
453
|
+
EVENT_PRODUCT_PUBLISHED,
|
|
454
|
+
status=COMPLETED,
|
|
455
|
+
payload=published,
|
|
456
|
+
)
|
|
457
|
+
result_json = result.as_json()
|
|
458
|
+
result_json = self.store.merge_evaluation_into_result(
|
|
459
|
+
execution_id, result_json
|
|
460
|
+
)
|
|
461
|
+
result_json["scenarios"] = scenarios
|
|
462
|
+
result_json["products"] = products
|
|
463
|
+
final_status = execution_completion_status(bool(result.pending))
|
|
464
|
+
if any(item.get("cause") == "unknown" for item in result.pending):
|
|
465
|
+
final_status = UNKNOWN
|
|
466
|
+
self.store.update_execution(
|
|
467
|
+
execution_id,
|
|
468
|
+
status=final_status,
|
|
469
|
+
result=result_json,
|
|
470
|
+
clear_error=True,
|
|
471
|
+
finished=True,
|
|
472
|
+
)
|
|
473
|
+
self.store.record_event(
|
|
474
|
+
execution_id,
|
|
475
|
+
EVENT_UNIT_COMPLETED if final_status == COMPLETED else EVENT_UNIT_INTERRUPTED,
|
|
476
|
+
status=final_status,
|
|
477
|
+
payload={"warnings": list(result.warnings), "pending": list(result.pending)},
|
|
478
|
+
)
|
|
479
|
+
return {
|
|
480
|
+
"id": execution_id,
|
|
481
|
+
"operation_id": spec.id,
|
|
482
|
+
"status": final_status,
|
|
483
|
+
"reused": False,
|
|
484
|
+
"result": result_json,
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
def _await_input(
|
|
488
|
+
self,
|
|
489
|
+
execution_id: str,
|
|
490
|
+
operation_id: str,
|
|
491
|
+
exc: MissingInputError,
|
|
492
|
+
) -> dict[str, Any]:
|
|
493
|
+
error = str(redact_error(str(exc)))
|
|
494
|
+
self.store.update_execution(
|
|
495
|
+
execution_id,
|
|
496
|
+
status=AWAITING_INPUT,
|
|
497
|
+
error=error,
|
|
498
|
+
finished=True,
|
|
499
|
+
)
|
|
500
|
+
self.store.record_event(
|
|
501
|
+
execution_id,
|
|
502
|
+
EVENT_UNIT_INTERRUPTED,
|
|
503
|
+
status=AWAITING_INPUT,
|
|
504
|
+
payload={"error": error, "pending": []},
|
|
505
|
+
)
|
|
506
|
+
return {
|
|
507
|
+
"id": execution_id,
|
|
508
|
+
"operation_id": operation_id,
|
|
509
|
+
"status": AWAITING_INPUT,
|
|
510
|
+
"reused": False,
|
|
511
|
+
"error": error,
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
def _fail(
|
|
515
|
+
self,
|
|
516
|
+
execution_id: str,
|
|
517
|
+
operation_id: str,
|
|
518
|
+
exc: Exception,
|
|
519
|
+
) -> dict[str, Any]:
|
|
520
|
+
error = str(redact_error(f"{type(exc).__name__}: {exc}"))
|
|
521
|
+
final_status = failure_status(exc)
|
|
522
|
+
event_type = EVENT_UNIT_UNKNOWN if final_status == UNKNOWN else EVENT_UNIT_FAILED
|
|
523
|
+
self.store.update_execution(
|
|
524
|
+
execution_id,
|
|
525
|
+
status=final_status,
|
|
526
|
+
error=error,
|
|
527
|
+
finished=True,
|
|
528
|
+
)
|
|
529
|
+
self.store.record_event(
|
|
530
|
+
execution_id,
|
|
531
|
+
event_type,
|
|
532
|
+
status=final_status,
|
|
533
|
+
payload={"error": error},
|
|
534
|
+
)
|
|
535
|
+
return {
|
|
536
|
+
"id": execution_id,
|
|
537
|
+
"operation_id": operation_id,
|
|
538
|
+
"status": final_status,
|
|
539
|
+
"reused": False,
|
|
540
|
+
"error": error,
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
@staticmethod
|
|
544
|
+
def _envelope(execution: Mapping[str, Any], *, reused: bool) -> dict[str, Any]:
|
|
545
|
+
status = str(execution.get("status") or UNKNOWN)
|
|
546
|
+
envelope: dict[str, Any] = {
|
|
547
|
+
"id": str(execution["id"]),
|
|
548
|
+
"operation_id": str(execution["operation_id"]),
|
|
549
|
+
"status": status,
|
|
550
|
+
"reused": reused,
|
|
551
|
+
}
|
|
552
|
+
raw_result = execution.get("result_json")
|
|
553
|
+
if raw_result not in (None, ""):
|
|
554
|
+
try:
|
|
555
|
+
result = json.loads(str(raw_result))
|
|
556
|
+
except json.JSONDecodeError as exc:
|
|
557
|
+
raise InputValidationError(
|
|
558
|
+
f"resultado persistido inválido na execução {execution['id']}"
|
|
559
|
+
) from exc
|
|
560
|
+
envelope["result"] = result
|
|
561
|
+
if execution.get("error") not in (None, ""):
|
|
562
|
+
envelope["error"] = str(execution["error"])
|
|
563
|
+
if status == RUNNING:
|
|
564
|
+
envelope["in_progress"] = True
|
|
565
|
+
return envelope
|