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/contracts.py ADDED
@@ -0,0 +1,532 @@
1
+ """Contratos compartilhados e identidades canônicas do Argos."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from .core import OperationContext
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Any, Callable, Iterable, Mapping, Protocol
17
+
18
+ from .errors import InputValidationError, MissingInputError
19
+ from .booleans import parse_bool
20
+
21
+
22
+ def utc_now() -> str:
23
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
24
+
25
+
26
+ def _json_default(value: Any) -> Any:
27
+ if isinstance(value, Path):
28
+ return str(value)
29
+ if isinstance(value, (set, frozenset)):
30
+ return sorted(value)
31
+ if isinstance(value, bytes):
32
+ return value.hex()
33
+ raise TypeError(f"valor não serializável: {type(value).__name__}")
34
+
35
+
36
+ def canonical_json(value: Any) -> str:
37
+ return json.dumps(
38
+ value,
39
+ ensure_ascii=False,
40
+ sort_keys=True,
41
+ separators=(",", ":"),
42
+ default=_json_default,
43
+ )
44
+
45
+
46
+ def sha256_bytes(value: bytes) -> str:
47
+ return hashlib.sha256(value).hexdigest()
48
+
49
+
50
+ def sha256_file(path: Path) -> str:
51
+ digest = hashlib.sha256()
52
+ with path.open("rb") as stream:
53
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
54
+ digest.update(chunk)
55
+ return digest.hexdigest()
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class ParameterSpec:
60
+ name: str
61
+ description: str = ""
62
+ required: bool = False
63
+ default: Any = None
64
+ multiple: bool = False
65
+ path: bool = False
66
+ default_from: str | None = None
67
+ boolean: bool = False
68
+ active_when: Mapping[str, Any] = field(default_factory=dict)
69
+ choices: tuple[str, ...] = ()
70
+ project_key: str | None = None
71
+ aliases: tuple[str, ...] = ()
72
+ positional: bool = False
73
+
74
+ def __post_init__(self) -> None:
75
+ if self.positional and (self.multiple or self.boolean):
76
+ raise InputValidationError(
77
+ f"parâmetro posicional não pode ser múltiplo nem booleano: {self.name}"
78
+ )
79
+ for alias in self.aliases:
80
+ if not alias or alias == self.name or not alias.replace("_", "").isalnum():
81
+ raise InputValidationError(f"alias inválido em {self.name}: {alias!r}")
82
+ if self.boolean and self.multiple:
83
+ raise InputValidationError(
84
+ f"parâmetro booleano não pode aceitar múltiplos valores: {self.name}"
85
+ )
86
+ if self.boolean and self.default is not None and not isinstance(self.default, bool):
87
+ raise InputValidationError(
88
+ f"default de parâmetro booleano deve ser bool: {self.name}"
89
+ )
90
+ if self.choices and (self.boolean or self.multiple):
91
+ raise InputValidationError(
92
+ f"parâmetro com choices não pode ser booleano ou múltiplo: {self.name}"
93
+ )
94
+ if self.default is not None and self.choices and str(self.default) not in self.choices:
95
+ raise InputValidationError(f"default fora de choices: {self.name}")
96
+
97
+ def is_empty(self, value: Any) -> bool:
98
+ """Um valor conta como vazio: ausente, string vazia ou lista múltipla vazia."""
99
+ if value in (None, ""):
100
+ return True
101
+ return self.multiple and isinstance(value, (list, tuple, set, frozenset)) and not value
102
+
103
+ def is_active(self, params: Mapping[str, Any]) -> bool:
104
+ """Indica se o parâmetro pertence à variante atualmente selecionada."""
105
+ return all(params.get(name) == expected for name, expected in self.active_when.items())
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class ProductDraft:
110
+ """Produto solicitado; content pode ser bytes, texto, JSON ou Path em staging."""
111
+
112
+ kind: str
113
+ path: Path | None = None
114
+ content: Any = None
115
+ media_type: str = "application/json"
116
+ metadata: Mapping[str, Any] = field(default_factory=dict)
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class ScenarioDraft:
121
+ """Cenário imutável a ser confirmado pelo motor após a operação."""
122
+
123
+ id: str
124
+ name: str | None = None
125
+ parent_id: str | None = None
126
+ kind: str | None = None
127
+ input_hash: str | None = None
128
+ metadata: Mapping[str, Any] | None = None
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class OperationResult:
133
+ summary: Mapping[str, Any]
134
+ products: tuple[ProductDraft, ...] = ()
135
+ scenarios: tuple[ScenarioDraft, ...] = ()
136
+ warnings: tuple[str, ...] = ()
137
+ pending: tuple[Mapping[str, Any], ...] = ()
138
+
139
+ def as_json(self) -> dict[str, Any]:
140
+ return {
141
+ "summary": dict(self.summary),
142
+ "warnings": list(self.warnings),
143
+ "pending": [dict(item) for item in self.pending],
144
+ "scenarios": [
145
+ {
146
+ "id": item.id,
147
+ "name": item.name,
148
+ "parent_id": item.parent_id,
149
+ "kind": item.kind,
150
+ "input_hash": item.input_hash,
151
+ "metadata": dict(item.metadata or {}),
152
+ }
153
+ for item in self.scenarios
154
+ ],
155
+ "products": [
156
+ {
157
+ "kind": item.kind,
158
+ "path": str(item.path) if item.path else None,
159
+ "media_type": item.media_type,
160
+ "metadata": dict(item.metadata),
161
+ }
162
+ for item in self.products
163
+ ],
164
+ }
165
+
166
+
167
+ class OperationHandler(Protocol):
168
+ def __call__(self, context: "OperationContext") -> OperationResult: ...
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class ResourceProfile:
173
+ cpu: int = 1
174
+ memory_mb: int = 256
175
+ network_slots: int = 0
176
+ estimated_tokens: int = 0
177
+ provider: str | None = None
178
+
179
+ def __post_init__(self) -> None:
180
+ if min(self.cpu, self.memory_mb, self.network_slots, self.estimated_tokens) < 0:
181
+ raise InputValidationError("ResourceProfile não aceita orçamento negativo")
182
+
183
+ def as_json(self) -> dict[str, Any]:
184
+ return {
185
+ "cpu": self.cpu,
186
+ "memory_mb": self.memory_mb,
187
+ "network_slots": self.network_slots,
188
+ "estimated_tokens": self.estimated_tokens,
189
+ "provider": self.provider,
190
+ }
191
+
192
+ @classmethod
193
+ def from_json(cls, value: Mapping[str, Any] | None) -> "ResourceProfile":
194
+ value = value or {}
195
+ return cls(
196
+ cpu=int(value.get("cpu", 1)),
197
+ memory_mb=int(value.get("memory_mb", 256)),
198
+ network_slots=int(value.get("network_slots", 0)),
199
+ estimated_tokens=int(value.get("estimated_tokens", 0)),
200
+ provider=str(value["provider"]) if value.get("provider") else None,
201
+ )
202
+
203
+
204
+ @dataclass(frozen=True)
205
+ class ProductPolicy:
206
+ """Política declarativa dos Produtos que uma Operação pode materializar.
207
+
208
+ ``kinds`` aceita nomes exatos e prefixos terminados em ``:*``. Políticas
209
+ vazias preservam extensões antigas como irrestritas; as Operações do
210
+ catálogo padrão declaram políticas estritas.
211
+ """
212
+
213
+ kinds: tuple[str, ...] = ()
214
+ path_parameters: tuple[str, ...] = ()
215
+ allow_inferred: bool = False
216
+ allow_dynamic: bool = False
217
+ directory_parameters: tuple[str, ...] = ()
218
+
219
+ def validate_declaration(self, parameters: Iterable[ParameterSpec]) -> None:
220
+ known = {parameter.name for parameter in parameters}
221
+ if set(self.directory_parameters) - set(self.path_parameters):
222
+ raise InputValidationError(
223
+ "directory_parameters deve estar contido em path_parameters"
224
+ )
225
+ unknown = sorted(set(self.path_parameters) - known)
226
+ if unknown:
227
+ raise InputValidationError(
228
+ "política de Produtos referencia parâmetros desconhecidos: "
229
+ + ", ".join(unknown)
230
+ )
231
+ if any(not kind or ("*" in kind and kind != "*" and not kind.endswith(":*")) for kind in self.kinds):
232
+ raise InputValidationError("kind inválido na política de Produtos")
233
+
234
+ def validate_result(
235
+ self,
236
+ params: Mapping[str, Any],
237
+ result: OperationResult,
238
+ *,
239
+ project_root: Path,
240
+ ) -> None:
241
+ if not self.kinds:
242
+ return
243
+ requested_paths = {
244
+ self._resolve_path(value, project_root)
245
+ for name in self.path_parameters
246
+ for value in self._parameter_values(params.get(name))
247
+ }
248
+ requested_dirs = {
249
+ self._resolve_path(value, project_root)
250
+ for name in self.directory_parameters
251
+ for value in self._parameter_values(params.get(name))
252
+ }
253
+ for draft in result.products:
254
+ if not any(self._matches_kind(draft.kind, declared) for declared in self.kinds):
255
+ raise InputValidationError(
256
+ f"Produto {draft.kind!r} não declarado no contrato da Operação"
257
+ )
258
+ if draft.path is None or self.allow_inferred or self.allow_dynamic:
259
+ continue
260
+ resolved_draft = draft.path.expanduser().resolve()
261
+ if resolved_draft not in requested_paths and not any(
262
+ directory in resolved_draft.parents for directory in requested_dirs
263
+ ):
264
+ raise InputValidationError(
265
+ f"caminho do Produto {draft.kind!r} não foi solicitado pelos parâmetros declarados"
266
+ )
267
+
268
+ @staticmethod
269
+ def _parameter_values(value: Any) -> tuple[str | Path, ...]:
270
+ if value in (None, ""):
271
+ return ()
272
+ if isinstance(value, (list, tuple, set, frozenset)):
273
+ return tuple(item for item in value if isinstance(item, (str, Path)))
274
+ return (value,) if isinstance(value, (str, Path)) else ()
275
+
276
+ @staticmethod
277
+ def _resolve_path(value: str | Path, project_root: Path) -> Path:
278
+ candidate = Path(value).expanduser()
279
+ if not candidate.is_absolute():
280
+ candidate = project_root / candidate
281
+ return candidate.resolve()
282
+
283
+ @staticmethod
284
+ def _matches_kind(actual: str, declared: str) -> bool:
285
+ if declared == "*":
286
+ return True
287
+ return actual.startswith(declared[:-1]) if declared.endswith(":*") else actual == declared
288
+
289
+
290
+ # Projeções são leituras puras e determinísticas do controle; retornam apenas
291
+ # os dados relevantes, que o fingerprint resume em um hash.
292
+ ParameterValidator = Callable[[Mapping[str, Any]], None]
293
+ ResourceEstimator = Callable[[Mapping[str, Any]], ResourceProfile]
294
+ StateProjection = Callable[[Any, Mapping[str, Any], Path], Mapping[str, Any]]
295
+
296
+
297
+ @dataclass(frozen=True)
298
+ class OperationResolution:
299
+ """Contrato resolvido de uma Operação antes de sua execução."""
300
+
301
+ params: Mapping[str, Any]
302
+ missing: tuple[Mapping[str, Any], ...] = ()
303
+ resources: ResourceProfile = field(default_factory=ResourceProfile)
304
+
305
+
306
+ # Alias de compatibilidade para extensões que importavam o nome anterior.
307
+ ResolvedParameters = OperationResolution
308
+
309
+
310
+ @dataclass(frozen=True)
311
+ class OperationSpec:
312
+ id: str
313
+ name: str
314
+ description: str
315
+ group: str
316
+ parameters: tuple[ParameterSpec, ...]
317
+ handler: OperationHandler
318
+ version: str = "1"
319
+ resources: ResourceProfile | ResourceEstimator = field(default_factory=ResourceProfile)
320
+ validators: tuple[ParameterValidator, ...] = ()
321
+ products: ProductPolicy = field(default_factory=ProductPolicy)
322
+ cacheable: bool | Callable[[Mapping[str, Any]], bool] = True
323
+ state_projection: StateProjection | None = None
324
+ state_projection_version: str = "1"
325
+ # Padrões próprios da operação: recebe os valores já combinados (projeto,
326
+ # `operacoes:`, overrides e argumentos explícitos) e o fiscalizacao.yml, e
327
+ # devolve só os padrões que acrescenta. Os argumentos explícitos prevalecem.
328
+ defaults: Callable[[dict[str, Any], Mapping[str, Any]], dict[str, Any]] | None = None
329
+
330
+ def __post_init__(self) -> None:
331
+ if sum(parameter.positional for parameter in self.parameters) > 1:
332
+ raise InputValidationError(f"mais de um parâmetro posicional em {self.id}")
333
+ if self.state_projection is not None and (
334
+ not isinstance(self.state_projection_version, str)
335
+ or not self.state_projection_version.strip()
336
+ ):
337
+ raise InputValidationError(f"versão de projeção de estado vazia em {self.id}")
338
+ names = [parameter.name for parameter in self.parameters]
339
+ if len(set(names)) != len(names):
340
+ raise InputValidationError(f"parâmetro repetido no contrato de {self.id}")
341
+ aliases = [alias for parameter in self.parameters for alias in parameter.aliases]
342
+ if len(set(aliases)) != len(aliases) or set(aliases) & set(names):
343
+ raise InputValidationError(f"alias repetido ou em conflito no contrato de {self.id}")
344
+ known = set(names)
345
+ for parameter in self.parameters:
346
+ if parameter.default_from and parameter.default_from not in known:
347
+ raise InputValidationError(
348
+ f"default_from desconhecido em {self.id}.{parameter.name}: {parameter.default_from}"
349
+ )
350
+ unknown_conditions = sorted(set(parameter.active_when) - known)
351
+ if unknown_conditions:
352
+ raise InputValidationError(
353
+ f"active_when desconhecido em {self.id}.{parameter.name}: "
354
+ + ", ".join(unknown_conditions)
355
+ )
356
+ self.products.validate_declaration(self.parameters)
357
+
358
+ def _canonical_supplied(self, supplied: Mapping[str, Any]) -> dict[str, Any]:
359
+ """Troca aliases pelo nome canônico; alias e nome juntos são ambíguos."""
360
+ result = dict(supplied)
361
+ for parameter in self.parameters:
362
+ for alias in parameter.aliases:
363
+ if alias not in result:
364
+ continue
365
+ if parameter.name in result:
366
+ raise InputValidationError(
367
+ f"{parameter.name} informado também pelo alias {alias}; use apenas um"
368
+ )
369
+ result[parameter.name] = result.pop(alias)
370
+ return result
371
+
372
+ def resolve(self, supplied: Mapping[str, Any], *, project_root: Path | None = None,
373
+ project_overrides: Mapping[str, Any] | None = None) -> OperationResolution:
374
+ """Resolve padrões do cadastro, parâmetros, validações e recursos.
375
+
376
+ A interface é o test surface dos três modos de consumo: o engine
377
+ levanta sobre o resultado, o planner registra as pendências e o CLI
378
+ preenche interativamente usando o mesmo predicado de vazio.
379
+ """
380
+ supplied = self._canonical_supplied(supplied)
381
+ if project_root is not None:
382
+ from .project import operation_parameters
383
+
384
+ supplied = operation_parameters(self, supplied, project_root, project_overrides)
385
+ resolved = dict(supplied)
386
+ known = {parameter.name for parameter in self.parameters}
387
+ unknown = sorted(set(resolved) - known)
388
+ if unknown:
389
+ raise InputValidationError(
390
+ f"parâmetros desconhecidos para {self.id}: {', '.join(unknown)}"
391
+ )
392
+ missing: list[dict[str, Any]] = []
393
+ resolution_order = (
394
+ *(parameter for parameter in self.parameters if not parameter.active_when),
395
+ *(parameter for parameter in self.parameters if parameter.active_when),
396
+ )
397
+ for parameter in resolution_order:
398
+ value = resolved.get(parameter.name)
399
+ if not parameter.is_active(resolved):
400
+ resolved.pop(parameter.name, None)
401
+ continue
402
+ if not parameter.is_empty(value):
403
+ continue
404
+ if parameter.default is not None:
405
+ resolved[parameter.name] = parameter.default
406
+ elif parameter.required:
407
+ missing.append(
408
+ {
409
+ "operation_id": self.id,
410
+ "parameter": parameter.name,
411
+ "description": parameter.description,
412
+ }
413
+ )
414
+ for parameter in self.parameters:
415
+ source = parameter.default_from
416
+ if source is None:
417
+ continue
418
+ if parameter.is_empty(resolved.get(parameter.name)) and not parameter.is_empty(resolved.get(source)):
419
+ resolved[parameter.name] = resolved[source]
420
+ for parameter in self.parameters:
421
+ if parameter.multiple and parameter.name in resolved:
422
+ value = resolved[parameter.name]
423
+ if isinstance(value, str) and "," in value:
424
+ resolved[parameter.name] = [
425
+ parte.strip() for parte in value.split(",") if parte.strip()
426
+ ]
427
+ for parameter in self.parameters:
428
+ if parameter.boolean and parameter.name in resolved:
429
+ resolved[parameter.name] = parse_bool(
430
+ resolved[parameter.name],
431
+ default=bool(parameter.default),
432
+ )
433
+ if (
434
+ parameter.choices
435
+ and parameter.name in resolved
436
+ and str(resolved[parameter.name]) not in parameter.choices
437
+ ):
438
+ raise InputValidationError(
439
+ f"{parameter.name} deve ser um de: {', '.join(parameter.choices)}"
440
+ )
441
+ if not missing:
442
+ for validator in self.validators:
443
+ validator(resolved)
444
+ resources = self.resources(resolved) if callable(self.resources) else self.resources
445
+ if resources.cpu < 1:
446
+ raise InputValidationError(f"ResourceProfile de {self.id} requer cpu positivo")
447
+ return OperationResolution(
448
+ params=resolved,
449
+ missing=tuple(missing),
450
+ resources=resources,
451
+ )
452
+
453
+ def resolve_parameters(self, supplied: Mapping[str, Any], *, project_root: Path | None = None,
454
+ project_overrides: Mapping[str, Any] | None = None) -> dict[str, Any]:
455
+ resolved = self.resolve(supplied, project_root=project_root, project_overrides=project_overrides)
456
+ if resolved.missing:
457
+ names = ", ".join(str(item["parameter"]) for item in resolved.missing)
458
+ raise MissingInputError(
459
+ f"parâmetros obrigatórios ausentes para {self.id}: {names}"
460
+ )
461
+ return dict(resolved.params)
462
+
463
+ def validate_result(
464
+ self,
465
+ params: Mapping[str, Any],
466
+ result: OperationResult,
467
+ *,
468
+ project_root: Path,
469
+ ) -> None:
470
+ """Confere ProductDrafts antes de qualquer materialização."""
471
+ self.products.validate_result(params, result, project_root=project_root)
472
+
473
+
474
+ _ID_PART = re.compile(r"[a-z](?:[a-z0-9-]*[a-z0-9])?")
475
+
476
+
477
+ def split_operation_id(operation_id: str) -> tuple[str, str | None]:
478
+ """Separa `objeto` ou `objeto.acao`; recusa qualquer outra forma de id."""
479
+ objeto, dot, acao = operation_id.partition(".")
480
+ if not _ID_PART.fullmatch(objeto) or (dot and not _ID_PART.fullmatch(acao)):
481
+ raise InputValidationError(
482
+ f"id de operação inválido: {operation_id!r}; use objeto ou objeto.acao "
483
+ "(minúsculas, dígitos e hífen)"
484
+ )
485
+ return objeto, (acao if dot else None)
486
+
487
+
488
+ class OperationCatalog:
489
+ """Catálogo único consumido pelo TUI, headless e testes."""
490
+
491
+ def __init__(self, specs: Iterable[OperationSpec] = ()) -> None:
492
+ self._specs: dict[str, OperationSpec] = {}
493
+ for spec in specs:
494
+ self.register(spec)
495
+
496
+ def register(self, spec: OperationSpec) -> None:
497
+ split_operation_id(spec.id)
498
+ if spec.id in self._specs:
499
+ raise ValueError(f"operação já registrada: {spec.id}")
500
+ self._specs[spec.id] = spec
501
+
502
+ def get(self, operation_id: str) -> OperationSpec:
503
+ try:
504
+ return self._specs[operation_id]
505
+ except KeyError as exc:
506
+ raise InputValidationError(f"operação desconhecida: {operation_id}") from exc
507
+
508
+ def all(self) -> tuple[OperationSpec, ...]:
509
+ return tuple(self._specs.values())
510
+
511
+ def objects(self) -> tuple[str, ...]:
512
+ """Objetos distintos, na ordem de registro."""
513
+ return tuple(dict.fromkeys(split_operation_id(spec_id)[0] for spec_id in self._specs))
514
+
515
+ def actions(self, objeto: str) -> tuple[OperationSpec, ...]:
516
+ """Operações do objeto (`objeto` e `objeto.acao`), na ordem de registro."""
517
+ return tuple(
518
+ spec for spec_id, spec in self._specs.items() if split_operation_id(spec_id)[0] == objeto
519
+ )
520
+
521
+ def search(self, text: str) -> tuple[OperationSpec, ...]:
522
+ needle = text.casefold().strip()
523
+ return tuple(
524
+ spec
525
+ for spec in self._specs.values()
526
+ if not needle
527
+ or needle in spec.id.casefold()
528
+ or needle in spec.name.casefold()
529
+ or needle in spec.group.casefold()
530
+ )
531
+
532
+