perucompras-cli 0.1.0__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 (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,429 @@
1
+ Metadata-Version: 2.5
2
+ Name: perucompras-cli
3
+ Version: 0.1.0
4
+ Summary: A command-line client for Perú Compras catalogs
5
+ License-Expression: LicenseRef-Proprietary
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.15
8
+ Requires-Dist: alembic<2,>=1.20.1
9
+ Requires-Dist: anthropic<3,>=2.8.0
10
+ Requires-Dist: httpx2<3,>=2.16.0
11
+ Requires-Dist: jsonschema<5,>=4.26.0
12
+ Requires-Dist: pydantic-settings>=2.16.2
13
+ Requires-Dist: pypdf<8,>=7.0.0
14
+ Requires-Dist: rich>=15.0.0
15
+ Requires-Dist: snowflake-sqlalchemy<2.2,>=2.1.0
16
+ Requires-Dist: sqlalchemy<2.2,>=2.0.57
17
+ Requires-Dist: typer>=0.28.0
18
+ Description-Content-Type: text/markdown
19
+
20
+ # piloto-ai-cli
21
+
22
+ A Python command-line client for Perú Compras catalogs.
23
+
24
+ ## Installation
25
+
26
+ The package is published on PyPI as
27
+ [`perucompras-cli`](https://pypi.org/project/perucompras-cli/). It installs the
28
+ `pc` command and the `piloto_ai_cli` import package:
29
+
30
+ ```shell
31
+ pip install perucompras-cli
32
+ pc --version
33
+ ```
34
+
35
+ ## Requirements
36
+
37
+ - Python 3.15
38
+ - [uv](https://docs.astral.sh/uv/)
39
+
40
+ ## Getting started
41
+
42
+ ```shell
43
+ uv sync --locked --group dev
44
+ uv run pc --version
45
+ ```
46
+
47
+ ## Configuration
48
+
49
+ `Settings` reads `PILOTO_`-prefixed environment variables and, by default, an
50
+ optional `.env` file in the current directory. Applications can load another
51
+ profile file with `Settings(_env_file="path/to/profile.env")`; environment
52
+ variables take precedence over values in the file.
53
+
54
+ | Environment variable | Default | Description |
55
+ |---|---|---|
56
+ | `PILOTO_PROFILE` | `pilot` | `pilot` requires database and LLM credentials; `ci-mock` selects in-memory SQLite and a mock LLM. |
57
+ | `PILOTO_DATABASE_URL` | Required for `pilot`; `sqlite:///:memory:` for `ci-mock` | SQLAlchemy database URL. Stored as a secret. |
58
+ | `PILOTO_PAYLOAD_STORE_PATH` | `.piloto-ai/payloads` | Directory for stored request payloads. |
59
+ | `PILOTO_PAYLOAD_STAGE` | Unset | Optional unquoted Snowflake internal stage, such as `@db.schema.payloads`. |
60
+ | `PILOTO_LLM_PROVIDER` | `anthropic` (`mock` for `ci-mock`) | `anthropic` (the Claude API, for local runs), `snowflake` (Snowflake Cortex, used inside SPCS) or `mock`. |
61
+ | `PILOTO_LLM_MODEL` | `claude-sonnet-4-5` (`mock` for `ci-mock`) | LLM model identifier. |
62
+ | `PILOTO_LLM_PROMPT_VERSION` | `v2` | Version used to identify extraction prompts. |
63
+ | `PILOTO_LLM_API_KEY` | Required for `pilot` with `anthropic`, or `snowflake` with `pat` auth; unset otherwise | The Claude API key, or a Snowflake PAT for Cortex outside SPCS. Stored as a secret. |
64
+ | `PILOTO_LLM_SNOWFLAKE_AUTH` | `spcs_oauth` | Cortex authentication: `spcs_oauth` uses the SPCS service's session token, re-read on every request; `pat` uses `PILOTO_LLM_API_KEY`. |
65
+ | `PILOTO_LLM_SNOWFLAKE_HOST` | `SNOWFLAKE_HOST` (set by SPCS) | Snowflake host for Cortex, such as `<org>-<account>.snowflakecomputing.com`; required with `snowflake`. The `SNOWFLAKE_HOST` fallback is read from the process environment, only for `snowflake` with `spcs_oauth` and only when this setting is unset (in the environment or `.env`); `pat` needs this setting. |
66
+ | `PILOTO_LLM_SNOWFLAKE_TOKEN_PATH` | `/snowflake/session/token` | SPCS session token file for `spcs_oauth`. |
67
+ | `PILOTO_LLM_INPUT_USD_PER_MTOK` | Unset | USD per million input tokens for `PILOTO_LLM_MODEL`; set it with the output rate, or neither (then extraction cost is not recorded). For Cortex, the credit rate per million tokens times the account's USD per credit. |
68
+ | `PILOTO_LLM_OUTPUT_USD_PER_MTOK` | Unset | USD per million output tokens, as above. |
69
+ | `PILOTO_CONFIDENCE_THRESHOLD` | `0.8` | Deployment threshold in the inclusive range 0–1; queries may override it. |
70
+ | `PILOTO_MAX_ITEMS` | `100` | Maximum fichas processed per call. |
71
+ | `PILOTO_HTTP_USER_AGENT` | `perucompras-cli/<installed version> (+https://github.com/GrupoJaedmik-PeruCompras/piloto-ai-cli/issues)` | Identifying User-Agent with a contact URL. |
72
+ | `PILOTO_PER_CALL_IN_FLIGHT_LIMIT` | `5` | Per-call concurrent page limit, between 1 and the process-wide hard cap of 20. |
73
+ | `PILOTO_HTTP_CONNECT_TIMEOUT_SECONDS` | `10` | HTTP connection timeout in seconds. |
74
+ | `PILOTO_HTTP_READ_TIMEOUT_SECONDS` | `30` | HTTP read timeout in seconds. |
75
+ | `PILOTO_LLM_TIMEOUT_SECONDS` | `120` | LLM request timeout in seconds. |
76
+ | `PILOTO_ENRICHMENT_RETRY_BASE_SECONDS` | `900` (15 minutes) | Wait before retrying a ficha whose enrichment (PDF download or LLM pass) failed; it doubles with each consecutive failure under the same site stamp. |
77
+ | `PILOTO_ENRICHMENT_RETRY_CAP_SECONDS` | `86400` (1 day) | Longest wait between enrichment retries; must be at least the base. A new site stamp resets the wait. |
78
+ | `PILOTO_CARD_LOOKUP_RETRY_BASE_SECONDS` | `900` (15 minutes) | Wait before looking up a ficha's card by part number again after a lookup that failed at the site (an error status, the error page, an undecodable answer, its own card unparseable, or a transport error) or whose card failed to be stored; it doubles with each consecutive failure under the same site stamp. |
79
+ | `PILOTO_CARD_LOOKUP_RETRY_CAP_SECONDS` | `86400` (1 day) | Longest wait between those lookups; must be at least the base. A new site stamp resets the wait. |
80
+
81
+ Tests can use the mock profile without service credentials:
82
+
83
+ ```python
84
+ from piloto_ai_cli.settings import Settings
85
+
86
+ settings = Settings(profile="ci-mock")
87
+ ```
88
+
89
+ `Settings` keeps database URLs and API keys in `SecretStr` fields so their
90
+ representations are masked. Do not pass credentials to `request_log` or logs.
91
+
92
+ Use `make_payload_store(settings, connection=None)` from
93
+ `piloto_ai_cli.payload_store` to select a payload backend. With no `payload_stage`
94
+ configured (including the `ci-mock` defaults), it uses `payload_store_path`.
95
+ When a stage is configured, pass an open Snowflake connection; the factory does
96
+ not open or close connections. Use that connection exclusively for the payload
97
+ store while requests are running; the store serializes its own stage operations.
98
+ The live payload test uses the same `Settings` configuration and requires
99
+ database credentials and a payload stage.
100
+
101
+ `HttpClient` requires a session factory, payload store, and the ID of an
102
+ already committed `run_log`. Pass the connector name as `endpoint` to
103
+ `write_request()` (it defaults to the URL path). Each attempt, including a
104
+ retry, commits its request and response payload in a separate transaction
105
+ before the response is returned. The response's `extensions["request_id"]`
106
+ identifies that attempt. Transport failures are logged before being raised.
107
+ Check `extensions["is_error_page"]` before parsing a successful response.
108
+ Automatic redirects and HTTPX authentication flows are rejected because they
109
+ can send additional unlogged requests; follow redirects explicitly and send
110
+ authentication through headers instead.
111
+ Forms must not contain credentials; known token and credential fields are
112
+ stripped from the log, and so are query parameters with those names. The logged
113
+ URL is the one sent, including `params=`. Every response body is stored,
114
+ whatever its status, error page or failure: raw sources are what the parsers and
115
+ extraction are improved against. A complete body is stored after its
116
+ `Content-Encoding` is undone; a partial or undecodable body is stored exactly as
117
+ received, with `; content-encoding=<value>` appended to its content type. Bodies
118
+ may contain sensitive data, so protect the payload store accordingly.
119
+
120
+ ## Library API
121
+
122
+ The frontend agent imports the CLI as a Python package instead of running
123
+ `pc`. The names in `piloto_ai_cli.__all__` are the stable, typed library
124
+ surface. They are versioned with the package under
125
+ [semantic versioning](https://semver.org/): a breaking change to any of them
126
+ needs a major version bump. Read the installed version with
127
+ `importlib.metadata.version("perucompras-cli")`. Other modules of the package
128
+ are internal and may change in any release.
129
+
130
+ ```python
131
+ import piloto_ai_cli
132
+
133
+ settings = piloto_ai_cli.Settings() # or omit settings: read from the environment
134
+ document = {
135
+ "contract_version": 1,
136
+ "scope": {"agreement": "EXT-CE-2024-18", "category": "AZÚCAR"},
137
+ "predicates": [],
138
+ }
139
+ try:
140
+ result = piloto_ai_cli.query(document, settings=settings)
141
+ except piloto_ai_cli.ContractError as refusal:
142
+ print(refusal.to_dict()) # code, location and message, to repair and retry
143
+ else:
144
+ print([match.ficha_id for match in result.matches])
145
+ ```
146
+
147
+ | Name | What it is |
148
+ |---|---|
149
+ | `query` | `query(document, *, settings=None, max_items=None) -> QueryResult`: what `pc query <document>` runs. |
150
+ | `query_saved` | `query_saved(query_id, *, settings=None, max_items=None) -> QueryResult`: what `pc query --saved <id>` runs. |
151
+ | `attributes` | `attributes(scope, *, settings=None) -> AttributesListing`: what `pc attributes <scope>` runs. |
152
+ | `save` | `save(document, *, settings=None) -> str`: what `pc save <document>` runs; returns the saved query id. |
153
+ | `QueryResult` | The result envelope: matches, non-match count, `unknown`, `not_applicable`, pending counts, facets, `contract_version` and `department_as_of`. A Pydantic model; `model_dump(mode="json")` gives the `pc --json query` output. |
154
+ | `QueryMatch` | One matching ficha, with its latest card values and stamps. |
155
+ | `UnknownCount` | One unknown count of the envelope, per predicate and reason. |
156
+ | `NotApplicable` | An attribute absent from the scope's checked fichas, with checked and pending counts. |
157
+ | `PendingCounts` | Pending cards, PDFs, extractions and proposals in the scope. |
158
+ | `FacetSummary` | One requested facet: its values and the count of fichas whose value is unknown. |
159
+ | `FacetValue` | One distinct facet value and its count. |
160
+ | `AttributesListing` | The answer of `attributes`: a one-category scope's `attributes`, or a wider scope's `categories`. |
161
+ | `ApplicableAttribute` | One attribute of a category, with kind, canonical unit and accepted values. |
162
+ | `ScopeCategory` | One category of a scope, with its catalogue. |
163
+ | `ContractError` | The typed refusal: `code`, `location` (a predicate index or a field such as `scope.agreement` or `saved`) and `message`. |
164
+ | `ContractErrorCode` | The refusal codes: `schema_violation`, `unknown_attribute`, `unit_not_convertible`, `bad_op_for_kind`, `department_unavailable`. |
165
+ | `Settings` | The configuration described above; every function reads `Settings()` from the environment when `settings` is omitted. |
166
+ | `CONTRACT_SCHEMA_PATH` | The packaged JSON Schema of predicate documents (`contract_version` 1), as an `importlib.resources` resource: use `read_text()`, or `importlib.resources.as_file()` for a filesystem path. |
167
+
168
+ Each call is one `run_log` run, exactly like the command: it validates its
169
+ input, makes its requests through `write_request()` and records its run. Inputs
170
+ are JSON values as `json.loads` returns them; a value JSON cannot hold (such as
171
+ `NaN` or a `Decimal`) is refused with `schema_violation`, as `pc` refuses it.
172
+ A refusal closes the run as `refused` and raises `ContractError`; any other
173
+ error closes it as `failed` and propagates. `max_items` below 1 raises
174
+ `ValueError`. The functions are synchronous and run their own event loop for
175
+ their requests, so call them through `asyncio.to_thread()` from async code.
176
+
177
+ ## Database schema
178
+
179
+ Set the `PILOTO_DATABASE_URL` environment variable, then run this from the
180
+ repository root to create or update the schema:
181
+
182
+ ```shell
183
+ alembic upgrade head
184
+ ```
185
+
186
+ Run `alembic check` to detect drift between the migration and the ORM models.
187
+ SQLite uses the default database in place of the models' `cli` schema.
188
+
189
+ ### Snowflake migrations: pull-request check and deploy
190
+
191
+ Two workflows run the migrations against real Snowflake, each with its own
192
+ identity from [Mirkiux/snowflake-infra](https://github.com/Mirkiux/snowflake-infra):
193
+
194
+ - **Check** (`ci.yml`, job `Snowflake migrations`): on every same-repository
195
+ pull request, push and manual run, it resets the scratch database
196
+ `PILOTO_AI_CLI_CI` to base, runs `alembic upgrade head` and `alembic check`,
197
+ then `alembic downgrade base` (also when the upgrade or check fails). It
198
+ connects as `PILOTO_AI_CLI_CI_MIGRATOR_SVC` with role
199
+ `PILOTO_AI_CLI_CI_MIGRATOR`, which has no access to `PILOTO_AI`, so a pull
200
+ request can never drop deployed tables. Database, user and role are fixed in
201
+ the workflow, not read from variables.
202
+ - **Deploy** (`migrations.yml`): after CI passes on a push to `main` (or on
203
+ manual dispatch), it runs `alembic upgrade head` on the commit CI checked
204
+ against `PILOTO_AI.CLI` as `PILOTO_AI_CLI_MIGRATOR_SVC` with role
205
+ `PILOTO_AI_CLI_MIGRATOR`, then fails unless `alembic current` reports head
206
+ and `alembic check` finds no drift. It never downgrades. Deploys are
207
+ serialized.
208
+
209
+ Maintainers must add:
210
+
211
+ - Repository variable **`SNOWFLAKE_MIGRATIONS_ENABLED`** with value **`true`**
212
+ (enables both).
213
+ - Repository variables **`SNOWFLAKE_ACCOUNT`** and **`SNOWFLAKE_WAREHOUSE`**.
214
+ - Repository secret **`SNOWFLAKE_CI_MIGRATOR_PAT`**: the role-restricted PAT of
215
+ `PILOTO_AI_CLI_CI_MIGRATOR_SVC` (snowflake-infra `bootstrap/15`).
216
+ - Environment **`snowflake-migrations`** with a deployment branch policy that
217
+ allows only `main`, and in it the environment secret
218
+ **`SNOWFLAKE_MIGRATOR_PAT`**: the PAT of `PILOTO_AI_CLI_MIGRATOR_SVC`
219
+ (snowflake-infra `bootstrap/13`). Not a repository secret: this role owns the
220
+ deployed tables, and pull requests can read repository secrets.
221
+
222
+ Both workflows build the SQLAlchemy URL with
223
+ `src/piloto_ai_cli/snowflake_url.py` (standard library only), which URL-encodes
224
+ the PAT, passes it as `token` with `authenticator=programmatic_access_token`,
225
+ masks the encoded PAT and the URL, and fails naming any missing value. No LLM
226
+ credentials are needed.
227
+
228
+ The check is skipped when `SNOWFLAKE_MIGRATIONS_ENABLED` is not `true`, its
229
+ secret is absent, or the pull request comes from a fork. With the deploy
230
+ enabled, a missing secret or variable fails the deploy at once. Snowflake DDL is
231
+ not transactional: review migrations before merging, since a failed deploy may
232
+ leave partial DDL in `PILOTO_AI.CLI` that needs a manual fix. Do not test
233
+ deliberately destructive migrations against pilot data.
234
+
235
+ ## Scheduled health workflow
236
+
237
+ `.github/workflows/health.yml` runs `pc --json health` once a day (and on
238
+ manual dispatch) against the live site and the pilot database. It never runs on
239
+ pull requests, and it has a single daily schedule because live checks must not
240
+ run more often than every 3 hours.
241
+
242
+ ### Live checks at most every 3 hours
243
+
244
+ The workflow enforces the 3-hour spacing itself. Before any live request, its
245
+ spacing steps read this workflow's runs and their jobs through the Actions API
246
+ (the job's token gets `actions: read` for this; the `gh` steps are the only
247
+ `run` steps given it, and the project's Python decides with no token in its
248
+ environment; the SHA-pinned `actions/checkout`, `actions/setup-python` and
249
+ `astral-sh/setup-uv` also receive this read-only token through their default
250
+ token inputs), and the
251
+ "Enforce the 3-hour spacing" step fails
252
+ with an error that names the earlier run and says when the next run is allowed
253
+ if live checks started less than 3 hours ago. This covers manual dispatches
254
+ (including `force_failure` tests), a run queued behind another in the
255
+ `pc-health` concurrency group, and re-runs.
256
+
257
+ An earlier run counts when its "Run pc health" step started less than 3 hours
258
+ before, measured from that step's start time. Every run of the workflow created
259
+ in the last 31 days is considered (an older run can no longer be re-run),
260
+ whatever its event, branch or result, and so is every earlier
261
+ attempt of the current run; only the current attempt is left out. A run counts
262
+ even if it failed or was cancelled after the live step started. A run does not
263
+ count when its job or its live step was skipped (for example
264
+ `HEALTH_CHECK_ENABLED` was off, the configuration check failed, or this spacing
265
+ check stopped it), or when it was cancelled before the live step started, so a
266
+ refused run never pushes the next allowed time back. If the runs or jobs cannot
267
+ be read or are malformed, the spacing steps fail and the live checks do not run.
268
+
269
+ Every response the checks receive is stored by `write_request()` in the
270
+ Snowflake payload stage, so the `payload` rows the run writes always point at
271
+ durable storage. The run's `health-report` artifact holds the redacted report.
272
+ Database credentials are redacted from the report, the issues and their
273
+ comments.
274
+
275
+ ### Issues: one per failed check
276
+
277
+ When a check fails, or `pc health` cannot produce its report (reported as the
278
+ `workflow.pc_health` check), the workflow handles each failed check on its own,
279
+ keyed by the check's name (for example `get_home.parse_home`). The key is kept
280
+ in a hidden `<!-- pc-health-workflow check=<name> -->` marker in the issue body,
281
+ and only open issues the workflow itself opened (author `github-actions[bot]`)
282
+ are considered:
283
+
284
+ - **No open issue for that check:** the workflow opens a new issue with the
285
+ failure, the full report and a link to the run, and assigns it to Copilot.
286
+ - **An open issue for that check:** the failure is already with its owner, so
287
+ no duplicate is opened. The workflow adds a comment to that issue with the
288
+ run link and the reason, and assigns Copilot again only if nobody is assigned.
289
+ - **The check's issue was closed:** closed issues are never reopened. If the
290
+ check fails again, the workflow opens a new issue for it, assigned to Copilot.
291
+ - **Re-running the issues job** (for example "Re-run failed jobs" after one
292
+ Copilot assignment failed) records nothing twice. Every issue body and
293
+ recurrence comment carries a hidden `<!-- pc-health-workflow report=<run
294
+ id>.<attempt> -->` marker for the health job attempt that produced the
295
+ report. The issues job reads every issue the workflow opened that changed
296
+ since the report, open or closed, and its own comments there: a check whose
297
+ report is already recorded anywhere gets no new issue or comment, even if
298
+ that issue was closed since, and only Copilot is assigned again if the open
299
+ issue that records it has nobody assigned. Issues and comments are stamped
300
+ with the time the report was made, not the time the issues job ran.
301
+
302
+ A check that did not run (its reason starts with `not run:`) names the failed
303
+ check that blocked it in the report's `blocked_by` field. It gets no issue of
304
+ its own only when that check failed in the same report, which has the issue;
305
+ the report still lists it. A check blocked by a precondition that is not a
306
+ check (for example `GET /` listing no agreement with fichas, or an export with
307
+ no PDF URL) has `blocked_by: null` and gets its own issue. Different checks never share an issue, so a new failure
308
+ always reaches an owner even while an earlier issue is still open.
309
+
310
+ To test the issue path, dispatch the workflow with **force_failure** checked
311
+ (at least 3 hours after the last run, like any run): it runs the real checks and adds a failed `workflow.forced_failure` check, which
312
+ has its own key and so its own issue, titled "(forced test)". Real failures in
313
+ the same run go to their own issues, and an open forced-test issue never
314
+ absorbs a real failure. Close the forced-test issue once the workflow is
315
+ verified.
316
+
317
+ ### Required configuration
318
+
319
+ Maintainers must add:
320
+
321
+ - Two environments (Settings → Environments), each with a deployment branch
322
+ policy that allows only `main`. The secrets below are environment secrets
323
+ there (not repository secrets), so a workflow edited or dispatched on another
324
+ branch cannot read them, and each secret is in the environment of only the
325
+ jobs that use it:
326
+ - **`pc-health`**, used only by the `pc health` job: holds
327
+ `PILOTO_HEALTH_DATABASE_URL`.
328
+ - **`pc-health-issues`**, used only by the `Check the issue token` and
329
+ `Health issues` jobs, which run no project or third-party dependencies:
330
+ holds `COPILOT_ASSIGN_TOKEN`.
331
+ - Repository variable **`HEALTH_CHECK_ENABLED`** with value **`true`**. Without
332
+ it the job is skipped.
333
+ - Environment secret **`PILOTO_HEALTH_DATABASE_URL`** in `pc-health`: the SQLAlchemy URL of the
334
+ pilot database that connects as the service user
335
+ **`PILOTO_AI_CLI_HEALTH_SVC`** with role **`PILOTO_AI_CLI_HEALTH`**, database
336
+ `PILOTO_AI`, schema `CLI` and warehouse `PILOTO_AI_WH`, for example
337
+ `snowflake://PILOTO_AI_CLI_HEALTH_SVC:<URL-encoded role-restricted PAT>@<account>/PILOTO_AI/CLI?warehouse=PILOTO_AI_WH&role=PILOTO_AI_CLI_HEALTH`.
338
+ The role and user are provisioned by
339
+ [Mirkiux/snowflake-infra](https://github.com/Mirkiux/snowflake-infra); do not
340
+ use the deploy or migrator role. The role is least-privilege and holds only
341
+ what `pc health` uses:
342
+ - USAGE on database `PILOTO_AI`, schema `PILOTO_AI.CLI` and warehouse
343
+ `PILOTO_AI_WH`;
344
+ - SELECT on every table in `PILOTO_AI.CLI` through a future grant, so each
345
+ table the migrations create is readable (the foreign-key orphan checks);
346
+ - INSERT and UPDATE on `run_log` (the run is opened, then closed) and INSERT
347
+ on `request_log` and `payload` (append-only), granted per table. These
348
+ exist only once the migrations are deployed and kept at head in
349
+ `PILOTO_AI.CLI` and snowflake-infra applies with `cli_tables_deployed =
350
+ true` ([#165](https://github.com/Mirkiux/piloto-ai-cli/issues/165)); until
351
+ then the health job cannot write its run log;
352
+ - READ and WRITE on stage `PILOTO_AI.CLI.PAYLOADS` (`PUT` of every response).
353
+ - Repository variable **`PILOTO_PAYLOAD_STAGE`** with value
354
+ **`@PILOTO_AI.CLI.PAYLOADS`**: the stage that keeps every raw response.
355
+ - Environment secret **`COPILOT_ASSIGN_TOKEN`** in `pc-health-issues`: a user token (fine-grained
356
+ PAT) of an account with access to the Copilot coding agent, with read and
357
+ write access to this repository's actions, contents, issues and pull
358
+ requests. The workflow's own token cannot assign Copilot. Two jobs reference
359
+ it, each on its own fresh runner. `Check the issue token` runs first, with no
360
+ permissions, no checkout and no install: it only tests whether the token is
361
+ set and stops the run before any live check if it is not, since a failure
362
+ could not reach an owner. `Health issues` runs after the `pc health` job,
363
+ holds the only `issues: write` permission, installs no dependencies (it runs
364
+ `gh` and the standard-library-only planner with plain `python -I`), and passes
365
+ the token only to the `gh` calls over the issue plan. The `pc health` job,
366
+ which installs runtime dependencies only (`UV_NO_DEV=1`), never references the
367
+ token at all.
368
+
369
+ With `HEALTH_CHECK_ENABLED` set, a missing secret or variable, or a stage name
370
+ that is not an unquoted Snowflake stage name, fails the run at once with an
371
+ error naming it, before any check runs, and opens no issue. If the CLI cannot
372
+ be installed (`setup-uv` or `uv sync --locked` fails, or hangs past its 5-minute step timeout), the run reports a failed
373
+ `workflow.install` check and opens its issue like any other failure. `pc health` makes no
374
+ LLM call, so the job passes a placeholder `PILOTO_LLM_API_KEY` rather than the
375
+ real key.
376
+
377
+ ## Releasing
378
+
379
+ Releases are published by `.github/workflows/publish.yml` with PyPI trusted
380
+ publishing (no API tokens). Each release tag is uploaded to
381
+ [TestPyPI](https://test.pypi.org/p/perucompras-cli) first, through the
382
+ `testpypi` environment, and to [PyPI](https://pypi.org/p/perucompras-cli)
383
+ only after that succeeds, through the `pypi` environment. Each index needs a
384
+ trusted publisher for owner `Mirkiux`, repository `piloto-ai-cli`, workflow
385
+ `publish.yml` and the matching environment name.
386
+
387
+ 1. Open a release pull request that sets `version` in `pyproject.toml` (if
388
+ it does not already have the target value, as `0.1.0` does) and moves the
389
+ `## [Unreleased]` entries of [`CHANGELOG.md`](https://github.com/Mirkiux/piloto-ai-cli/blob/main/CHANGELOG.md) under
390
+ `## [<version>] - YYYY-MM-DD`, with its release link, right before
391
+ tagging.
392
+ 2. After it merges, create the GitHub release `v<version>` on `main`; every
393
+ release needs one. Creating it pushes the tag, which runs the workflow; the
394
+ workflow refuses a tag that does not match the project version.
395
+ `auto-tag.yml` pushes the tag by itself only when a push to `main` changes
396
+ the version; in that case create the release from the existing tag with
397
+ `gh release create v<version> --verify-tag`. A release whose version is
398
+ already on `main`, such as `0.1.0`, is started by creating the release.
399
+ 3. When the run finishes, verify the release: in a clean virtualenv,
400
+ `pip install perucompras-cli==<version>`, run `pc --version` and a replay
401
+ `pc query` smoke, and check that the GitHub release `v<version>` exists.
402
+ Record the result on the release issue.
403
+ 4. If the PyPI job fails after TestPyPI succeeded (for example, the PyPI
404
+ trusted publisher is missing), fix the cause and use **Re-run failed jobs**
405
+ on the same workflow run, within GitHub's 30-day re-run window. That keeps
406
+ the successful TestPyPI job and the distributions it already uploaded.
407
+ Do not use "Re-run all jobs" or delete and re-push the tag: either
408
+ rebuilds the files, and TestPyPI rejects a same-named file with different
409
+ contents, which stops the release before PyPI. Past that window, or if the
410
+ code itself must change, release the next version instead.
411
+ 5. To stage a build on TestPyPI without releasing, run the workflow manually
412
+ with `target: testpypi`: it uploads a unique `<version>.devN` build (N is
413
+ the run number), so it never takes the release version. `build-only`, the
414
+ default, only builds and checks the distributions. PyPI uploads only run
415
+ for a `v*` tag push.
416
+
417
+ ## Checks
418
+
419
+ ```shell
420
+ uv run ruff check
421
+ uv run ruff format --check
422
+ uv run mypy --strict src
423
+ uv run pytest
424
+ ```
425
+
426
+ ## License
427
+
428
+ Copyright (c) 2026 Grupo Jaedmik. All rights reserved. Use of the CLI is
429
+ subject to licensing by the copyright holder; see [LICENSE](https://github.com/Mirkiux/piloto-ai-cli/blob/main/LICENSE).
@@ -0,0 +1,50 @@
1
+ piloto_ai_cli/__init__.py,sha256=6s42fYoSHE79ILrhctOuWrPl5CbAYcTZb46a1sjDkpM,1695
2
+ piloto_ai_cli/__main__.py,sha256=dpXfDFpPAJlMb_Ctv_UBxpE_Aauc9dGREc3j6YijbkA,60
3
+ piloto_ai_cli/api.py,sha256=uqw-yggcFsxAiaDH3HCrcOCOc00DzG0fXzyeZ3TC50w,16298
4
+ piloto_ai_cli/attribute_text.py,sha256=JbyCC8sKQnkFvLEBNsmQgWoTwVRlxTbNA4QrwwdW4rQ,3636
5
+ piloto_ai_cli/attributes_service.py,sha256=dZRbPbR8gy5tuGP0yT101mHxUFJ61j3csEkkrOQureY,10132
6
+ piloto_ai_cli/auto_tag.py,sha256=glu2qRZS5pB4m0HNbI3-IHrzu3LHtKM0Yl0FA2b8_Ls,2015
7
+ piloto_ai_cli/backoff.py,sha256=h0wKSf7jiwPwZ6OFYG-ADQgOodoBztc9CTjrJwuundQ,988
8
+ piloto_ai_cli/cards.py,sha256=njYv4fJtM3A3S8nFHpyb4-O_8aTsv3GWFocVcVvOnVo,40455
9
+ piloto_ai_cli/cli.py,sha256=GsImB9Uz5v7T62OSZ9lE45xaq98Gy6CgTsLPeVD-qWM,23807
10
+ piloto_ai_cli/connectors.py,sha256=XTIfyhwTo-1thdrwxh_Qjp-Mp3s7PvI4zvSJPxO53Os,3879
11
+ piloto_ai_cli/database.py,sha256=zXtiqLbs_6U-0oZQMUwFY7e_LTQlpWmyN6Gbgi3hd9M,20277
12
+ piloto_ai_cli/enrichment.py,sha256=Bfsm8vQRPGlodMPlIj9n8Gbz_jdrUtKCBEeBOZMQ7x8,24149
13
+ piloto_ai_cli/errors.py,sha256=5ZBhsCbz6Mpqw4-9qtIGHukFkcd0b9lclICezx3UNF8,3016
14
+ piloto_ai_cli/excel.py,sha256=KP3pwpD7XunNYAbvoF1dYEFMyp_OPfK-jHcTscZo9iE,6548
15
+ piloto_ai_cli/extraction.py,sha256=8MDZj6KoRFPysVmZWqH9SA6VCCy_GhzQzSLuPiuLRgY,57125
16
+ piloto_ai_cli/health.py,sha256=HaiGTBcX-G6KHKFlVFjR6R6j5o2VxpWwE6vvzCAkRss,16144
17
+ piloto_ai_cli/health_workflow.py,sha256=-l3k4JHFX_K9XbYBv2VDVur6-atZziMh0NXkbvURCbs,40773
18
+ piloto_ai_cli/http_client.py,sha256=Y0u_U1y2PPPGGnEQAAWebVo-v0nDysbWWmrAJCkCBWg,23243
19
+ piloto_ai_cli/llm_client.py,sha256=ZKTd-u9thkteZrb87_NyFGedNkXaxlTsRXIi2EJ3cSs,10297
20
+ piloto_ai_cli/llm_extraction.py,sha256=V4jtsx4XzhndQkQWfAH6hjEiMO_DGJx5lu7sAVpx13s,17301
21
+ piloto_ai_cli/llm_output.py,sha256=A9GrCPw2JR1A8AFf6CoyC8jocm4N3qFdMM8rxekKQPE,3338
22
+ piloto_ai_cli/pane.py,sha256=F2oRQ1xmakK8ibcVDzGnOIBoCfEqvUSGKslV3tbCyRk,12710
23
+ piloto_ai_cli/parsers.py,sha256=jH58RJ9qf0C_SS_JbjeeTaqoPRamor7JFhm46Diukvo,16599
24
+ piloto_ai_cli/payload_store.py,sha256=woD7O958xKpEOl2-2nSIWXoLKbM0MwO4nx204lPCV1Q,8822
25
+ piloto_ai_cli/pdf_parser.py,sha256=lss_kjNTDGVCELBnDFA5XZXLEGe3nlK_sIPnqqq4efc,445
26
+ piloto_ai_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
+ piloto_ai_cli/query_compiler.py,sha256=ONdGezRNOXMY5XVvi8HFPQVaSRYOuC47Hv6lpiWxcK8,43217
28
+ piloto_ai_cli/query_result.py,sha256=OIiq9NxUWePDNbKw-aE2wQ12qBwRQPznWxQqeQKN5-o,6227
29
+ piloto_ai_cli/query_service.py,sha256=pd4GgkaMdr5UAk7_4o7Qi4RX01N5HZvz5bv3C2DpvSI,7666
30
+ piloto_ai_cli/reextract.py,sha256=YjCwbveH-55_WuZoxrmbUR-ghM6Y0R71MxFr9L1ZxUg,5033
31
+ piloto_ai_cli/review.py,sha256=wfbQIyG0ro2n3kYJQN17GYojEs1IpgIGo7zBmePe80A,7895
32
+ piloto_ai_cli/rules.py,sha256=rozr02UY0bz_akpCyorTD0CeAzBXwxPTqkUq0bsXKXM,2492
33
+ piloto_ai_cli/run_log.py,sha256=dcu6xCeJyWLkVdMejSsEioGEuKu9r7orARV-AzeMZaQ,8432
34
+ piloto_ai_cli/search_form.py,sha256=TugXKpskqaVGgiFkQ6KYxtiPibXKsjKmuhu3n_Df_Tw,3069
35
+ piloto_ai_cli/settings.py,sha256=jfUpGvqqqzEJtW3e062DkqJMIfvXeNlxSg9zrUoOmSM,8243
36
+ piloto_ai_cli/snowflake_url.py,sha256=CFbXFd6fEqjLF0Z21RtXrWJzpbZgnGKUpbapQPu5iIs,2967
37
+ piloto_ai_cli/stamp_service.py,sha256=aVtB2AqPlneAQCccRumP6Fv6GK049UI62iKgAjIa35I,1761
38
+ piloto_ai_cli/sync.py,sha256=wyWiOQ0bm6sL59_ycybHOlJIExzsztKHNBw1-fzsEZg,48390
39
+ piloto_ai_cli/unit_converter.py,sha256=zwhb303VKNdEZvwNsugJhKAh05vQP5FCkBka1m-I0q8,3311
40
+ piloto_ai_cli/schema/__init__.py,sha256=B0z_BLz226dopyGO-uV90kAPwZOy2YfCE9pCwkb2g3E,503
41
+ piloto_ai_cli/schema/contract-v1.schema.json,sha256=5cDRaXtwgsPyHq_mMct8sRw5Kf0149CxisM0uoEXObE,5585
42
+ piloto_ai_cli/schema/contract.py,sha256=Syt_nO5qqPQfM_OM2SA0kBN8GGJtm0HdJT6fP87BnKA,10006
43
+ piloto_ai_cli/schema/migration_filters.py,sha256=msEWzlzf6GDPRgSsQQJOAum2CjoobfT9Aqc307iQN2Q,1731
44
+ piloto_ai_cli/schema/models.py,sha256=ZcL6jvbwl53wmFHcoBBYfNgkdj2bLZkYdwM-rK41bVg,33521
45
+ piloto_ai_cli/schema/snowflake_autogen.py,sha256=pFFxlEy1za31_OYpsULNOHA1pTVh7Rq8r3jxmskZPso,5375
46
+ perucompras_cli-0.1.0.dist-info/METADATA,sha256=dEP0nCL-87il_b7TsEE2HvCnEkD33ZLptgHSPE_wI-w,25800
47
+ perucompras_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
48
+ perucompras_cli-0.1.0.dist-info/entry_points.txt,sha256=ppm2yYldLlvaPodiPbmPYPoslr23HfoLp6vH15xhkoo,45
49
+ perucompras_cli-0.1.0.dist-info/licenses/LICENSE,sha256=YNYV36QxLNEI39AMy10tK1OxidxF47JpLdrLo2bbtmA,879
50
+ perucompras_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pc = piloto_ai_cli.cli:app
@@ -0,0 +1,16 @@
1
+ Copyright (c) 2026 Grupo Jaedmik. All rights reserved.
2
+
3
+ This software and its source code are proprietary. No license, express or
4
+ implied, is granted to use, copy, modify, merge, publish, distribute,
5
+ sublicense or sell copies of this software, in whole or in part, except under
6
+ a separate written license agreement with the copyright holder.
7
+
8
+ Use of the perucompras-cli package and its `pc` command is subject to
9
+ licensing by the copyright holder. Installing the package from PyPI does not
10
+ grant a license to use it.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING
16
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR ITS USE.
@@ -0,0 +1,51 @@
1
+ """Perú Compras command-line client, and the library API the frontend agent imports.
2
+
3
+ The names in ``__all__`` are the stable, typed library surface, versioned with
4
+ the package under semantic versioning: :func:`query` (and :func:`query_saved`),
5
+ :func:`attributes` and :func:`save`, the result types they return, the
6
+ :class:`ContractError` refusal and its codes, :class:`Settings`, and
7
+ ``CONTRACT_SCHEMA_PATH``. The ``pc`` commands are thin wrappers over them.
8
+ """
9
+
10
+ DISTRIBUTION_NAME = "perucompras-cli"
11
+ """Name of the distribution on PyPI, used for version and User-Agent lookups."""
12
+
13
+ # Imported after DISTRIBUTION_NAME, which these modules read from this package.
14
+ from piloto_ai_cli.api import attributes, query, query_saved, save # noqa: E402
15
+ from piloto_ai_cli.attributes_service import ( # noqa: E402
16
+ ApplicableAttribute,
17
+ AttributesListing,
18
+ ScopeCategory,
19
+ )
20
+ from piloto_ai_cli.errors import ContractError, ContractErrorCode # noqa: E402
21
+ from piloto_ai_cli.query_compiler import ( # noqa: E402
22
+ FacetSummary,
23
+ FacetValue,
24
+ NotApplicable,
25
+ PendingCounts,
26
+ UnknownCount,
27
+ )
28
+ from piloto_ai_cli.query_result import QueryMatch, QueryResult # noqa: E402
29
+ from piloto_ai_cli.schema.contract import CONTRACT_SCHEMA_PATH # noqa: E402
30
+ from piloto_ai_cli.settings import Settings # noqa: E402
31
+
32
+ __all__ = [
33
+ "CONTRACT_SCHEMA_PATH",
34
+ "ApplicableAttribute",
35
+ "AttributesListing",
36
+ "ContractError",
37
+ "ContractErrorCode",
38
+ "FacetSummary",
39
+ "FacetValue",
40
+ "NotApplicable",
41
+ "PendingCounts",
42
+ "QueryMatch",
43
+ "QueryResult",
44
+ "ScopeCategory",
45
+ "Settings",
46
+ "UnknownCount",
47
+ "attributes",
48
+ "query",
49
+ "query_saved",
50
+ "save",
51
+ ]
@@ -0,0 +1,5 @@
1
+ """Run the CLI as a module."""
2
+
3
+ from .cli import app
4
+
5
+ app()