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
|
@@ -0,0 +1,856 @@
|
|
|
1
|
+
"""Contrato de resposta dos modelos (*response profiles*).
|
|
2
|
+
|
|
3
|
+
Cada profile conhece o schema que o modelo recebe, valida o que ele devolve, devolve a
|
|
4
|
+
forma armazenada e gera a própria resposta mínima válida (``example``), que o provider
|
|
5
|
+
falso e os testes consomem em vez de desenhar o payload à mão.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Mapping, Sequence
|
|
13
|
+
|
|
14
|
+
from .errors import InputValidationError
|
|
15
|
+
|
|
16
|
+
SUPPORT_DECISIONS_REQUIRING_FOUNDATIONS = frozenset({"fundamentada", "parcialmente_fundamentada"})
|
|
17
|
+
_EVIDENCE_CONCLUSION_KEYS = frozenset(
|
|
18
|
+
{"item_codigo", "item_texto", "decisao", "justificativa", "fundamentos", "lacunas", "detalhes"}
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def fill_item_texts(result: dict[str, Any], subject: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
23
|
+
"""Preenche ``item_texto`` vazio com o texto do item no catálogo (``subject.itens``)."""
|
|
24
|
+
items = (subject or {}).get("itens")
|
|
25
|
+
texts = {
|
|
26
|
+
str(item.get("codigo")): str(item.get("texto") or "")
|
|
27
|
+
for item in items or ()
|
|
28
|
+
if isinstance(item, Mapping)
|
|
29
|
+
}
|
|
30
|
+
for conclusion in result.get("conclusoes") or ():
|
|
31
|
+
if isinstance(conclusion, dict) and not conclusion.get("item_texto"):
|
|
32
|
+
conclusion["item_texto"] = texts.get(str(conclusion.get("item_codigo")), "")
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _with_default_error(payload: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
37
|
+
"""Alguns modelos omitem ``error`` quando está vazio; ausência equivale a texto vazio."""
|
|
38
|
+
if "error" in payload:
|
|
39
|
+
return payload
|
|
40
|
+
return {**payload, "error": ""}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# --- response_profiles ---
|
|
44
|
+
BASE_FIELDS = {
|
|
45
|
+
"item_codigo",
|
|
46
|
+
"item_texto",
|
|
47
|
+
"afirmacao_auditado",
|
|
48
|
+
"estado",
|
|
49
|
+
"justificativa",
|
|
50
|
+
"lacunas",
|
|
51
|
+
"arquivos_referenciados",
|
|
52
|
+
"trechos_ou_elementos",
|
|
53
|
+
"paginas_ou_localizacao",
|
|
54
|
+
}
|
|
55
|
+
TEMPORAL_FIELDS = {
|
|
56
|
+
"estado_temporal",
|
|
57
|
+
"conclusoes_motivos",
|
|
58
|
+
"providencias_informadas",
|
|
59
|
+
"comentarios_encaminhamento",
|
|
60
|
+
"consequencias_praticas",
|
|
61
|
+
"alternativas_propostas",
|
|
62
|
+
}
|
|
63
|
+
LIST_FIELDS = {
|
|
64
|
+
"lacunas",
|
|
65
|
+
"arquivos_referenciados",
|
|
66
|
+
"trechos_ou_elementos",
|
|
67
|
+
"paginas_ou_localizacao",
|
|
68
|
+
}
|
|
69
|
+
TEMPORAL_LIST_FIELDS = {
|
|
70
|
+
"conclusoes_motivos",
|
|
71
|
+
"providencias_informadas",
|
|
72
|
+
"consequencias_praticas",
|
|
73
|
+
"alternativas_propostas",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Texto do juiz é apresentado ao jurisdicionado: não pode revelar o processo de avaliação.
|
|
78
|
+
JUDGE_TEXT_LIMIT = 1200
|
|
79
|
+
_PROCESS_REFERENCES = re.compile(
|
|
80
|
+
r"\b(opini(?:ão|ões)|avaliador(?:es)?|votos?|juiz|llm|inteligência artificial|modelos? de linguagem"
|
|
81
|
+
r"|crit[ée]rios? sint[ée]ticos?)\b",
|
|
82
|
+
re.IGNORECASE,
|
|
83
|
+
)
|
|
84
|
+
_ACRONYM_AI = re.compile(r"\bIA\b")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def judge_voice_problems(result: Mapping[str, Any]) -> list[str]:
|
|
88
|
+
"""Problemas de voz na justificativa e nas lacunas do juiz (texto vai ao jurisdicionado)."""
|
|
89
|
+
problems: list[str] = []
|
|
90
|
+
for position, conclusion in enumerate(result.get("conclusoes") or ()):
|
|
91
|
+
if not isinstance(conclusion, Mapping):
|
|
92
|
+
continue
|
|
93
|
+
text = str(conclusion.get("justificativa") or "")
|
|
94
|
+
fields = [("justificativa", text), *(("lacunas", str(gap)) for gap in conclusion.get("lacunas") or ())]
|
|
95
|
+
for field, value in fields:
|
|
96
|
+
found = _PROCESS_REFERENCES.search(value) or _ACRONYM_AI.search(value)
|
|
97
|
+
if found:
|
|
98
|
+
problems.append(f"{field} da conclusão {position} refere o processo de avaliação ({found.group(0)!r})")
|
|
99
|
+
if "\n" in text or "**" in text or re.match(r"\s*[-*•]", text):
|
|
100
|
+
problems.append(f"justificativa da conclusão {position} deve ser um parágrafo único, sem listas nem formatação")
|
|
101
|
+
if len(text) > JUDGE_TEXT_LIMIT:
|
|
102
|
+
problems.append(f"justificativa da conclusão {position} excede {JUDGE_TEXT_LIMIT} caracteres ({len(text)})")
|
|
103
|
+
return problems
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def check_judge_voice(result: Mapping[str, Any]) -> None:
|
|
107
|
+
problems = judge_voice_problems(result)
|
|
108
|
+
if problems:
|
|
109
|
+
raise InputValidationError(
|
|
110
|
+
"texto do juiz fora do padrão: " + "; ".join(problems)
|
|
111
|
+
+ ". Reescreva seguindo o modelo da justificativa, sem referir opiniões, avaliadores, modelos "
|
|
112
|
+
"ou o processo de avaliação."
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
EXAMPLE_JUSTIFICATION = "Resposta de exemplo do profile."
|
|
117
|
+
EXAMPLE_EXCERPT = "Trecho de exemplo do profile."
|
|
118
|
+
EXAMPLE_REASON_JUSTIFICATION = "Motivo mantido na resposta de exemplo."
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _example_files(files: Sequence[str]) -> list[str]:
|
|
122
|
+
return [str(name) for name in files] or ["evidencia-exemplo"]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class ResponseProfile:
|
|
127
|
+
name: str
|
|
128
|
+
temporal: bool = False
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def decision_values(self) -> set[str]:
|
|
132
|
+
if self.temporal:
|
|
133
|
+
return {
|
|
134
|
+
"mantida",
|
|
135
|
+
"afastada_na_data_base",
|
|
136
|
+
"corrigida_posteriormente",
|
|
137
|
+
}
|
|
138
|
+
return {"conforme", "nao_conforme"}
|
|
139
|
+
|
|
140
|
+
def decision(self, conclusion: Mapping[str, Any]) -> str:
|
|
141
|
+
field = "estado_temporal" if self.temporal else "estado"
|
|
142
|
+
return str(conclusion.get(field) or "")
|
|
143
|
+
|
|
144
|
+
def example(
|
|
145
|
+
self,
|
|
146
|
+
item_codes: Sequence[str],
|
|
147
|
+
*,
|
|
148
|
+
texts: Mapping[str, str] | None = None,
|
|
149
|
+
assertions: Mapping[str, str] | None = None,
|
|
150
|
+
files: Sequence[str] = (),
|
|
151
|
+
reason_ids: Sequence[str] = (),
|
|
152
|
+
decision: str | None = None,
|
|
153
|
+
) -> dict[str, Any]:
|
|
154
|
+
"""Resposta mínima válida para ``item_codes``; ``decision`` troca o estado (ou o estado temporal)."""
|
|
155
|
+
conclusions: list[dict[str, Any]] = []
|
|
156
|
+
for code in item_codes:
|
|
157
|
+
conclusion: dict[str, Any] = {
|
|
158
|
+
"item_codigo": code,
|
|
159
|
+
"item_texto": str((texts or {}).get(code) or code),
|
|
160
|
+
"afirmacao_auditado": str((assertions or {}).get(code) or ""),
|
|
161
|
+
"estado": decision if decision and not self.temporal else ("nao_conforme" if self.temporal else "conforme"),
|
|
162
|
+
"justificativa": EXAMPLE_JUSTIFICATION,
|
|
163
|
+
"lacunas": [],
|
|
164
|
+
"arquivos_referenciados": [str(name) for name in files],
|
|
165
|
+
"trechos_ou_elementos": [],
|
|
166
|
+
"paginas_ou_localizacao": [],
|
|
167
|
+
}
|
|
168
|
+
if self.temporal:
|
|
169
|
+
conclusion.update(
|
|
170
|
+
{
|
|
171
|
+
"estado_temporal": decision or "mantida",
|
|
172
|
+
"conclusoes_motivos": [
|
|
173
|
+
{
|
|
174
|
+
"id_motivo": str(reason),
|
|
175
|
+
"estado_motivo": "mantido",
|
|
176
|
+
"justificativa": EXAMPLE_REASON_JUSTIFICATION,
|
|
177
|
+
}
|
|
178
|
+
for reason in reason_ids
|
|
179
|
+
],
|
|
180
|
+
"providencias_informadas": [],
|
|
181
|
+
"comentarios_encaminhamento": "",
|
|
182
|
+
"consequencias_praticas": [],
|
|
183
|
+
"alternativas_propostas": [],
|
|
184
|
+
}
|
|
185
|
+
)
|
|
186
|
+
conclusions.append(conclusion)
|
|
187
|
+
return {"status": "completed", "conclusoes": conclusions, "error": ""}
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def schema(self) -> Mapping[str, Any]:
|
|
191
|
+
conclusion_properties: dict[str, Any] = {
|
|
192
|
+
"item_codigo": {"type": "string"},
|
|
193
|
+
"item_texto": {"type": "string"},
|
|
194
|
+
"afirmacao_auditado": {"type": "string"},
|
|
195
|
+
"estado": {
|
|
196
|
+
"type": "string",
|
|
197
|
+
"enum": ["conforme", "nao_conforme"],
|
|
198
|
+
},
|
|
199
|
+
"justificativa": {"type": "string"},
|
|
200
|
+
"lacunas": {"type": "array", "items": {"type": "string"}},
|
|
201
|
+
"arquivos_referenciados": {
|
|
202
|
+
"type": "array",
|
|
203
|
+
"items": {"type": "string"},
|
|
204
|
+
},
|
|
205
|
+
"trechos_ou_elementos": {
|
|
206
|
+
"type": "array",
|
|
207
|
+
"items": {"type": "string"},
|
|
208
|
+
},
|
|
209
|
+
"paginas_ou_localizacao": {
|
|
210
|
+
"type": "array",
|
|
211
|
+
"items": {"type": "string"},
|
|
212
|
+
},
|
|
213
|
+
}
|
|
214
|
+
required = set(BASE_FIELDS)
|
|
215
|
+
if self.temporal:
|
|
216
|
+
conclusion_properties.update(
|
|
217
|
+
{
|
|
218
|
+
"estado_temporal": {
|
|
219
|
+
"type": "string",
|
|
220
|
+
"enum": [
|
|
221
|
+
"mantida",
|
|
222
|
+
"afastada_na_data_base",
|
|
223
|
+
"corrigida_posteriormente",
|
|
224
|
+
],
|
|
225
|
+
},
|
|
226
|
+
"conclusoes_motivos": {
|
|
227
|
+
"type": "array",
|
|
228
|
+
"items": {
|
|
229
|
+
"type": "object",
|
|
230
|
+
"additionalProperties": False,
|
|
231
|
+
"properties": {
|
|
232
|
+
"id_motivo": {"type": "string"},
|
|
233
|
+
"estado_motivo": {
|
|
234
|
+
"type": "string",
|
|
235
|
+
"enum": ["mantido", "afastado"],
|
|
236
|
+
},
|
|
237
|
+
"justificativa": {"type": "string"},
|
|
238
|
+
},
|
|
239
|
+
"required": [
|
|
240
|
+
"id_motivo",
|
|
241
|
+
"estado_motivo",
|
|
242
|
+
"justificativa",
|
|
243
|
+
],
|
|
244
|
+
},
|
|
245
|
+
},
|
|
246
|
+
"providencias_informadas": {
|
|
247
|
+
"type": "array",
|
|
248
|
+
"items": {"type": "string"},
|
|
249
|
+
},
|
|
250
|
+
"comentarios_encaminhamento": {"type": "string"},
|
|
251
|
+
"consequencias_praticas": {
|
|
252
|
+
"type": "array",
|
|
253
|
+
"items": {"type": "string"},
|
|
254
|
+
},
|
|
255
|
+
"alternativas_propostas": {
|
|
256
|
+
"type": "array",
|
|
257
|
+
"items": {"type": "string"},
|
|
258
|
+
},
|
|
259
|
+
}
|
|
260
|
+
)
|
|
261
|
+
required.update(TEMPORAL_FIELDS)
|
|
262
|
+
return {
|
|
263
|
+
"type": "object",
|
|
264
|
+
"additionalProperties": False,
|
|
265
|
+
"properties": {
|
|
266
|
+
"status": {"type": "string", "enum": ["completed"]},
|
|
267
|
+
"conclusoes": {
|
|
268
|
+
"type": "array",
|
|
269
|
+
"items": {
|
|
270
|
+
"type": "object",
|
|
271
|
+
"additionalProperties": False,
|
|
272
|
+
"properties": conclusion_properties,
|
|
273
|
+
"required": sorted(required),
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
"error": {"type": "string"},
|
|
277
|
+
},
|
|
278
|
+
"required": ["status", "conclusoes", "error"],
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
def validate(
|
|
282
|
+
self,
|
|
283
|
+
payload: Mapping[str, Any],
|
|
284
|
+
*,
|
|
285
|
+
expected_item_codes: Sequence[str] = (),
|
|
286
|
+
expected_reason_ids: Sequence[str] = (),
|
|
287
|
+
) -> dict[str, Any]:
|
|
288
|
+
payload = _with_default_error(payload)
|
|
289
|
+
if set(payload) != {"status", "conclusoes", "error"}:
|
|
290
|
+
raise InputValidationError(
|
|
291
|
+
"resposta deve conter somente status, conclusoes e error"
|
|
292
|
+
)
|
|
293
|
+
if payload.get("status") != "completed":
|
|
294
|
+
raise InputValidationError("resposta de Avaliação não está completed")
|
|
295
|
+
if not isinstance(payload.get("error"), str):
|
|
296
|
+
raise InputValidationError("campo error deve ser texto")
|
|
297
|
+
conclusions = payload.get("conclusoes")
|
|
298
|
+
if not isinstance(conclusions, list) or not conclusions:
|
|
299
|
+
raise InputValidationError("resposta precisa de conclusoes não vazias")
|
|
300
|
+
received_items: list[str] = []
|
|
301
|
+
for position, conclusion in enumerate(conclusions):
|
|
302
|
+
if not isinstance(conclusion, Mapping):
|
|
303
|
+
raise InputValidationError(f"conclusão {position} deve ser objeto")
|
|
304
|
+
expected_fields = BASE_FIELDS | (TEMPORAL_FIELDS if self.temporal else set())
|
|
305
|
+
if set(conclusion) != expected_fields:
|
|
306
|
+
missing = sorted(expected_fields.difference(conclusion))
|
|
307
|
+
extra = sorted(set(conclusion).difference(expected_fields))
|
|
308
|
+
raise InputValidationError(
|
|
309
|
+
f"conclusão {position} incompatível; faltantes={missing}, extras={extra}"
|
|
310
|
+
)
|
|
311
|
+
code = str(conclusion.get("item_codigo") or "").strip()
|
|
312
|
+
if not code:
|
|
313
|
+
raise InputValidationError(f"conclusão {position} sem item_codigo")
|
|
314
|
+
received_items.append(code)
|
|
315
|
+
if conclusion.get("estado") not in {"conforme", "nao_conforme"}:
|
|
316
|
+
raise InputValidationError(f"estado inválido na conclusão {position}")
|
|
317
|
+
if not isinstance(conclusion.get("justificativa"), str):
|
|
318
|
+
raise InputValidationError(f"justificativa inválida na conclusão {position}")
|
|
319
|
+
for field_name in LIST_FIELDS:
|
|
320
|
+
if not isinstance(conclusion.get(field_name), list):
|
|
321
|
+
raise InputValidationError(
|
|
322
|
+
f"campo {field_name} deve ser lista na conclusão {position}"
|
|
323
|
+
)
|
|
324
|
+
if self.temporal:
|
|
325
|
+
self._validate_temporal(
|
|
326
|
+
conclusion,
|
|
327
|
+
position=position,
|
|
328
|
+
expected_reason_ids=expected_reason_ids,
|
|
329
|
+
)
|
|
330
|
+
self._validate_exact_scope(
|
|
331
|
+
received_items,
|
|
332
|
+
expected_item_codes,
|
|
333
|
+
label="itens",
|
|
334
|
+
)
|
|
335
|
+
return dict(payload)
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def _validate_exact_scope(
|
|
339
|
+
received: Sequence[str],
|
|
340
|
+
expected: Sequence[str],
|
|
341
|
+
*,
|
|
342
|
+
label: str,
|
|
343
|
+
) -> None:
|
|
344
|
+
if len(received) != len(set(received)):
|
|
345
|
+
raise InputValidationError(f"{label} duplicados na resposta")
|
|
346
|
+
if expected and (len(received) != len(expected) or set(received) != set(expected)):
|
|
347
|
+
raise InputValidationError(
|
|
348
|
+
f"escopo de {label} inválido; esperados={list(expected)}, recebidos={list(received)}"
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
def _validate_temporal(
|
|
352
|
+
self,
|
|
353
|
+
conclusion: Mapping[str, Any],
|
|
354
|
+
*,
|
|
355
|
+
position: int,
|
|
356
|
+
expected_reason_ids: Sequence[str],
|
|
357
|
+
) -> None:
|
|
358
|
+
state = conclusion.get("estado_temporal")
|
|
359
|
+
if state not in {
|
|
360
|
+
"mantida",
|
|
361
|
+
"afastada_na_data_base",
|
|
362
|
+
"corrigida_posteriormente",
|
|
363
|
+
}:
|
|
364
|
+
raise InputValidationError(f"estado_temporal inválido na conclusão {position}")
|
|
365
|
+
for field_name in TEMPORAL_LIST_FIELDS:
|
|
366
|
+
if not isinstance(conclusion.get(field_name), list):
|
|
367
|
+
raise InputValidationError(
|
|
368
|
+
f"campo {field_name} deve ser lista na conclusão {position}"
|
|
369
|
+
)
|
|
370
|
+
if not isinstance(conclusion.get("comentarios_encaminhamento"), str):
|
|
371
|
+
raise InputValidationError("comentarios_encaminhamento deve ser texto")
|
|
372
|
+
reasons = conclusion["conclusoes_motivos"]
|
|
373
|
+
received_reasons: list[str] = []
|
|
374
|
+
reason_states: list[str] = []
|
|
375
|
+
for reason_position, reason in enumerate(reasons):
|
|
376
|
+
if not isinstance(reason, Mapping) or set(reason) != {
|
|
377
|
+
"id_motivo",
|
|
378
|
+
"estado_motivo",
|
|
379
|
+
"justificativa",
|
|
380
|
+
}:
|
|
381
|
+
raise InputValidationError(
|
|
382
|
+
f"motivo {reason_position} da conclusão {position} é inválido"
|
|
383
|
+
)
|
|
384
|
+
received_reasons.append(str(reason.get("id_motivo") or "").strip())
|
|
385
|
+
reason_state = str(reason.get("estado_motivo") or "")
|
|
386
|
+
if reason_state not in {"mantido", "afastado"}:
|
|
387
|
+
raise InputValidationError("estado_motivo inválido")
|
|
388
|
+
reason_states.append(reason_state)
|
|
389
|
+
self._validate_exact_scope(
|
|
390
|
+
received_reasons,
|
|
391
|
+
expected_reason_ids,
|
|
392
|
+
label="motivos",
|
|
393
|
+
)
|
|
394
|
+
if state == "mantida" and expected_reason_ids and "mantido" not in reason_states:
|
|
395
|
+
raise InputValidationError("situação mantida exige motivo mantido")
|
|
396
|
+
if state in {"afastada_na_data_base", "corrigida_posteriormente"} and any(
|
|
397
|
+
item != "afastado" for item in reason_states
|
|
398
|
+
):
|
|
399
|
+
raise InputValidationError(f"{state} exige todos os motivos afastados")
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@dataclass(frozen=True)
|
|
403
|
+
class ComparableResponseProfile:
|
|
404
|
+
"""Profile v2 com núcleo comparável e decisão específica do domínio."""
|
|
405
|
+
|
|
406
|
+
name: str
|
|
407
|
+
decision_values: set[str]
|
|
408
|
+
manager_comment: bool = False
|
|
409
|
+
|
|
410
|
+
def example(
|
|
411
|
+
self,
|
|
412
|
+
item_codes: Sequence[str],
|
|
413
|
+
*,
|
|
414
|
+
texts: Mapping[str, str] | None = None,
|
|
415
|
+
assertions: Mapping[str, str] | None = None,
|
|
416
|
+
files: Sequence[str] = (),
|
|
417
|
+
reason_ids: Sequence[str] = (),
|
|
418
|
+
decision: str | None = None,
|
|
419
|
+
) -> dict[str, Any]:
|
|
420
|
+
"""Resposta mínima válida para ``item_codes``, na forma que o modelo devolve.
|
|
421
|
+
|
|
422
|
+
Evidência: só os cinco campos pedidos (com um fundamento por arquivo quando a decisão
|
|
423
|
+
exige citação). Comentário do gestor: o contrato completo, com ``detalhes``.
|
|
424
|
+
"""
|
|
425
|
+
conclusions: list[dict[str, Any]] = []
|
|
426
|
+
for code in item_codes:
|
|
427
|
+
if self.manager_comment:
|
|
428
|
+
conclusions.append(
|
|
429
|
+
{
|
|
430
|
+
"item_codigo": code,
|
|
431
|
+
"item_texto": str((texts or {}).get(code) or code),
|
|
432
|
+
"objeto_avaliado": str((assertions or {}).get(code) or ""),
|
|
433
|
+
"decisao": decision or "manter",
|
|
434
|
+
"justificativa": EXAMPLE_JUSTIFICATION,
|
|
435
|
+
"fundamentos": [],
|
|
436
|
+
"lacunas": [],
|
|
437
|
+
"detalhes": {
|
|
438
|
+
"estado_temporal": "mantida",
|
|
439
|
+
"conclusoes_motivos": [
|
|
440
|
+
{
|
|
441
|
+
"id_motivo": str(reason),
|
|
442
|
+
"decisao": "manter",
|
|
443
|
+
"justificativa": EXAMPLE_REASON_JUSTIFICATION,
|
|
444
|
+
}
|
|
445
|
+
for reason in reason_ids
|
|
446
|
+
],
|
|
447
|
+
"providencias_informadas": [],
|
|
448
|
+
"comentarios_encaminhamento": "",
|
|
449
|
+
"consequencias_praticas": [],
|
|
450
|
+
"alternativas_propostas": [],
|
|
451
|
+
},
|
|
452
|
+
}
|
|
453
|
+
)
|
|
454
|
+
continue
|
|
455
|
+
chosen = decision or "fundamentada"
|
|
456
|
+
cited = chosen in SUPPORT_DECISIONS_REQUIRING_FOUNDATIONS
|
|
457
|
+
conclusions.append(
|
|
458
|
+
{
|
|
459
|
+
"item_codigo": code,
|
|
460
|
+
"decisao": chosen,
|
|
461
|
+
"justificativa": EXAMPLE_JUSTIFICATION,
|
|
462
|
+
"fundamentos": [
|
|
463
|
+
{"arquivo": name, "localizacao": "página 1", "elemento": EXAMPLE_EXCERPT}
|
|
464
|
+
for name in (_example_files(files) if cited else [])
|
|
465
|
+
],
|
|
466
|
+
"lacunas": [],
|
|
467
|
+
}
|
|
468
|
+
)
|
|
469
|
+
if self.manager_comment:
|
|
470
|
+
return {"status": "completed", "conclusoes": conclusions, "error": ""}
|
|
471
|
+
return {"conclusoes": conclusions}
|
|
472
|
+
|
|
473
|
+
@property
|
|
474
|
+
def schema(self) -> Mapping[str, Any]:
|
|
475
|
+
details: dict[str, Any]
|
|
476
|
+
if self.manager_comment:
|
|
477
|
+
details = {
|
|
478
|
+
"type": "object",
|
|
479
|
+
"additionalProperties": False,
|
|
480
|
+
"properties": {
|
|
481
|
+
"estado_temporal": {
|
|
482
|
+
"type": ["string", "null"],
|
|
483
|
+
"enum": [
|
|
484
|
+
"mantida",
|
|
485
|
+
"afastada_na_data_base",
|
|
486
|
+
"corrigida_posteriormente",
|
|
487
|
+
None,
|
|
488
|
+
],
|
|
489
|
+
},
|
|
490
|
+
"conclusoes_motivos": {
|
|
491
|
+
"type": "array",
|
|
492
|
+
"items": {
|
|
493
|
+
"type": "object",
|
|
494
|
+
"additionalProperties": False,
|
|
495
|
+
"properties": {
|
|
496
|
+
"id_motivo": {"type": "string"},
|
|
497
|
+
"decisao": {
|
|
498
|
+
"type": "string",
|
|
499
|
+
"enum": ["manter", "modificar", "remover"],
|
|
500
|
+
},
|
|
501
|
+
"justificativa": {"type": "string"},
|
|
502
|
+
},
|
|
503
|
+
"required": ["id_motivo", "decisao", "justificativa"],
|
|
504
|
+
},
|
|
505
|
+
},
|
|
506
|
+
"providencias_informadas": {
|
|
507
|
+
"type": "array",
|
|
508
|
+
"items": {"type": "string"},
|
|
509
|
+
},
|
|
510
|
+
"comentarios_encaminhamento": {"type": "string"},
|
|
511
|
+
"consequencias_praticas": {
|
|
512
|
+
"type": "array",
|
|
513
|
+
"items": {"type": "string"},
|
|
514
|
+
},
|
|
515
|
+
"alternativas_propostas": {
|
|
516
|
+
"type": "array",
|
|
517
|
+
"items": {"type": "string"},
|
|
518
|
+
},
|
|
519
|
+
},
|
|
520
|
+
"required": [
|
|
521
|
+
"estado_temporal",
|
|
522
|
+
"conclusoes_motivos",
|
|
523
|
+
"providencias_informadas",
|
|
524
|
+
"comentarios_encaminhamento",
|
|
525
|
+
"consequencias_praticas",
|
|
526
|
+
"alternativas_propostas",
|
|
527
|
+
],
|
|
528
|
+
}
|
|
529
|
+
else:
|
|
530
|
+
details = {
|
|
531
|
+
"type": "object",
|
|
532
|
+
"additionalProperties": False,
|
|
533
|
+
"properties": {},
|
|
534
|
+
}
|
|
535
|
+
if not self.manager_comment:
|
|
536
|
+
return self._evidence_schema()
|
|
537
|
+
conclusion = {
|
|
538
|
+
"type": "object",
|
|
539
|
+
"additionalProperties": False,
|
|
540
|
+
"properties": {
|
|
541
|
+
"item_codigo": {"type": "string"},
|
|
542
|
+
"item_texto": {"type": "string"},
|
|
543
|
+
"objeto_avaliado": {"type": "string"},
|
|
544
|
+
"decisao": {
|
|
545
|
+
"type": "string",
|
|
546
|
+
"enum": sorted(self.decision_values),
|
|
547
|
+
},
|
|
548
|
+
"justificativa": {"type": "string"},
|
|
549
|
+
"fundamentos": {
|
|
550
|
+
"type": "array",
|
|
551
|
+
"items": {
|
|
552
|
+
"type": "object",
|
|
553
|
+
"additionalProperties": False,
|
|
554
|
+
"properties": {
|
|
555
|
+
"arquivo": {"type": "string"},
|
|
556
|
+
"localizacao": {"type": "string"},
|
|
557
|
+
"elemento": {"type": "string"},
|
|
558
|
+
},
|
|
559
|
+
"required": ["arquivo", "localizacao", "elemento"],
|
|
560
|
+
},
|
|
561
|
+
},
|
|
562
|
+
"lacunas": {"type": "array", "items": {"type": "string"}},
|
|
563
|
+
"detalhes": details,
|
|
564
|
+
},
|
|
565
|
+
"required": [
|
|
566
|
+
"item_codigo",
|
|
567
|
+
"item_texto",
|
|
568
|
+
"objeto_avaliado",
|
|
569
|
+
"decisao",
|
|
570
|
+
"justificativa",
|
|
571
|
+
"fundamentos",
|
|
572
|
+
"lacunas",
|
|
573
|
+
"detalhes",
|
|
574
|
+
],
|
|
575
|
+
}
|
|
576
|
+
return {
|
|
577
|
+
"type": "object",
|
|
578
|
+
"additionalProperties": False,
|
|
579
|
+
"properties": {
|
|
580
|
+
"status": {"type": "string", "enum": ["completed"]},
|
|
581
|
+
"conclusoes": {"type": "array", "items": conclusion},
|
|
582
|
+
"error": {"type": "string"},
|
|
583
|
+
},
|
|
584
|
+
"required": ["status", "conclusoes", "error"],
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
def _evidence_schema(self) -> Mapping[str, Any]:
|
|
588
|
+
"""O modelo devolve só o que o motor consome; o resto é preenchido na validação."""
|
|
589
|
+
foundation = {
|
|
590
|
+
"type": "object",
|
|
591
|
+
"additionalProperties": False,
|
|
592
|
+
"properties": {
|
|
593
|
+
"arquivo": {"type": "string"},
|
|
594
|
+
"localizacao": {"type": "string"},
|
|
595
|
+
"elemento": {"type": "string"},
|
|
596
|
+
},
|
|
597
|
+
"required": ["arquivo", "localizacao", "elemento"],
|
|
598
|
+
}
|
|
599
|
+
conclusion = {
|
|
600
|
+
"type": "object",
|
|
601
|
+
"additionalProperties": False,
|
|
602
|
+
"properties": {
|
|
603
|
+
"item_codigo": {"type": "string"},
|
|
604
|
+
"decisao": {"type": "string", "enum": sorted(self.decision_values)},
|
|
605
|
+
"justificativa": {"type": "string", "minLength": 1},
|
|
606
|
+
"fundamentos": {"type": "array", "items": foundation},
|
|
607
|
+
"lacunas": {"type": "array", "items": {"type": "string"}},
|
|
608
|
+
},
|
|
609
|
+
"required": ["item_codigo", "decisao", "justificativa", "fundamentos", "lacunas"],
|
|
610
|
+
}
|
|
611
|
+
return {
|
|
612
|
+
"type": "object",
|
|
613
|
+
"additionalProperties": False,
|
|
614
|
+
"properties": {"conclusoes": {"type": "array", "items": conclusion}},
|
|
615
|
+
"required": ["conclusoes"],
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
def _validate_evidence(
|
|
619
|
+
self, payload: Mapping[str, Any], expected_item_codes: Sequence[str]
|
|
620
|
+
) -> dict[str, Any]:
|
|
621
|
+
"""Valida o essencial e descarta chaves desconhecidas; devolve a forma completa armazenada."""
|
|
622
|
+
if payload.get("status", "completed") != "completed":
|
|
623
|
+
raise InputValidationError("resposta de Avaliação não está completed")
|
|
624
|
+
conclusions = payload.get("conclusoes")
|
|
625
|
+
if not isinstance(conclusions, list) or not conclusions:
|
|
626
|
+
raise InputValidationError("resposta precisa de conclusoes não vazias")
|
|
627
|
+
normalized: list[dict[str, Any]] = []
|
|
628
|
+
received: list[str] = []
|
|
629
|
+
for position, conclusion in enumerate(conclusions):
|
|
630
|
+
if not isinstance(conclusion, Mapping):
|
|
631
|
+
raise InputValidationError(f"conclusão v2 {position} deve ser objeto")
|
|
632
|
+
missing = sorted({"item_codigo", "decisao", "justificativa", "fundamentos"}.difference(conclusion))
|
|
633
|
+
if missing:
|
|
634
|
+
unexpected = sorted(set(conclusion).difference(_EVIDENCE_CONCLUSION_KEYS))
|
|
635
|
+
hint = f"; chaves recebidas fora do contrato: {unexpected}" if unexpected else ""
|
|
636
|
+
raise InputValidationError(
|
|
637
|
+
f"conclusão v2 {position} sem campos obrigatórios: {missing}{hint}"
|
|
638
|
+
)
|
|
639
|
+
code = str(conclusion.get("item_codigo") or "").strip()
|
|
640
|
+
if not code:
|
|
641
|
+
raise InputValidationError(f"conclusão v2 {position} sem item_codigo")
|
|
642
|
+
received.append(code)
|
|
643
|
+
decision = conclusion.get("decisao")
|
|
644
|
+
if decision not in self.decision_values:
|
|
645
|
+
raise InputValidationError(f"decisão inválida na conclusão {position}")
|
|
646
|
+
reasoning = conclusion.get("justificativa")
|
|
647
|
+
if not isinstance(reasoning, str) or not reasoning.strip():
|
|
648
|
+
raise InputValidationError(f"justificativa vazia na conclusão {position}")
|
|
649
|
+
gaps = conclusion.get("lacunas", [])
|
|
650
|
+
if not isinstance(gaps, list) or not all(isinstance(gap, str) for gap in gaps):
|
|
651
|
+
raise InputValidationError(f"lacunas inválidas na conclusão {position}")
|
|
652
|
+
self._validate_foundations(conclusion.get("fundamentos"), position)
|
|
653
|
+
if decision in SUPPORT_DECISIONS_REQUIRING_FOUNDATIONS and not any(
|
|
654
|
+
str(item["arquivo"]).strip() and str(item["elemento"]).strip()
|
|
655
|
+
for item in conclusion["fundamentos"]
|
|
656
|
+
):
|
|
657
|
+
raise InputValidationError(
|
|
658
|
+
f"decisão {decision} exige ao menos um fundamento citável na conclusão {position}: "
|
|
659
|
+
"inclua em `fundamentos` ao menos um objeto com `arquivo`, `localizacao` e `elemento` preenchidos"
|
|
660
|
+
)
|
|
661
|
+
item_text = conclusion.get("item_texto")
|
|
662
|
+
normalized.append(
|
|
663
|
+
{
|
|
664
|
+
"item_codigo": code,
|
|
665
|
+
"item_texto": item_text if isinstance(item_text, str) else "",
|
|
666
|
+
"decisao": decision,
|
|
667
|
+
"justificativa": reasoning,
|
|
668
|
+
"fundamentos": [dict(item) for item in conclusion["fundamentos"]],
|
|
669
|
+
"lacunas": list(gaps),
|
|
670
|
+
"detalhes": {},
|
|
671
|
+
}
|
|
672
|
+
)
|
|
673
|
+
ResponseProfile._validate_exact_scope(received, expected_item_codes, label="itens")
|
|
674
|
+
return {"status": "completed", "conclusoes": normalized, "error": ""}
|
|
675
|
+
|
|
676
|
+
def validate(
|
|
677
|
+
self,
|
|
678
|
+
payload: Mapping[str, Any],
|
|
679
|
+
*,
|
|
680
|
+
expected_item_codes: Sequence[str] = (),
|
|
681
|
+
expected_reason_ids: Sequence[str] = (),
|
|
682
|
+
) -> dict[str, Any]:
|
|
683
|
+
if not self.manager_comment:
|
|
684
|
+
return self._validate_evidence(payload, expected_item_codes)
|
|
685
|
+
payload = _with_default_error(payload)
|
|
686
|
+
if set(payload) != {"status", "conclusoes", "error"}:
|
|
687
|
+
raise InputValidationError(
|
|
688
|
+
"resposta deve conter somente status, conclusoes e error"
|
|
689
|
+
)
|
|
690
|
+
if payload.get("status") != "completed" or not isinstance(
|
|
691
|
+
payload.get("error"), str
|
|
692
|
+
):
|
|
693
|
+
raise InputValidationError("resposta de Avaliação v2 inválida")
|
|
694
|
+
conclusions = payload.get("conclusoes")
|
|
695
|
+
if not isinstance(conclusions, list) or not conclusions:
|
|
696
|
+
raise InputValidationError("resposta precisa de conclusoes não vazias")
|
|
697
|
+
received: list[str] = []
|
|
698
|
+
expected_fields = {
|
|
699
|
+
"item_codigo",
|
|
700
|
+
"item_texto",
|
|
701
|
+
"objeto_avaliado",
|
|
702
|
+
"decisao",
|
|
703
|
+
"justificativa",
|
|
704
|
+
"fundamentos",
|
|
705
|
+
"lacunas",
|
|
706
|
+
"detalhes",
|
|
707
|
+
}
|
|
708
|
+
for position, conclusion in enumerate(conclusions):
|
|
709
|
+
if not isinstance(conclusion, Mapping):
|
|
710
|
+
raise InputValidationError(f"conclusão v2 {position} deve ser objeto")
|
|
711
|
+
if set(conclusion) != expected_fields:
|
|
712
|
+
missing = sorted(expected_fields.difference(conclusion))
|
|
713
|
+
extra = sorted(set(conclusion).difference(expected_fields))
|
|
714
|
+
raise InputValidationError(
|
|
715
|
+
f"conclusão v2 {position} incompatível; faltantes={missing}, extras={extra}"
|
|
716
|
+
)
|
|
717
|
+
code = str(conclusion.get("item_codigo") or "").strip()
|
|
718
|
+
if not code:
|
|
719
|
+
raise InputValidationError(f"conclusão v2 {position} sem item_codigo")
|
|
720
|
+
received.append(code)
|
|
721
|
+
if conclusion.get("decisao") not in self.decision_values:
|
|
722
|
+
raise InputValidationError(f"decisão inválida na conclusão {position}")
|
|
723
|
+
if not isinstance(conclusion.get("justificativa"), str):
|
|
724
|
+
raise InputValidationError(f"justificativa inválida na conclusão {position}")
|
|
725
|
+
if not isinstance(conclusion.get("lacunas"), list):
|
|
726
|
+
raise InputValidationError(f"lacunas inválidas na conclusão {position}")
|
|
727
|
+
self._validate_foundations(conclusion.get("fundamentos"), position)
|
|
728
|
+
if self.manager_comment:
|
|
729
|
+
self._validate_manager_details(
|
|
730
|
+
conclusion.get("detalhes"),
|
|
731
|
+
position=position,
|
|
732
|
+
expected_reason_ids=expected_reason_ids,
|
|
733
|
+
)
|
|
734
|
+
elif conclusion.get("detalhes") != {}:
|
|
735
|
+
raise InputValidationError(
|
|
736
|
+
f"detalhes de evidência devem ser vazios na conclusão {position}"
|
|
737
|
+
)
|
|
738
|
+
ResponseProfile._validate_exact_scope(received, expected_item_codes, label="itens")
|
|
739
|
+
return dict(payload)
|
|
740
|
+
|
|
741
|
+
@staticmethod
|
|
742
|
+
def _validate_foundations(value: Any, position: int) -> None:
|
|
743
|
+
expected = ("arquivo", "localizacao", "elemento")
|
|
744
|
+
shape = "objetos com exatamente as chaves `arquivo`, `localizacao` e `elemento`"
|
|
745
|
+
if not isinstance(value, list):
|
|
746
|
+
raise InputValidationError(
|
|
747
|
+
f"fundamentos inválidos na conclusão {position}: esperada lista de {shape}; "
|
|
748
|
+
f"recebido {type(value).__name__}"
|
|
749
|
+
)
|
|
750
|
+
for index, foundation in enumerate(value):
|
|
751
|
+
where = f"fundamento {index} da conclusão {position}"
|
|
752
|
+
if not isinstance(foundation, Mapping):
|
|
753
|
+
raise InputValidationError(
|
|
754
|
+
f"fundamento inválido na conclusão {position}: {where} deve ser objeto "
|
|
755
|
+
f"com as chaves `arquivo`, `localizacao` e `elemento`; recebido {type(foundation).__name__}"
|
|
756
|
+
)
|
|
757
|
+
if set(foundation) != set(expected):
|
|
758
|
+
missing = [name for name in expected if name not in foundation]
|
|
759
|
+
extra = sorted(str(name) for name in foundation if name not in expected)
|
|
760
|
+
raise InputValidationError(
|
|
761
|
+
f"fundamento inválido na conclusão {position}: {where} "
|
|
762
|
+
f"sem as chaves {missing} e com chaves fora do contrato {extra}"
|
|
763
|
+
)
|
|
764
|
+
if not all(isinstance(foundation[name], str) for name in foundation):
|
|
765
|
+
raise InputValidationError(
|
|
766
|
+
f"fundamento não textual na conclusão {position}: {where} exige texto em todas as chaves"
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
@staticmethod
|
|
770
|
+
def _validate_manager_details(
|
|
771
|
+
value: Any,
|
|
772
|
+
*,
|
|
773
|
+
position: int,
|
|
774
|
+
expected_reason_ids: Sequence[str],
|
|
775
|
+
) -> None:
|
|
776
|
+
fields = {
|
|
777
|
+
"estado_temporal",
|
|
778
|
+
"conclusoes_motivos",
|
|
779
|
+
"providencias_informadas",
|
|
780
|
+
"comentarios_encaminhamento",
|
|
781
|
+
"consequencias_praticas",
|
|
782
|
+
"alternativas_propostas",
|
|
783
|
+
}
|
|
784
|
+
if not isinstance(value, Mapping) or set(value) != fields:
|
|
785
|
+
raise InputValidationError(f"detalhes gerenciais inválidos na conclusão {position}")
|
|
786
|
+
if value.get("estado_temporal") not in {
|
|
787
|
+
None,
|
|
788
|
+
"mantida",
|
|
789
|
+
"afastada_na_data_base",
|
|
790
|
+
"corrigida_posteriormente",
|
|
791
|
+
}:
|
|
792
|
+
raise InputValidationError(f"estado_temporal inválido na conclusão {position}")
|
|
793
|
+
for name in {
|
|
794
|
+
"conclusoes_motivos",
|
|
795
|
+
"providencias_informadas",
|
|
796
|
+
"consequencias_praticas",
|
|
797
|
+
"alternativas_propostas",
|
|
798
|
+
}:
|
|
799
|
+
if not isinstance(value.get(name), list):
|
|
800
|
+
raise InputValidationError(f"{name} inválido na conclusão {position}")
|
|
801
|
+
if not isinstance(value.get("comentarios_encaminhamento"), str):
|
|
802
|
+
raise InputValidationError("comentarios_encaminhamento deve ser texto")
|
|
803
|
+
received: list[str] = []
|
|
804
|
+
for reason in value["conclusoes_motivos"]:
|
|
805
|
+
if not isinstance(reason, Mapping) or set(reason) != {
|
|
806
|
+
"id_motivo",
|
|
807
|
+
"decisao",
|
|
808
|
+
"justificativa",
|
|
809
|
+
}:
|
|
810
|
+
raise InputValidationError("conclusão de motivo inválida")
|
|
811
|
+
received.append(str(reason.get("id_motivo") or "").strip())
|
|
812
|
+
if reason.get("decisao") not in {"manter", "modificar", "remover"}:
|
|
813
|
+
raise InputValidationError("decisão de motivo inválida")
|
|
814
|
+
ResponseProfile._validate_exact_scope(
|
|
815
|
+
received, expected_reason_ids, label="motivos"
|
|
816
|
+
)
|
|
817
|
+
|
|
818
|
+
@staticmethod
|
|
819
|
+
def decision(conclusion: Mapping[str, Any]) -> str:
|
|
820
|
+
return str(conclusion.get("decisao") or "")
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
class ResponseProfileRegistry:
|
|
824
|
+
"""Registry fechado dos profiles comparáveis suportados pelo núcleo."""
|
|
825
|
+
|
|
826
|
+
def __init__(self) -> None:
|
|
827
|
+
evidence = ResponseProfile("evidence", temporal=False)
|
|
828
|
+
temporal = ResponseProfile("manager_comments_temporal", temporal=True)
|
|
829
|
+
evidence_v2 = ComparableResponseProfile(
|
|
830
|
+
"evidence_support/v2",
|
|
831
|
+
{
|
|
832
|
+
"fundamentada",
|
|
833
|
+
"parcialmente_fundamentada",
|
|
834
|
+
"nao_fundamentada",
|
|
835
|
+
"inconclusiva",
|
|
836
|
+
},
|
|
837
|
+
)
|
|
838
|
+
manager_v2 = ComparableResponseProfile(
|
|
839
|
+
"manager_comment/v2",
|
|
840
|
+
{"manter", "modificar", "remover", "inconclusiva"},
|
|
841
|
+
manager_comment=True,
|
|
842
|
+
)
|
|
843
|
+
self._profiles = {
|
|
844
|
+
"evidence": evidence,
|
|
845
|
+
"evidence/v1": evidence,
|
|
846
|
+
"manager_comments_temporal": temporal,
|
|
847
|
+
"manager_comments_temporal/v1": temporal,
|
|
848
|
+
"evidence_support/v2": evidence_v2,
|
|
849
|
+
"manager_comment/v2": manager_v2,
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
def get(self, name: str) -> ResponseProfile:
|
|
853
|
+
try:
|
|
854
|
+
return self._profiles[str(name)]
|
|
855
|
+
except KeyError as exc:
|
|
856
|
+
raise InputValidationError(f"response_profile desconhecido: {name}") from exc
|