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/products.py ADDED
@@ -0,0 +1,220 @@
1
+ """Publicação atômica e enxuta de Produtos."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import tempfile
8
+ import threading
9
+ import uuid
10
+ from contextlib import contextmanager
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any, BinaryIO, Callable, Iterable, Iterator
14
+
15
+ from .core import ARGOS_VERSION, ArgosError, InputValidationError, ProductDraft, WorkspaceStore, canonical_json, sha256_bytes, sha256_file
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class _MaterializedProduct:
20
+ publication: dict[str, Any]
21
+ created: bool
22
+
23
+
24
+ class _DivergentTarget(Exception):
25
+ """O caminho já está ocupado por conteúdo divergente."""
26
+
27
+
28
+ class ProductLifecycle:
29
+ """Ciclo de publicação atômica de Produtos sem journals burocráticos."""
30
+
31
+ _LOCK = threading.RLock()
32
+
33
+ def __init__(self, store: WorkspaceStore) -> None:
34
+ self._store = store
35
+
36
+ def publish(
37
+ self,
38
+ execution_id: str,
39
+ operation_id: str,
40
+ drafts: Iterable[ProductDraft],
41
+ *,
42
+ validate_snapshot: Callable[[], None] | None = None,
43
+ ) -> list[dict[str, Any]]:
44
+ prepared = [
45
+ (draft, self._product_bytes(draft))
46
+ for draft in drafts
47
+ if draft.path is not None
48
+ ]
49
+ materialized: list[_MaterializedProduct] = []
50
+ with self._LOCK, self._target_lock(Path(tempfile.gettempdir()) / "argos-publication"):
51
+ try:
52
+ if validate_snapshot is not None:
53
+ validate_snapshot()
54
+ for draft, content in prepared:
55
+ materialized.append(self._materialize(draft, content))
56
+ if validate_snapshot is not None:
57
+ validate_snapshot()
58
+ return self._store.record_products(
59
+ execution_id,
60
+ operation_id,
61
+ [item.publication for item in materialized],
62
+ )
63
+ except Exception:
64
+ self._compensate(materialized)
65
+ raise
66
+
67
+ @staticmethod
68
+ @contextmanager
69
+ def _target_lock(target: Path) -> Iterator[None]:
70
+ owner = str(getattr(os, "getuid", lambda: "user")())
71
+ lock_root = Path(tempfile.gettempdir()) / f"argos-product-locks-{owner}"
72
+ lock_root.mkdir(mode=0o700, parents=True, exist_ok=True)
73
+ lock_path = lock_root / f"{sha256_bytes(str(target).encode('utf-8'))}.lock"
74
+ with lock_path.open("a+b") as stream:
75
+ ProductLifecycle._acquire_file_lock(stream)
76
+ try:
77
+ yield
78
+ finally:
79
+ ProductLifecycle._release_file_lock(stream)
80
+
81
+ @staticmethod
82
+ def _acquire_file_lock(stream: BinaryIO) -> None:
83
+ try:
84
+ import fcntl
85
+ except ImportError: # pragma: no cover - exercitado em Windows
86
+ import msvcrt
87
+
88
+ stream.seek(0, os.SEEK_END)
89
+ if stream.tell() == 0:
90
+ stream.write(b"\0")
91
+ stream.flush()
92
+ stream.seek(0)
93
+ msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
94
+ return
95
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
96
+
97
+ @staticmethod
98
+ def _release_file_lock(stream: BinaryIO) -> None:
99
+ try:
100
+ import fcntl
101
+ except ImportError: # pragma: no cover - exercitado em Windows
102
+ import msvcrt
103
+
104
+ stream.seek(0)
105
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
106
+ return
107
+ fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
108
+
109
+ def _materialize(self, draft: ProductDraft, content: bytes | Path) -> _MaterializedProduct:
110
+ assert draft.path is not None
111
+ digest = sha256_file(content) if isinstance(content, Path) else sha256_bytes(content)
112
+ requested = draft.path.expanduser().resolve()
113
+ if draft.metadata.get("must_be_new") and (requested.exists() or requested.is_symlink()):
114
+ raise InputValidationError(f"destino deve ser novo: {requested}")
115
+ try:
116
+ target, created = self._claim(requested, content, digest)
117
+ except _DivergentTarget:
118
+ if draft.metadata.get("must_be_new"):
119
+ raise InputValidationError(f"destino ocupado durante publicação: {requested}") from None
120
+ target = requested.with_name(
121
+ f"{requested.stem}.argos-{digest[:12]}{requested.suffix}"
122
+ )
123
+ try:
124
+ target, created = self._claim(target, content, digest)
125
+ except _DivergentTarget as exc:
126
+ raise ArgosError(
127
+ f"produto divergente já ocupa o caminho derivado: {target}"
128
+ ) from exc
129
+
130
+ metadata = dict(draft.metadata)
131
+ if metadata.get("must_be_new") and not created:
132
+ raise InputValidationError(f"destino ocupado durante publicação: {target}")
133
+ metadata.setdefault("argos_version", ARGOS_VERSION)
134
+ if target != requested:
135
+ metadata["requested_path"] = str(requested)
136
+ metadata["divergent_path"] = True
137
+ if not created:
138
+ metadata["reused_existing"] = True
139
+ return _MaterializedProduct(
140
+ publication={
141
+ "kind": draft.kind,
142
+ "path": str(target),
143
+ "sha256": digest,
144
+ "size_bytes": content.stat().st_size if isinstance(content, Path) else len(content),
145
+ "media_type": draft.media_type,
146
+ "metadata": metadata,
147
+ },
148
+ created=created,
149
+ )
150
+
151
+ @staticmethod
152
+ def _claim(target: Path, content: bytes | Path, digest: str) -> tuple[Path, bool]:
153
+ target.parent.mkdir(parents=True, exist_ok=True)
154
+ if target.exists():
155
+ ProductLifecycle._assert_file(target)
156
+ if sha256_file(target) == digest:
157
+ return target, False
158
+ raise _DivergentTarget
159
+
160
+ staging = target.with_name(f".argos-{uuid.uuid4().hex}.tmp")
161
+ try:
162
+ with staging.open("xb") as stream:
163
+ if isinstance(content, Path):
164
+ with content.open("rb") as source:
165
+ shutil.copyfileobj(source, stream, length=1024 * 1024)
166
+ else:
167
+ stream.write(content)
168
+ stream.flush()
169
+ os.fsync(stream.fileno())
170
+ if isinstance(content, Path) and sha256_file(staging) != digest:
171
+ raise InputValidationError("arquivo de staging mudou durante a publicação")
172
+ try:
173
+ os.link(staging, target)
174
+ return target, True
175
+ except FileExistsError:
176
+ ProductLifecycle._assert_file(target)
177
+ if sha256_file(target) == digest:
178
+ return target, False
179
+ raise _DivergentTarget from None
180
+ finally:
181
+ if staging.exists():
182
+ staging.unlink()
183
+
184
+ @staticmethod
185
+ def _assert_file(path: Path) -> None:
186
+ if not path.is_file():
187
+ raise InputValidationError(f"caminho de produto não é arquivo: {path}")
188
+
189
+ def _compensate(self, materialized: Iterable[_MaterializedProduct]) -> None:
190
+ for item in reversed(tuple(materialized)):
191
+ if not item.created:
192
+ continue
193
+ path = Path(item.publication["path"])
194
+ try:
195
+ if isinstance(self._store, WorkspaceStore):
196
+ try:
197
+ committed = self._store._execute(
198
+ "SELECT 1 FROM product WHERE path=? AND sha256=? LIMIT 1",
199
+ (str(path), item.publication["sha256"]),
200
+ ).fetchone()
201
+ except Exception: # noqa: BLE001
202
+ continue
203
+ if committed:
204
+ continue
205
+ if path.is_file() and sha256_file(path) == item.publication["sha256"]:
206
+ path.unlink()
207
+ except OSError:
208
+ continue
209
+
210
+ @staticmethod
211
+ def _product_bytes(draft: ProductDraft) -> bytes | Path:
212
+ if isinstance(draft.content, Path):
213
+ if not draft.content.is_file():
214
+ raise InputValidationError(f"arquivo de staging ausente: {draft.content}")
215
+ return draft.content
216
+ if isinstance(draft.content, bytes):
217
+ return draft.content
218
+ if isinstance(draft.content, str):
219
+ return draft.content.encode("utf-8")
220
+ return (canonical_json(draft.content) + "\n").encode("utf-8")
argos/progress.py ADDED
@@ -0,0 +1,221 @@
1
+ """Acompanhamento de progresso de operações longas, sempre em stderr.
2
+
3
+ O stdout fica reservado ao resultado (``--json``). Em terminal interativo a barra
4
+ se atualiza na mesma linha; em logs e pipes, linhas curtas saem em intervalos.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import shutil
10
+ import sys
11
+ import threading
12
+ import time
13
+ from typing import Any, Callable, Protocol, TextIO
14
+
15
+ STATUSES = ("ok", "reused", "failed", "blocked", "skipped")
16
+ _LABELS = {"ok": "ok", "reused": "reuso", "failed": "falhas", "blocked": "bloqueados", "skipped": "pulados"}
17
+ MAX_NOTES = 30
18
+
19
+
20
+ class ProgressSink(Protocol):
21
+ def start(self, phase: str, total: int) -> None: ...
22
+
23
+ def advance(self, label: str = "", status: str = "ok") -> None: ...
24
+
25
+ def note(self, message: str) -> None: ...
26
+
27
+ def finish(self) -> None: ...
28
+
29
+
30
+ class NullProgress:
31
+ """Sink que não faz nada; padrão quando ninguém acompanha."""
32
+
33
+ def start(self, phase: str, total: int) -> None:
34
+ pass
35
+
36
+ def advance(self, label: str = "", status: str = "ok") -> None:
37
+ pass
38
+
39
+ def note(self, message: str) -> None:
40
+ pass
41
+
42
+ def finish(self) -> None:
43
+ pass
44
+
45
+
46
+ def format_duration(seconds: float) -> str:
47
+ seconds = max(0, int(round(seconds)))
48
+ hours, rest = divmod(seconds, 3600)
49
+ minutes, secs = divmod(rest, 60)
50
+ return f"{hours:d}:{minutes:02d}:{secs:02d}" if hours else f"{minutes:02d}:{secs:02d}"
51
+
52
+
53
+ def format_line(
54
+ phase: str,
55
+ done: int,
56
+ total: int,
57
+ counts: dict[str, int],
58
+ elapsed: float,
59
+ label: str = "",
60
+ *,
61
+ width: int | None = None,
62
+ bar_width: int = 20,
63
+ ) -> str:
64
+ """Linha de progresso; função pura para facilitar o teste."""
65
+ fraction = 1.0 if total <= 0 else min(1.0, done / total)
66
+ filled = int(round(fraction * bar_width))
67
+ bar = "█" * filled + "░" * (bar_width - filled)
68
+ parts = [f"{phase} [{bar}] {done}/{total} {int(fraction * 100):d}%"]
69
+ parts.extend(f"{_LABELS[key]} {counts[key]}" for key in ("reused", "failed", "blocked") if counts.get(key))
70
+ parts.append(f"decorrido {format_duration(elapsed)}")
71
+ if 0 < done < total and elapsed > 0:
72
+ parts.append(f"ETA {format_duration(elapsed / done * (total - done))}")
73
+ if label:
74
+ parts.append(label)
75
+ line = " · ".join(parts)
76
+ if width is not None and len(line) > width:
77
+ line = line[: max(0, width - 1)] + "…"
78
+ return line
79
+
80
+
81
+ class ConsoleProgress:
82
+ """Barra de progresso em stderr, segura para uso com várias threads."""
83
+
84
+ def __init__(
85
+ self,
86
+ stream: TextIO | None = None,
87
+ *,
88
+ interactive: bool | None = None,
89
+ clock: Callable[[], float] = time.monotonic,
90
+ interval: float | None = None,
91
+ width: Callable[[], int] | None = None,
92
+ heartbeat: float | None = None,
93
+ ) -> None:
94
+ self._stream = stream if stream is not None else sys.stderr
95
+ isatty = getattr(self._stream, "isatty", lambda: False)
96
+ self.interactive = bool(isatty()) if interactive is None else interactive
97
+ self._clock = clock
98
+ self._interval = interval if interval is not None else (0.2 if self.interactive else 15.0)
99
+ self._width = width or (lambda: shutil.get_terminal_size((100, 24)).columns)
100
+ self._lock = threading.Lock()
101
+ self._phase: str | None = None
102
+ self._total = 0
103
+ self._done = 0
104
+ self._counts: dict[str, int] = {}
105
+ self._started = 0.0
106
+ self._last_render = 0.0
107
+ self._last_label = ""
108
+ self._notes = 0
109
+ self._dirty = False
110
+ # Em terminal, redesenha periodicamente para mostrar que uma etapa longa (OCR) segue viva.
111
+ self._heartbeat = (1.0 if self.interactive else None) if heartbeat is None else heartbeat
112
+ self._stop = threading.Event()
113
+ self._thread: threading.Thread | None = None
114
+
115
+ def _tick(self, stop: threading.Event) -> None:
116
+ while not stop.wait(self._heartbeat or 1.0):
117
+ with self._lock:
118
+ if self._phase is None:
119
+ return
120
+ self._render(force=True)
121
+
122
+ def _write(self, text: str) -> None:
123
+ try:
124
+ self._stream.write(text)
125
+ self._stream.flush()
126
+ except (OSError, ValueError): # stream fechado: o progresso nunca derruba a operação
127
+ pass
128
+
129
+ def _line(self) -> str:
130
+ return format_line(
131
+ self._phase or "",
132
+ self._done,
133
+ self._total,
134
+ self._counts,
135
+ self._clock() - self._started,
136
+ self._last_label,
137
+ width=(self._width() - 1) if self.interactive else None,
138
+ )
139
+
140
+ def _render(self, *, force: bool = False) -> None:
141
+ now = self._clock()
142
+ if not force and now - self._last_render < self._interval:
143
+ self._dirty = True
144
+ return
145
+ self._last_render = now
146
+ self._dirty = False
147
+ if self.interactive:
148
+ self._write("\r\033[K" + self._line())
149
+ else:
150
+ self._write(self._line() + "\n")
151
+
152
+ def start(self, phase: str, total: int) -> None:
153
+ with self._lock:
154
+ if self._phase is not None:
155
+ self._finish_locked()
156
+ self._phase, self._total, self._done = phase, max(0, int(total)), 0
157
+ self._counts = {key: 0 for key in STATUSES}
158
+ self._started = self._clock()
159
+ self._start_ticker()
160
+ self._last_render = 0.0
161
+ self._last_label = ""
162
+ self._notes = 0
163
+ if not self.interactive:
164
+ self._write(f"{phase}: {self._total} itens\n")
165
+ self._last_render = self._started
166
+ else:
167
+ self._render(force=True)
168
+
169
+ def advance(self, label: str = "", status: str = "ok") -> None:
170
+ with self._lock:
171
+ if self._phase is None:
172
+ return
173
+ self._done += 1
174
+ self._counts[status if status in STATUSES else "ok"] += 1
175
+ if label:
176
+ self._last_label = label
177
+ self._render(force=self._done >= self._total and self.interactive)
178
+
179
+ def note(self, message: str) -> None:
180
+ with self._lock:
181
+ if self._notes >= MAX_NOTES:
182
+ if self._notes == MAX_NOTES:
183
+ self._notes += 1
184
+ self._emit_note("(demais avisos omitidos; consulte o resultado da execução)")
185
+ return
186
+ self._notes += 1
187
+ self._emit_note(message)
188
+
189
+ def _emit_note(self, message: str) -> None:
190
+ if self.interactive and self._phase is not None:
191
+ self._write("\r\033[K" + message + "\n")
192
+ self._render(force=True)
193
+ else:
194
+ self._write(message + "\n")
195
+
196
+ def _start_ticker(self) -> None:
197
+ if not self._heartbeat or not self.interactive:
198
+ return
199
+ self._stop.set()
200
+ self._stop = threading.Event()
201
+ self._thread = threading.Thread(target=self._tick, args=(self._stop,), daemon=True)
202
+ self._thread.start()
203
+
204
+ def _finish_locked(self) -> None:
205
+ if self._phase is None:
206
+ return
207
+ self._stop.set()
208
+ if self.interactive:
209
+ self._write("\r\033[K" + self._line() + "\n")
210
+ else:
211
+ self._write(self._line() + "\n")
212
+ self._phase = None
213
+
214
+ def finish(self) -> None:
215
+ with self._lock:
216
+ self._finish_locked()
217
+
218
+
219
+ def make_progress(enabled: bool = True, stream: Any = None) -> ProgressSink:
220
+ """Sink de console quando habilitado; senão o sink nulo."""
221
+ return ConsoleProgress(stream) if enabled else NullProgress()