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/store.py ADDED
@@ -0,0 +1,1228 @@
1
+ """Persistência SQLite enxuta por fiscalização.
2
+
3
+ Cinco responsabilidades usam seis tabelas funcionais:
4
+
5
+ 1. ``fiscalizacao`` — identidade registrada do trabalho;
6
+ 2. ``scenario`` — cenários imutáveis derivados (``base`` → ``01-...``);
7
+ 3. ``execution`` (+ ``execution_event``) — execuções, resultados e trilha;
8
+ 4. ``product`` — proveniência de produtos publicados;
9
+ 5. ``evaluation_cache`` — pedidos e respostas reutilizáveis de IA.
10
+
11
+ O cache deduplica pedidos efetivos por ``(fiscalizacao_id, semantic_hash)``;
12
+ resultados e decisões humanas por execução ficam em ``execution.result_json``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import sqlite3
20
+ import threading
21
+ import uuid
22
+ import weakref
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Mapping, Sequence
26
+
27
+ from .errors import ArgosError, AuditIdentityRequiredError, InputValidationError
28
+ from .version import __version__ as ARGOS_VERSION
29
+ from .status import EVENT_EXECUTION_CREATED, INITIAL_EXECUTION_STATUS, REUSABLE_EXECUTION_STATUSES, UNKNOWN
30
+
31
+
32
+ from .contracts import ScenarioDraft, canonical_json, sha256_bytes, sha256_file, utc_now
33
+ from .telemetry import redact_error, redact_payload
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class WorkspaceLocation:
38
+ """Localização resolvida de um workspace e do seu arquivo SQLite.
39
+
40
+ A interface aceita tanto o diretório histórico do Argos quanto um arquivo
41
+ ``.sqlite3`` nomeado pelo usuário. O diretório continua sendo a unidade
42
+ usada pela sessão para resolver insumos relativos.
43
+ """
44
+
45
+ root: Path
46
+ db_path: Path
47
+
48
+ @classmethod
49
+ def from_path(cls, value: str | Path) -> "WorkspaceLocation":
50
+ candidate = Path(value).expanduser().resolve()
51
+ if candidate.exists() and candidate.is_dir():
52
+ return cls(root=candidate, db_path=candidate / "argos.sqlite3")
53
+ if candidate.exists() and candidate.is_file():
54
+ if candidate.suffix.casefold() not in {".sqlite", ".sqlite3"}:
55
+ raise ArgosError(f"arquivo de workspace deve terminar em .sqlite ou .sqlite3: {candidate}")
56
+ return cls(root=candidate.parent, db_path=candidate)
57
+ if candidate.suffix.casefold() in {".sqlite", ".sqlite3"}:
58
+ return cls(root=candidate.parent, db_path=candidate)
59
+ return cls(root=candidate, db_path=candidate / "argos.sqlite3")
60
+
61
+
62
+ class WorkspaceStore:
63
+ """Adapter SQLite do workspace de uma fiscalização."""
64
+
65
+ SCHEMA_VERSION = 1
66
+ _OPEN_STORES: weakref.WeakSet["WorkspaceStore"] = weakref.WeakSet()
67
+
68
+ SCHEMA = """
69
+ PRAGMA foreign_keys = ON;
70
+ CREATE TABLE IF NOT EXISTS fiscalizacao (
71
+ id TEXT PRIMARY KEY,
72
+ numero TEXT NOT NULL UNIQUE,
73
+ nome TEXT NOT NULL,
74
+ created_at TEXT NOT NULL,
75
+ updated_at TEXT NOT NULL
76
+ );
77
+ CREATE TABLE IF NOT EXISTS scenario (
78
+ id TEXT NOT NULL,
79
+ fiscalizacao_id TEXT NOT NULL REFERENCES fiscalizacao(id),
80
+ parent_id TEXT,
81
+ kind TEXT NOT NULL,
82
+ name TEXT NOT NULL,
83
+ input_hash TEXT NOT NULL,
84
+ metadata_json TEXT NOT NULL,
85
+ created_at TEXT NOT NULL,
86
+ PRIMARY KEY(fiscalizacao_id, id),
87
+ FOREIGN KEY(fiscalizacao_id, parent_id) REFERENCES scenario(fiscalizacao_id, id)
88
+ );
89
+ CREATE TABLE IF NOT EXISTS execution (
90
+ id TEXT PRIMARY KEY,
91
+ fiscalizacao_id TEXT NOT NULL REFERENCES fiscalizacao(id),
92
+ operation_id TEXT NOT NULL,
93
+ scenario_id TEXT NOT NULL DEFAULT 'base',
94
+ status TEXT NOT NULL,
95
+ params_json TEXT NOT NULL,
96
+ input_hash TEXT NOT NULL,
97
+ argos_version TEXT NOT NULL DEFAULT '',
98
+ result_json TEXT,
99
+ error TEXT,
100
+ created_at TEXT NOT NULL,
101
+ started_at TEXT,
102
+ finished_at TEXT,
103
+ FOREIGN KEY(fiscalizacao_id, scenario_id) REFERENCES scenario(fiscalizacao_id, id)
104
+ );
105
+ CREATE TABLE IF NOT EXISTS execution_event (
106
+ event_id INTEGER PRIMARY KEY AUTOINCREMENT,
107
+ execution_id TEXT NOT NULL REFERENCES execution(id),
108
+ unit_id TEXT,
109
+ event_type TEXT NOT NULL,
110
+ status TEXT,
111
+ occurred_at TEXT NOT NULL,
112
+ payload_json TEXT NOT NULL
113
+ );
114
+ CREATE INDEX IF NOT EXISTS ix_execution_event_execution
115
+ ON execution_event(execution_id, event_id);
116
+ CREATE TABLE IF NOT EXISTS product (
117
+ id TEXT PRIMARY KEY,
118
+ execution_id TEXT NOT NULL REFERENCES execution(id),
119
+ operation_id TEXT NOT NULL,
120
+ kind TEXT NOT NULL,
121
+ path TEXT NOT NULL,
122
+ sha256 TEXT NOT NULL,
123
+ size_bytes INTEGER NOT NULL,
124
+ media_type TEXT NOT NULL,
125
+ metadata_json TEXT NOT NULL,
126
+ created_at TEXT NOT NULL
127
+ );
128
+ CREATE TABLE IF NOT EXISTS evaluation_cache (
129
+ fiscalizacao_id TEXT NOT NULL REFERENCES fiscalizacao(id),
130
+ semantic_hash TEXT NOT NULL,
131
+ status TEXT NOT NULL,
132
+ request_json TEXT NOT NULL,
133
+ result_json TEXT,
134
+ technical_json TEXT NOT NULL,
135
+ error TEXT,
136
+ attempts INTEGER NOT NULL,
137
+ created_at TEXT NOT NULL,
138
+ updated_at TEXT NOT NULL,
139
+ PRIMARY KEY(fiscalizacao_id, semantic_hash)
140
+ );
141
+ CREATE INDEX IF NOT EXISTS ix_execution_reuse
142
+ ON execution(fiscalizacao_id, operation_id, input_hash, status);
143
+ CREATE INDEX IF NOT EXISTS ix_product_identity
144
+ ON product(operation_id, sha256);
145
+ CREATE INDEX IF NOT EXISTS ix_evaluation_cache_status
146
+ ON evaluation_cache(fiscalizacao_id, status, updated_at);
147
+ """
148
+
149
+ _TABLE_COLUMNS = {
150
+ "fiscalizacao": {"id", "numero", "nome", "created_at", "updated_at"},
151
+ "scenario": {"id", "fiscalizacao_id", "parent_id", "kind", "name", "input_hash", "metadata_json", "created_at"},
152
+ "execution": {"id", "fiscalizacao_id", "operation_id", "scenario_id", "status", "params_json", "input_hash", "argos_version", "result_json", "error", "created_at", "started_at", "finished_at"},
153
+ "execution_event": {"event_id", "execution_id", "unit_id", "event_type", "status", "occurred_at", "payload_json"},
154
+ "product": {"id", "execution_id", "operation_id", "kind", "path", "sha256", "size_bytes", "media_type", "metadata_json", "created_at"},
155
+ "evaluation_cache": {"fiscalizacao_id", "semantic_hash", "status", "request_json", "result_json", "technical_json", "error", "attempts", "created_at", "updated_at"},
156
+ }
157
+
158
+ def __init__(self, db_path: Path, *, numero: str, nome: str) -> None:
159
+ self.db_path = db_path
160
+ self.numero = numero
161
+ self.nome = nome
162
+ self._lock = threading.RLock()
163
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
164
+ self.connection = sqlite3.connect(
165
+ self.db_path,
166
+ check_same_thread=False,
167
+ isolation_level=None,
168
+ )
169
+ self.connection.row_factory = sqlite3.Row
170
+ self.connection.execute("PRAGMA busy_timeout = 5000")
171
+ try:
172
+ with self._lock:
173
+ self.connection.execute("PRAGMA foreign_keys = ON")
174
+ self._initialize_schema()
175
+ self._register_identity(numero, nome)
176
+ self._OPEN_STORES.add(self)
177
+ except Exception:
178
+ self.connection.close()
179
+ raise
180
+
181
+ def _initialize_schema(self) -> None:
182
+ tables = {
183
+ str(row[0])
184
+ for row in self.connection.execute(
185
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
186
+ ).fetchall()
187
+ }
188
+ version = int(self.connection.execute("PRAGMA user_version").fetchone()[0])
189
+ if not tables:
190
+ if version > self.SCHEMA_VERSION:
191
+ raise InputValidationError(
192
+ f"schema {version} é mais novo que o suportado ({self.SCHEMA_VERSION})"
193
+ )
194
+ self.connection.executescript(self.SCHEMA)
195
+ self.connection.execute(f"PRAGMA user_version = {self.SCHEMA_VERSION}")
196
+ return
197
+ if version > self.SCHEMA_VERSION:
198
+ raise InputValidationError(
199
+ f"schema {version} é mais novo que o suportado ({self.SCHEMA_VERSION})"
200
+ )
201
+ if version != self.SCHEMA_VERSION or tables != set(self._TABLE_COLUMNS):
202
+ raise InputValidationError(
203
+ "formato SQLite incompatível com esta versão do Argos; crie um workspace novo"
204
+ )
205
+ for table, required in self._TABLE_COLUMNS.items():
206
+ columns = {
207
+ str(row["name"])
208
+ for row in self.connection.execute(f"PRAGMA table_info({table})").fetchall()
209
+ }
210
+ if columns != required:
211
+ raise InputValidationError(
212
+ f"schema incompatível na tabela {table}; crie um workspace novo"
213
+ )
214
+
215
+ def _register_identity(self, numero: str, nome: str) -> None:
216
+ self.connection.execute("BEGIN IMMEDIATE")
217
+ try:
218
+ existing = self.connection.execute("SELECT nome FROM fiscalizacao WHERE numero=?", (numero,)).fetchone()
219
+ if existing is not None and str(existing["nome"]) != nome:
220
+ raise InputValidationError("nome informado diverge da fiscalização registrada; identidade não pode ser alterada implicitamente")
221
+ now = utc_now()
222
+ fiscalizacao_id = self._fiscalizacao_id(numero, nome)
223
+ self.connection.execute(
224
+ """
225
+ INSERT INTO fiscalizacao(id, numero, nome, created_at, updated_at)
226
+ VALUES(?, ?, ?, ?, ?)
227
+ ON CONFLICT(numero) DO NOTHING
228
+ """,
229
+ (fiscalizacao_id, numero, nome, now, now),
230
+ )
231
+ row = self.connection.execute(
232
+ "SELECT id, numero, nome FROM fiscalizacao WHERE numero = ?", (numero,)
233
+ ).fetchone()
234
+ assert row is not None
235
+ self.fiscalizacao_id = str(row["id"])
236
+ self.numero = str(row["numero"])
237
+ self.nome = str(row["nome"])
238
+ self._ensure_scenario_row_locked(
239
+ "base",
240
+ name="Base",
241
+ kind="base",
242
+ input_hash="base",
243
+ )
244
+ self.connection.commit()
245
+ except Exception:
246
+ self.connection.rollback()
247
+ raise
248
+
249
+ @staticmethod
250
+ def _fiscalizacao_id(numero: str, nome: str) -> str:
251
+ return sha256_bytes(f"{numero}\0{nome}".encode("utf-8"))[:32]
252
+
253
+ # --- Cenários ---------------------------------------------------------
254
+
255
+ def ensure_scenario(
256
+ self,
257
+ scenario_id: str,
258
+ *,
259
+ name: str | None = None,
260
+ parent_id: str | None = None,
261
+ kind: str | None = None,
262
+ input_hash: str | None = None,
263
+ metadata: Mapping[str, Any] | None = None,
264
+ ) -> dict[str, Any]:
265
+ """Cria um cenário uma única vez; divergências de metadados são recusadas."""
266
+ with self._lock:
267
+ self.connection.execute("BEGIN IMMEDIATE")
268
+ try:
269
+ row = self._ensure_scenario_row_locked(
270
+ scenario_id,
271
+ name=name,
272
+ parent_id=parent_id,
273
+ kind=kind,
274
+ input_hash=input_hash,
275
+ metadata=metadata,
276
+ )
277
+ self.connection.execute("COMMIT")
278
+ except Exception:
279
+ if self.connection.in_transaction:
280
+ self.connection.execute("ROLLBACK")
281
+ raise
282
+ return row
283
+
284
+ def _ensure_scenario_row_locked(
285
+ self,
286
+ scenario_id: str,
287
+ *,
288
+ name: str | None = None,
289
+ parent_id: str | None = None,
290
+ kind: str | None = None,
291
+ input_hash: str | None = None,
292
+ metadata: Mapping[str, Any] | None = None,
293
+ ) -> dict[str, Any]:
294
+ identifier = str(scenario_id or "").strip()
295
+ if not identifier:
296
+ raise InputValidationError("cenário exige id não vazio")
297
+ resolved_name = str(name or identifier).strip() or identifier
298
+ resolved_kind = str(kind or "named").strip() or "named"
299
+ resolved_hash = str(input_hash if input_hash is not None else "").strip()
300
+ resolved_metadata = dict(metadata or {})
301
+ parent = str(parent_id).strip() if parent_id not in (None, "") else None
302
+ if parent == identifier:
303
+ raise InputValidationError("cenário não pode ser pai de si mesmo")
304
+ if parent is None and identifier != "base":
305
+ parent = "base"
306
+ if parent is not None and self.connection.execute(
307
+ "SELECT 1 FROM scenario WHERE fiscalizacao_id=? AND id=?",
308
+ (self.fiscalizacao_id, parent),
309
+ ).fetchone() is None:
310
+ self._ensure_scenario_row(
311
+ parent,
312
+ name="Base" if parent == "base" else parent,
313
+ parent_id=None if parent == "base" else "base",
314
+ kind="base" if parent == "base" else "named",
315
+ input_hash="base" if parent == "base" else "",
316
+ )
317
+ existing = self.connection.execute(
318
+ "SELECT * FROM scenario WHERE fiscalizacao_id=? AND id=?",
319
+ (self.fiscalizacao_id, identifier),
320
+ ).fetchone()
321
+ if existing is None:
322
+ self.connection.execute(
323
+ "INSERT INTO scenario(id, fiscalizacao_id, parent_id, kind, name, "
324
+ "input_hash, metadata_json, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
325
+ (
326
+ identifier,
327
+ self.fiscalizacao_id,
328
+ parent,
329
+ resolved_kind,
330
+ resolved_name,
331
+ resolved_hash,
332
+ canonical_json(resolved_metadata),
333
+ utc_now(),
334
+ ),
335
+ )
336
+ else:
337
+ if str(existing["parent_id"] or "") != str(parent or ""):
338
+ raise InputValidationError(f"cenário {identifier} já existe com outro pai")
339
+ if name not in (None, "") and str(existing["name"]) != resolved_name:
340
+ raise InputValidationError(f"cenário {identifier} já existe com outro nome")
341
+ stored = json.loads(str(existing["metadata_json"] or "{}"))
342
+ if resolved_metadata and stored != resolved_metadata:
343
+ raise InputValidationError(f"cenário {identifier} já existe com outros metadados")
344
+ row = self.connection.execute(
345
+ "SELECT * FROM scenario WHERE fiscalizacao_id=? AND id=?",
346
+ (self.fiscalizacao_id, identifier),
347
+ ).fetchone()
348
+ assert row is not None
349
+ return dict(row)
350
+
351
+ def _ensure_scenario_row(self, scenario_id: str, **values: Any) -> None:
352
+ existing = self.connection.execute(
353
+ "SELECT 1 FROM scenario WHERE fiscalizacao_id=? AND id=?",
354
+ (self.fiscalizacao_id, scenario_id),
355
+ ).fetchone()
356
+ if existing is None:
357
+ self.connection.execute(
358
+ "INSERT INTO scenario(id, fiscalizacao_id, parent_id, kind, name, "
359
+ "input_hash, metadata_json, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
360
+ (
361
+ scenario_id,
362
+ self.fiscalizacao_id,
363
+ values.get("parent_id"),
364
+ str(values.get("kind") or "named"),
365
+ str(values.get("name") or scenario_id),
366
+ str(values.get("input_hash") or ""),
367
+ canonical_json(dict(values.get("metadata") or {})),
368
+ utc_now(),
369
+ ),
370
+ )
371
+
372
+ def ensure_session_scenario(self, scenario_id: str) -> str:
373
+ """Garante um cenário de sessão sem alterar a filiação já publicada."""
374
+ identifier = str(scenario_id or "").strip() or "base"
375
+ if identifier == "base":
376
+ self.ensure_scenario("base", name="Base", kind="base", input_hash="base")
377
+ return identifier
378
+
379
+ if self.get_scenario(identifier) is None:
380
+ self.ensure_scenario(identifier, parent_id="base")
381
+ return identifier
382
+
383
+ def get_scenario(self, scenario_id: str) -> dict[str, Any] | None:
384
+ # `_execute` serializes execute(), but the cursor is consumed after it
385
+ # returns. Keep the shared connection locked through fetchone() too:
386
+ # report batches call this getter from multiple worker threads.
387
+ with self._lock:
388
+ rows = self._query(
389
+ "SELECT * FROM scenario WHERE fiscalizacao_id=? AND id=?",
390
+ (self.fiscalizacao_id, str(scenario_id)),
391
+ )
392
+ return dict(rows[0]) if rows else None
393
+
394
+ def list_scenarios(self) -> list[dict[str, Any]]:
395
+ rows = self._query(
396
+ "SELECT * FROM scenario WHERE fiscalizacao_id=? ORDER BY created_at, id",
397
+ (self.fiscalizacao_id,),
398
+ )
399
+
400
+ return [dict(row) for row in rows]
401
+
402
+ def publish_scenario(self, draft: ScenarioDraft, *, execution_id: str | None = None) -> dict[str, Any]:
403
+ """Confirma um cenário somente depois de a operação produzir seu draft."""
404
+ with self._lock:
405
+ row = self._ensure_scenario_row_locked(
406
+ draft.id,
407
+ name=draft.name,
408
+ parent_id=draft.parent_id,
409
+ kind=draft.kind,
410
+ input_hash=draft.input_hash,
411
+ metadata=draft.metadata,
412
+ )
413
+ return {
414
+ "id": str(row["id"]),
415
+ "name": str(row["name"]),
416
+ "parent_id": row["parent_id"],
417
+ "kind": str(row["kind"]),
418
+ "input_hash": str(row["input_hash"]),
419
+ "metadata": json.loads(str(row["metadata_json"])),
420
+ }
421
+
422
+ @classmethod
423
+ def open(
424
+ cls,
425
+ root: str | Path,
426
+ *,
427
+ numero: str | None = None,
428
+ nome: str | None = None,
429
+ ) -> "WorkspaceStore":
430
+ """Abre um workspace isolado em um SQLite.
431
+
432
+ ``root`` pode ser um diretório (``root/argos.sqlite3``) ou um arquivo
433
+ ``.sqlite``/``.sqlite3`` explícito. Sem identidade, reabre a única
434
+ fiscalização registrada; workspace vazio ou ambíguo exige número e nome.
435
+ """
436
+ db_path = WorkspaceLocation.from_path(root).db_path
437
+ if (numero is None) != (nome is None):
438
+ raise ArgosError(
439
+ "informe --numero e --nome juntos; "
440
+ "para reabrir a fiscalização registrada, omita ambos"
441
+ )
442
+ if numero is None and nome is None:
443
+ if not db_path.exists():
444
+ raise AuditIdentityRequiredError(
445
+ f"workspace sem SQLite: {db_path}; informe a identidade para criar"
446
+ )
447
+ try:
448
+ connection = sqlite3.connect(db_path)
449
+ connection.row_factory = sqlite3.Row
450
+ rows = connection.execute(
451
+ "SELECT numero, nome FROM fiscalizacao ORDER BY created_at, numero"
452
+ ).fetchall()
453
+ except sqlite3.Error as exc:
454
+ raise ArgosError(
455
+ f"não foi possível ler a fiscalização registrada em {db_path}: {exc}"
456
+ ) from exc
457
+ finally:
458
+ connection.close()
459
+ if not rows:
460
+ raise AuditIdentityRequiredError(
461
+ f"nenhuma fiscalização registrada em {db_path}; informe --numero e --nome"
462
+ )
463
+ if len(rows) > 1:
464
+ registered = ", ".join(f"{row['numero']} ({row['nome']})" for row in rows)
465
+ raise AuditIdentityRequiredError(
466
+ f"workspace contém mais de uma fiscalização ({registered}); "
467
+ "use um workspace separado ou informe explicitamente --numero e --nome"
468
+ )
469
+ numero = str(rows[0]["numero"])
470
+ nome = str(rows[0]["nome"])
471
+ assert numero is not None and nome is not None
472
+ return cls(db_path, numero=numero, nome=nome)
473
+
474
+ def close(self) -> None:
475
+ with self._lock:
476
+ self._OPEN_STORES.discard(self)
477
+ self.connection.close()
478
+
479
+ @classmethod
480
+ def close_under(cls, directory: str | Path) -> None:
481
+ target = Path(directory).expanduser().resolve()
482
+ for store in list(cls._OPEN_STORES):
483
+ try:
484
+ resolved = store.db_path.resolve()
485
+ if resolved == target or target in resolved.parents:
486
+ store.close()
487
+ except Exception: # noqa: BLE001
488
+ continue
489
+
490
+ def health(self) -> dict[str, Any]:
491
+ with self._lock:
492
+ integrity = [str(row[0]) for row in self.connection.execute("PRAGMA integrity_check")]
493
+ violations = [tuple(row) for row in self.connection.execute("PRAGMA foreign_key_check")]
494
+ return {
495
+ "ok": integrity == ["ok"] and not violations,
496
+ "integrity": integrity,
497
+ "foreign_key_violations": violations,
498
+ "schema_version": int(self.connection.execute("PRAGMA user_version").fetchone()[0]),
499
+ }
500
+
501
+ def backup(self, destination: str | Path) -> dict[str, Any]:
502
+ with self._lock:
503
+ return self._copy_database(self.connection, Path(destination))
504
+
505
+ @classmethod
506
+ def restore(cls, source: str | Path, destination: str | Path) -> dict[str, Any]:
507
+ source_path = Path(source).expanduser().resolve()
508
+ if not source_path.is_file():
509
+ raise InputValidationError(f"backup ausente: {source_path}")
510
+ connection = sqlite3.connect(source_path.as_uri() + "?mode=ro", uri=True)
511
+ try:
512
+ health = cls._database_health(connection)
513
+ if not health["ok"]:
514
+ raise InputValidationError("backup inválido; restauração recusada")
515
+ cls._validate_connection_schema(connection)
516
+ return cls._copy_database(connection, Path(destination))
517
+ except sqlite3.DatabaseError as exc:
518
+ raise InputValidationError("arquivo não é um backup SQLite íntegro") from exc
519
+ finally:
520
+ connection.close()
521
+
522
+ @staticmethod
523
+ def _database_health(connection: sqlite3.Connection) -> dict[str, Any]:
524
+ integrity = [str(row[0]) for row in connection.execute("PRAGMA integrity_check")]
525
+ violations = [tuple(row) for row in connection.execute("PRAGMA foreign_key_check")]
526
+ return {
527
+ "ok": integrity == ["ok"] and not violations,
528
+ "integrity": integrity,
529
+ "foreign_key_violations": violations,
530
+ "schema_version": int(connection.execute("PRAGMA user_version").fetchone()[0]),
531
+ }
532
+
533
+ @classmethod
534
+ def _validate_connection_schema(cls, connection: sqlite3.Connection) -> None:
535
+ tables = {
536
+ str(row[0])
537
+ for row in connection.execute(
538
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
539
+ ).fetchall()
540
+ }
541
+ version = int(connection.execute("PRAGMA user_version").fetchone()[0])
542
+ if version > cls.SCHEMA_VERSION:
543
+ raise InputValidationError(
544
+ f"schema {version} é mais novo que o suportado ({cls.SCHEMA_VERSION})"
545
+ )
546
+ if version != cls.SCHEMA_VERSION or tables != set(cls._TABLE_COLUMNS):
547
+ raise InputValidationError("backup não contém o schema atual do Argos")
548
+ for table, required in cls._TABLE_COLUMNS.items():
549
+ columns = {
550
+ str(row[1])
551
+ for row in connection.execute(f"PRAGMA table_info({table})").fetchall()
552
+ }
553
+ if columns != required:
554
+ raise InputValidationError("backup não contém o schema atual do Argos")
555
+
556
+ @classmethod
557
+ def _copy_database(cls, connection: sqlite3.Connection, destination: Path) -> dict[str, Any]:
558
+ destination = destination.expanduser().absolute()
559
+ if destination.exists() or destination.is_symlink():
560
+ raise InputValidationError(f"destino do backup/restauração já existe: {destination}")
561
+ destination.parent.mkdir(parents=True, exist_ok=True)
562
+ staging = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp")
563
+ try:
564
+ target = sqlite3.connect(staging)
565
+ try:
566
+ connection.backup(target, pages=256)
567
+ health = cls._database_health(target)
568
+ if not health["ok"]:
569
+ raise InputValidationError("snapshot contém falha de integridade ou relações inválidas")
570
+ cls._validate_connection_schema(target)
571
+ finally:
572
+ target.close()
573
+ with staging.open("r+b") as stream:
574
+ os.fsync(stream.fileno())
575
+ try:
576
+ os.link(staging, destination)
577
+ except FileExistsError as exc:
578
+ raise InputValidationError(f"destino ocupado durante publicação: {destination}") from exc
579
+ return {"path": str(destination), "sha256": sha256_file(destination), **health}
580
+ finally:
581
+ staging.unlink(missing_ok=True)
582
+
583
+ def _execute(self, sql: str, parameters: Sequence[Any] = ()) -> sqlite3.Cursor:
584
+ with self._lock:
585
+ return self.connection.execute(sql, parameters)
586
+
587
+ def _query(self, sql: str, parameters: Sequence[Any] = ()) -> list[sqlite3.Row]:
588
+ """Executa e materializa o cursor sob o lock compartilhado.
589
+
590
+ A conexão é única e compartilhada pelo scheduler; consumir o cursor
591
+ fora do lock deixaria outra thread avançar a conexão no meio da leitura.
592
+ """
593
+ with self._lock:
594
+ return self.connection.execute(sql, parameters).fetchall()
595
+
596
+ # --- Execuções --------------------------------------------------------
597
+
598
+ def record_event(
599
+ self,
600
+ execution_id: str,
601
+ event_type: str,
602
+ *,
603
+ status: str | None = None,
604
+ unit_id: str | None = None,
605
+ payload: Mapping[str, Any] | None = None,
606
+ ) -> int:
607
+ with self._lock:
608
+ cursor = self.connection.execute(
609
+ "INSERT INTO execution_event(execution_id, unit_id, event_type, status, "
610
+ "occurred_at, payload_json) VALUES(?, ?, ?, ?, ?, ?)",
611
+ (
612
+ execution_id,
613
+ unit_id,
614
+ event_type,
615
+ status,
616
+ utc_now(),
617
+ canonical_json(redact_payload(payload or {})),
618
+ ),
619
+ )
620
+ return int(cursor.lastrowid)
621
+
622
+ def discard_product(self, product_id: str, *, execution_id: str, reason: str) -> dict[str, Any] | None:
623
+ """Retira um produto do controle, guardando a linha original num evento.
624
+
625
+ O arquivo não é tocado: quem chama decide quando isso faz sentido (o
626
+ ``status`` só descarta produtos cujo arquivo já não existe). A linha apagada
627
+ fica em ``product_discarded`` na execução informada, para auditoria.
628
+ """
629
+ with self._lock:
630
+ self.connection.execute("BEGIN IMMEDIATE")
631
+ try:
632
+ row = self.connection.execute("SELECT * FROM product WHERE id=?", (product_id,)).fetchone()
633
+ if row is None:
634
+ self.connection.execute("COMMIT")
635
+ return None
636
+ original = {key: row[key] for key in row.keys()}
637
+ self.connection.execute(
638
+ "INSERT INTO execution_event(execution_id, unit_id, event_type, status, "
639
+ "occurred_at, payload_json) VALUES(?, ?, ?, ?, ?, ?)",
640
+ (
641
+ execution_id,
642
+ product_id,
643
+ "product_discarded",
644
+ "completed",
645
+ utc_now(),
646
+ canonical_json({"reason": reason, "product": original}),
647
+ ),
648
+ )
649
+ self.connection.execute("DELETE FROM product WHERE id=?", (product_id,))
650
+ self.connection.execute("COMMIT")
651
+ return original
652
+ except BaseException:
653
+ self.connection.execute("ROLLBACK")
654
+ raise
655
+
656
+ def create_execution(
657
+ self,
658
+ operation_id: str,
659
+ params: Mapping[str, Any],
660
+ input_hash: str,
661
+ *,
662
+ scenario_id: str = "base",
663
+ initial_status: str = INITIAL_EXECUTION_STATUS,
664
+ ) -> str:
665
+ execution_id = uuid.uuid4().hex
666
+ with self._lock:
667
+ self.connection.execute(
668
+ "INSERT INTO execution(id, fiscalizacao_id, operation_id, scenario_id, "
669
+ "status, params_json, input_hash, argos_version, created_at) "
670
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
671
+ (
672
+ execution_id,
673
+ self.fiscalizacao_id,
674
+ operation_id,
675
+ scenario_id,
676
+ initial_status,
677
+ canonical_json(params),
678
+ input_hash,
679
+ ARGOS_VERSION,
680
+ utc_now(),
681
+ ),
682
+ )
683
+ self.record_event(
684
+ execution_id,
685
+ EVENT_EXECUTION_CREATED,
686
+ status=initial_status,
687
+ payload={"argos_version": ARGOS_VERSION},
688
+ )
689
+ return execution_id
690
+
691
+ def ensure_evaluation_execution(
692
+ self, execution_id: str, *, operation_id: str, scenario_id: str, params: Mapping[str, Any]
693
+ ) -> bool:
694
+ """Registers a direct EvaluationLifecycle call under its execution ID.
695
+
696
+ Normal product execution already creates this row in ExecutionLifecycle;
697
+ this path keeps direct in-process use backed by the same execution result.
698
+ """
699
+ if self.get_execution(execution_id) is not None:
700
+ return False
701
+ scenario = self.ensure_session_scenario(scenario_id)
702
+ now = utc_now()
703
+ with self._lock:
704
+ cursor = self.connection.execute(
705
+ "INSERT OR IGNORE INTO execution(id, fiscalizacao_id, operation_id, scenario_id, status, params_json, input_hash, argos_version, created_at, started_at) "
706
+ "VALUES(?, ?, ?, ?, 'running', ?, ?, ?, ?, ?)",
707
+ (
708
+ execution_id,
709
+ self.fiscalizacao_id,
710
+ operation_id,
711
+ scenario,
712
+ canonical_json(params),
713
+ sha256_bytes(canonical_json({"execution_id": execution_id, "scenario": scenario, "params": dict(params)}).encode("utf-8")),
714
+ ARGOS_VERSION,
715
+ now,
716
+ now,
717
+ ),
718
+ )
719
+ created = cursor.rowcount > 0
720
+ if created:
721
+ self.record_event(execution_id, EVENT_EXECUTION_CREATED, status="running", payload={"origin": "evaluation_lifecycle"})
722
+ return created
723
+
724
+ def update_execution(
725
+ self,
726
+ execution_id: str,
727
+ *,
728
+ status: str | None = None,
729
+ result: Mapping[str, Any] | None = None,
730
+ error: str | None = None,
731
+ started: bool = False,
732
+ finished: bool = False,
733
+ clear_result: bool = False,
734
+ clear_error: bool = False,
735
+ clear_finished: bool = False,
736
+ ) -> None:
737
+ if self.get_execution(execution_id) is None:
738
+ return
739
+ result_changed = result is not None
740
+ error_changed = error is not None or clear_error
741
+ with self._lock:
742
+ self.connection.execute(
743
+ """
744
+ UPDATE execution
745
+ SET status = COALESCE(?, status),
746
+ result_json = CASE WHEN ? THEN ? WHEN ? THEN NULL ELSE result_json END,
747
+ error = CASE WHEN ? THEN ? ELSE error END,
748
+ started_at = CASE WHEN ? THEN COALESCE(started_at, ?) ELSE started_at END,
749
+ finished_at = CASE WHEN ? THEN NULL WHEN ? THEN COALESCE(finished_at, ?) ELSE finished_at END
750
+ WHERE id = ? AND fiscalizacao_id = ?
751
+ """,
752
+ (
753
+ status,
754
+ result_changed,
755
+ canonical_json(result) if result is not None else None,
756
+ clear_result,
757
+ error_changed,
758
+ redact_error(error) if error is not None else None,
759
+ started,
760
+ utc_now() if started else None,
761
+ clear_finished,
762
+ finished,
763
+ utc_now() if finished else None,
764
+ execution_id,
765
+ self.fiscalizacao_id,
766
+ ),
767
+ )
768
+
769
+ def get_execution(self, execution_id: str) -> dict[str, Any] | None:
770
+ rows = self._query(
771
+ "SELECT * FROM execution WHERE id = ? AND fiscalizacao_id = ?",
772
+ (execution_id, self.fiscalizacao_id),
773
+ )
774
+ return dict(rows[0]) if rows else None
775
+
776
+ @staticmethod
777
+ def _merge_evaluation_documents(
778
+ current: Mapping[str, Any] | None,
779
+ incoming: Mapping[str, Any] | None,
780
+ ) -> dict[str, Any] | None:
781
+ if not current and not incoming:
782
+ return None
783
+ merged = dict(current or {})
784
+ merged.update({key: value for key, value in dict(incoming or {}).items() if key != "cases"})
785
+ cases: dict[tuple[str, str, str], dict[str, Any]] = {}
786
+ for document in (current or {}, incoming or {}):
787
+ for case in document.get("cases") or ():
788
+ if not isinstance(case, Mapping):
789
+ continue
790
+ value = dict(case)
791
+ key = (
792
+ str(value.get("section") or ""),
793
+ str(value.get("evaluation_type") or ""),
794
+ str(value.get("case_key") or ""),
795
+ )
796
+ cases[key] = value
797
+ merged["cases"] = list(cases.values())
798
+ merged["status"] = (
799
+ "completed"
800
+ if merged["cases"] and all(case.get("status") == "completed" for case in merged["cases"])
801
+ else "awaiting_input"
802
+ )
803
+ return merged
804
+
805
+ @staticmethod
806
+ def _read_result_json(raw: Any) -> dict[str, Any]:
807
+ if isinstance(raw, Mapping):
808
+ return dict(raw)
809
+ try:
810
+ value = json.loads(str(raw or "{}"))
811
+ except (TypeError, ValueError):
812
+ return {}
813
+ return dict(value) if isinstance(value, Mapping) else {}
814
+
815
+ def evaluation_document(self, execution_id: str) -> dict[str, Any] | None:
816
+ execution = self.get_execution(execution_id)
817
+ if execution is None:
818
+ return None
819
+ result = self._read_result_json(execution.get("result_json"))
820
+ summary = result.get("summary")
821
+ document = summary.get("evaluation") if isinstance(summary, Mapping) else None
822
+ return dict(document) if isinstance(document, Mapping) else None
823
+
824
+ @staticmethod
825
+ def _decode_json(raw: Any, default: Any) -> Any:
826
+ try:
827
+ return json.loads(str(raw))
828
+ except (TypeError, ValueError):
829
+ return default
830
+
831
+ @classmethod
832
+ def _ai_call_from_row(cls, row: Mapping[str, Any]) -> dict[str, Any]:
833
+ return {
834
+ "semantic_hash": str(row["semantic_hash"]),
835
+ "status": str(row["status"]),
836
+ "request": cls._decode_json(row["request_json"], {}),
837
+ "result": cls._decode_json(row["result_json"], {}) if row["result_json"] is not None else None,
838
+ "technical": cls._decode_json(row["technical_json"], {}),
839
+ "error": row["error"],
840
+ "attempts": int(row["attempts"]),
841
+ "created_at": str(row["created_at"]),
842
+ "updated_at": str(row["updated_at"]),
843
+ }
844
+
845
+ def claim_ai_call(
846
+ self,
847
+ semantic_hash: str,
848
+ request: Mapping[str, Any],
849
+ *,
850
+ retry_failed: bool = False,
851
+ retry_unknown: bool = False,
852
+ ) -> dict[str, Any]:
853
+ """Atomically reserves one provider call by semantic request identity.
854
+
855
+ ``failed`` (falha confirmada) só volta com ``retry_failed``. ``unknown`` (timeout ou
856
+ erro de transporte: o provider pode ter processado e cobrado) só volta com
857
+ ``retry_unknown``, que o usuário pede de forma explícita.
858
+ """
859
+ digest = str(semantic_hash or "").strip()
860
+ if len(digest) != 64:
861
+ raise InputValidationError("semantic_hash de chamada de IA inválido")
862
+ now = utc_now()
863
+ sanitized_request = redact_payload(dict(request))
864
+ with self._lock:
865
+ self.connection.execute("BEGIN IMMEDIATE")
866
+ try:
867
+ row = self.connection.execute(
868
+ "SELECT * FROM evaluation_cache WHERE fiscalizacao_id=? AND semantic_hash=?",
869
+ (self.fiscalizacao_id, digest),
870
+ ).fetchone()
871
+ if row is not None:
872
+ payload = self._ai_call_from_row(row)
873
+ if (payload["status"] == "failed" and retry_failed) or (
874
+ payload["status"] == "unknown" and retry_unknown
875
+ ):
876
+ self.connection.execute(
877
+ "UPDATE evaluation_cache SET status='running', request_json=?, result_json=NULL, "
878
+ "technical_json='{}', error=NULL, attempts=attempts+1, updated_at=? "
879
+ "WHERE fiscalizacao_id=? AND semantic_hash=?",
880
+ (canonical_json(sanitized_request), now, self.fiscalizacao_id, digest),
881
+ )
882
+ row = self.connection.execute(
883
+ "SELECT * FROM evaluation_cache WHERE fiscalizacao_id=? AND semantic_hash=?",
884
+ (self.fiscalizacao_id, digest),
885
+ ).fetchone()
886
+ assert row is not None
887
+ self.connection.execute("COMMIT")
888
+ return {**self._ai_call_from_row(row), "claimed": True, "retried": True}
889
+ self.connection.execute("COMMIT")
890
+ return {**payload, "claimed": False}
891
+ self.connection.execute(
892
+ "INSERT INTO evaluation_cache(fiscalizacao_id, semantic_hash, status, request_json, "
893
+ "result_json, technical_json, error, attempts, created_at, updated_at) "
894
+ "VALUES(?, ?, 'running', ?, NULL, '{}', NULL, 1, ?, ?)",
895
+ (self.fiscalizacao_id, digest, canonical_json(sanitized_request), now, now),
896
+ )
897
+ row = self.connection.execute(
898
+ "SELECT * FROM evaluation_cache WHERE fiscalizacao_id=? AND semantic_hash=?",
899
+ (self.fiscalizacao_id, digest),
900
+ ).fetchone()
901
+ assert row is not None
902
+ self.connection.execute("COMMIT")
903
+ return {**self._ai_call_from_row(row), "claimed": True, "retried": False}
904
+ except Exception:
905
+ if self.connection.in_transaction:
906
+ self.connection.execute("ROLLBACK")
907
+ raise
908
+
909
+ def finish_ai_call(
910
+ self,
911
+ semantic_hash: str,
912
+ *,
913
+ status: str,
914
+ result: Mapping[str, Any] | None = None,
915
+ technical: Mapping[str, Any] | None = None,
916
+ error: str | None = None,
917
+ ) -> None:
918
+ """Stores a provider response; completed responses stay immutable."""
919
+ digest = str(semantic_hash)
920
+ resolved_status = str(status)
921
+ if resolved_status not in {"completed", "failed", "unknown"}:
922
+ raise InputValidationError("estado final de chamada de IA inválido")
923
+ now = utc_now()
924
+ with self._lock:
925
+ self.connection.execute("BEGIN IMMEDIATE")
926
+ try:
927
+ row = self.connection.execute(
928
+ "SELECT status FROM evaluation_cache WHERE fiscalizacao_id=? AND semantic_hash=?",
929
+ (self.fiscalizacao_id, digest),
930
+ ).fetchone()
931
+ if row is None:
932
+ raise InputValidationError("claim de chamada de IA não encontrado")
933
+ if str(row["status"]) == "completed":
934
+ self.connection.execute("COMMIT")
935
+ return
936
+ result_json = canonical_json(redact_payload(dict(result or {}))) if result is not None else None
937
+ self.connection.execute(
938
+ "UPDATE evaluation_cache SET status=?, result_json=?, technical_json=?, error=?, updated_at=? "
939
+ "WHERE fiscalizacao_id=? AND semantic_hash=?",
940
+ (
941
+ resolved_status,
942
+ result_json,
943
+ canonical_json(redact_payload(dict(technical or {}))),
944
+ redact_error(error) if error else None,
945
+ now,
946
+ self.fiscalizacao_id,
947
+ digest,
948
+ ),
949
+ )
950
+ self.connection.execute("COMMIT")
951
+ except Exception:
952
+ if self.connection.in_transaction:
953
+ self.connection.execute("ROLLBACK")
954
+ raise
955
+
956
+ def evaluation_ai_call(self, semantic_hash: str) -> dict[str, Any] | None:
957
+ rows = self._query(
958
+ "SELECT * FROM evaluation_cache WHERE fiscalizacao_id=? AND semantic_hash=?",
959
+ (self.fiscalizacao_id, str(semantic_hash)),
960
+ )
961
+ return self._ai_call_from_row(rows[0]) if rows else None
962
+
963
+ def evaluation_ai_calls(self) -> list[dict[str, Any]]:
964
+ rows = self._query(
965
+ "SELECT * FROM evaluation_cache WHERE fiscalizacao_id=? ORDER BY created_at, semantic_hash",
966
+ (self.fiscalizacao_id,),
967
+ )
968
+ return [self._ai_call_from_row(row) for row in rows]
969
+
970
+ def merge_evaluation_document(
971
+ self, execution_id: str, evaluation: Mapping[str, Any]
972
+ ) -> None:
973
+ """Persists evaluation cases inside their owning execution result."""
974
+ with self._lock:
975
+ self.connection.execute("BEGIN IMMEDIATE")
976
+ try:
977
+ row = self.connection.execute(
978
+ "SELECT result_json FROM execution WHERE id=? AND fiscalizacao_id=?",
979
+ (execution_id, self.fiscalizacao_id),
980
+ ).fetchone()
981
+ if row is None:
982
+ self.connection.execute("COMMIT")
983
+ return
984
+ result = self._read_result_json(row["result_json"])
985
+ summary = dict(result.get("summary") or {})
986
+ current = summary.get("evaluation")
987
+ summary["evaluation"] = self._merge_evaluation_documents(
988
+ current if isinstance(current, Mapping) else None, evaluation
989
+ )
990
+ result["summary"] = summary
991
+ self.connection.execute(
992
+ "UPDATE execution SET result_json=? WHERE id=? AND fiscalizacao_id=?",
993
+ (canonical_json(result), execution_id, self.fiscalizacao_id),
994
+ )
995
+ self.connection.execute("COMMIT")
996
+ except Exception:
997
+ if self.connection.in_transaction:
998
+ self.connection.execute("ROLLBACK")
999
+ raise
1000
+
1001
+ def merge_evaluation_into_result(
1002
+ self, execution_id: str, result: Mapping[str, Any]
1003
+ ) -> dict[str, Any]:
1004
+ """Carries sub-operation evaluation cases into the final execution result."""
1005
+ merged = dict(result)
1006
+ summary = dict(merged.get("summary") or {})
1007
+ incoming = summary.get("evaluation")
1008
+ current = self.evaluation_document(execution_id)
1009
+ document = self._merge_evaluation_documents(
1010
+ current, incoming if isinstance(incoming, Mapping) else None
1011
+ )
1012
+ if document is not None:
1013
+ summary["evaluation"] = document
1014
+ merged["summary"] = summary
1015
+ return merged
1016
+
1017
+ def record_evaluation_review(
1018
+ self,
1019
+ execution_id: str,
1020
+ *,
1021
+ case_key: str,
1022
+ item_code: str,
1023
+ semantic_identity: str,
1024
+ review_identity: str,
1025
+ decision: Mapping[str, Any],
1026
+ ) -> bool:
1027
+ """Updates one reviewable item in the execution result, idempotently."""
1028
+ now = utc_now()
1029
+ with self._lock:
1030
+ self.connection.execute("BEGIN IMMEDIATE")
1031
+ try:
1032
+ row = self.connection.execute(
1033
+ "SELECT result_json FROM execution WHERE id=? AND fiscalizacao_id=?",
1034
+ (execution_id, self.fiscalizacao_id),
1035
+ ).fetchone()
1036
+ if row is None:
1037
+ raise InputValidationError(f"execução de avaliação não encontrada: {execution_id}")
1038
+ result = self._read_result_json(row["result_json"])
1039
+ summary = dict(result.get("summary") or {})
1040
+ evaluation = summary.get("evaluation")
1041
+ if not isinstance(evaluation, Mapping):
1042
+ raise InputValidationError("execução não contém resultado estruturado de avaliação")
1043
+ updated = False
1044
+ previous: Mapping[str, Any] | None = None
1045
+ for case in evaluation.get("cases") or ():
1046
+ if str(case.get("case_key") or "") != case_key:
1047
+ continue
1048
+ for item in case.get("items") or ():
1049
+ if str(item.get("item_code") or "") != item_code:
1050
+ continue
1051
+ if (
1052
+ str(item.get("semantic_identity") or "") != semantic_identity
1053
+ or str(item.get("review_identity") or "") != review_identity
1054
+ ):
1055
+ continue
1056
+ previous = item.get("human_review")
1057
+ normalized = {**dict(decision), "applied_at": now}
1058
+ if isinstance(previous, Mapping):
1059
+ prior_without_time = {key: value for key, value in previous.items() if key != "applied_at"}
1060
+ new_without_time = {key: value for key, value in normalized.items() if key != "applied_at"}
1061
+ if prior_without_time == new_without_time:
1062
+ self.connection.execute("COMMIT")
1063
+ return False
1064
+ item["human_review"] = normalized
1065
+ updated = True
1066
+ break
1067
+ if updated:
1068
+ break
1069
+ if not updated:
1070
+ raise InputValidationError("revisão desatualizada: caso, item ou identidade consolidada diverge")
1071
+ summary["evaluation"] = dict(evaluation)
1072
+ result["summary"] = summary
1073
+ self.connection.execute(
1074
+ "UPDATE execution SET result_json=? WHERE id=? AND fiscalizacao_id=?",
1075
+ (canonical_json(result), execution_id, self.fiscalizacao_id),
1076
+ )
1077
+ self.connection.execute(
1078
+ "INSERT INTO execution_event(execution_id, unit_id, event_type, status, occurred_at, payload_json) "
1079
+ "VALUES(?, NULL, 'evaluation_review_applied', NULL, ?, ?)",
1080
+ (execution_id, now, canonical_json({"case_key": case_key, "item_code": item_code, "review_identity": review_identity})),
1081
+ )
1082
+ self.connection.execute("COMMIT")
1083
+ return True
1084
+ except Exception:
1085
+ if self.connection.in_transaction:
1086
+ self.connection.execute("ROLLBACK")
1087
+ raise
1088
+
1089
+ def find_execution_by_input(
1090
+ self,
1091
+ operation_id: str,
1092
+ input_hash: str,
1093
+ *,
1094
+ include_unknown: bool = False,
1095
+ ) -> dict[str, Any] | None:
1096
+ reusable_statuses = REUSABLE_EXECUTION_STATUSES | ({UNKNOWN} if include_unknown else set())
1097
+ reuse_placeholders = ", ".join("?" for _ in sorted(reusable_statuses))
1098
+ reuse_query = (
1099
+ "SELECT * FROM execution "
1100
+ "WHERE fiscalizacao_id = ? AND operation_id = ? AND input_hash = ? "
1101
+ f"AND status IN ({reuse_placeholders}) " # nosec B608 - placeholders de conjunto interno estável; valores parametrizados
1102
+ "ORDER BY created_at DESC LIMIT 1"
1103
+ )
1104
+ rows = self._query(
1105
+ reuse_query,
1106
+ (
1107
+ self.fiscalizacao_id,
1108
+ operation_id,
1109
+ input_hash,
1110
+ *sorted(reusable_statuses),
1111
+ ),
1112
+ )
1113
+ return dict(rows[0]) if rows else None
1114
+
1115
+ def list_executions(self, limit: int = 30) -> list[dict[str, Any]]:
1116
+ rows = self._query(
1117
+ "SELECT * FROM execution WHERE fiscalizacao_id = ? "
1118
+ "ORDER BY created_at DESC LIMIT ?",
1119
+ (self.fiscalizacao_id, limit),
1120
+ )
1121
+
1122
+ return [dict(row) for row in rows]
1123
+
1124
+ def events(self, execution_id: str) -> list[dict[str, Any]]:
1125
+ rows = self._query(
1126
+ "SELECT * FROM execution_event WHERE execution_id = ? ORDER BY event_id",
1127
+ (execution_id,),
1128
+ )
1129
+
1130
+ return [dict(row) for row in rows]
1131
+
1132
+ # --- Produtos ---------------------------------------------------------
1133
+
1134
+ def record_products(
1135
+ self,
1136
+ execution_id: str,
1137
+ operation_id: str,
1138
+ publications: Sequence[Mapping[str, Any]],
1139
+ ) -> list[dict[str, Any]]:
1140
+ """Registra a proveniência de um lote em uma única transação.
1141
+
1142
+ A identidade observável (execução, operação, caminho e sha256) torna a
1143
+ retomada idempotente inclusive para workspaces legados.
1144
+ """
1145
+ recorded: list[dict[str, Any]] = []
1146
+ with self._lock:
1147
+ self.connection.execute("BEGIN IMMEDIATE")
1148
+ try:
1149
+ for publication in publications:
1150
+ path = str(publication["path"])
1151
+ digest = str(publication["sha256"])
1152
+ kind = str(publication["kind"])
1153
+ existing = self.connection.execute(
1154
+ "SELECT id FROM product "
1155
+ "WHERE execution_id=? AND operation_id=? AND path=? AND sha256=?",
1156
+ (execution_id, operation_id, path, digest),
1157
+ ).fetchone()
1158
+ product_id = str(existing["id"]) if existing else uuid.uuid4().hex
1159
+ if existing is None:
1160
+ self.connection.execute(
1161
+ "INSERT INTO product(id, execution_id, operation_id, kind, path, "
1162
+ "sha256, size_bytes, media_type, metadata_json, created_at) "
1163
+ "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1164
+ (
1165
+ product_id,
1166
+ execution_id,
1167
+ operation_id,
1168
+ kind,
1169
+ path,
1170
+ digest,
1171
+ int(publication.get("size_bytes") or 0),
1172
+ str(publication.get("media_type") or "application/octet-stream"),
1173
+ canonical_json(dict(publication.get("metadata") or {})),
1174
+ utc_now(),
1175
+ ),
1176
+ )
1177
+ recorded.append(
1178
+ {
1179
+ "id": product_id,
1180
+ "kind": kind,
1181
+ "path": path,
1182
+ "sha256": digest,
1183
+ "size_bytes": int(publication.get("size_bytes") or 0),
1184
+ "media_type": str(publication.get("media_type") or "application/octet-stream"),
1185
+ "metadata": dict(publication.get("metadata") or {}),
1186
+ }
1187
+ )
1188
+ self.connection.execute("COMMIT")
1189
+ except Exception:
1190
+ if self.connection.in_transaction:
1191
+ self.connection.execute("ROLLBACK")
1192
+ raise
1193
+ return recorded
1194
+
1195
+ def has_product(self, *, kind: str, sha256: str) -> bool:
1196
+ rows = self._query(
1197
+ "SELECT 1 FROM product WHERE operation_id IS NOT NULL AND kind=? AND sha256=? LIMIT 1",
1198
+ (str(kind), str(sha256)),
1199
+ )
1200
+ return bool(rows)
1201
+
1202
+ def has_catalog_approval(self, *, content_hash: str, reviewer: str, approved_at: str) -> bool:
1203
+ """Consulta a aprovação histórica, independente do índice de arquivos.
1204
+
1205
+ O evento de publicação e a conclusão da execução são gravados na mesma
1206
+ transação. Descartar um produto não remove esses eventos nem a decisão.
1207
+ """
1208
+ if not all((content_hash, reviewer, approved_at)):
1209
+ return False
1210
+ rows = self._query(
1211
+ "SELECT ev.payload_json FROM execution_event ev "
1212
+ "JOIN execution ex ON ex.id=ev.execution_id "
1213
+ "WHERE ex.fiscalizacao_id=? AND ex.status='completed' "
1214
+ "AND ev.event_type='product_published'",
1215
+ (self.fiscalizacao_id,),
1216
+ )
1217
+ for row in rows:
1218
+ published = json.loads(row["payload_json"])
1219
+ if published.get("kind") != "prompt-catalog-approved":
1220
+ continue
1221
+ metadata = published.get("metadata") or {}
1222
+ if (
1223
+ metadata.get("catalog_content_hash") == content_hash
1224
+ and metadata.get("reviewer") == reviewer
1225
+ and metadata.get("approved_at") == approved_at
1226
+ ):
1227
+ return True
1228
+ return False