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,201 @@
1
+ """Preparo de um pedido ao modelo: anexos, ``AIRequest``, estimativa, identidade semântica e bloqueio.
2
+
3
+ O preflight (``preview_request``) e a execução (``_evaluate``) consomem o mesmo
4
+ ``PreparedRequest``, então o que o preflight promete é o que a execução decide.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import dataclass
11
+ from typing import Any, Mapping
12
+
13
+ from ..adapters.ai import (
14
+ AIRequest,
15
+ AIServiceRegistry,
16
+ AttachmentPolicy,
17
+ AttachmentProcessingService,
18
+ estimate_request_tokens,
19
+ )
20
+ from ..adapters.capabilities import ModelCapabilities
21
+ from ..core import InputValidationError, canonical_json, sha256_bytes
22
+
23
+ ATTACHMENT_BLOCKS = frozenset({"attachment_not_prepared", "attachment_without_content"})
24
+ BLOCKING_REASONS = ATTACHMENT_BLOCKS | {"payload_limit"}
25
+
26
+
27
+ class RequestBlockedError(InputValidationError):
28
+ """Requisição recusada antes do envio; nenhum provider foi chamado."""
29
+
30
+ def __init__(self, message: str, *, reason: str, details: Mapping[str, Any]) -> None:
31
+ super().__init__(message)
32
+ self.reason = reason
33
+ self.details = dict(details)
34
+
35
+
36
+ def request_policy(request: Any) -> AttachmentPolicy:
37
+ return request.attachment_policy or AttachmentPolicy()
38
+
39
+
40
+ def request_material(ai_request: AIRequest, profile_version: str, attachment_report: Any) -> dict[str, Any]:
41
+ """Identidade semântica do pedido; ``lacunas_tecnicas`` (nomes de arquivo) fica de fora."""
42
+ context = {key: value for key, value in dict(ai_request.context).items() if key != "lacunas_tecnicas"}
43
+ return {
44
+ "format": "argos.ai-request/v1",
45
+ "provider": ai_request.provider,
46
+ "model": ai_request.model,
47
+ "profile_version": profile_version,
48
+ "prompt": ai_request.prompt,
49
+ "subject": dict(ai_request.subject),
50
+ "context": context,
51
+ "schema": dict(ai_request.schema),
52
+ "response_profile": ai_request.response_profile,
53
+ "reasoning_level": ai_request.reasoning_level,
54
+ "attachments": attachment_report.semantic_manifest(),
55
+ "parameters": dict(ai_request.metadata),
56
+ }
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class PreparedRequest:
61
+ """Pedido pronto para decidir: o que será enviado, quanto custa, quem é e se deve ser bloqueado."""
62
+
63
+ request: Any
64
+ profile: Any
65
+ caps: ModelCapabilities
66
+ policy: AttachmentPolicy
67
+ report: Any # AttachmentReport
68
+ context: Mapping[str, Any] # contexto enviado ao modelo (inclui lacunas_tecnicas)
69
+ schema: Mapping[str, Any]
70
+ snapshot: Mapping[str, Any]
71
+ ai_request: AIRequest
72
+ estimate: Mapping[str, int]
73
+ material: Mapping[str, Any]
74
+ semantic_hash: str
75
+ block: RequestBlockedError | None
76
+
77
+ def with_prompt(self, prompt: str) -> "PreparedRequest":
78
+ """Mesmo pedido com outro prompt (correção de resposta): reestima, refaz o hash e o bloqueio."""
79
+ return _build(
80
+ self.request, self.profile, self.caps, self.policy, self.report,
81
+ self.context, self.schema, self.snapshot, prompt,
82
+ )
83
+
84
+ @property
85
+ def blocked_action(self) -> str | None:
86
+ """Ação do preflight quando bloqueado (``blocked_attachment`` ou ``blocked_payload``)."""
87
+ if self.block is None:
88
+ return None
89
+ return "blocked_attachment" if self.block.reason in ATTACHMENT_BLOCKS else "blocked_payload"
90
+
91
+
92
+ def _block(request: Any, report: Any, caps: ModelCapabilities, ai_request: AIRequest, estimate: Mapping[str, int]):
93
+ if report.pending:
94
+ return RequestBlockedError(
95
+ "anexo não preparado; requisição não enviada",
96
+ reason="attachment_not_prepared",
97
+ details={"pending": [item.as_dict() for item in report.pending]},
98
+ )
99
+ if request.attachment_paths and not report.processed:
100
+ return RequestBlockedError(
101
+ "anexos declarados sem conteúdo processável; requisição não enviada",
102
+ reason="attachment_without_content",
103
+ details={"ignored": [item.as_dict() for item in report.ignored]},
104
+ )
105
+ if not caps.counts_tokens and ai_request.token_limit and estimate["total"] > ai_request.token_limit:
106
+ return RequestBlockedError(
107
+ f"payload estimado em {estimate['total']} tokens excede o limite de {ai_request.token_limit}",
108
+ reason="payload_limit",
109
+ details={"estimate": dict(estimate), "limit": ai_request.token_limit},
110
+ )
111
+ return None
112
+
113
+
114
+ def _build(request, profile, caps, policy, report, context, schema, snapshot, prompt) -> PreparedRequest:
115
+ ai_request = AIRequest(
116
+ prompt=prompt,
117
+ subject=request.subject_payload,
118
+ context=context,
119
+ attachments=report.processed,
120
+ schema=schema,
121
+ response_profile=request.response_profile,
122
+ provider=request.provider,
123
+ model=request.model,
124
+ metadata={"case_key": request.case_key, **dict(request.metadata)},
125
+ reasoning_level=request.reasoning_level or policy.reasoning_level,
126
+ token_limit=policy.token_limit(request.provider, caps.token_limit),
127
+ on_event=request.on_event,
128
+ )
129
+ estimate = estimate_request_tokens(ai_request)
130
+ material = request_material(ai_request, request.profile_version, report)
131
+ return PreparedRequest(
132
+ request=request,
133
+ profile=profile,
134
+ caps=caps,
135
+ policy=policy,
136
+ report=report,
137
+ context=context,
138
+ schema=schema,
139
+ snapshot=snapshot,
140
+ ai_request=ai_request,
141
+ estimate=estimate,
142
+ material=material,
143
+ semantic_hash=sha256_bytes(canonical_json(material).encode("utf-8")),
144
+ block=_block(request, report, caps, ai_request, estimate),
145
+ )
146
+
147
+
148
+ def _digest(value: Any, **options: Any) -> str:
149
+ return sha256_bytes(json.dumps(value, ensure_ascii=False, sort_keys=True, **options).encode("utf-8"))
150
+
151
+
152
+ class RequestPreparer:
153
+ """Prepara anexos e monta o ``PreparedRequest`` de cada pedido."""
154
+
155
+ def __init__(
156
+ self,
157
+ attachment_service: AttachmentProcessingService,
158
+ ai_services: AIServiceRegistry,
159
+ response_profiles: Any,
160
+ ) -> None:
161
+ self._attachments = attachment_service
162
+ self._ai_services = ai_services
163
+ self._profiles = response_profiles
164
+
165
+ def prepare(self, request: Any) -> PreparedRequest:
166
+ prompt = request.prompt
167
+ context = dict(request.context_payload) if isinstance(request.context_payload, Mapping) else {}
168
+ profile = self._profiles.get(request.response_profile)
169
+ schema = request.schema or profile.schema
170
+ caps = self._ai_services.capabilities(request.provider, request.model)
171
+ policy = request_policy(request)
172
+ report = self._attachments.prepare(request.attachment_paths, delivery=caps.delivery, policy=policy)
173
+ snapshot: dict[str, Any] = {
174
+ "prompt_profile": sha256_bytes(prompt.encode("utf-8")),
175
+ "schema_profile": _digest(schema),
176
+ "response_profile": request.response_profile,
177
+ "subject_profile": _digest(request.subject_payload, default=str),
178
+ "context_profile": _digest(context, default=str),
179
+ "attachment_manifest_hash": _digest(report.semantic_manifest()),
180
+ }
181
+ material_context = dict(context)
182
+ if request.metadata.get("opinion_revision_ids"):
183
+ material_context.pop("opinions", None)
184
+ material_snapshot = {
185
+ "catalog_entry_id": request.metadata.get("catalog_entry_id"),
186
+ "response_profile": request.response_profile,
187
+ "prompt": prompt,
188
+ "schema": dict(schema),
189
+ "subject": dict(request.subject_payload),
190
+ "context": material_context,
191
+ "opinion_revision_ids": list(request.metadata.get("opinion_revision_ids", [])),
192
+ "expected_item_codes": list(request.metadata.get("expected_item_codes", [])),
193
+ "expected_reason_ids": list(request.metadata.get("expected_reason_ids", [])),
194
+ "prompt_profile": snapshot["prompt_profile"],
195
+ "schema_profile": snapshot["schema_profile"],
196
+ "attachment_manifest": report.semantic_manifest(),
197
+ }
198
+ snapshot["material_snapshot_id"] = sha256_bytes(canonical_json(material_snapshot).encode("utf-8"))
199
+ if report.gaps:
200
+ context = {**context, "lacunas_tecnicas": [dict(item) for item in report.gaps]}
201
+ return _build(request, profile, caps, policy, report, context, schema, snapshot, prompt)
@@ -0,0 +1,137 @@
1
+ """Publicação comum de um DOCX de relatório.
2
+
3
+ O module concentra a sequência que não deve variar entre o caminho de Markdown
4
+ simples e o caminho de template/contexto: renderização, composição
5
+ institucional opcional, finalização de campos e devolução do resultado.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import re
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any, Callable, Mapping
15
+
16
+ from ..adapters.docx_pdf import finalize_docx_toc, render_markdown_docx
17
+ from ..adapters.report_publication import compose_report_document, fill_template_fields
18
+ from ..errors import InputValidationError
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ReportDocumentRequest:
23
+ markdown: str
24
+ output: Path
25
+ resource_root: Path
26
+ resource_overrides: Mapping[str, Path]
27
+ reference: Path | None
28
+ publication_config: Path | None
29
+ layout: Mapping[str, Any] | None
30
+ values: Mapping[str, Any]
31
+ document_label: str = "relatório"
32
+ resolve_path: Callable[[str | Path], Path] | None = None
33
+ resolved_resources: dict[str, Path] | None = None
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ReportDocumentResult:
38
+ content: bytes
39
+ pending: tuple[Mapping[str, Any], ...]
40
+ publication: Mapping[str, Any] | None
41
+ docx_fields: Mapping[str, Any]
42
+ resources: Mapping[str, Path]
43
+
44
+
45
+ def _require_file(path: Path | None, label: str) -> Path | None:
46
+ if path is None:
47
+ return None
48
+ if not path.is_file():
49
+ raise InputValidationError(f"fonte do relatório indisponível ({label}): {path}")
50
+ return path
51
+
52
+
53
+ def _finalize_report_fields(
54
+ content: bytes,
55
+ publication: dict[str, Any] | None,
56
+ layout: Mapping[str, Any] | None = None,
57
+ ) -> tuple[bytes, dict[str, Any]]:
58
+ sumario = publication.get("sumario") if publication else None
59
+ requested = sumario.get("atualizar") if isinstance(sumario, Mapping) else None
60
+ finalized, fields = finalize_docx_toc(content, update=requested)
61
+ if layout is not None:
62
+ # Word/LibreOffice may redistribute a table's integer-twip grid when
63
+ # saving the materialized TOC. Reapply the declared geometry after
64
+ # that round-trip so the published DOCX retains the configured widths.
65
+ from docx import Document
66
+
67
+ from ..adapters.docx_pdf import apply_report_layout
68
+
69
+ document = Document(io.BytesIO(finalized))
70
+ apply_report_layout(document, layout)
71
+ serialized = io.BytesIO()
72
+ document.save(serialized)
73
+ finalized = serialized.getvalue()
74
+ if publication is not None:
75
+ publication["sumario"] = fields
76
+ return finalized, fields
77
+
78
+
79
+ _FRONT_MATTER = re.compile(r"\A---[ \t]*\n(?P<yaml>.*?)\n---[ \t]*(?:\n|\Z)", re.DOTALL)
80
+ FIELD_SECTIONS = ("orgao", "fiscalizacao", "relatorio")
81
+
82
+
83
+ def template_field_values(values: Mapping[str, Any], markdown: str) -> dict[str, Any]:
84
+ """Contexto dos campos `[[secao.chave]]`: o front matter do Markdown prevalece sobre o contexto."""
85
+ merged = dict(values)
86
+ match = _FRONT_MATTER.match(markdown)
87
+ if not match:
88
+ return merged
89
+ import yaml
90
+
91
+ try:
92
+ front = yaml.safe_load(match.group("yaml"))
93
+ except yaml.YAMLError as exc:
94
+ raise InputValidationError(f"front matter do Markdown inválido: {exc}") from exc
95
+ if not isinstance(front, Mapping):
96
+ return merged
97
+ for section in FIELD_SECTIONS:
98
+ local = front.get(section)
99
+ if isinstance(local, Mapping):
100
+ merged[section] = {**dict(merged.get(section) or {}), **dict(local)}
101
+ return merged
102
+
103
+
104
+ def publish_document(request: ReportDocumentRequest) -> ReportDocumentResult:
105
+ """Publica o DOCX a partir de Markdown já renderizado."""
106
+ reference = _require_file(request.reference, "modelo DOCX")
107
+ publication_config = _require_file(request.publication_config, "configuração de publicação")
108
+ resources: dict[str, Path] = request.resolved_resources if request.resolved_resources is not None else {}
109
+ content, pending = render_markdown_docx(
110
+ request.markdown,
111
+ document_label=request.document_label,
112
+ reference=reference,
113
+ resource_root=request.resource_root,
114
+ resolve_path=request.resolve_path or (lambda value: Path(value)),
115
+ resource_overrides=request.resource_overrides,
116
+ resolved_resources=resources,
117
+ layout=request.layout if publication_config is None else None,
118
+ )
119
+ publication: dict[str, Any] | None = None
120
+ field_values = template_field_values(request.values, request.markdown)
121
+ if publication_config is not None:
122
+ content, publication = compose_report_document(
123
+ content,
124
+ publication_config,
125
+ field_values,
126
+ layout=request.layout,
127
+ )
128
+ else:
129
+ content = fill_template_fields(content, field_values)
130
+ content, docx_fields = _finalize_report_fields(content, publication, request.layout)
131
+ return ReportDocumentResult(
132
+ content=content,
133
+ pending=tuple(pending),
134
+ publication=publication,
135
+ docx_fields=docx_fields,
136
+ resources=resources,
137
+ )