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.
Files changed (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
argos/cli.py ADDED
@@ -0,0 +1,606 @@
1
+ """Interface única do Argos: TUI interativo e modo headless."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import textwrap
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any, Iterable
14
+
15
+ from . import __version__
16
+ from .core import AuditIdentityRequiredError, ArgosError, OperationCatalog, OperationSpec, split_operation_id
17
+ from .catalog import build_catalog
18
+ from .core import AuditSession
19
+ from .status import is_execution_exit_success
20
+ from .envfile import load_env_file
21
+ from .progress import make_progress
22
+
23
+
24
+ def _parser() -> argparse.ArgumentParser:
25
+ parser = argparse.ArgumentParser(
26
+ prog="argos",
27
+ description="Núcleo genérico Argos para fiscalizações, sem subprocessos.",
28
+ # Sem abreviação de flags: `--limit` não pode valer como prefixo de `--limite` (nomes antigos não têm alias).
29
+ allow_abbrev=False,
30
+ )
31
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
32
+ parser.add_argument("--headless", action="store_true", help="executa sem TUI")
33
+ parser.add_argument("--list-operations", "--list", action="store_true", help="lista o catálogo de operações")
34
+ parser.add_argument("--run", metavar="OPERACAO", help="operação a executar no modo headless")
35
+ parser.add_argument("--jobs", type=int, help="unidades simultâneas de lotes")
36
+ parser.add_argument("--resume", metavar="EXECUCAO", help="retoma uma execução pelo id")
37
+ parser.add_argument(
38
+ "--param", action="append", default=[], metavar="CHAVE=VALOR", help="parâmetro da operação; pode repetir"
39
+ )
40
+ parser.add_argument("--numero", help="substitui o número nos produtos; em projetos sem fiscalizacao.yml, seleciona a fiscalização")
41
+ parser.add_argument("--nome", help="substitui o título nos produtos; em projetos sem fiscalizacao.yml, seleciona a fiscalização")
42
+ parser.add_argument("--project-root", default=".", help="diretório do projeto; padrão: diretório atual")
43
+ parser.add_argument(
44
+ "--workspace-root",
45
+ default=None,
46
+ help="opção avançada: controle SQLite alternativo; por padrão usa fiscalizacao.yml",
47
+ )
48
+ parser.add_argument("--force", action="store_true", help="não reutiliza execução idêntica")
49
+ parser.add_argument("--json", action="store_true", help="imprime resultado JSON")
50
+ parser.add_argument(
51
+ "--no-progress",
52
+ dest="no_progress",
53
+ action="store_true",
54
+ help="não mostra o andamento de operações longas (barra, contagens e ETA em stderr)",
55
+ )
56
+ parser.add_argument(
57
+ "operation",
58
+ nargs="?",
59
+ metavar="OPERACAO",
60
+ help="operação: `objeto` ou `objeto acao` (id `objeto.acao`); implica execução headless (atalho para --run)",
61
+ )
62
+ parser.epilog = (
63
+ "Operações: argos OBJETO [ACAO] [VALOR] [--chave valor] (ou chave=valor). "
64
+ "`argos OBJETO --help` lista as ações do objeto. "
65
+ "Novo projeto: argos init DESTINO --numero NNN/AAAA --nome NOME --objetivo OBJETIVO (alias: criar-projeto)"
66
+ )
67
+ return parser
68
+
69
+
70
+ def parse_parameters(values: Iterable[str]) -> dict[str, Any]:
71
+ params: dict[str, Any] = {}
72
+ for raw in values:
73
+ if "=" not in raw:
74
+ raise ArgosError(f"parâmetro inválido {raw!r}; use chave=valor")
75
+ key, value = raw.split("=", 1)
76
+ key = key.strip().replace("-", "_")
77
+ if not key:
78
+ raise ArgosError(f"parâmetro sem nome: {raw!r}")
79
+ coerced = value
80
+ if key in params:
81
+ if isinstance(params[key], list):
82
+ params[key].append(coerced)
83
+ else:
84
+ params[key] = [params[key], coerced]
85
+ else:
86
+ params[key] = coerced
87
+ return params
88
+
89
+
90
+ def _parameter_flags(parameter: Any) -> tuple[str, ...]:
91
+ """Flag canônica seguida dos aliases declarados no contrato."""
92
+ return tuple(
93
+ "--" + name.replace("_", "-") for name in (parameter.name, *parameter.aliases)
94
+ )
95
+
96
+
97
+ def _operation_arguments(parser: argparse.ArgumentParser, spec: OperationSpec) -> dict[str, str]:
98
+ """Expõe o contrato existente como flags, sem outra lista de parâmetros."""
99
+ names: dict[str, str] = {}
100
+ existing = {option: action.dest for action in parser._actions for option in action.option_strings}
101
+ group = parser.add_argument_group(f"parâmetros de {spec.id}", spec.description)
102
+ for parameter in spec.parameters:
103
+ flags = _parameter_flags(parameter)
104
+ if flags[0] in existing:
105
+ names[parameter.name] = existing[flags[0]]
106
+ continue
107
+ flags = tuple(flag for flag in flags if flag not in existing)
108
+ dest = "op_" + parameter.name
109
+ help_text = parameter.description
110
+ if parameter.positional:
111
+ help_text = f"{help_text} (também aceito como argumento posicional)".strip()
112
+ options: dict[str, Any] = {"dest": dest, "default": None, "help": help_text}
113
+ if parameter.multiple:
114
+ options["action"] = "append"
115
+ elif parameter.boolean:
116
+ options.update(nargs="?", const="true")
117
+ group.add_argument(*flags, **options)
118
+ names[parameter.name] = dest
119
+ return names
120
+
121
+
122
+ def _supplied_parameters(args: argparse.Namespace) -> dict[str, Any]:
123
+ params = parse_parameters(args.param)
124
+ for name, dest in getattr(args, "operation_arguments", {}).items():
125
+ if name not in getattr(args, "explicit_operation_parameters", ()):
126
+ continue
127
+ value = getattr(args, dest, None)
128
+ if value is None:
129
+ continue
130
+ if name in params:
131
+ raise ArgosError(f"parâmetro {name} foi informado por flag e por --param/chave=valor; escolha uma forma")
132
+ params[name] = value
133
+ positional = getattr(args, "positional", None)
134
+ if positional is not None:
135
+ name, value = positional
136
+ if name in params:
137
+ raise ArgosError(
138
+ f"{name} foi informado como argumento posicional e também por flag ou --param/chave=valor; use apenas um"
139
+ )
140
+ params[name] = value
141
+ return params
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class _Invocation:
146
+ """Operação resolvida a partir do argv, antes de montar as flags dinâmicas."""
147
+
148
+ argv: list[str] # para o argparse: a operação aparece como um único token
149
+ operation: str | None = None
150
+ positional: tuple[str, str] | None = None # (parâmetro, valor)
151
+ objeto: str | None = None # objeto citado sem ação; a ajuda lista as ações
152
+
153
+
154
+ def _first_word(argv: list[str], parser: argparse.ArgumentParser) -> int | None:
155
+ """Índice do primeiro token que não é flag global (nem valor dela)."""
156
+ options = {option: action for action in parser._actions for option in action.option_strings}
157
+ index = 0
158
+ while index < len(argv):
159
+ token = argv[index]
160
+ if not token.startswith("-"):
161
+ return index
162
+ action = options.get(token.partition("=")[0])
163
+ if action is None:
164
+ return None
165
+ index += 1 if "=" in token or action.nargs == 0 else 2
166
+ return None
167
+
168
+
169
+ def _bare(argv: list[str], index: int) -> str | None:
170
+ return argv[index] if index < len(argv) and not argv[index].startswith("-") else None
171
+
172
+
173
+ def _is_assignment(token: str, spec: OperationSpec) -> bool:
174
+ """`chave=valor` cuja chave é parâmetro da operação (não um posicional com '=')."""
175
+ key, equals, _ = token.partition("=")
176
+ names = {name for parameter in spec.parameters for name in (parameter.name, *parameter.aliases)}
177
+ return bool(equals) and key.replace("-", "_") in names
178
+
179
+
180
+ def _action_names(catalog: OperationCatalog, objeto: str) -> str:
181
+ return ", ".join(
182
+ acao for acao in (split_operation_id(spec.id)[1] for spec in catalog.actions(objeto)) if acao
183
+ )
184
+
185
+
186
+ def _wants_help(argv: list[str]) -> bool:
187
+ return "-h" in argv or "--help" in argv
188
+
189
+
190
+ def _resolve_invocation(
191
+ argv: list[str], parser: argparse.ArgumentParser, catalog: OperationCatalog
192
+ ) -> _Invocation:
193
+ """Resolve `objeto`, `objeto acao` e o posicional; falha listando as ações válidas."""
194
+ ids = {spec.id for spec in catalog.all()}
195
+ objects = set(catalog.objects())
196
+ first = _first_word(argv, parser)
197
+ word = argv[first] if first is not None else None
198
+ if word is not None and (word in ids or word in objects):
199
+ following = _bare(argv, first + 1)
200
+ operation: str | None = None
201
+ consumed = 1
202
+ if following is not None and f"{word}.{following}" in ids:
203
+ operation, consumed = f"{word}.{following}", 2
204
+ elif word in ids:
205
+ operation = word
206
+ has_actions = len(catalog.actions(word)) > 1
207
+ if consumed == 1 and operation is not None:
208
+ spec = catalog.get(operation)
209
+ if (
210
+ following is not None
211
+ and has_actions
212
+ and not any(parameter.positional for parameter in spec.parameters)
213
+ and not _is_assignment(following, spec)
214
+ ):
215
+ raise ArgosError(
216
+ f"ação desconhecida para {word}: {following}; ações: {_action_names(catalog, word)}"
217
+ )
218
+ if operation is None:
219
+ if _wants_help(argv):
220
+ return _Invocation(argv, objeto=word)
221
+ if following is None:
222
+ raise ArgosError(
223
+ f"informe a ação de {word}; ações: {_action_names(catalog, word)}"
224
+ )
225
+ raise ArgosError(
226
+ f"ação desconhecida para {word}: {following}; ações: {_action_names(catalog, word)}"
227
+ )
228
+ positional = None
229
+ target = next((p for p in catalog.get(operation).parameters if p.positional), None)
230
+ value = _bare(argv, first + consumed)
231
+ if target is not None and value is not None and not _is_assignment(value, catalog.get(operation)):
232
+ positional = (target.name, value)
233
+ consumed += 1
234
+ resolved = argv[:first] + [operation] + argv[first + consumed :]
235
+ objeto = word if consumed == 1 and has_actions else None
236
+ return _Invocation(resolved, operation, positional, objeto)
237
+
238
+ uses_run = any(token == "--run" or token.startswith("--run=") for token in argv)
239
+ if word is not None and not uses_run:
240
+ # Sem isso, o argparse acusa as flags do comando antigo (`--fase`, `--audit-result`...)
241
+ # em vez de dizer que a operação não existe.
242
+ raise ArgosError(
243
+ f"operação desconhecida: {word}; objetos: {', '.join(catalog.objects())}. "
244
+ "Use `argos --list-operations`."
245
+ )
246
+
247
+ selected: str | None = None
248
+ index = 0
249
+ while index < len(argv):
250
+ token = argv[index]
251
+ if token == "--run":
252
+ if index + 1 < len(argv):
253
+ selected = argv[index + 1]
254
+ index += 2
255
+ continue
256
+ elif token.startswith("--run="):
257
+ selected = token.partition("=")[2]
258
+ index += 1
259
+ return _Invocation(argv, selected if selected in ids else None)
260
+
261
+
262
+ def _print_object_help(parser: argparse.ArgumentParser, catalog: OperationCatalog, objeto: str) -> None:
263
+ """Ajuda do objeto: flags da operação de mesmo nome (se houver) e as ações."""
264
+ parser.print_help()
265
+ print("\nações:")
266
+ actions = [
267
+ (acao, spec)
268
+ for spec in catalog.actions(objeto)
269
+ for acao in (split_operation_id(spec.id)[1],)
270
+ if acao
271
+ ]
272
+ width = max(len(acao) for acao, _ in actions)
273
+ for acao, spec in actions:
274
+ lines = spec.description.strip().splitlines()
275
+ print(f" {acao:<{width}} {lines[0] if lines else spec.name}")
276
+ print(f"\nUse `argos {objeto} AÇÃO --help` para as flags de cada ação.")
277
+
278
+
279
+ def _catalog_width() -> int:
280
+ """Obtém uma largura previsível para o catálogo textual.
281
+
282
+ ``ARGOS_CATALOG_WIDTH`` permite screenshots, logs e testes determinísticos;
283
+ sem override, a largura do terminal é usada com limites para evitar linhas
284
+ excessivamente estreitas ou longas.
285
+ """
286
+ override = os.environ.get("ARGOS_CATALOG_WIDTH")
287
+ if override:
288
+ try:
289
+ return max(72, min(int(override), 160))
290
+ except ValueError:
291
+ pass
292
+ columns = shutil.get_terminal_size((100, 24)).columns
293
+ return max(72, min(columns, 160))
294
+
295
+
296
+ def _display_default(value: Any) -> str:
297
+ if isinstance(value, bool):
298
+ return "true" if value else "false"
299
+ if isinstance(value, (dict, list, tuple)):
300
+ return json.dumps(value, ensure_ascii=False, default=str, separators=(",", ":"))
301
+ return str(value)
302
+
303
+
304
+ def _parameter_token(parameter: Any) -> str:
305
+ return parameter.name + ("[]" if parameter.multiple else "")
306
+
307
+
308
+ def _wrapped_lines(value: Any, width: int) -> list[str]:
309
+ text = " ".join(str(value or "").split())
310
+ return textwrap.wrap(text, width=max(20, width)) or ["(sem descrição)"]
311
+
312
+
313
+ def _print_operation(spec: OperationSpec, number: int, width: int) -> None:
314
+ print(f" {number:02d}. {spec.id} — {spec.name} (versão {spec.version})")
315
+ description_indent = " "
316
+ for line in _wrapped_lines(spec.description, width - len(description_indent)):
317
+ print(f"{description_indent}{line}")
318
+ if not spec.parameters:
319
+ print(" parâmetros: nenhum")
320
+ return
321
+
322
+ print(" parâmetros:")
323
+ tokens = [_parameter_token(parameter) for parameter in spec.parameters]
324
+ label_width = min(max(len(token) for token in tokens), 48)
325
+ for parameter, token in zip(spec.parameters, tokens):
326
+ marker = "*" if parameter.required else " "
327
+ prefix = f" {marker} {token:<{label_width}} "
328
+ annotations: list[str] = []
329
+ if parameter.path:
330
+ annotations.append("path")
331
+ if parameter.boolean:
332
+ annotations.append("boolean")
333
+ if parameter.positional:
334
+ annotations.append("posicional")
335
+ for alias in parameter.aliases:
336
+ annotations.append(f"alias: --{alias.replace('_', '-')}")
337
+ if parameter.default is not None:
338
+ annotations.append(f"default: {_display_default(parameter.default)}")
339
+ description = parameter.description or "(sem descrição)"
340
+ if annotations:
341
+ description = f"{description} ({'; '.join(annotations)})"
342
+ lines = _wrapped_lines(description, width - len(prefix))
343
+ print(f"{prefix}{lines[0]}")
344
+ continuation_indent = " " * len(prefix)
345
+ for line in lines[1:]:
346
+ print(f"{continuation_indent}{line}")
347
+
348
+
349
+ def print_catalog(catalog: OperationCatalog, *, as_json: bool = False) -> None:
350
+ if as_json:
351
+ print(
352
+ json.dumps(
353
+ [
354
+ {
355
+ "id": spec.id,
356
+ "object": split_operation_id(spec.id)[0],
357
+ "action": split_operation_id(spec.id)[1],
358
+ "version": spec.version,
359
+ "name": spec.name,
360
+ "group": spec.group,
361
+ "description": spec.description,
362
+ "resources": (
363
+ spec.resources.as_json()
364
+ if not callable(spec.resources)
365
+ else {"derived_from_parameters": True}
366
+ ),
367
+ "products": {
368
+ "kinds": list(spec.products.kinds),
369
+ "path_parameters": list(spec.products.path_parameters),
370
+ "allow_inferred": spec.products.allow_inferred,
371
+ "allow_dynamic": spec.products.allow_dynamic,
372
+ },
373
+ "parameters": [
374
+ {
375
+ "name": parameter.name,
376
+ "required": parameter.required,
377
+ "multiple": parameter.multiple,
378
+ "boolean": parameter.boolean,
379
+ "positional": parameter.positional,
380
+ "aliases": list(parameter.aliases),
381
+ "active_when": dict(parameter.active_when),
382
+ "choices": list(parameter.choices),
383
+ "default": parameter.default,
384
+ "description": parameter.description,
385
+ }
386
+ for parameter in spec.parameters
387
+ ],
388
+ }
389
+ for spec in catalog.all()
390
+ ],
391
+ ensure_ascii=False,
392
+ indent=2,
393
+ )
394
+ )
395
+ return
396
+ specs = catalog.all()
397
+ width = _catalog_width()
398
+ print("Argos CLI · catálogo de operações")
399
+ print(f"{len(specs)} operações disponíveis · largura {width} colunas")
400
+ print("Legenda: * obrigatório · [] aceita vários valores · [path] caminho de arquivo")
401
+ print("Use `argos <objeto> [<ação>] [--flag valor]` ou `argos --headless --run <id>` para execução direta.")
402
+ print("=" * width)
403
+
404
+ operation_number = 0
405
+ for objeto in catalog.objects():
406
+ group = catalog.actions(objeto)
407
+ plural = "operação" if len(group) == 1 else "operações"
408
+ print(f"\n[{objeto} · {len(group)} {plural}]")
409
+ print("-" * min(width, max(24, len(objeto) + 15)))
410
+ for spec in group:
411
+ operation_number += 1
412
+ _print_operation(spec, operation_number, width)
413
+
414
+
415
+ def print_result(result: dict[str, Any], *, as_json: bool = False) -> None:
416
+ if as_json:
417
+ print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
418
+ return
419
+ status = result.get("status", "-")
420
+ execution_id = result.get("id", "-")
421
+ reused = " (reutilizada)" if result.get("reused") else ""
422
+ print(f"[{status}] execução {execution_id}{reused}")
423
+ if result.get("error"):
424
+ print(f"erro: {result['error']}")
425
+ payload = result.get("result")
426
+ if payload:
427
+ summary = payload.get("summary", payload)
428
+ print(json.dumps(summary, ensure_ascii=False, indent=2, default=str))
429
+ products = payload.get("products", [])
430
+ for product in products:
431
+ print(f"produto: {product.get('path')} ({product.get('sha256')})")
432
+
433
+
434
+ def print_evaluations(items: list[dict[str, Any]], *, as_json: bool = False) -> None:
435
+ if as_json:
436
+ print(json.dumps(items, ensure_ascii=False, indent=2, default=str))
437
+ return
438
+ if not items:
439
+ print("nenhuma avaliação encontrada")
440
+ return
441
+ for item in items:
442
+ print(
443
+ f"{item['revision_id']} {item['status']:<10}"
444
+ f" {item['provider']}/{item['model']}"
445
+ f" {item['tipo']} {item['case_key']} cenário={item['cenario_id']}"
446
+ )
447
+
448
+
449
+ def _open_session(
450
+ args: argparse.Namespace,
451
+ catalog: OperationCatalog,
452
+ *,
453
+ interactive: bool,
454
+ ) -> AuditSession:
455
+ values = {
456
+ "project_root": args.project_root,
457
+ "workspace_root": args.workspace_root,
458
+ "catalog": catalog,
459
+ "numero": args.numero,
460
+ "nome": args.nome,
461
+ }
462
+ try:
463
+ return AuditSession.open(**values)
464
+ except AuditIdentityRequiredError:
465
+ if not interactive or args.numero is not None or args.nome is not None:
466
+ raise
467
+ number = input("Número da fiscalização (ex.: 01/2026): ").strip()
468
+ name = input("Nome da fiscalização: ").strip()
469
+ if not number or not name:
470
+ raise ArgosError("informe --numero e --nome para abrir a fiscalização")
471
+ return AuditSession.open(**{**values, "numero": number, "nome": name})
472
+
473
+
474
+ def _resolve_positional_operation(args: argparse.Namespace, catalog: OperationCatalog) -> None:
475
+ operation = args.operation
476
+ if not operation:
477
+ return
478
+ conflicting = [
479
+ option
480
+ for option, present in (
481
+ ("--run", bool(args.run)),
482
+ ("--resume", bool(args.resume)),
483
+ ("--list", bool(args.list_operations)),
484
+ )
485
+ if present
486
+ ]
487
+ if conflicting:
488
+ raise ArgosError(f"não combine a operação posicional {operation!r} com " + ", ".join(conflicting))
489
+ try:
490
+ catalog.get(operation)
491
+ except ArgosError as exc:
492
+ raise ArgosError(f"operação desconhecida: {operation}") from exc
493
+ args.run = operation
494
+
495
+
496
+ def run_headless(args: argparse.Namespace, catalog: OperationCatalog) -> int:
497
+ if args.list_operations:
498
+ print_catalog(catalog, as_json=args.json)
499
+ return 0
500
+ if not args.run and not args.resume:
501
+ raise ArgosError("use OPERACAO, --run OPERACAO, --resume EXECUCAO ou --list-operations")
502
+ session = _open_session(args, catalog, interactive=False)
503
+ engine = session.engine
504
+ # O andamento vai para stderr e nunca contamina o stdout de `--json`.
505
+ engine.executions.progress = make_progress(enabled=not getattr(args, "no_progress", False))
506
+ try:
507
+ if args.resume:
508
+ result = engine.resume(args.resume)
509
+ else:
510
+ result = engine.run(args.run, _supplied_parameters(args), force=args.force)
511
+ if args.run == "controle.avaliacoes" and result.get("status") == "completed":
512
+ payload = result["result"]
513
+ print_evaluations(payload["summary"]["items"], as_json=args.json)
514
+ if not args.json:
515
+ for product in payload.get("products", []):
516
+ print(f"produto: {product.get('path')} ({product.get('sha256')})")
517
+ return 0
518
+ print_result(result, as_json=args.json)
519
+ return 0 if is_execution_exit_success(str(result.get("status"))) else 1
520
+ finally:
521
+ session.close()
522
+
523
+
524
+ def run_tui(args: argparse.Namespace, catalog: OperationCatalog) -> int:
525
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
526
+ raise ArgosError("o modo interativo exige TTY; use --headless")
527
+ from .tui import run_textual_app
528
+
529
+ from .project import read_project
530
+
531
+ config = read_project(Path(args.project_root).expanduser().resolve()) if args.workspace_root is None else None
532
+ workspace = args.workspace_root or (config["caminhos"]["control_db"] if config else ".argos")
533
+
534
+ return run_textual_app(
535
+ catalog=catalog,
536
+ project_root=args.project_root,
537
+ workspace_root=workspace,
538
+ numero=args.numero,
539
+ nome=args.nome,
540
+ )
541
+
542
+
543
+ def main(argv: list[str] | None = None) -> int:
544
+ supplied = list(sys.argv[1:] if argv is None else argv)
545
+ if supplied and supplied[0] in {"criar-projeto", "init"}:
546
+ from .project import project_command
547
+
548
+ try:
549
+ return project_command(supplied[1:])
550
+ except ArgosError as exc:
551
+ print(f"argos: {exc}", file=sys.stderr)
552
+ return 2
553
+ catalog = build_catalog()
554
+ parser = _parser()
555
+ try:
556
+ invocation = _resolve_invocation(supplied, parser, catalog)
557
+ except ArgosError as exc:
558
+ print(f"argos: {exc}", file=sys.stderr)
559
+ return 2
560
+ operation = invocation.operation
561
+ names = _operation_arguments(parser, catalog.get(operation)) if operation else {}
562
+ operation_flags = (
563
+ {parameter.name: _parameter_flags(parameter) for parameter in catalog.get(operation).parameters}
564
+ if operation
565
+ else {}
566
+ )
567
+ if invocation.objeto and _wants_help(supplied):
568
+ _print_object_help(parser, catalog, invocation.objeto)
569
+ return 0
570
+ args, extra = parser.parse_known_args(invocation.argv)
571
+ args.positional = invocation.positional
572
+ # Não reescrever argv: valores de flags podem conter '=' e devem permanecer inteiros.
573
+ if operation and args.run and args.operation and args.operation != operation:
574
+ positional_parameter = next((p for p in catalog.get(operation).parameters if p.positional), None)
575
+ if "=" in args.operation:
576
+ extra.insert(0, args.operation)
577
+ args.operation = None
578
+ elif positional_parameter is not None and args.positional is None:
579
+ args.positional = (positional_parameter.name, args.operation)
580
+ args.operation = None
581
+ if extra:
582
+ if not operation or any(token.startswith("-") or "=" not in token for token in extra):
583
+ parser.error("unrecognized arguments: " + " ".join(extra))
584
+ args.param.extend(extra)
585
+ args.operation_arguments = names
586
+ # `.env` da raiz do projeto: só define variáveis ausentes; os valores nunca são exibidos.
587
+ load_env_file(Path(args.project_root).expanduser() / ".env")
588
+ flags = {token.partition("=")[0] for token in supplied if token.startswith("--")}
589
+ args.explicit_operation_parameters = {
590
+ name for name in names if any(flag in flags for flag in operation_flags.get(name, ()))
591
+ }
592
+ try:
593
+ _resolve_positional_operation(args, catalog)
594
+ if args.list_operations and not args.run and not args.resume:
595
+ print_catalog(catalog, as_json=args.json)
596
+ return 0
597
+ if args.headless or args.run or args.resume:
598
+ return run_headless(args, catalog)
599
+ return run_tui(args, catalog)
600
+ except ArgosError as exc:
601
+ print(f"argos: {exc}", file=sys.stderr)
602
+ return 2
603
+
604
+
605
+ if __name__ == "__main__": # pragma: no cover
606
+ raise SystemExit(main())