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/scheduler.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Scheduler compartilhado: dependências e orçamento de recursos."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
|
|
7
|
+
from collections import deque
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Callable, Iterable, Mapping
|
|
10
|
+
|
|
11
|
+
from .errors import ArgosError, InputValidationError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
from .contracts import ResourceProfile
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ScheduledUnit:
|
|
18
|
+
id: str
|
|
19
|
+
handler: Callable[[], Any]
|
|
20
|
+
resources: ResourceProfile = field(default_factory=ResourceProfile)
|
|
21
|
+
event_meta: Mapping[str, Any] = field(default_factory=dict)
|
|
22
|
+
dependencies: tuple[str, ...] = ()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class BatchOutcome:
|
|
27
|
+
"""Resultado ordenado de um lote, com contagens e erros prontos.
|
|
28
|
+
|
|
29
|
+
``units`` preserva o envelope de cada unidade na ordem de entrada
|
|
30
|
+
(``{"status": "completed", "result": <dict>}`` ou
|
|
31
|
+
``{"status": "failed", "error": <str>}``); ``completed`` e ``failed``
|
|
32
|
+
são as vistas filtradas e ``errors`` as mensagens das unidades falhas,
|
|
33
|
+
para que os handlers não reimplementem a mesma contagem nem a política
|
|
34
|
+
de erros.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
units: tuple[Mapping[str, Any], ...]
|
|
38
|
+
completed: tuple[Mapping[str, Any], ...]
|
|
39
|
+
failed: tuple[Mapping[str, Any], ...]
|
|
40
|
+
errors: tuple[str, ...]
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def total(self) -> int:
|
|
44
|
+
return len(self.units)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ExecutionScheduler:
|
|
48
|
+
"""Scheduler pequeno e compartilhado para tarefas independentes."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
*,
|
|
53
|
+
cpu: int | None = None,
|
|
54
|
+
memory_mb: int = 1024,
|
|
55
|
+
network_slots: int = 4,
|
|
56
|
+
estimated_tokens: int = 100_000,
|
|
57
|
+
) -> None:
|
|
58
|
+
self.cpu = max(1, cpu or (os.cpu_count() or 1))
|
|
59
|
+
self.memory_mb = max(1, memory_mb)
|
|
60
|
+
self.network_slots = max(0, network_slots)
|
|
61
|
+
self.estimated_tokens = max(0, estimated_tokens)
|
|
62
|
+
|
|
63
|
+
def run(self, units: Iterable[ScheduledUnit]) -> dict[str, Any]:
|
|
64
|
+
units = tuple(units)
|
|
65
|
+
by_id = {unit.id: unit for unit in units}
|
|
66
|
+
if len(by_id) != len(units):
|
|
67
|
+
raise InputValidationError("id de unidade repetido no scheduler")
|
|
68
|
+
for unit in units:
|
|
69
|
+
unknown = sorted(set(unit.dependencies) - set(by_id))
|
|
70
|
+
if unknown:
|
|
71
|
+
raise InputValidationError(
|
|
72
|
+
f"dependências desconhecidas em {unit.id}: {', '.join(unknown)}"
|
|
73
|
+
)
|
|
74
|
+
if unit.id in unit.dependencies:
|
|
75
|
+
raise InputValidationError(f"unidade {unit.id} depende de si mesma")
|
|
76
|
+
remaining = {unit.id: set(unit.dependencies) for unit in units}
|
|
77
|
+
acyclic = {unit_id: set(value) for unit_id, value in remaining.items()}
|
|
78
|
+
while acyclic:
|
|
79
|
+
ready = {unit_id for unit_id, deps in acyclic.items() if not deps}
|
|
80
|
+
if not ready:
|
|
81
|
+
raise InputValidationError("ciclo nas dependências do scheduler")
|
|
82
|
+
for unit_id in ready:
|
|
83
|
+
acyclic.pop(unit_id)
|
|
84
|
+
for deps in acyclic.values():
|
|
85
|
+
deps.difference_update(ready)
|
|
86
|
+
pending = deque(units)
|
|
87
|
+
available = ResourceProfile(
|
|
88
|
+
cpu=self.cpu,
|
|
89
|
+
memory_mb=self.memory_mb,
|
|
90
|
+
network_slots=self.network_slots,
|
|
91
|
+
estimated_tokens=self.estimated_tokens,
|
|
92
|
+
)
|
|
93
|
+
futures: dict[Future[Any], ScheduledUnit] = {}
|
|
94
|
+
results: dict[str, Any] = {}
|
|
95
|
+
|
|
96
|
+
def fits(profile: ResourceProfile) -> bool:
|
|
97
|
+
return (
|
|
98
|
+
profile.cpu <= available.cpu
|
|
99
|
+
and profile.memory_mb <= available.memory_mb
|
|
100
|
+
and profile.network_slots <= available.network_slots
|
|
101
|
+
and profile.estimated_tokens <= available.estimated_tokens
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def reserve(profile: ResourceProfile, sign: int) -> None:
|
|
105
|
+
nonlocal available
|
|
106
|
+
available = ResourceProfile(
|
|
107
|
+
cpu=available.cpu - sign * profile.cpu,
|
|
108
|
+
memory_mb=available.memory_mb - sign * profile.memory_mb,
|
|
109
|
+
network_slots=available.network_slots - sign * profile.network_slots,
|
|
110
|
+
estimated_tokens=available.estimated_tokens - sign * profile.estimated_tokens,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
with ThreadPoolExecutor(max_workers=self.cpu, thread_name_prefix="argos") as executor:
|
|
114
|
+
while pending or futures:
|
|
115
|
+
started = False
|
|
116
|
+
for _ in range(len(pending)):
|
|
117
|
+
unit = pending.popleft()
|
|
118
|
+
profile = unit.resources
|
|
119
|
+
if profile.cpu > self.cpu or profile.memory_mb > self.memory_mb or profile.network_slots > self.network_slots or profile.estimated_tokens > self.estimated_tokens:
|
|
120
|
+
raise ArgosError(f"unidade {unit.id} excede o orçamento compartilhado")
|
|
121
|
+
if remaining[unit.id]:
|
|
122
|
+
pending.append(unit)
|
|
123
|
+
elif fits(profile):
|
|
124
|
+
reserve(profile, 1)
|
|
125
|
+
futures[executor.submit(unit.handler)] = unit
|
|
126
|
+
started = True
|
|
127
|
+
else:
|
|
128
|
+
pending.append(unit)
|
|
129
|
+
if not futures:
|
|
130
|
+
if pending and not started:
|
|
131
|
+
raise ArgosError("scheduler não conseguiu reservar recursos para as unidades")
|
|
132
|
+
continue
|
|
133
|
+
done, _ = wait(tuple(futures), return_when=FIRST_COMPLETED)
|
|
134
|
+
for future in done:
|
|
135
|
+
unit = futures.pop(future)
|
|
136
|
+
reserve(unit.resources, -1)
|
|
137
|
+
results[unit.id] = future.result()
|
|
138
|
+
for dependencies in remaining.values():
|
|
139
|
+
dependencies.discard(unit.id)
|
|
140
|
+
return results
|
|
141
|
+
|
|
142
|
+
|
argos/status.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Vocabulário de estados, classificações, transições e eventos.
|
|
2
|
+
|
|
3
|
+
Um único dono das strings de política de Execuções e Planos: estado inicial,
|
|
4
|
+
estados terminais, retomáveis, repetíveis, reutilizáveis e malsucedidos, o
|
|
5
|
+
resultado agregado de um Plano, a interpretação do CLI e os nomes de eventos
|
|
6
|
+
com granularidade inequívoca (``unit_*`` = ciclo da Execução;
|
|
7
|
+
``batch_unit_*`` = unidades agendadas do lote). Estados de avaliação de IA
|
|
8
|
+
ficam fora do escopo.
|
|
9
|
+
|
|
10
|
+
Não é um arquivo de constantes: as classificações e transições concentram
|
|
11
|
+
comportamento consultado pelos consumidores, sem conjuntos redeclarados.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TYPE_CHECKING, Any, Iterable, Mapping
|
|
19
|
+
|
|
20
|
+
from .contracts import OperationResult, ProductDraft, sha256_file
|
|
21
|
+
from .errors import InputValidationError
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from .core import OperationContext, WorkspaceStore
|
|
25
|
+
|
|
26
|
+
# --- Estados de Execução ---
|
|
27
|
+
PLANNED = "planned"
|
|
28
|
+
RUNNING = "running"
|
|
29
|
+
COMPLETED = "completed"
|
|
30
|
+
FAILED = "failed"
|
|
31
|
+
UNKNOWN = "unknown"
|
|
32
|
+
AWAITING_INPUT = "awaiting_input"
|
|
33
|
+
CANCELLED = "cancelled"
|
|
34
|
+
|
|
35
|
+
INITIAL_EXECUTION_STATUS = PLANNED
|
|
36
|
+
RESUMABLE_EXECUTION_STATUSES = frozenset({PLANNED, AWAITING_INPUT, FAILED, UNKNOWN})
|
|
37
|
+
RETRYABLE_EXECUTION_STATUSES = frozenset({FAILED, UNKNOWN})
|
|
38
|
+
REUSABLE_EXECUTION_STATUSES = frozenset({COMPLETED, RUNNING})
|
|
39
|
+
EXECUTION_EXIT_SUCCESS_STATUSES = frozenset({COMPLETED, AWAITING_INPUT})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_resumable_execution(status: str) -> bool:
|
|
43
|
+
"""Uma Execução nesse estado pode ser retomada pela mesma identidade."""
|
|
44
|
+
return status in RESUMABLE_EXECUTION_STATUSES
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_retryable_execution(status: str) -> bool:
|
|
48
|
+
"""Repetir nesse estado pode reenviar chamadas externas (retry autorizado)."""
|
|
49
|
+
return status in RETRYABLE_EXECUTION_STATUSES
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_reusable_execution(status: str) -> bool:
|
|
53
|
+
"""O resultado desse estado pode ser reutilizado sem nova execução."""
|
|
54
|
+
return status in REUSABLE_EXECUTION_STATUSES
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_execution_exit_success(status: str) -> bool:
|
|
58
|
+
"""O CLI trata esse estado como saída de sucesso (0)."""
|
|
59
|
+
return status in EXECUTION_EXIT_SUCCESS_STATUSES
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def execution_completion_status(has_pending: bool) -> str:
|
|
63
|
+
"""Estado final de uma Execução que concluiu o handler."""
|
|
64
|
+
return AWAITING_INPUT if has_pending else COMPLETED
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def failure_status(exception: Any) -> str:
|
|
68
|
+
"""Classifica uma falha: ``unknown`` se o envio externo é indeterminado."""
|
|
69
|
+
return UNKNOWN if getattr(exception, "unknown", False) else FAILED
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# --- Estados de unidade de Plano ---
|
|
73
|
+
UNIT_READY = "ready"
|
|
74
|
+
UNIT_RUNNING = RUNNING
|
|
75
|
+
UNIT_COMPLETED = COMPLETED
|
|
76
|
+
UNIT_FAILED = FAILED
|
|
77
|
+
UNIT_UNKNOWN = UNKNOWN
|
|
78
|
+
UNIT_AWAITING_INPUT = AWAITING_INPUT
|
|
79
|
+
UNIT_BLOCKED = "blocked"
|
|
80
|
+
UNIT_CANCELLED = "cancelled"
|
|
81
|
+
|
|
82
|
+
TERMINAL_UNIT_STATUSES = frozenset(
|
|
83
|
+
{
|
|
84
|
+
UNIT_COMPLETED,
|
|
85
|
+
UNIT_FAILED,
|
|
86
|
+
UNIT_UNKNOWN,
|
|
87
|
+
UNIT_AWAITING_INPUT,
|
|
88
|
+
UNIT_BLOCKED,
|
|
89
|
+
UNIT_CANCELLED,
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
UNSUCCESSFUL_UNIT_STATUSES = frozenset(
|
|
93
|
+
{UNIT_FAILED, UNIT_UNKNOWN, UNIT_AWAITING_INPUT, UNIT_BLOCKED, UNIT_CANCELLED}
|
|
94
|
+
)
|
|
95
|
+
RESET_UNIT_STATUSES = frozenset(
|
|
96
|
+
{UNIT_FAILED, UNIT_UNKNOWN, UNIT_RUNNING, UNIT_AWAITING_INPUT, UNIT_BLOCKED, UNIT_CANCELLED}
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def is_terminal_unit(status: str) -> bool:
|
|
101
|
+
"""Unidade que não é candidata a execução."""
|
|
102
|
+
return status in TERMINAL_UNIT_STATUSES
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def is_unsuccessful_unit(status: str) -> bool:
|
|
106
|
+
"""Unidade que bloqueia dependentes."""
|
|
107
|
+
return status in UNSUCCESSFUL_UNIT_STATUSES
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def unit_requires_reset(status: str) -> bool:
|
|
111
|
+
"""Unidade voltada a ``ready`` numa nova execução do Plano."""
|
|
112
|
+
return status in RESET_UNIT_STATUSES
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# --- Estados de Plano ---
|
|
116
|
+
PLAN_READY = "ready"
|
|
117
|
+
PLAN_RUNNING = RUNNING
|
|
118
|
+
PLAN_COMPLETED = COMPLETED
|
|
119
|
+
PLAN_FAILED = FAILED
|
|
120
|
+
PLAN_AWAITING_INPUT = AWAITING_INPUT
|
|
121
|
+
PLAN_EXIT_SUCCESS_STATUSES = frozenset({PLAN_READY, PLAN_AWAITING_INPUT, PLAN_RUNNING, PLAN_COMPLETED})
|
|
122
|
+
PLAN_EXECUTION_SUCCESS_STATUSES = frozenset({PLAN_COMPLETED, PLAN_AWAITING_INPUT})
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def is_plan_exit_success(status: str) -> bool:
|
|
126
|
+
"""Criar/validar um Plano nesse estado é saída de sucesso (0)."""
|
|
127
|
+
return status in PLAN_EXIT_SUCCESS_STATUSES
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def is_plan_execution_exit_success(status: str) -> bool:
|
|
131
|
+
"""Executar um Plano terminando nesse estado é saída de sucesso (0)."""
|
|
132
|
+
return status in PLAN_EXECUTION_SUCCESS_STATUSES
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def plan_aggregate_status(unit_statuses: Iterable[str]) -> str:
|
|
136
|
+
"""Resultado agregado do Plano a partir dos estados das unidades."""
|
|
137
|
+
statuses = set(unit_statuses)
|
|
138
|
+
if statuses <= {UNIT_COMPLETED}:
|
|
139
|
+
return PLAN_COMPLETED
|
|
140
|
+
if statuses & {UNIT_AWAITING_INPUT, UNIT_BLOCKED, UNIT_CANCELLED}:
|
|
141
|
+
return PLAN_AWAITING_INPUT
|
|
142
|
+
return PLAN_FAILED
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# --- Eventos ---
|
|
146
|
+
EVENT_EXECUTION_CREATED = "execution_created"
|
|
147
|
+
EVENT_EXECUTION_RESUMED = "execution_resumed"
|
|
148
|
+
EVENT_UNIT_STARTED = "unit_started"
|
|
149
|
+
EVENT_UNIT_COMPLETED = "unit_completed"
|
|
150
|
+
EVENT_UNIT_INTERRUPTED = "unit_interrupted"
|
|
151
|
+
EVENT_UNIT_FAILED = "unit_failed"
|
|
152
|
+
EVENT_UNIT_UNKNOWN = "unit_unknown"
|
|
153
|
+
EVENT_PRODUCT_PUBLISHED = "product_published"
|
|
154
|
+
EVENT_BATCH_UNIT_STARTED = "batch_unit_started"
|
|
155
|
+
EVENT_BATCH_UNIT_COMPLETED = "batch_unit_completed"
|
|
156
|
+
EVENT_BATCH_UNIT_FAILED = "batch_unit_failed"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def backup_control(context: OperationContext) -> OperationResult:
|
|
160
|
+
staging = context.stage_file(".sqlite")
|
|
161
|
+
snapshot = context.store.backup(staging)
|
|
162
|
+
return OperationResult(
|
|
163
|
+
summary={key: value for key, value in snapshot.items() if key != "path"},
|
|
164
|
+
products=(
|
|
165
|
+
ProductDraft(
|
|
166
|
+
"control-backup",
|
|
167
|
+
context.path(context.params["output"]),
|
|
168
|
+
staging,
|
|
169
|
+
"application/vnd.sqlite3",
|
|
170
|
+
{"must_be_new": True},
|
|
171
|
+
),
|
|
172
|
+
),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def restore_control(context: OperationContext) -> OperationResult:
|
|
177
|
+
from .store import WorkspaceStore
|
|
178
|
+
|
|
179
|
+
staging = context.stage_file(".sqlite")
|
|
180
|
+
snapshot = WorkspaceStore.restore(context.path(context.params["backup"]), staging)
|
|
181
|
+
if snapshot["schema_version"] > WorkspaceStore.SCHEMA_VERSION:
|
|
182
|
+
raise InputValidationError("backup usa schema mais novo que o suportado")
|
|
183
|
+
return OperationResult(
|
|
184
|
+
summary={key: value for key, value in snapshot.items() if key != "path"},
|
|
185
|
+
products=(
|
|
186
|
+
ProductDraft(
|
|
187
|
+
"control-restored",
|
|
188
|
+
context.path(context.params["output"]),
|
|
189
|
+
staging,
|
|
190
|
+
"application/vnd.sqlite3",
|
|
191
|
+
{"must_be_new": True},
|
|
192
|
+
),
|
|
193
|
+
),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def inspect_product_states(
|
|
198
|
+
store: WorkspaceStore,
|
|
199
|
+
*,
|
|
200
|
+
catalog: Any,
|
|
201
|
+
project_root: Path,
|
|
202
|
+
project_overrides: Mapping[str, Any] | None = None,
|
|
203
|
+
scenario: str | None = "base",
|
|
204
|
+
artifact_id: str | None = None,
|
|
205
|
+
) -> list[dict[str, Any]]:
|
|
206
|
+
"""Confere integridade e atualidade dos produtos pela identidade da execução."""
|
|
207
|
+
from .fingerprints import execution_fingerprint
|
|
208
|
+
|
|
209
|
+
rows = store._query(
|
|
210
|
+
"""
|
|
211
|
+
SELECT p.*, e.scenario_id, e.status AS execution_status,
|
|
212
|
+
e.operation_id AS execution_operation_id,
|
|
213
|
+
e.input_hash AS execution_input_hash,
|
|
214
|
+
e.params_json AS execution_params_json
|
|
215
|
+
FROM product p
|
|
216
|
+
JOIN execution e ON e.id = p.execution_id
|
|
217
|
+
WHERE e.fiscalizacao_id = ?
|
|
218
|
+
AND (? IS NULL OR e.scenario_id = ?)
|
|
219
|
+
AND (? IS NULL OR p.id = ?)
|
|
220
|
+
ORDER BY p.created_at, p.id
|
|
221
|
+
""",
|
|
222
|
+
(store.fiscalizacao_id, scenario, scenario, artifact_id, artifact_id),
|
|
223
|
+
)
|
|
224
|
+
states = []
|
|
225
|
+
for row in rows:
|
|
226
|
+
path = Path(str(row["path"]))
|
|
227
|
+
reasons: list[str] = []
|
|
228
|
+
try:
|
|
229
|
+
exists = path.is_file()
|
|
230
|
+
except OSError:
|
|
231
|
+
exists = False
|
|
232
|
+
reasons.append("unverifiable")
|
|
233
|
+
if not exists:
|
|
234
|
+
reasons.append("missing_output")
|
|
235
|
+
intact = False
|
|
236
|
+
else:
|
|
237
|
+
try:
|
|
238
|
+
intact = sha256_file(path) == str(row["sha256"])
|
|
239
|
+
except OSError:
|
|
240
|
+
intact = False
|
|
241
|
+
reasons.append("unverifiable")
|
|
242
|
+
if not intact and "unverifiable" not in reasons:
|
|
243
|
+
reasons.append("changed_output")
|
|
244
|
+
|
|
245
|
+
execution_status = str(row["execution_status"])
|
|
246
|
+
input_current = False
|
|
247
|
+
if execution_status != COMPLETED:
|
|
248
|
+
reasons.append("execution_not_completed")
|
|
249
|
+
else:
|
|
250
|
+
try:
|
|
251
|
+
spec = catalog.get(str(row["execution_operation_id"]))
|
|
252
|
+
stored_params = json.loads(str(row["execution_params_json"]))
|
|
253
|
+
if not isinstance(stored_params, Mapping):
|
|
254
|
+
raise InputValidationError("parâmetros persistidos não são um objeto")
|
|
255
|
+
resolved = spec.resolve_parameters(
|
|
256
|
+
stored_params,
|
|
257
|
+
project_root=project_root,
|
|
258
|
+
project_overrides=project_overrides,
|
|
259
|
+
)
|
|
260
|
+
input_current = execution_fingerprint(
|
|
261
|
+
spec,
|
|
262
|
+
resolved,
|
|
263
|
+
project_root,
|
|
264
|
+
store,
|
|
265
|
+
catalog,
|
|
266
|
+
) == str(row["execution_input_hash"])
|
|
267
|
+
if not input_current:
|
|
268
|
+
reasons.append("changed_input")
|
|
269
|
+
except Exception: # noqa: BLE001 - relata este item não verificável e segue
|
|
270
|
+
reasons.append("unverifiable")
|
|
271
|
+
|
|
272
|
+
current = intact and input_current and execution_status == COMPLETED
|
|
273
|
+
states.append(
|
|
274
|
+
{
|
|
275
|
+
"artifact": dict(row),
|
|
276
|
+
"integrity": intact,
|
|
277
|
+
"input_current": input_current,
|
|
278
|
+
"current": current,
|
|
279
|
+
"reasons": list(dict.fromkeys(reasons)),
|
|
280
|
+
}
|
|
281
|
+
)
|
|
282
|
+
return states
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def inspect_artifacts(context: OperationContext) -> OperationResult:
|
|
286
|
+
scenario = None if context.params.get("all_scenarios") else context.params.get("scenario", "base")
|
|
287
|
+
states = inspect_product_states(
|
|
288
|
+
context.store,
|
|
289
|
+
catalog=context.catalog,
|
|
290
|
+
project_root=context.project_root,
|
|
291
|
+
project_overrides=context.project_overrides,
|
|
292
|
+
scenario=scenario,
|
|
293
|
+
artifact_id=context.params.get("produto"),
|
|
294
|
+
)
|
|
295
|
+
executions = [
|
|
296
|
+
{
|
|
297
|
+
"id": execution["id"],
|
|
298
|
+
"operation": execution["operation_id"],
|
|
299
|
+
"status": execution["status"],
|
|
300
|
+
}
|
|
301
|
+
for execution in context.store.list_executions()
|
|
302
|
+
if execution["id"] != context.execution_id and execution["status"] != COMPLETED
|
|
303
|
+
]
|
|
304
|
+
summary = {
|
|
305
|
+
"artifacts": states,
|
|
306
|
+
"executions": executions,
|
|
307
|
+
"current": sum(item["current"] for item in states),
|
|
308
|
+
"outdated": sum(not item["current"] for item in states),
|
|
309
|
+
}
|
|
310
|
+
return OperationResult(
|
|
311
|
+
summary=summary,
|
|
312
|
+
products=(ProductDraft("artifact-state", context.path(context.params["output"]), summary),)
|
|
313
|
+
if context.params.get("output")
|
|
314
|
+
else (),
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def discard_obsolete_products(context: OperationContext) -> OperationResult:
|
|
319
|
+
"""Retira do controle os produtos obsoletos: arquivo ausente ou substituído.
|
|
320
|
+
|
|
321
|
+
Dois casos, ambos sem tocar em arquivos: (1) ``missing_output`` confirmado, isto é,
|
|
322
|
+
o arquivo foi removido de propósito; (2) o mesmo caminho foi produzido de novo por
|
|
323
|
+
uma execução mais recente, e o registro antigo não descreve mais o arquivo. Arquivos
|
|
324
|
+
alterados fora do controle ou não verificáveis nunca são descartados. Cada retirada
|
|
325
|
+
deixa um evento ``product_discarded`` com a linha original e o motivo.
|
|
326
|
+
"""
|
|
327
|
+
scenario = None if context.params.get("all_scenarios") else context.params.get("scenario", "base")
|
|
328
|
+
states = inspect_product_states(
|
|
329
|
+
context.store,
|
|
330
|
+
catalog=context.catalog,
|
|
331
|
+
project_root=context.project_root,
|
|
332
|
+
project_overrides=context.project_overrides,
|
|
333
|
+
scenario=scenario,
|
|
334
|
+
artifact_id=context.params.get("produto"),
|
|
335
|
+
)
|
|
336
|
+
newest: dict[str, tuple[str, str]] = {}
|
|
337
|
+
for state in states:
|
|
338
|
+
artifact = state["artifact"]
|
|
339
|
+
key = (str(artifact["created_at"]), str(artifact["id"]))
|
|
340
|
+
path = str(artifact["path"])
|
|
341
|
+
if path not in newest or key > newest[path]:
|
|
342
|
+
newest[path] = key
|
|
343
|
+
discarded = []
|
|
344
|
+
for state in states:
|
|
345
|
+
reasons = state["reasons"]
|
|
346
|
+
artifact = state["artifact"]
|
|
347
|
+
key = (str(artifact["created_at"]), str(artifact["id"]))
|
|
348
|
+
if "unverifiable" in reasons:
|
|
349
|
+
continue
|
|
350
|
+
if key < newest[str(artifact["path"])]:
|
|
351
|
+
reason = "substituído por produto mais recente no mesmo caminho"
|
|
352
|
+
elif "missing_output" in reasons:
|
|
353
|
+
reason = "arquivo ausente"
|
|
354
|
+
else:
|
|
355
|
+
continue
|
|
356
|
+
original = context.store.discard_product(str(artifact["id"]), execution_id=context.execution_id, reason=reason)
|
|
357
|
+
if original is not None:
|
|
358
|
+
discarded.append(
|
|
359
|
+
{"id": original["id"], "kind": original["kind"], "path": original["path"], "reason": reason}
|
|
360
|
+
)
|
|
361
|
+
remaining = inspect_artifacts(context).summary
|
|
362
|
+
return OperationResult(summary={**remaining, "discarded": discarded, "discarded_count": len(discarded)})
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def run_status(context: OperationContext) -> OperationResult:
|
|
366
|
+
"""Consulta de integridade e atualidade; backup, restauração e limpeza são `controle`."""
|
|
367
|
+
return inspect_artifacts(context)
|