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/tui.py
ADDED
|
@@ -0,0 +1,1262 @@
|
|
|
1
|
+
"""Aplicação Textual do Argos.
|
|
2
|
+
|
|
3
|
+
O núcleo continua sem conhecimento de widgets: a aplicação recebe um
|
|
4
|
+
``OperationCatalog`` e uma ``AuditSession`` opcional, apresenta os dados pelos
|
|
5
|
+
adapters de ``tui_models`` e encaminha a execução para ``ExecutionEngine``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import shlex
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Callable
|
|
14
|
+
|
|
15
|
+
from textual.app import App, ComposeResult
|
|
16
|
+
from textual.containers import Horizontal, Vertical, VerticalScroll
|
|
17
|
+
from textual.screen import ModalScreen, Screen
|
|
18
|
+
from textual.widgets import Button, Checkbox, Footer, Input, Label, ListItem, ListView, Select, Static
|
|
19
|
+
from textual.worker import Worker, WorkerState
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
from .core import ArgosError, AuditIdentityRequiredError, OperationCatalog, WorkspaceLocation
|
|
23
|
+
from .errors import InputValidationError, MissingInputError
|
|
24
|
+
from .catalog import build_catalog
|
|
25
|
+
from .core import AuditSession
|
|
26
|
+
from .project import resolve_workspace
|
|
27
|
+
from .tui_models import AuditIdentity, AuditIdentityRequest, AuditSnapshot, OperationDirectory, OperationView, OPERATION_AREAS, format_date, list_registered_audits
|
|
28
|
+
from .tui_path import PathInput
|
|
29
|
+
from .tui_widgets import ArgosBrandPanel, AuditStageWidget, AuditWorkflow, CurrentAuditPanel, HeaderBar, OperationItem, OperationsDashboard
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ArgosApp(App[None]):
|
|
33
|
+
"""Composition root da experiência Textual."""
|
|
34
|
+
|
|
35
|
+
CSS_PATH = Path(__file__).with_name("tui.tcss")
|
|
36
|
+
TITLE = "ARGOS"
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
*,
|
|
41
|
+
catalog: OperationCatalog | None = None,
|
|
42
|
+
project_root: str | Path = ".",
|
|
43
|
+
workspace_root: str | Path | None = None,
|
|
44
|
+
numero: str | None = None,
|
|
45
|
+
nome: str | None = None,
|
|
46
|
+
session: AuditSession | None = None,
|
|
47
|
+
) -> None:
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.catalog = catalog or build_catalog()
|
|
50
|
+
self.directory = OperationDirectory.from_catalog(self.catalog)
|
|
51
|
+
self.project_root = Path(project_root).expanduser().resolve()
|
|
52
|
+
workspace_path = resolve_workspace(self.project_root, workspace_root)
|
|
53
|
+
self.workspace_path = workspace_path.resolve()
|
|
54
|
+
self.workspace_root = WorkspaceLocation.from_path(self.workspace_path).root
|
|
55
|
+
self.numero = numero
|
|
56
|
+
self.nome = nome
|
|
57
|
+
self.session = session
|
|
58
|
+
self._owns_session = False
|
|
59
|
+
self.snapshot = AuditSnapshot.empty()
|
|
60
|
+
self.status_message = "[WAIT] Nenhuma auditoria carregada"
|
|
61
|
+
self._home_screen: ArgosHomeScreen | None = None
|
|
62
|
+
|
|
63
|
+
def compose(self) -> ComposeResult:
|
|
64
|
+
# A home é uma Screen real, empilhada no mount. Mantê-la como filha da
|
|
65
|
+
# Screen implícita do App faria os bindings e o foco serem resolvidos
|
|
66
|
+
# contra a tela errada.
|
|
67
|
+
if False: # pragma: no cover - mantém ComposeResult como generator
|
|
68
|
+
yield Static("")
|
|
69
|
+
|
|
70
|
+
def on_mount(self) -> None:
|
|
71
|
+
self._home_screen = ArgosHomeScreen(self.directory, version=__version__)
|
|
72
|
+
self.push_screen(self._home_screen)
|
|
73
|
+
if self.session is None:
|
|
74
|
+
self._open_initial_session()
|
|
75
|
+
else:
|
|
76
|
+
self.workspace_path = self.session.workspace_root
|
|
77
|
+
self.workspace_root = self.session.workspace_root
|
|
78
|
+
self.status_message = "[OK] Auditoria carregada"
|
|
79
|
+
self.refresh_dashboard()
|
|
80
|
+
|
|
81
|
+
def on_unmount(self) -> None:
|
|
82
|
+
if self.session is not None and self._owns_session:
|
|
83
|
+
self.session.close()
|
|
84
|
+
self.session = None
|
|
85
|
+
|
|
86
|
+
def _open_initial_session(self) -> None:
|
|
87
|
+
try:
|
|
88
|
+
self.session = AuditSession.open(
|
|
89
|
+
project_root=self.project_root,
|
|
90
|
+
workspace_root=self.workspace_path,
|
|
91
|
+
catalog=self.catalog,
|
|
92
|
+
numero=self.numero,
|
|
93
|
+
nome=self.nome,
|
|
94
|
+
)
|
|
95
|
+
self._owns_session = True
|
|
96
|
+
self.status_message = "[OK] Auditoria carregada"
|
|
97
|
+
except AuditIdentityRequiredError:
|
|
98
|
+
self.status_message = "[WAIT] Crie ou abra uma auditoria para começar"
|
|
99
|
+
except ArgosError as exc:
|
|
100
|
+
self.status_message = f"[ERR] {exc}"
|
|
101
|
+
|
|
102
|
+
def refresh_dashboard(self) -> None:
|
|
103
|
+
if self.session is None:
|
|
104
|
+
self.snapshot = AuditSnapshot.empty()
|
|
105
|
+
else:
|
|
106
|
+
try:
|
|
107
|
+
self.snapshot = AuditSnapshot.from_session(self.session, self.directory)
|
|
108
|
+
except Exception as exc: # noqa: BLE001 - estado da UI deve continuar utilizável
|
|
109
|
+
self.snapshot = AuditSnapshot.empty()
|
|
110
|
+
self.status_message = f"[ERR] Não foi possível carregar o dashboard: {exc}"
|
|
111
|
+
if self._home_screen is not None and self._home_screen.is_attached and self._home_screen.query("#header-bar"):
|
|
112
|
+
self._home_screen.set_state(self.snapshot, self.status_message)
|
|
113
|
+
|
|
114
|
+
def set_status(self, message: str) -> None:
|
|
115
|
+
self.status_message = message
|
|
116
|
+
self.refresh_dashboard()
|
|
117
|
+
|
|
118
|
+
def _push_with_restore(
|
|
119
|
+
self,
|
|
120
|
+
screen: Screen,
|
|
121
|
+
callback: Callable[[Any], None] | None = None,
|
|
122
|
+
) -> None:
|
|
123
|
+
previous = self.focused
|
|
124
|
+
|
|
125
|
+
def complete(result: Any) -> None:
|
|
126
|
+
if callback is not None:
|
|
127
|
+
callback(result)
|
|
128
|
+
if (
|
|
129
|
+
result is not None
|
|
130
|
+
and isinstance(screen, (AuditIdentityScreen, RecentAuditsScreen))
|
|
131
|
+
and self.snapshot.loaded
|
|
132
|
+
and self._home_screen is not None
|
|
133
|
+
):
|
|
134
|
+
self._home_screen._focus_primary()
|
|
135
|
+
elif previous is not None and previous.is_attached:
|
|
136
|
+
previous.focus()
|
|
137
|
+
|
|
138
|
+
self.push_screen(screen, complete)
|
|
139
|
+
|
|
140
|
+
def open_identity(self, mode: str) -> None:
|
|
141
|
+
self._push_with_restore(
|
|
142
|
+
AuditIdentityScreen(
|
|
143
|
+
mode=mode,
|
|
144
|
+
project_root=self.project_root,
|
|
145
|
+
workspace_root=self.workspace_path,
|
|
146
|
+
),
|
|
147
|
+
self._handle_identity_request,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
def open_recent(self) -> None:
|
|
151
|
+
self._push_with_restore(
|
|
152
|
+
RecentAuditsScreen(self.workspace_path),
|
|
153
|
+
self._handle_identity_request,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def open_operations(self, area: str | None = None) -> None:
|
|
157
|
+
self._push_with_restore(
|
|
158
|
+
OperationsScreen(self.directory, initial_area=area),
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def open_operation(self, operation: OperationView) -> None:
|
|
162
|
+
self._push_with_restore(OperationConfigScreen(operation, project_root=self.project_root))
|
|
163
|
+
|
|
164
|
+
def open_evaluation_review(self) -> None:
|
|
165
|
+
self._push_with_restore(EvaluationReviewScreen())
|
|
166
|
+
|
|
167
|
+
def show_help(self) -> None:
|
|
168
|
+
self._push_with_restore(HelpScreen())
|
|
169
|
+
|
|
170
|
+
def _handle_identity_request(self, request: AuditIdentityRequest | None) -> None:
|
|
171
|
+
if request is None:
|
|
172
|
+
return
|
|
173
|
+
try:
|
|
174
|
+
project_root = request.project_root or self.project_root
|
|
175
|
+
workspace = request.workspace_root
|
|
176
|
+
if request.mode == "project":
|
|
177
|
+
from .project import create_project
|
|
178
|
+
|
|
179
|
+
created = create_project(project_root, number=request.number or "", name=request.name or "", objective=request.objective,
|
|
180
|
+
process_number=request.process_number, git=request.git)
|
|
181
|
+
workspace = Path(created["workspace"])
|
|
182
|
+
candidate = AuditSession.open(
|
|
183
|
+
project_root=project_root,
|
|
184
|
+
workspace_root=workspace,
|
|
185
|
+
catalog=self.catalog,
|
|
186
|
+
numero=request.number,
|
|
187
|
+
nome=request.name,
|
|
188
|
+
)
|
|
189
|
+
except ArgosError as exc:
|
|
190
|
+
self.set_status(f"[ERR] {exc}")
|
|
191
|
+
return
|
|
192
|
+
if self.session is not None and self._owns_session:
|
|
193
|
+
self.session.close()
|
|
194
|
+
self.session = candidate
|
|
195
|
+
self.project_root = project_root
|
|
196
|
+
self._owns_session = True
|
|
197
|
+
self.workspace_root = candidate.workspace_root
|
|
198
|
+
self.workspace_path = workspace
|
|
199
|
+
self.status_message = "[OK] Auditoria carregada"
|
|
200
|
+
self.refresh_dashboard()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class ArgosHomeScreen(Screen[None]):
|
|
204
|
+
BINDINGS = [
|
|
205
|
+
("n", "new_audit", "Nova"),
|
|
206
|
+
("a", "open_audit", "Abrir"),
|
|
207
|
+
("r", "recent_audits", "Recentes"),
|
|
208
|
+
("slash", "search_operations", "Buscar"),
|
|
209
|
+
("v", "review_evaluations", "Revisar IA"),
|
|
210
|
+
("question_mark", "help", "Ajuda"),
|
|
211
|
+
("f1", "help", "Ajuda"),
|
|
212
|
+
("q", "quit", "Sair"),
|
|
213
|
+
]
|
|
214
|
+
|
|
215
|
+
def __init__(self, directory: OperationDirectory, *, version: str, **kwargs) -> None:
|
|
216
|
+
super().__init__(**kwargs)
|
|
217
|
+
self.directory = directory
|
|
218
|
+
self.version = version
|
|
219
|
+
|
|
220
|
+
def compose(self) -> ComposeResult:
|
|
221
|
+
with Vertical(id="home-shell"):
|
|
222
|
+
yield HeaderBar(self.version)
|
|
223
|
+
with Horizontal(id="home-body"):
|
|
224
|
+
yield ArgosBrandPanel(id="brand-panel")
|
|
225
|
+
with VerticalScroll(id="home-main"):
|
|
226
|
+
yield CurrentAuditPanel(id="current-audit-panel")
|
|
227
|
+
yield AuditWorkflow(AuditSnapshot.empty().stages, id="audit-workflow")
|
|
228
|
+
yield OperationsDashboard(self.directory, id="operations-dashboard")
|
|
229
|
+
with Horizontal(id="footer-row"):
|
|
230
|
+
yield Static(
|
|
231
|
+
"TAB foco ENTER selecionar",
|
|
232
|
+
id="status-text",
|
|
233
|
+
markup=False,
|
|
234
|
+
)
|
|
235
|
+
yield Footer(id="footer", show_command_palette=False)
|
|
236
|
+
yield Static(
|
|
237
|
+
"Terminal muito pequeno. Redimensione para pelo menos 80 x 24.",
|
|
238
|
+
id="too-small",
|
|
239
|
+
markup=False,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
def on_mount(self) -> None:
|
|
243
|
+
app = self.app
|
|
244
|
+
if isinstance(app, ArgosApp):
|
|
245
|
+
self.set_state(app.snapshot, app.status_message)
|
|
246
|
+
self._set_layout(self.size.width)
|
|
247
|
+
self._focus_primary()
|
|
248
|
+
|
|
249
|
+
def set_state(self, snapshot: AuditSnapshot, status: str) -> None:
|
|
250
|
+
self.query_one("#header-bar", HeaderBar).set_state(snapshot, _short_status(status))
|
|
251
|
+
workflow = self.query_one(AuditWorkflow)
|
|
252
|
+
dashboard = self.query_one(OperationsDashboard)
|
|
253
|
+
self.query_one(CurrentAuditPanel).set_snapshot(snapshot)
|
|
254
|
+
workflow.set_snapshot(snapshot)
|
|
255
|
+
dashboard.set_context(snapshot.current_phase)
|
|
256
|
+
workflow.select_stage(dashboard.active_stage_index, focus_operations=False)
|
|
257
|
+
self.query_one("#status-text", Static).update(
|
|
258
|
+
f"{_short_status(status)} | ←/→ etapas ↑/↓ operações ENTER selecionar"
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def _focus_primary(self) -> None:
|
|
262
|
+
if self.app.snapshot.loaded:
|
|
263
|
+
dashboard = self.query_one(OperationsDashboard)
|
|
264
|
+
if dashboard.focus_for_stage(dashboard.active_stage_index, 0):
|
|
265
|
+
return
|
|
266
|
+
dashboard.focus()
|
|
267
|
+
return
|
|
268
|
+
try:
|
|
269
|
+
self.query_one("#action-new", Button).focus()
|
|
270
|
+
except Exception:
|
|
271
|
+
pass
|
|
272
|
+
|
|
273
|
+
def _input_is_focused(self) -> bool:
|
|
274
|
+
return isinstance(self.app.focused, Input)
|
|
275
|
+
|
|
276
|
+
def action_new_audit(self) -> None:
|
|
277
|
+
if not self._input_is_focused():
|
|
278
|
+
self.app.open_identity("create")
|
|
279
|
+
|
|
280
|
+
def action_open_audit(self) -> None:
|
|
281
|
+
if not self._input_is_focused():
|
|
282
|
+
self.app.open_identity("open")
|
|
283
|
+
|
|
284
|
+
def action_recent_audits(self) -> None:
|
|
285
|
+
if not self._input_is_focused():
|
|
286
|
+
self.app.open_recent()
|
|
287
|
+
|
|
288
|
+
def action_search_operations(self) -> None:
|
|
289
|
+
if not self._input_is_focused():
|
|
290
|
+
self.app.open_operations()
|
|
291
|
+
|
|
292
|
+
def action_review_evaluations(self) -> None:
|
|
293
|
+
if not self._input_is_focused():
|
|
294
|
+
self.app.open_evaluation_review()
|
|
295
|
+
|
|
296
|
+
def action_help(self) -> None:
|
|
297
|
+
self.app.show_help()
|
|
298
|
+
|
|
299
|
+
def action_quit(self) -> None:
|
|
300
|
+
if not self._input_is_focused():
|
|
301
|
+
self.app.exit()
|
|
302
|
+
|
|
303
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
304
|
+
button_id = event.button.id or ""
|
|
305
|
+
actions = {
|
|
306
|
+
"action-new": lambda: self.app.open_identity("create"),
|
|
307
|
+
"action-open": lambda: self.app.open_identity("open"),
|
|
308
|
+
"action-recent": self.app.open_recent,
|
|
309
|
+
"empty-new": lambda: self.app.open_identity("create"),
|
|
310
|
+
"empty-open": lambda: self.app.open_identity("open"),
|
|
311
|
+
"empty-recent": self.app.open_recent,
|
|
312
|
+
}
|
|
313
|
+
if button_id in actions:
|
|
314
|
+
actions[button_id]()
|
|
315
|
+
event.stop()
|
|
316
|
+
return
|
|
317
|
+
if button_id.startswith("more-"):
|
|
318
|
+
self.app.open_operations(event.button.name)
|
|
319
|
+
event.stop()
|
|
320
|
+
|
|
321
|
+
def on_operation_item_selected(self, event: OperationItem.Selected) -> None:
|
|
322
|
+
self.app.open_operation(event.operation)
|
|
323
|
+
event.stop()
|
|
324
|
+
|
|
325
|
+
def on_audit_stage_widget_selected(self, event: AuditStageWidget.Selected) -> None:
|
|
326
|
+
self.app.set_status(f"[INFO] Fase selecionada: {event.stage.title} · {event.stage.detail}")
|
|
327
|
+
event.stop()
|
|
328
|
+
|
|
329
|
+
def on_resize(self, event) -> None:
|
|
330
|
+
too_small = event.size.width < 80 or event.size.height < 24
|
|
331
|
+
self.query_one("#home-shell").display = not too_small
|
|
332
|
+
self.query_one("#too-small").display = too_small
|
|
333
|
+
self._set_layout(event.size.width)
|
|
334
|
+
|
|
335
|
+
def _set_layout(self, width: int) -> None:
|
|
336
|
+
for name in ("layout-compact", "layout-standard", "layout-expanded", "layout-wide"):
|
|
337
|
+
self.remove_class(name)
|
|
338
|
+
if width < 90:
|
|
339
|
+
self.add_class("layout-compact")
|
|
340
|
+
elif width < 110:
|
|
341
|
+
self.add_class("layout-standard")
|
|
342
|
+
elif width < 140:
|
|
343
|
+
self.add_class("layout-expanded")
|
|
344
|
+
else:
|
|
345
|
+
self.add_class("layout-wide")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class AuditIdentityScreen(ModalScreen[AuditIdentityRequest | None]):
|
|
349
|
+
BINDINGS = [("escape", "cancel", "Cancelar")]
|
|
350
|
+
|
|
351
|
+
def __init__(
|
|
352
|
+
self,
|
|
353
|
+
*,
|
|
354
|
+
mode: str,
|
|
355
|
+
project_root: Path,
|
|
356
|
+
workspace_root: Path,
|
|
357
|
+
**kwargs,
|
|
358
|
+
) -> None:
|
|
359
|
+
super().__init__(**kwargs)
|
|
360
|
+
self.mode = mode
|
|
361
|
+
self.project_root = project_root
|
|
362
|
+
self.workspace_root = workspace_root
|
|
363
|
+
|
|
364
|
+
def compose(self) -> ComposeResult:
|
|
365
|
+
with Vertical(id="identity-dialog"):
|
|
366
|
+
yield Static(
|
|
367
|
+
"NOVO PROJETO" if self.mode == "project" else ("NOVA AUDITORIA" if self.mode == "create" else "ABRIR AUDITORIA"),
|
|
368
|
+
classes="dialog-title",
|
|
369
|
+
markup=False,
|
|
370
|
+
)
|
|
371
|
+
yield Static(
|
|
372
|
+
"Informe o arquivo SQLite existente para reabrir a auditoria."
|
|
373
|
+
if self.mode == "open"
|
|
374
|
+
else ("Crie o repositório com cadastro, diretrizes e controle central." if self.mode == "project" else "Uma fiscalização exige número, nome e um workspace próprio."),
|
|
375
|
+
classes="dialog-description",
|
|
376
|
+
markup=False,
|
|
377
|
+
)
|
|
378
|
+
if self.mode in {"create", "project"}:
|
|
379
|
+
yield Label("Número da fiscalização *")
|
|
380
|
+
yield Input(id="audit-number", placeholder="ex.: 01/2026")
|
|
381
|
+
yield Label("Nome da fiscalização *")
|
|
382
|
+
yield Input(id="audit-name", placeholder="ex.: Auditoria interna")
|
|
383
|
+
if self.mode == "project":
|
|
384
|
+
yield Label("Objetivo da fiscalização *")
|
|
385
|
+
yield Input(id="audit-objective")
|
|
386
|
+
yield Label("Número do processo")
|
|
387
|
+
yield Input(id="audit-process")
|
|
388
|
+
yield Checkbox("Inicializar Git (extra git)", id="audit-git")
|
|
389
|
+
yield Label("Diretório novo do projeto *" if self.mode == "project" else "Workspace SQLite *")
|
|
390
|
+
yield PathInput(
|
|
391
|
+
value="" if self.mode == "project" else str(self.workspace_root),
|
|
392
|
+
id="audit-workspace",
|
|
393
|
+
base_path=self.project_root,
|
|
394
|
+
allowed_suffixes=(".sqlite", ".sqlite3"),
|
|
395
|
+
placeholder="diretório ou arquivo .sqlite3",
|
|
396
|
+
)
|
|
397
|
+
else:
|
|
398
|
+
try:
|
|
399
|
+
default_path = WorkspaceLocation.from_path(self.workspace_root).db_path
|
|
400
|
+
except ArgosError:
|
|
401
|
+
default_path = self.workspace_root
|
|
402
|
+
yield Label("Arquivo SQLite *")
|
|
403
|
+
yield PathInput(
|
|
404
|
+
value=str(default_path),
|
|
405
|
+
id="audit-workspace",
|
|
406
|
+
base_path=self.project_root,
|
|
407
|
+
include_directories=False,
|
|
408
|
+
allowed_suffixes=(".sqlite", ".sqlite3"),
|
|
409
|
+
placeholder="caminho para um arquivo .sqlite3 existente",
|
|
410
|
+
)
|
|
411
|
+
yield Static("", id="identity-feedback", classes="form-feedback", markup=False)
|
|
412
|
+
with Horizontal(classes="dialog-actions"):
|
|
413
|
+
yield Button(
|
|
414
|
+
"[ CRIAR ]" if self.mode in {"create", "project"} else "[ ABRIR ]",
|
|
415
|
+
id="identity-submit",
|
|
416
|
+
variant="success",
|
|
417
|
+
)
|
|
418
|
+
yield Button("[ CANCELAR ]", id="identity-cancel")
|
|
419
|
+
if self.mode == "create":
|
|
420
|
+
yield Button("[ NOVO PROJETO ]", id="identity-project")
|
|
421
|
+
|
|
422
|
+
def on_mount(self) -> None:
|
|
423
|
+
target = "#audit-number" if self.mode in {"create", "project"} else "#audit-workspace"
|
|
424
|
+
self.query_one(target, Input).focus()
|
|
425
|
+
|
|
426
|
+
def on_key(self, event) -> None:
|
|
427
|
+
if _handle_form_key(self, event):
|
|
428
|
+
return
|
|
429
|
+
|
|
430
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
431
|
+
if event.button.id == "identity-cancel":
|
|
432
|
+
self.action_cancel()
|
|
433
|
+
elif event.button.id == "identity-submit":
|
|
434
|
+
self._submit()
|
|
435
|
+
elif event.button.id == "identity-project":
|
|
436
|
+
self.app.pop_screen()
|
|
437
|
+
self.app.open_identity("project")
|
|
438
|
+
|
|
439
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
440
|
+
if event.input.id in {"audit-number", "audit-name", "audit-workspace"}:
|
|
441
|
+
self._submit()
|
|
442
|
+
|
|
443
|
+
def action_cancel(self) -> None:
|
|
444
|
+
self.dismiss(None)
|
|
445
|
+
|
|
446
|
+
def _submit(self) -> None:
|
|
447
|
+
number = self.query_one("#audit-number", Input).value.strip() or None if self.mode in {"create", "project"} else None
|
|
448
|
+
name = self.query_one("#audit-name", Input).value.strip() or None if self.mode in {"create", "project"} else None
|
|
449
|
+
workspace_value = self.query_one("#audit-workspace", Input).value.strip()
|
|
450
|
+
if not workspace_value:
|
|
451
|
+
self._error("Informe o workspace ou o arquivo .sqlite3.")
|
|
452
|
+
return
|
|
453
|
+
if self.mode in {"create", "project"} and (not number or not name):
|
|
454
|
+
self._error("Criar uma auditoria exige número e nome.")
|
|
455
|
+
return
|
|
456
|
+
workspace_path = Path(workspace_value).expanduser()
|
|
457
|
+
if not workspace_path.is_absolute():
|
|
458
|
+
workspace_path = self.project_root / workspace_path
|
|
459
|
+
workspace_path = workspace_path.resolve()
|
|
460
|
+
try:
|
|
461
|
+
location = WorkspaceLocation.from_path(workspace_path)
|
|
462
|
+
except ArgosError as exc:
|
|
463
|
+
self._error(str(exc))
|
|
464
|
+
return
|
|
465
|
+
if self.mode == "open":
|
|
466
|
+
if workspace_path.suffix.casefold() not in {".sqlite", ".sqlite3"} or not workspace_path.is_file():
|
|
467
|
+
self._error("Abrir auditoria exige um arquivo .sqlite3 existente.")
|
|
468
|
+
return
|
|
469
|
+
workspace_path = location.db_path
|
|
470
|
+
if self.mode == "project":
|
|
471
|
+
objective = self.query_one("#audit-objective", Input).value.strip()
|
|
472
|
+
if not objective or workspace_path.exists() or workspace_path.is_symlink():
|
|
473
|
+
self._error("Informe objetivo e diretório inexistente para o projeto.")
|
|
474
|
+
return
|
|
475
|
+
if self.mode == "create":
|
|
476
|
+
try:
|
|
477
|
+
if list_registered_audits(location.db_path):
|
|
478
|
+
self._error("Este workspace já contém uma fiscalização; escolha um local SQLite vazio.")
|
|
479
|
+
return
|
|
480
|
+
except ArgosError as exc:
|
|
481
|
+
self._error(str(exc))
|
|
482
|
+
return
|
|
483
|
+
self.dismiss(
|
|
484
|
+
AuditIdentityRequest(
|
|
485
|
+
mode=self.mode,
|
|
486
|
+
workspace_root=workspace_path,
|
|
487
|
+
number=number,
|
|
488
|
+
name=name,
|
|
489
|
+
project_root=workspace_path if self.mode == "project" else None,
|
|
490
|
+
objective=self.query_one("#audit-objective", Input).value.strip() if self.mode == "project" else "",
|
|
491
|
+
process_number=self.query_one("#audit-process", Input).value.strip() if self.mode == "project" else "",
|
|
492
|
+
git=self.query_one("#audit-git", Checkbox).value if self.mode == "project" else False,
|
|
493
|
+
)
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
def _error(self, message: str) -> None:
|
|
497
|
+
self.query_one("#identity-feedback", Static).update(f"[ERR] {message}")
|
|
498
|
+
target = "#audit-number" if self.mode in {"create", "project"} else "#audit-workspace"
|
|
499
|
+
self.query_one(target, Input).focus()
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
class RecentAuditItem(ListItem):
|
|
503
|
+
def __init__(self, identity: AuditIdentity, **kwargs) -> None:
|
|
504
|
+
text = Static(
|
|
505
|
+
f"{identity.number} · {identity.name} · atualizado {format_date(identity.updated_at)}",
|
|
506
|
+
markup=False,
|
|
507
|
+
)
|
|
508
|
+
super().__init__(text, classes="recent-audit-item", **kwargs)
|
|
509
|
+
self.identity = identity
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
class RecentAuditsScreen(ModalScreen[AuditIdentityRequest | None]):
|
|
513
|
+
BINDINGS = [("escape", "cancel", "Voltar")]
|
|
514
|
+
|
|
515
|
+
def __init__(self, workspace_root: Path, **kwargs) -> None:
|
|
516
|
+
super().__init__(**kwargs)
|
|
517
|
+
self.workspace_root = workspace_root
|
|
518
|
+
try:
|
|
519
|
+
self.identities = list_registered_audits(workspace_root)
|
|
520
|
+
self.error: str | None = None
|
|
521
|
+
except ArgosError as exc:
|
|
522
|
+
self.identities = ()
|
|
523
|
+
self.error = str(exc)
|
|
524
|
+
|
|
525
|
+
def compose(self) -> ComposeResult:
|
|
526
|
+
with Vertical(id="recent-dialog"):
|
|
527
|
+
yield Static("AUDITORIAS RECENTES", classes="dialog-title", markup=False)
|
|
528
|
+
yield Static(
|
|
529
|
+
f"Workspace: {self.workspace_root}",
|
|
530
|
+
classes="dialog-description",
|
|
531
|
+
markup=False,
|
|
532
|
+
)
|
|
533
|
+
if self.error:
|
|
534
|
+
yield Static(f"[ERR] {self.error}", id="recent-feedback", classes="form-feedback", markup=False)
|
|
535
|
+
elif not self.identities:
|
|
536
|
+
yield Static(
|
|
537
|
+
"Nenhuma auditoria registrada neste workspace.",
|
|
538
|
+
id="recent-feedback",
|
|
539
|
+
classes="empty-state",
|
|
540
|
+
markup=False,
|
|
541
|
+
)
|
|
542
|
+
else:
|
|
543
|
+
yield ListView(
|
|
544
|
+
*(RecentAuditItem(identity) for identity in self.identities),
|
|
545
|
+
id="recent-list",
|
|
546
|
+
)
|
|
547
|
+
with Horizontal(classes="dialog-actions"):
|
|
548
|
+
yield Button("[ FECHAR ]", id="recent-cancel")
|
|
549
|
+
|
|
550
|
+
def on_mount(self) -> None:
|
|
551
|
+
if self.identities and self.query("#recent-list"):
|
|
552
|
+
self.query_one("#recent-list", ListView).focus()
|
|
553
|
+
else:
|
|
554
|
+
self.query_one("#recent-cancel", Button).focus()
|
|
555
|
+
|
|
556
|
+
def on_list_view_selected(self, event: ListView.Selected) -> None:
|
|
557
|
+
item = event.item
|
|
558
|
+
if isinstance(item, RecentAuditItem):
|
|
559
|
+
self.dismiss(
|
|
560
|
+
AuditIdentityRequest(
|
|
561
|
+
mode="open",
|
|
562
|
+
workspace_root=self.workspace_root,
|
|
563
|
+
number=item.identity.number,
|
|
564
|
+
name=item.identity.name,
|
|
565
|
+
)
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
569
|
+
if event.button.id == "recent-cancel":
|
|
570
|
+
self.action_cancel()
|
|
571
|
+
|
|
572
|
+
def action_cancel(self) -> None:
|
|
573
|
+
self.dismiss(None)
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
class OperationListItem(ListItem):
|
|
577
|
+
def __init__(self, operation: OperationView, **kwargs) -> None:
|
|
578
|
+
text = Static(
|
|
579
|
+
f"{operation.id} · {operation.name}\n{operation.area} / {operation.phase}\n{operation.description}",
|
|
580
|
+
markup=False,
|
|
581
|
+
)
|
|
582
|
+
super().__init__(text, classes="operation-list-item", **kwargs)
|
|
583
|
+
self.operation = operation
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
class OperationsScreen(Screen[None]):
|
|
587
|
+
BINDINGS = [
|
|
588
|
+
("escape", "back", "Voltar"),
|
|
589
|
+
("slash", "focus_search", "Buscar"),
|
|
590
|
+
]
|
|
591
|
+
|
|
592
|
+
def __init__(self, directory: OperationDirectory, *, initial_area: str | None = None, **kwargs) -> None:
|
|
593
|
+
super().__init__(**kwargs)
|
|
594
|
+
self.directory = directory
|
|
595
|
+
self.initial_area = initial_area or "all"
|
|
596
|
+
|
|
597
|
+
def compose(self) -> ComposeResult:
|
|
598
|
+
with Vertical(id="operations-screen-shell"):
|
|
599
|
+
yield Static("CATÁLOGO DE OPERAÇÕES", classes="screen-title", markup=False)
|
|
600
|
+
with Horizontal(id="operation-toolbar"):
|
|
601
|
+
yield Input(placeholder="buscar por id, nome ou descrição", id="operation-search")
|
|
602
|
+
yield Select(
|
|
603
|
+
[("Todas as áreas", "all"), *((area, area) for area in OPERATION_AREAS)],
|
|
604
|
+
prompt="Área",
|
|
605
|
+
allow_blank=False,
|
|
606
|
+
value=self.initial_area if self.initial_area in OPERATION_AREAS else "all",
|
|
607
|
+
id="operation-area-filter",
|
|
608
|
+
)
|
|
609
|
+
yield Static("", id="operation-count", markup=False)
|
|
610
|
+
yield ListView(id="operation-list")
|
|
611
|
+
with Horizontal(classes="screen-actions"):
|
|
612
|
+
yield Button("[ ESC ] Voltar", id="operations-back")
|
|
613
|
+
yield Footer(id="operations-footer", show_command_palette=False)
|
|
614
|
+
|
|
615
|
+
def on_mount(self) -> None:
|
|
616
|
+
self._refresh_list()
|
|
617
|
+
self.query_one("#operation-search", Input).focus()
|
|
618
|
+
self._set_layout(self.size.width)
|
|
619
|
+
|
|
620
|
+
def on_resize(self, event) -> None:
|
|
621
|
+
self._set_layout(event.size.width)
|
|
622
|
+
|
|
623
|
+
def _set_layout(self, width: int) -> None:
|
|
624
|
+
self.set_class(width < 90, "operations-compact")
|
|
625
|
+
|
|
626
|
+
def _refresh_list(self) -> None:
|
|
627
|
+
search = self.query_one("#operation-search", Input).value
|
|
628
|
+
area_value = self.query_one("#operation-area-filter", Select).value
|
|
629
|
+
area = None if area_value in (None, "all") else str(area_value)
|
|
630
|
+
entries = self.directory.search(search, area=area)
|
|
631
|
+
list_view = self.query_one("#operation-list", ListView)
|
|
632
|
+
list_view.clear()
|
|
633
|
+
list_view.mount(*(OperationListItem(entry) for entry in entries))
|
|
634
|
+
self.query_one("#operation-count", Static).update(
|
|
635
|
+
f"{len(entries)} operação(ões) · setas navegam · ENTER configura"
|
|
636
|
+
if entries
|
|
637
|
+
else "Nenhuma operação encontrada. Ajuste a busca ou o filtro."
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
def on_input_changed(self, event: Input.Changed) -> None:
|
|
641
|
+
if event.input.id == "operation-search":
|
|
642
|
+
self._refresh_list()
|
|
643
|
+
|
|
644
|
+
def on_select_changed(self, event: Select.Changed) -> None:
|
|
645
|
+
if event.select.id == "operation-area-filter":
|
|
646
|
+
self._refresh_list()
|
|
647
|
+
|
|
648
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
649
|
+
if event.input.id != "operation-search":
|
|
650
|
+
return
|
|
651
|
+
list_view = self.query_one("#operation-list", ListView)
|
|
652
|
+
list_view.focus()
|
|
653
|
+
if list_view.children:
|
|
654
|
+
list_view.index = 0
|
|
655
|
+
|
|
656
|
+
def on_list_view_selected(self, event: ListView.Selected) -> None:
|
|
657
|
+
if isinstance(event.item, OperationListItem):
|
|
658
|
+
self.app.open_operation(event.item.operation)
|
|
659
|
+
|
|
660
|
+
def action_focus_search(self) -> None:
|
|
661
|
+
self.query_one("#operation-search", Input).focus()
|
|
662
|
+
|
|
663
|
+
def action_back(self) -> None:
|
|
664
|
+
self.dismiss(None)
|
|
665
|
+
|
|
666
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
667
|
+
if event.button.id == "operations-back":
|
|
668
|
+
self.action_back()
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
class OperationConfigScreen(ModalScreen[None]):
|
|
672
|
+
BINDINGS = [("escape", "cancel_or_back", "Cancelar / voltar")]
|
|
673
|
+
|
|
674
|
+
def __init__(self, operation: OperationView, *, project_root: Path, **kwargs) -> None:
|
|
675
|
+
super().__init__(**kwargs)
|
|
676
|
+
self.operation = operation
|
|
677
|
+
self.project_root = project_root
|
|
678
|
+
self._worker: Worker[dict[str, Any]] | None = None
|
|
679
|
+
self._pending_params: dict[str, Any] = {}
|
|
680
|
+
self._automatic_template: str | None = None
|
|
681
|
+
|
|
682
|
+
def compose(self) -> ComposeResult:
|
|
683
|
+
from .project import operation_parameters
|
|
684
|
+
from .booleans import parse_bool
|
|
685
|
+
|
|
686
|
+
defaults = operation_parameters(
|
|
687
|
+
self.operation.spec, {}, self.project_root,
|
|
688
|
+
self.app.session.engine.executions.project_overrides if self.app.session else None,
|
|
689
|
+
)
|
|
690
|
+
template_default = defaults.get("template")
|
|
691
|
+
self._automatic_template = str(template_default) if template_default not in (None, "") else None
|
|
692
|
+
with Vertical(id="operation-dialog"):
|
|
693
|
+
yield Static(
|
|
694
|
+
f"{self.operation.id} / {self.operation.name}",
|
|
695
|
+
classes="dialog-title",
|
|
696
|
+
markup=False,
|
|
697
|
+
)
|
|
698
|
+
yield Static(self.operation.description, classes="dialog-description", markup=False)
|
|
699
|
+
yield Static(
|
|
700
|
+
f"Área: {self.operation.area} · fase: {self.operation.phase} · contrato v{self.operation.version}",
|
|
701
|
+
classes="operation-meta",
|
|
702
|
+
markup=False,
|
|
703
|
+
)
|
|
704
|
+
with VerticalScroll(id="parameters-scroll"):
|
|
705
|
+
if not self.operation.parameters:
|
|
706
|
+
yield Static("Esta operação não requer parâmetros.", classes="empty-state", markup=False)
|
|
707
|
+
for parameter in self.operation.parameters:
|
|
708
|
+
default_value = defaults.get(parameter.name, parameter.default)
|
|
709
|
+
with Vertical(
|
|
710
|
+
classes="parameter-field",
|
|
711
|
+
id=f"field-{parameter.name}",
|
|
712
|
+
):
|
|
713
|
+
marker = " *" if parameter.required else ""
|
|
714
|
+
yield Label(f"{parameter.name}{marker}")
|
|
715
|
+
if parameter.boolean:
|
|
716
|
+
yield Checkbox(
|
|
717
|
+
"ativado",
|
|
718
|
+
value=parse_bool(default_value) if default_value is not None else False,
|
|
719
|
+
id=f"param-{parameter.name}",
|
|
720
|
+
)
|
|
721
|
+
elif parameter.choices:
|
|
722
|
+
yield Select(
|
|
723
|
+
tuple((choice, choice) for choice in parameter.choices),
|
|
724
|
+
value=(
|
|
725
|
+
str(default_value)
|
|
726
|
+
if default_value is not None
|
|
727
|
+
else Select.BLANK
|
|
728
|
+
),
|
|
729
|
+
allow_blank=not parameter.required,
|
|
730
|
+
id=f"param-{parameter.name}",
|
|
731
|
+
)
|
|
732
|
+
else:
|
|
733
|
+
default = _display_default(default_value) if default_value is not None else ""
|
|
734
|
+
placeholder = "separado por espaço" if parameter.multiple else parameter.description
|
|
735
|
+
input_kwargs = {
|
|
736
|
+
"value": default,
|
|
737
|
+
"placeholder": placeholder,
|
|
738
|
+
"id": f"param-{parameter.name}",
|
|
739
|
+
"classes": "operation-input",
|
|
740
|
+
}
|
|
741
|
+
if parameter.path:
|
|
742
|
+
yield PathInput(
|
|
743
|
+
**input_kwargs,
|
|
744
|
+
base_path=self.project_root,
|
|
745
|
+
multiple=parameter.multiple,
|
|
746
|
+
)
|
|
747
|
+
else:
|
|
748
|
+
yield Input(**input_kwargs)
|
|
749
|
+
yield Static(
|
|
750
|
+
_parameter_hint(parameter.description, parameter.multiple, parameter.path),
|
|
751
|
+
classes="parameter-help",
|
|
752
|
+
markup=False,
|
|
753
|
+
)
|
|
754
|
+
yield Static("", id="operation-feedback", classes="form-feedback", markup=False)
|
|
755
|
+
yield Static("", id="operation-result", classes="operation-result", markup=False)
|
|
756
|
+
with Horizontal(classes="dialog-actions"):
|
|
757
|
+
yield Button("[ EXECUTAR ]", id="operation-execute", variant="success")
|
|
758
|
+
yield Button("[ CANCELAR ]", id="operation-cancel")
|
|
759
|
+
yield Footer(id="operation-footer", show_command_palette=False)
|
|
760
|
+
|
|
761
|
+
def on_mount(self) -> None:
|
|
762
|
+
self._refresh_active_fields()
|
|
763
|
+
controls = _form_controls(self)
|
|
764
|
+
if controls:
|
|
765
|
+
controls[0].focus()
|
|
766
|
+
else:
|
|
767
|
+
self.query_one("#operation-execute", Button).focus()
|
|
768
|
+
|
|
769
|
+
def on_key(self, event) -> None:
|
|
770
|
+
if _handle_form_key(self, event):
|
|
771
|
+
return
|
|
772
|
+
|
|
773
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
774
|
+
self.action_execute()
|
|
775
|
+
|
|
776
|
+
def on_input_changed(self, event: Input.Changed) -> None:
|
|
777
|
+
self._refresh_matrix_template_default(changed_id=event.input.id)
|
|
778
|
+
self._refresh_active_fields()
|
|
779
|
+
|
|
780
|
+
def on_select_changed(self, event: Select.Changed) -> None:
|
|
781
|
+
self._refresh_matrix_template_default(changed_id=event.select.id)
|
|
782
|
+
self._refresh_active_fields()
|
|
783
|
+
|
|
784
|
+
def on_checkbox_changed(self, event: Checkbox.Changed) -> None:
|
|
785
|
+
self._refresh_matrix_template_default(changed_id=event.checkbox.id)
|
|
786
|
+
self._refresh_active_fields()
|
|
787
|
+
|
|
788
|
+
def _refresh_matrix_template_default(self, *, changed_id: str) -> None:
|
|
789
|
+
if self.operation.object != "matriz" or changed_id == "param-template" or not self.is_mounted:
|
|
790
|
+
return
|
|
791
|
+
if not self.query("#param-template"):
|
|
792
|
+
return
|
|
793
|
+
from .project import operation_parameters
|
|
794
|
+
|
|
795
|
+
template_input = self.query_one("#param-template", Input)
|
|
796
|
+
current = template_input.value.strip()
|
|
797
|
+
if current and current != self._automatic_template:
|
|
798
|
+
return
|
|
799
|
+
params = self._collect_params()
|
|
800
|
+
params.pop("template", None)
|
|
801
|
+
resolved = operation_parameters(
|
|
802
|
+
self.operation.spec,
|
|
803
|
+
params,
|
|
804
|
+
self.project_root,
|
|
805
|
+
self.app.session.engine.executions.project_overrides if self.app.session else None,
|
|
806
|
+
)
|
|
807
|
+
value = resolved.get("template")
|
|
808
|
+
new_template = str(value) if value not in (None, "") else None
|
|
809
|
+
template_input.value = new_template or ""
|
|
810
|
+
self._automatic_template = new_template
|
|
811
|
+
|
|
812
|
+
def _refresh_active_fields(self) -> None:
|
|
813
|
+
values = self._collect_params()
|
|
814
|
+
for parameter in self.operation.parameters:
|
|
815
|
+
self.query_one(f"#field-{parameter.name}").display = parameter.is_active(values)
|
|
816
|
+
|
|
817
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
818
|
+
if event.button.id == "operation-execute":
|
|
819
|
+
self.action_execute()
|
|
820
|
+
elif event.button.id == "operation-cancel":
|
|
821
|
+
self.action_cancel()
|
|
822
|
+
|
|
823
|
+
def action_cancel_or_back(self) -> None:
|
|
824
|
+
self.action_cancel()
|
|
825
|
+
|
|
826
|
+
def action_cancel(self) -> None:
|
|
827
|
+
if self._worker is not None and self._worker.state in {WorkerState.PENDING, WorkerState.RUNNING}:
|
|
828
|
+
self._worker.cancel()
|
|
829
|
+
self._worker = None
|
|
830
|
+
self._set_busy(False)
|
|
831
|
+
self._feedback("[WAIT] Cancelamento solicitado; a operação pode concluir em segundo plano.")
|
|
832
|
+
return
|
|
833
|
+
self.dismiss(None)
|
|
834
|
+
|
|
835
|
+
def action_execute(self) -> None:
|
|
836
|
+
if self._worker is not None and self._worker.state in {WorkerState.PENDING, WorkerState.RUNNING}:
|
|
837
|
+
return
|
|
838
|
+
try:
|
|
839
|
+
params = self._collect_params()
|
|
840
|
+
resolution = self.operation.spec.resolve(
|
|
841
|
+
params, project_root=self.app.project_root,
|
|
842
|
+
project_overrides=self.app.session.engine.executions.project_overrides if self.app.session else None,
|
|
843
|
+
)
|
|
844
|
+
if resolution.missing:
|
|
845
|
+
names = ", ".join(str(item["parameter"]) for item in resolution.missing)
|
|
846
|
+
raise MissingInputError(f"parâmetros obrigatórios ausentes: {names}")
|
|
847
|
+
self._pending_params = params
|
|
848
|
+
except (ArgosError, ValueError, TypeError) as exc:
|
|
849
|
+
self._feedback(f"[ERR] {exc}")
|
|
850
|
+
return
|
|
851
|
+
if self.app.session is None:
|
|
852
|
+
self._feedback("[WAIT] Crie ou abra uma auditoria antes de executar operações.")
|
|
853
|
+
return
|
|
854
|
+
self._set_busy(True)
|
|
855
|
+
self._feedback(f"[RUN] Executando {self.operation.id}…")
|
|
856
|
+
self._worker = self.run_worker(
|
|
857
|
+
self._execute,
|
|
858
|
+
name=f"operation-{self.operation.id}",
|
|
859
|
+
description=f"Executando {self.operation.id}",
|
|
860
|
+
exit_on_error=False,
|
|
861
|
+
thread=True,
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
def _collect_params(self) -> dict[str, Any]:
|
|
865
|
+
values: dict[str, Any] = {}
|
|
866
|
+
for parameter in self.operation.parameters:
|
|
867
|
+
field_id = f"#param-{parameter.name}"
|
|
868
|
+
if parameter.boolean:
|
|
869
|
+
checkbox = self.query_one(field_id, Checkbox)
|
|
870
|
+
if parameter.required or checkbox.value or parameter.default is not None:
|
|
871
|
+
values[parameter.name] = checkbox.value
|
|
872
|
+
continue
|
|
873
|
+
if parameter.choices:
|
|
874
|
+
selected = self.query_one(field_id, Select).value
|
|
875
|
+
if selected is not Select.BLANK:
|
|
876
|
+
values[parameter.name] = str(selected)
|
|
877
|
+
continue
|
|
878
|
+
value = self.query_one(field_id, Input).value.strip()
|
|
879
|
+
if parameter.multiple:
|
|
880
|
+
values[parameter.name] = shlex.split(value) if value else []
|
|
881
|
+
elif value:
|
|
882
|
+
values[parameter.name] = value
|
|
883
|
+
return values
|
|
884
|
+
|
|
885
|
+
def _execute(self) -> dict[str, Any]:
|
|
886
|
+
session = self.app.session
|
|
887
|
+
if session is None:
|
|
888
|
+
raise InputValidationError("nenhuma auditoria carregada")
|
|
889
|
+
try:
|
|
890
|
+
return session.engine.run(self.operation.id, self._pending_params)
|
|
891
|
+
except Exception as exc: # noqa: BLE001 - a tela transforma a falha em feedback acionável
|
|
892
|
+
return {
|
|
893
|
+
"status": "failed",
|
|
894
|
+
"error": f"{type(exc).__name__}: {exc}",
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
def on_worker_state_changed(self, event: Worker.StateChanged) -> None:
|
|
898
|
+
if event.worker is not self._worker:
|
|
899
|
+
return
|
|
900
|
+
if event.state == WorkerState.PENDING:
|
|
901
|
+
return
|
|
902
|
+
if event.state == WorkerState.RUNNING:
|
|
903
|
+
self._feedback(f"[RUN] Executando {self.operation.id}…")
|
|
904
|
+
return
|
|
905
|
+
worker = event.worker
|
|
906
|
+
self._worker = None
|
|
907
|
+
self._set_busy(False)
|
|
908
|
+
if event.state == WorkerState.SUCCESS:
|
|
909
|
+
result = worker.result or {}
|
|
910
|
+
self._render_result(result)
|
|
911
|
+
self.app.set_status(_result_status(result))
|
|
912
|
+
elif event.state == WorkerState.CANCELLED:
|
|
913
|
+
self._feedback("[WAIT] Operação cancelada.")
|
|
914
|
+
else:
|
|
915
|
+
self._feedback(f"[ERR] Falha na execução: {worker.error or 'erro desconhecido'}")
|
|
916
|
+
self.app.set_status("[ERR] Falha na operação")
|
|
917
|
+
|
|
918
|
+
def _set_busy(self, busy: bool) -> None:
|
|
919
|
+
for widget in self.query(Button):
|
|
920
|
+
if widget.id != "operation-cancel":
|
|
921
|
+
widget.disabled = busy
|
|
922
|
+
for widget in self.query(Input):
|
|
923
|
+
widget.disabled = busy
|
|
924
|
+
for widget in self.query(Checkbox):
|
|
925
|
+
widget.disabled = busy
|
|
926
|
+
for widget in self.query(Select):
|
|
927
|
+
widget.disabled = busy
|
|
928
|
+
self.query_one("#operation-cancel", Button).label = "[ CANCELAR ]" if not busy else "[ PARAR ]"
|
|
929
|
+
|
|
930
|
+
def _feedback(self, message: str) -> None:
|
|
931
|
+
self.query_one("#operation-feedback", Static).update(message)
|
|
932
|
+
|
|
933
|
+
def _render_result(self, result: dict[str, Any]) -> None:
|
|
934
|
+
status = str(result.get("status") or "unknown")
|
|
935
|
+
payload = result.get("result") or {}
|
|
936
|
+
summary = payload.get("summary", payload) if isinstance(payload, dict) else payload
|
|
937
|
+
lines = [f"[{status.upper()}] execução {result.get('id', '—')}"]
|
|
938
|
+
if result.get("error"):
|
|
939
|
+
lines.append(f"erro: {result['error']}")
|
|
940
|
+
if result.get("reused"):
|
|
941
|
+
lines.append("Resultado reutilizado pelo fingerprint da operação.")
|
|
942
|
+
if isinstance(summary, dict):
|
|
943
|
+
lines.extend(f"{key}: {value}" for key, value in summary.items())
|
|
944
|
+
if isinstance(payload, dict):
|
|
945
|
+
warnings = payload.get("warnings") or []
|
|
946
|
+
pending = payload.get("pending") or []
|
|
947
|
+
products = payload.get("products") or []
|
|
948
|
+
lines.append(f"warnings: {len(warnings)} · pendências: {len(pending)} · produtos: {len(products)}")
|
|
949
|
+
self.query_one("#operation-result", Static).update("\n".join(lines))
|
|
950
|
+
self.query_one("#operation-result", Static).add_class(
|
|
951
|
+
"result-success" if status in {"completed", "awaiting_input"} else "result-error"
|
|
952
|
+
)
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
class EvaluationPriorityListItem(ListItem):
|
|
956
|
+
"""Linha substantiva da fila de revisão, sem detalhes técnicos de modelo."""
|
|
957
|
+
|
|
958
|
+
def __init__(self, item: dict[str, Any], **kwargs) -> None:
|
|
959
|
+
reasons = ", ".join(item.get("priority_reasons") or ())
|
|
960
|
+
votes = ", ".join(
|
|
961
|
+
f"{decision}={count}"
|
|
962
|
+
for decision, count in sorted((item.get("votes") or {}).items())
|
|
963
|
+
)
|
|
964
|
+
text = Static(
|
|
965
|
+
f"{item.get('item_code', '—')} · {reasons or 'sem prioridade'}\n"
|
|
966
|
+
f"votos: {votes or '—'} · maioria: {item.get('majority_decision') or 'nenhuma'} "
|
|
967
|
+
f"· juiz: {item.get('judge_decision') or '—'} · {item.get('review_status')}",
|
|
968
|
+
markup=False,
|
|
969
|
+
)
|
|
970
|
+
super().__init__(text, classes="evaluation-review-item", **kwargs)
|
|
971
|
+
self.item = item
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
class EvaluationReviewScreen(Screen[None]):
|
|
975
|
+
"""Fila final de revisão construída sobre as mesmas Operações do headless."""
|
|
976
|
+
|
|
977
|
+
BINDINGS = [("escape", "back", "Voltar")]
|
|
978
|
+
|
|
979
|
+
def __init__(self, **kwargs) -> None:
|
|
980
|
+
super().__init__(**kwargs)
|
|
981
|
+
self._items: list[dict[str, Any]] = []
|
|
982
|
+
self._selected: dict[str, Any] | None = None
|
|
983
|
+
|
|
984
|
+
def compose(self) -> ComposeResult:
|
|
985
|
+
with Vertical(id="evaluation-review-shell"):
|
|
986
|
+
yield Static("REVISÃO HUMANA DAS AVALIAÇÕES", classes="screen-title", markup=False)
|
|
987
|
+
yield Static(
|
|
988
|
+
"Somente indecisões entre avaliadores e decisões do juiz contra a maioria.",
|
|
989
|
+
classes="dialog-description",
|
|
990
|
+
markup=False,
|
|
991
|
+
)
|
|
992
|
+
with Horizontal(id="evaluation-review-toolbar"):
|
|
993
|
+
yield Input(id="review-run-id", placeholder="run_id da avaliação")
|
|
994
|
+
yield Input(id="review-reviewer", placeholder="identificação da pessoa revisora")
|
|
995
|
+
yield Button("[ CARREGAR ]", id="review-load", variant="success")
|
|
996
|
+
yield Static("Informe uma execução para carregar a fila.", id="review-summary", markup=False)
|
|
997
|
+
yield ListView(id="review-items")
|
|
998
|
+
yield Static("", id="review-detail", classes="operation-result", markup=False)
|
|
999
|
+
with Horizontal(id="evaluation-review-decision"):
|
|
1000
|
+
yield Select(
|
|
1001
|
+
(("Confirmar juiz", "confirm"), ("Substituir decisão", "override"), ("Adiar", "defer")),
|
|
1002
|
+
value="confirm",
|
|
1003
|
+
allow_blank=False,
|
|
1004
|
+
id="review-action",
|
|
1005
|
+
)
|
|
1006
|
+
yield Input(id="review-replacement", placeholder="decisão substituta (somente override)")
|
|
1007
|
+
yield Input(id="review-rationale", placeholder="justificativa obrigatória para override")
|
|
1008
|
+
yield Static("", id="review-feedback", classes="form-feedback", markup=False)
|
|
1009
|
+
with Horizontal(classes="screen-actions"):
|
|
1010
|
+
yield Button("[ REGISTRAR DECISÃO ]", id="review-apply", variant="success")
|
|
1011
|
+
yield Button("[ ESC ] Voltar", id="review-back")
|
|
1012
|
+
yield Footer(id="review-footer", show_command_palette=False)
|
|
1013
|
+
|
|
1014
|
+
def on_mount(self) -> None:
|
|
1015
|
+
self.query_one("#review-run-id", Input).focus()
|
|
1016
|
+
|
|
1017
|
+
def _load(self) -> None:
|
|
1018
|
+
run_id = self.query_one("#review-run-id", Input).value.strip()
|
|
1019
|
+
if not run_id:
|
|
1020
|
+
self._feedback("[ERR] Informe o run_id da avaliação.")
|
|
1021
|
+
return
|
|
1022
|
+
if self.app.session is None:
|
|
1023
|
+
self._feedback("[ERR] Crie ou abra uma auditoria antes da revisão.")
|
|
1024
|
+
return
|
|
1025
|
+
try:
|
|
1026
|
+
from .engines.evaluation import EvaluationQuery
|
|
1027
|
+
|
|
1028
|
+
view = self.app.session.engine.evaluations.inspect(
|
|
1029
|
+
EvaluationQuery(run_id=run_id, priority_only=True, limit=100_000)
|
|
1030
|
+
)
|
|
1031
|
+
except ArgosError as exc:
|
|
1032
|
+
self._feedback(f"[ERR] {exc}")
|
|
1033
|
+
return
|
|
1034
|
+
self._items = [
|
|
1035
|
+
{
|
|
1036
|
+
"run_id": item.run_id,
|
|
1037
|
+
"case_key": item.case_key,
|
|
1038
|
+
"item_code": item.item_code,
|
|
1039
|
+
"review_identity": item.review_identity,
|
|
1040
|
+
"semantic_identity": item.semantic_identity,
|
|
1041
|
+
"priority_reasons": list(item.priority_reasons),
|
|
1042
|
+
"votes": dict(item.votes),
|
|
1043
|
+
"valid_opinions": item.valid_opinions,
|
|
1044
|
+
"majority_decision": item.majority_decision,
|
|
1045
|
+
"judge_decision": item.judge_decision,
|
|
1046
|
+
"effective_decision": item.effective_decision,
|
|
1047
|
+
"review_status": item.review_status,
|
|
1048
|
+
"conclusion": dict(item.conclusion),
|
|
1049
|
+
}
|
|
1050
|
+
for item in view.priority_items
|
|
1051
|
+
]
|
|
1052
|
+
self._selected = None
|
|
1053
|
+
listing = self.query_one("#review-items", ListView)
|
|
1054
|
+
listing.clear()
|
|
1055
|
+
listing.mount(*(EvaluationPriorityListItem(item) for item in self._items))
|
|
1056
|
+
pending = sum(item.get("review_status") not in {"confirmed", "overridden"} for item in self._items)
|
|
1057
|
+
self.query_one("#review-summary", Static).update(
|
|
1058
|
+
f"{len(self._items)} item(ns) prioritário(s) · {pending} pendente(s)"
|
|
1059
|
+
)
|
|
1060
|
+
if self._items:
|
|
1061
|
+
listing.focus()
|
|
1062
|
+
listing.index = 0
|
|
1063
|
+
else:
|
|
1064
|
+
self.query_one("#review-rationale", Input).focus()
|
|
1065
|
+
self._feedback("[OK] Fila atualizada.")
|
|
1066
|
+
|
|
1067
|
+
def on_list_view_selected(self, event: ListView.Selected) -> None:
|
|
1068
|
+
if not isinstance(event.item, EvaluationPriorityListItem):
|
|
1069
|
+
return
|
|
1070
|
+
self._selected = event.item.item
|
|
1071
|
+
conclusion = self._selected.get("conclusion") or {}
|
|
1072
|
+
self.query_one("#review-detail", Static).update(
|
|
1073
|
+
"\n".join(
|
|
1074
|
+
(
|
|
1075
|
+
f"Item: {self._selected.get('item_code')}",
|
|
1076
|
+
f"Decisão do juiz: {self._selected.get('judge_decision')}",
|
|
1077
|
+
f"Justificativa: {conclusion.get('justificativa') or '—'}",
|
|
1078
|
+
f"Lacunas: {conclusion.get('lacunas') or []}",
|
|
1079
|
+
)
|
|
1080
|
+
)
|
|
1081
|
+
)
|
|
1082
|
+
|
|
1083
|
+
def _apply(self) -> None:
|
|
1084
|
+
if self._selected is None:
|
|
1085
|
+
self._feedback("[ERR] Selecione um item prioritário.")
|
|
1086
|
+
return
|
|
1087
|
+
reviewer = self.query_one("#review-reviewer", Input).value.strip()
|
|
1088
|
+
rationale = self.query_one("#review-rationale", Input).value.strip()
|
|
1089
|
+
action = str(self.query_one("#review-action", Select).value or "")
|
|
1090
|
+
replacement = self.query_one("#review-replacement", Input).value.strip()
|
|
1091
|
+
try:
|
|
1092
|
+
from .engines.evaluation import (
|
|
1093
|
+
PriorityReviewCommand,
|
|
1094
|
+
PriorityReviewDecision,
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
self.app.session.engine.evaluations.review(
|
|
1098
|
+
PriorityReviewCommand(
|
|
1099
|
+
run_id=self._selected["run_id"],
|
|
1100
|
+
reviewer=reviewer,
|
|
1101
|
+
decisions=(
|
|
1102
|
+
PriorityReviewDecision(
|
|
1103
|
+
case_key=self._selected["case_key"],
|
|
1104
|
+
item_code=self._selected["item_code"],
|
|
1105
|
+
semantic_identity=self._selected["semantic_identity"],
|
|
1106
|
+
review_identity=self._selected["review_identity"],
|
|
1107
|
+
action=action,
|
|
1108
|
+
rationale=rationale,
|
|
1109
|
+
replacement_decision=replacement or None,
|
|
1110
|
+
),
|
|
1111
|
+
),
|
|
1112
|
+
)
|
|
1113
|
+
)
|
|
1114
|
+
except ArgosError as exc:
|
|
1115
|
+
self._feedback(f"[ERR] {exc}")
|
|
1116
|
+
return
|
|
1117
|
+
self.query_one("#review-rationale", Input).value = ""
|
|
1118
|
+
self.query_one("#review-replacement", Input).value = ""
|
|
1119
|
+
self._load()
|
|
1120
|
+
|
|
1121
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
1122
|
+
actions = {
|
|
1123
|
+
"review-load": self._load,
|
|
1124
|
+
"review-apply": self._apply,
|
|
1125
|
+
"review-back": self.action_back,
|
|
1126
|
+
}
|
|
1127
|
+
action = actions.get(event.button.id or "")
|
|
1128
|
+
if action:
|
|
1129
|
+
action()
|
|
1130
|
+
|
|
1131
|
+
def _feedback(self, message: str) -> None:
|
|
1132
|
+
self.query_one("#review-feedback", Static).update(message)
|
|
1133
|
+
|
|
1134
|
+
def action_back(self) -> None:
|
|
1135
|
+
self.dismiss(None)
|
|
1136
|
+
|
|
1137
|
+
|
|
1138
|
+
class HelpScreen(Screen[None]):
|
|
1139
|
+
BINDINGS = [("escape", "back", "Voltar")]
|
|
1140
|
+
|
|
1141
|
+
def compose(self) -> ComposeResult:
|
|
1142
|
+
with Vertical(id="help-dialog"):
|
|
1143
|
+
yield Static("AJUDA / NAVEGAÇÃO", classes="screen-title", markup=False)
|
|
1144
|
+
with VerticalScroll(id="help-scroll"):
|
|
1145
|
+
yield Static(
|
|
1146
|
+
"Onde estou? A barra superior mostra ARGOS, versão, auditoria corrente e status.\n\n"
|
|
1147
|
+
"Foco TAB / SHIFT+TAB navegam pelos controles.\n"
|
|
1148
|
+
"Seleção ENTER abre ou executa; SPACE alterna campos booleanos.\n"
|
|
1149
|
+
"Movimento Setas navegam por fases e operações.\n"
|
|
1150
|
+
"Auditoria N nova · A abrir · R recentes.\n"
|
|
1151
|
+
"Operações / abre o catálogo de operações pesquisável.\n"
|
|
1152
|
+
"Retorno ESC cancela ou volta.\n"
|
|
1153
|
+
"Aplicação Q sai da home quando nenhum campo está sendo editado.\n\n"
|
|
1154
|
+
"Estados [OK] concluído · [RUN] em andamento · [ ] pendente ·\n"
|
|
1155
|
+
" [BLOCK] aguardando insumos · [ERR] erro.\n\n"
|
|
1156
|
+
"A TUI e o modo headless usam o mesmo catálogo de operações, motor e SQLite.\n"
|
|
1157
|
+
"Avaliações de IA permanecem drafts sujeitos à revisão humana.",
|
|
1158
|
+
markup=False,
|
|
1159
|
+
)
|
|
1160
|
+
yield Button("[ ESC ] Voltar", id="help-back")
|
|
1161
|
+
|
|
1162
|
+
def on_mount(self) -> None:
|
|
1163
|
+
self.query_one("#help-back", Button).focus()
|
|
1164
|
+
|
|
1165
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
1166
|
+
if event.button.id == "help-back":
|
|
1167
|
+
self.action_back()
|
|
1168
|
+
|
|
1169
|
+
def action_back(self) -> None:
|
|
1170
|
+
self.dismiss(None)
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
def _form_controls(screen: Screen) -> list[Input | Select | Checkbox | Button]:
|
|
1174
|
+
"""Retorna os controles focáveis na ordem visual do formulário."""
|
|
1175
|
+
|
|
1176
|
+
return [
|
|
1177
|
+
widget
|
|
1178
|
+
for widget in screen.query("Input, Select, Checkbox, Button")
|
|
1179
|
+
if widget.can_focus and not widget.disabled and widget.display
|
|
1180
|
+
]
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
def _move_form_focus(screen: Screen, delta: int) -> None:
|
|
1184
|
+
controls = _form_controls(screen)
|
|
1185
|
+
if not controls:
|
|
1186
|
+
return
|
|
1187
|
+
current = screen.app.focused
|
|
1188
|
+
try:
|
|
1189
|
+
index = controls.index(current)
|
|
1190
|
+
except ValueError:
|
|
1191
|
+
index = 0 if delta >= 0 else len(controls) - 1
|
|
1192
|
+
target = controls[(index + delta) % len(controls)]
|
|
1193
|
+
target.focus()
|
|
1194
|
+
target.scroll_visible()
|
|
1195
|
+
|
|
1196
|
+
|
|
1197
|
+
def _handle_form_key(screen: Screen, event) -> bool:
|
|
1198
|
+
"""Aplica a política de teclado comum aos formulários modais."""
|
|
1199
|
+
|
|
1200
|
+
if event.key in {"tab", "shift+tab"}:
|
|
1201
|
+
focused = screen.app.focused
|
|
1202
|
+
if event.key == "tab" and isinstance(focused, PathInput):
|
|
1203
|
+
focused.complete_path()
|
|
1204
|
+
event.stop()
|
|
1205
|
+
event.prevent_default()
|
|
1206
|
+
return True
|
|
1207
|
+
if event.key in {"up", "down"}:
|
|
1208
|
+
_move_form_focus(screen, -1 if event.key == "up" else 1)
|
|
1209
|
+
event.stop()
|
|
1210
|
+
event.prevent_default()
|
|
1211
|
+
return True
|
|
1212
|
+
return False
|
|
1213
|
+
|
|
1214
|
+
|
|
1215
|
+
def _display_default(value: Any) -> str:
|
|
1216
|
+
if isinstance(value, (dict, list, tuple)):
|
|
1217
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
1218
|
+
return str(value)
|
|
1219
|
+
|
|
1220
|
+
|
|
1221
|
+
def _parameter_hint(description: str, multiple: bool, path: bool) -> str:
|
|
1222
|
+
hints = [description or "sem descrição"]
|
|
1223
|
+
if multiple:
|
|
1224
|
+
hints.append("aceita múltiplos valores")
|
|
1225
|
+
if path:
|
|
1226
|
+
hints.append("caminho")
|
|
1227
|
+
return " · ".join(hints)
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
def _short_status(status: str) -> str:
|
|
1231
|
+
normalized = " ".join(str(status).split())
|
|
1232
|
+
return normalized if len(normalized) <= 58 else normalized[:55] + "..."
|
|
1233
|
+
|
|
1234
|
+
|
|
1235
|
+
def _result_status(result: dict[str, Any]) -> str:
|
|
1236
|
+
status = str(result.get("status") or "unknown")
|
|
1237
|
+
if status == "completed":
|
|
1238
|
+
return "[OK] Operação concluída"
|
|
1239
|
+
if status == "awaiting_input":
|
|
1240
|
+
return "[WARN] Operação concluída com pendências"
|
|
1241
|
+
return f"[ERR] Operação {status}"
|
|
1242
|
+
|
|
1243
|
+
|
|
1244
|
+
def run_textual_app(
|
|
1245
|
+
*,
|
|
1246
|
+
catalog: OperationCatalog,
|
|
1247
|
+
project_root: str | Path,
|
|
1248
|
+
workspace_root: str | Path,
|
|
1249
|
+
numero: str | None = None,
|
|
1250
|
+
nome: str | None = None,
|
|
1251
|
+
) -> int:
|
|
1252
|
+
"""Launcher pequeno para o CLI, mantendo ``main`` como ponto de entrada."""
|
|
1253
|
+
|
|
1254
|
+
app = ArgosApp(
|
|
1255
|
+
catalog=catalog,
|
|
1256
|
+
project_root=project_root,
|
|
1257
|
+
workspace_root=workspace_root,
|
|
1258
|
+
numero=numero,
|
|
1259
|
+
nome=nome,
|
|
1260
|
+
)
|
|
1261
|
+
app.run()
|
|
1262
|
+
return 0
|