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
@@ -0,0 +1,132 @@
1
+ """Conversões de anexos por ferramentas externas: LibreOffice e extração de RAR."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess # nosec B404 - binários resolvidos localmente, sem shell
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ from ..errors import InputValidationError
13
+
14
+ OFFICE_CONVERSIONS = frozenset({(".doc", "pdf"), (".pptx", "pdf"), (".ods", "xlsx")})
15
+ RAR_TIMEOUT_SECONDS = 180
16
+
17
+
18
+ def safe_member_name(name: str) -> str | None:
19
+ """Normaliza o caminho de um membro de arquivo compactado; ``None`` se inseguro."""
20
+ name = name.replace("\\", "/")
21
+ if name.startswith("/") or re.match(r"^[A-Za-z]:", name):
22
+ return None
23
+ parts = [part for part in name.split("/") if part not in {"", "."}]
24
+ if any(part == ".." for part in parts):
25
+ return None
26
+ return "/".join(parts) or None
27
+
28
+
29
+ def convert_office_bytes(content: bytes, *, suffix: str, target: str) -> bytes:
30
+ """Converte bytes de um documento Office com LibreOffice em diretório temporário."""
31
+ from .docx_pdf import _convert_with_libreoffice, _soffice_executable
32
+
33
+ suffix = suffix.casefold()
34
+ if (suffix, target) not in OFFICE_CONVERSIONS:
35
+ raise InputValidationError(f"conversão não suportada: {suffix} -> {target}")
36
+ if _soffice_executable() is None:
37
+ raise InputValidationError(f"LibreOffice (soffice) ausente para converter {suffix}")
38
+ with tempfile.TemporaryDirectory(prefix="argos-office-") as temporary:
39
+ root = Path(temporary)
40
+ source = root / f"documento{suffix}"
41
+ source.write_bytes(content)
42
+ destination = root / f"documento.{target}"
43
+ _convert_with_libreoffice(source, destination, target=target)
44
+ if not destination.is_file() or destination.stat().st_size == 0:
45
+ raise InputValidationError(f"LibreOffice não gerou {target} para {suffix}")
46
+ return destination.read_bytes()
47
+
48
+
49
+ def _normalize_permissions(root: Path) -> None:
50
+ """Os atributos do arquivo compactado podem negar leitura; o destino é nosso e temporário."""
51
+ for current, directories, names in os.walk(root):
52
+ os.chmod(current, 0o700)
53
+ for name in directories:
54
+ candidate = Path(current) / name
55
+ if not candidate.is_symlink():
56
+ os.chmod(candidate, 0o700)
57
+ for name in names:
58
+ candidate = Path(current) / name
59
+ if not candidate.is_symlink():
60
+ os.chmod(candidate, 0o600)
61
+
62
+
63
+ def _collect(root: Path) -> list[tuple[str, bytes]]:
64
+ _normalize_permissions(root)
65
+ base = root.resolve()
66
+ members: list[tuple[str, bytes]] = []
67
+ for path in sorted(root.rglob("*")):
68
+ if not path.is_file():
69
+ continue
70
+ resolved = path.resolve()
71
+ if not resolved.is_relative_to(base):
72
+ raise InputValidationError("RAR contém caminho fora do destino de extração")
73
+ members.append((resolved.relative_to(base).as_posix(), resolved.read_bytes()))
74
+ return members
75
+
76
+
77
+ def _extract_with_rarfile(archive: Path, output: Path) -> str | None:
78
+ """Extrai com ``rarfile``; devolve o motivo da falha ou ``None`` em caso de sucesso."""
79
+ try:
80
+ import rarfile
81
+ except ImportError:
82
+ return "rarfile ausente"
83
+ try:
84
+ rarfile.tool_setup()
85
+ with rarfile.RarFile(str(archive)) as bundle:
86
+ for info in bundle.infolist():
87
+ if safe_member_name(info.filename) is None:
88
+ raise InputValidationError(f"caminho inseguro no RAR: {info.filename}")
89
+ bundle.extractall(str(output))
90
+ except InputValidationError:
91
+ raise
92
+ except Exception as exc: # noqa: BLE001 - qualquer falha da ferramenta aciona o fallback
93
+ return f"{type(exc).__name__}: {exc}"
94
+ return None
95
+
96
+
97
+ def _extract_with_7z(archive: Path, output: Path) -> str | None:
98
+ executable = shutil.which("7z") or shutil.which("7za") or shutil.which("7zz")
99
+ if executable is None:
100
+ return "7z ausente"
101
+ try:
102
+ completed = subprocess.run( # nosec B603 - lista de argumentos, binário resolvido, sem shell
103
+ [executable, "x", str(archive), f"-o{output}", "-y"],
104
+ check=False,
105
+ capture_output=True,
106
+ text=True,
107
+ timeout=RAR_TIMEOUT_SECONDS,
108
+ )
109
+ except (subprocess.TimeoutExpired, OSError) as exc:
110
+ return f"{type(exc).__name__}: {exc}"
111
+ if completed.returncode != 0:
112
+ return (completed.stderr or completed.stdout or f"código {completed.returncode}").strip()
113
+ return None
114
+
115
+
116
+ def extract_rar_members(content: bytes) -> list[tuple[str, bytes]]:
117
+ """Extrai um RAR em memória e devolve ``(caminho relativo POSIX, bytes)`` ordenados."""
118
+ with tempfile.TemporaryDirectory(prefix="argos-rar-") as temporary:
119
+ root = Path(temporary)
120
+ archive = root / "pacote.rar"
121
+ archive.write_bytes(content)
122
+ output = root / "saida"
123
+ output.mkdir()
124
+ first = _extract_with_rarfile(archive, output)
125
+ if first is None:
126
+ return _collect(output)
127
+ second = _extract_with_7z(archive, output)
128
+ if second is None:
129
+ return _collect(output)
130
+ if first == "rarfile ausente" and second == "7z ausente":
131
+ raise InputValidationError("RAR sem ferramenta de extração (unrar ou 7z)")
132
+ raise InputValidationError(f"RAR não pôde ser extraído (rarfile: {first}; 7z: {second})")
@@ -0,0 +1,31 @@
1
+ """O que um modelo aceita: entrega de anexos, limite de tokens e níveis de raciocínio.
2
+
3
+ Cada adapter declara isso em ``capabilities(modelo)``; o resto do Argos consulta o
4
+ ``ModelCapabilities`` em vez de conhecer nomes de provider. Quem não declara herda o
5
+ padrão permissivo (PDF como texto, imagens aceitas, sem limite, sem contagem nativa).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Delivery:
15
+ """Como os anexos chegam ao modelo; é tudo que o preparo de anexos precisa saber."""
16
+
17
+ pdf: str = "text" # "native": arquivo inline ou File API; "text": texto por página (com OCR) e imagens
18
+ images: bool = True # False: o modelo só lê texto; imagens avulsas bloqueiam e as embutidas viram lacuna
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ModelCapabilities:
23
+ pdf: str = "text"
24
+ images: bool = True
25
+ token_limit: int = 0 # 0 = sem limite padrão; `--limite-tokens provider=N` sobrescreve
26
+ counts_tokens: bool = False # o provider conta (e recusa) o payload; senão o Argos estima localmente
27
+ reasoning_levels: tuple[str, ...] | None = None # None = o provider não informa; ele mesmo recusa
28
+
29
+ @property
30
+ def delivery(self) -> Delivery:
31
+ return Delivery(self.pdf, self.images)
@@ -0,0 +1,72 @@
1
+ """Renderer opcional de gráficos analíticos.
2
+
3
+ O import de matplotlib é tardio: o núcleo de analytics continua puro e as
4
+ tabelas/JSON funcionam sem o extra `charts`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import os
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from ..errors import InputValidationError
16
+
17
+
18
+ def _pyplot():
19
+ os.environ.setdefault("MPLCONFIGDIR", str(Path(tempfile.gettempdir()) / "argos-matplotlib"))
20
+ try:
21
+ import matplotlib
22
+
23
+ matplotlib.use("Agg")
24
+ import matplotlib.pyplot as plt
25
+ except ImportError as exc: # pragma: no cover - depende do extra
26
+ raise InputValidationError("gráficos analíticos requerem matplotlib; instale argos-cli[charts]") from exc
27
+ return plt
28
+
29
+
30
+ def render_chart(spec: Any, data: Any) -> bytes:
31
+ plt = _pyplot()
32
+ labels = list(data.labels)
33
+ series = list(data.series)
34
+ figure, axis = plt.subplots(figsize=(max(spec.width, 320) / 100, max(spec.height, 240) / 100), dpi=100)
35
+ try:
36
+ if spec.type == "donut":
37
+ values = list(series[0].values) if series else [1]
38
+ axis.pie(values or [1], labels=labels, autopct="%1.0f%%", wedgeprops={"width": 0.4})
39
+ elif spec.type == "heatmap":
40
+ rows = [list(item.values) for item in series] if series else [[0] * max(1, len(labels))]
41
+ image = axis.imshow(rows, aspect="auto")
42
+ axis.set_xticks(range(len(labels)))
43
+ axis.set_xticklabels(labels, rotation=45, ha="right")
44
+ axis.set_yticks(range(len(series)))
45
+ axis.set_yticklabels([item.name for item in series])
46
+ figure.colorbar(image, ax=axis)
47
+ elif spec.type in {"stacked_bar", "grouped_bar"}:
48
+ positions = list(range(len(labels)))
49
+ if spec.type == "stacked_bar":
50
+ bottom = [0.0] * len(labels)
51
+ for item in series:
52
+ axis.bar(positions, list(item.values), bottom=bottom, label=item.name)
53
+ bottom = [left + value for left, value in zip(bottom, item.values)]
54
+ else:
55
+ width = 0.8 / max(1, len(series))
56
+ for index, item in enumerate(series):
57
+ axis.bar([position + index * width for position in positions], list(item.values), width=width, label=item.name)
58
+ axis.set_xticks(positions)
59
+ axis.set_xticklabels(labels, rotation=45, ha="right")
60
+ if series:
61
+ axis.legend(fontsize="small")
62
+ else:
63
+ values = list(series[0].values) if series else []
64
+ axis.bar(labels, values)
65
+ axis.tick_params(axis="x", rotation=45)
66
+ axis.set_title(spec.title)
67
+ figure.tight_layout()
68
+ buffer = io.BytesIO()
69
+ figure.savefig(buffer, format="png", metadata={"Software": "Argos CLI"})
70
+ return buffer.getvalue()
71
+ finally:
72
+ plt.close(figure)