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,134 @@
1
+ """Snowflake-only adjustments to Alembic's autogenerate comparison.
2
+
3
+ Everything here exists because of how Snowflake reflects a schema, and is
4
+ wired in only for the ``snowflake`` dialect: ``SnowflakeImpl`` is Alembic's
5
+ implementation for that dialect alone, and ``compare_type_for`` returns
6
+ Alembic's default comparison for every other dialect. The models and the
7
+ migration files stay engine-agnostic; these hooks change only what
8
+ ``alembic check`` and ``revision --autogenerate`` consider a difference.
9
+ """
10
+
11
+ from typing import cast
12
+
13
+ from alembic.ddl.impl import DefaultImpl
14
+ from sqlalchemy import Float, ForeignKeyConstraint, Integer, Numeric, String, Table, Text
15
+ from sqlalchemy.types import TypeEngine
16
+
17
+ from piloto_ai_cli.schema.migration_filters import is_cli_schema
18
+
19
+ SNOWFLAKE_DIALECT = "snowflake"
20
+ SNOWFLAKE_MAX_VARCHAR = 16_777_216
21
+
22
+
23
+ ForeignKeyKey = tuple[str, tuple[str, ...], str, tuple[str, ...], str | None, str | None, str]
24
+
25
+
26
+ def _referential_action(action: str | None) -> str | None:
27
+ """Normalise an ON DELETE/UPDATE action the way Alembic's signature does."""
28
+ if not action or action.lower() == "no action":
29
+ return None
30
+ return action.lower()
31
+
32
+
33
+ def _deferrability(constraint: ForeignKeyConstraint) -> str:
34
+ """Alembic's three-state value for ``deferrable`` and ``initially``."""
35
+ if constraint.initially and constraint.initially.lower() == "deferred":
36
+ return "initially_deferrable"
37
+ return "deferrable" if constraint.deferrable else "not deferrable"
38
+
39
+
40
+ def _foreign_key_key(constraint: ForeignKeyConstraint) -> ForeignKeyKey:
41
+ """Everything Alembic compares on a foreign key except the two schemas."""
42
+ parent = cast(Table, constraint.parent)
43
+ return (
44
+ parent.name,
45
+ tuple(column.name for column in constraint.columns),
46
+ constraint.elements[0].column.table.name,
47
+ tuple(element.column.name for element in constraint.elements),
48
+ _referential_action(constraint.ondelete),
49
+ _referential_action(constraint.onupdate),
50
+ _deferrability(constraint),
51
+ )
52
+
53
+
54
+ def drop_default_schema_fk_matches(
55
+ conn_fks: set[ForeignKeyConstraint],
56
+ metadata_fks: set[ForeignKeyConstraint],
57
+ ) -> None:
58
+ """Drop foreign-key pairs that differ only because ``cli`` is the default schema.
59
+
60
+ With ``cli`` as the connection's default schema, Snowflake reflects a
61
+ table and the target of its foreign keys with no schema, while the models
62
+ name ``cli``. Alembic matches the tables across that gap but not the
63
+ foreign keys, so each would show up as removed and added again. A pair
64
+ that matches on everything else is the same constraint, so both sides are
65
+ dropped from the comparison. The models keep their schema, so generated
66
+ revisions stay qualified with ``cli``.
67
+ """
68
+ metadata_by_key: dict[ForeignKeyKey, ForeignKeyConstraint] = {}
69
+ for constraint in metadata_fks:
70
+ parent = cast(Table, constraint.parent)
71
+ target = constraint.elements[0].column.table
72
+ if is_cli_schema(parent.schema) and is_cli_schema(target.schema):
73
+ metadata_by_key[_foreign_key_key(constraint)] = constraint
74
+ for constraint in list(conn_fks):
75
+ parent = cast(Table, constraint.parent)
76
+ if parent.schema is not None or constraint.elements[0].column.table.schema is not None:
77
+ continue
78
+ match = metadata_by_key.pop(_foreign_key_key(constraint), None)
79
+ if match is not None:
80
+ conn_fks.discard(constraint)
81
+ metadata_fks.discard(match)
82
+
83
+
84
+ def snowflake_compare_type(
85
+ context: object,
86
+ inspected_column: object,
87
+ metadata_column: object,
88
+ inspected_type: TypeEngine[object],
89
+ metadata_type: TypeEngine[object],
90
+ ) -> bool | None:
91
+ """Treat Snowflake's reflected aliases of ``Integer`` and ``Text`` as equal.
92
+
93
+ Snowflake stores INT as NUMBER(38, 0) and reflects it as a Numeric type,
94
+ which Alembic's default comparison reports as a type change on every
95
+ Integer column. Only that exact type is equal: a narrower NUMBER(p, 0)
96
+ still reports a change. Likewise TEXT is stored as VARCHAR(16777216), the
97
+ maximum length, and only that length (or none) equals ``Text``. Returning
98
+ ``None`` keeps the default comparison.
99
+ """
100
+ if (
101
+ isinstance(metadata_type, Text)
102
+ and type(inspected_type) is not Text
103
+ and isinstance(inspected_type, String)
104
+ and inspected_type.length in {None, SNOWFLAKE_MAX_VARCHAR}
105
+ ):
106
+ return False
107
+ if (
108
+ isinstance(metadata_type, Integer)
109
+ and isinstance(inspected_type, Numeric)
110
+ and not isinstance(inspected_type, Float)
111
+ and inspected_type.precision == 38
112
+ and inspected_type.scale == 0
113
+ ):
114
+ return False
115
+ return None
116
+
117
+
118
+ class SnowflakeImpl(DefaultImpl):
119
+ """Alembic's implementation for the ``snowflake`` dialect only."""
120
+
121
+ __dialect__ = SNOWFLAKE_DIALECT
122
+ transactional_ddl = False
123
+
124
+ def correct_for_autogen_foreignkeys(
125
+ self,
126
+ conn_fks: set[ForeignKeyConstraint],
127
+ metadata_fks: set[ForeignKeyConstraint],
128
+ ) -> None:
129
+ drop_default_schema_fk_matches(conn_fks, metadata_fks)
130
+
131
+
132
+ def compare_type_for(dialect_name: str) -> object:
133
+ """The ``compare_type`` option for a dialect: Snowflake's, or Alembic's default."""
134
+ return snowflake_compare_type if dialect_name == SNOWFLAKE_DIALECT else True
@@ -0,0 +1,82 @@
1
+ """Typed builder for the Perú Compras search and download form."""
2
+
3
+ import json
4
+ from collections.abc import Mapping, Sequence
5
+ from dataclasses import dataclass, field
6
+
7
+ from piloto_ai_cli.schema import STRUCTURAL_FIELDS
8
+
9
+ type ScopeValue = str | Sequence[str]
10
+ type ServerFilterValues = Sequence[Sequence[str]]
11
+
12
+ _SERVER_FILTER_FIELDS = (*STRUCTURAL_FIELDS, "feature")
13
+
14
+
15
+ def _json_array(values: Sequence[object]) -> str:
16
+ return json.dumps(values, ensure_ascii=False, separators=(",", ":"))
17
+
18
+
19
+ def _scope_values(value: ScopeValue | None) -> list[str]:
20
+ if value is None or value == "":
21
+ return []
22
+ if isinstance(value, str):
23
+ return [value]
24
+ return list(value)
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class SearchForm:
29
+ """Search criteria and state echoed by the site's form."""
30
+
31
+ scope: Mapping[str, ScopeValue] = field(default_factory=dict)
32
+ features: Sequence[str] = ()
33
+ server_filters: Mapping[str, ServerFilterValues] = field(default_factory=dict)
34
+ search_text: str = ""
35
+ search_text_previous: str = ""
36
+ sort_field: str = ""
37
+ sort_direction: str = ""
38
+ product_status: str = ""
39
+ download_id: str = ""
40
+ pagination_page: str = ""
41
+ pagination_left_most_page: str = ""
42
+ pagination_paging: int = 0
43
+ is_new_search: bool = False
44
+ is_download: bool = False
45
+
46
+ def to_form(self, *, antiforgery_token: str) -> dict[str, str]:
47
+ """Build every form field, including empty fields required by the site."""
48
+ unknown_scope = set(self.scope) - set(STRUCTURAL_FIELDS)
49
+ if unknown_scope:
50
+ raise ValueError(f"unknown structural scope fields: {sorted(unknown_scope)}")
51
+ unknown_server_filters = set(self.server_filters) - set(_SERVER_FILTER_FIELDS)
52
+ if unknown_server_filters:
53
+ raise ValueError(f"unknown server filter fields: {sorted(unknown_server_filters)}")
54
+
55
+ form = {
56
+ "__RequestVerificationToken": antiforgery_token,
57
+ **{
58
+ f"ClientFilter.{name.capitalize()}": _json_array(
59
+ _scope_values(self.scope.get(name))
60
+ )
61
+ for name in STRUCTURAL_FIELDS
62
+ },
63
+ "ClientFilter.Feature": _json_array(self.features),
64
+ **{
65
+ f"ServerFilter.{name.capitalize()}": _json_array(self.server_filters.get(name, ()))
66
+ for name in _SERVER_FILTER_FIELDS
67
+ },
68
+ "IsNewSearch": str(self.is_new_search),
69
+ "Pagination.Paging": str(self.pagination_paging),
70
+ "Status": "VIGENTE",
71
+ "From": "Result",
72
+ "IsDownload": str(self.is_download),
73
+ "SearchText": self.search_text,
74
+ "SearchTextPrevious": self.search_text_previous,
75
+ "SortField": self.sort_field,
76
+ "SortDirection": self.sort_direction,
77
+ "ProductStatus": self.product_status,
78
+ "DownloadId": self.download_id,
79
+ "Pagination.Page": self.pagination_page,
80
+ "Pagination.LeftMostPage": self.pagination_left_most_page,
81
+ }
82
+ return form
@@ -0,0 +1,174 @@
1
+ """Application settings loaded from environment variables and an optional .env file."""
2
+
3
+ import os
4
+ import re
5
+ from decimal import Decimal
6
+ from importlib.metadata import PackageNotFoundError, version
7
+ from pathlib import Path
8
+ from typing import Any, Literal
9
+
10
+ from pydantic import Field, SecretStr, field_validator, model_validator
11
+ from pydantic_settings import BaseSettings, SettingsConfigDict
12
+
13
+ from piloto_ai_cli import DISTRIBUTION_NAME
14
+
15
+ MAX_PAGES_IN_FLIGHT = 20
16
+ SPCS_SESSION_TOKEN_PATH = Path("/snowflake/session/token")
17
+ # A bare host name. Snowflake account URLs may contain underscores
18
+ # (``<org>-<account_name>.snowflakecomputing.com``), so they are allowed.
19
+ SNOWFLAKE_HOST_RE = re.compile(r"\A[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?\Z")
20
+ PAYLOAD_STAGE_RE = re.compile(r"\A@[A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*){0,2}\Z")
21
+
22
+
23
+ def _package_version() -> str:
24
+ try:
25
+ return version(DISTRIBUTION_NAME)
26
+ except PackageNotFoundError:
27
+ return "0.0.0+unknown"
28
+
29
+
30
+ def _default_http_user_agent() -> str:
31
+ return (
32
+ f"{DISTRIBUTION_NAME}/{_package_version()} "
33
+ "(+https://github.com/GrupoJaedmik-PeruCompras/piloto-ai-cli/issues)"
34
+ )
35
+
36
+
37
+ class Settings(BaseSettings):
38
+ """Configuration for database, extraction, limits, and HTTP identity."""
39
+
40
+ model_config = SettingsConfigDict(
41
+ env_prefix="PILOTO_",
42
+ env_file=".env",
43
+ env_file_encoding="utf-8",
44
+ extra="ignore",
45
+ hide_input_in_errors=True,
46
+ )
47
+
48
+ profile: Literal["pilot", "ci-mock"] = "pilot"
49
+ database_url: SecretStr | None = None
50
+ payload_store_path: Path = Path(".piloto-ai/payloads")
51
+ payload_stage: str | None = Field(default=None, pattern=PAYLOAD_STAGE_RE)
52
+ llm_provider: Literal["anthropic", "snowflake", "mock"] = "anthropic"
53
+ llm_model: str = "claude-sonnet-4-5"
54
+ llm_prompt_version: str = "v2"
55
+ # anthropic: the Claude API key. snowflake with pat auth: a Snowflake PAT.
56
+ llm_api_key: SecretStr | None = None
57
+ # Snowflake Cortex (llm_provider "snowflake"): inside SPCS the service's
58
+ # session token (re-read from llm_snowflake_token_path on every request);
59
+ # elsewhere a PAT in llm_api_key. When unset with spcs_oauth, the host falls
60
+ # back to the SNOWFLAKE_HOST variable SPCS sets in every container (process environment
61
+ # only, read after every other source so it never overrides an explicit
62
+ # PILOTO_LLM_SNOWFLAKE_HOST, wherever that is set).
63
+ llm_snowflake_auth: Literal["spcs_oauth", "pat"] = "spcs_oauth"
64
+ llm_snowflake_host: str | None = None
65
+ llm_snowflake_token_path: Path = SPCS_SESSION_TOKEN_PATH
66
+ # USD per million tokens for llm_model; unset means extraction cost is not recorded.
67
+ llm_input_usd_per_mtok: Decimal | None = Field(default=None, ge=0)
68
+ llm_output_usd_per_mtok: Decimal | None = Field(default=None, ge=0)
69
+ confidence_threshold: float = Field(default=0.8, ge=0, le=1)
70
+ max_items: int = Field(default=100, gt=0)
71
+ http_user_agent: str = Field(default_factory=_default_http_user_agent)
72
+ per_call_in_flight_limit: int = Field(default=5, gt=0, le=MAX_PAGES_IN_FLIGHT)
73
+ http_connect_timeout_seconds: float = Field(default=10.0, gt=0)
74
+ http_read_timeout_seconds: float = Field(default=30.0, gt=0)
75
+ http_excel_read_timeout_seconds: float = Field(default=240.0, gt=0)
76
+ llm_timeout_seconds: float = Field(default=120.0, gt=0)
77
+ # Enrichment retry backoff: a ficha whose enrichment failed is retried
78
+ # after base * 2 ** (failures - 1), capped; a new site stamp resets it.
79
+ enrichment_retry_base_seconds: float = Field(default=900.0, gt=0)
80
+ enrichment_retry_cap_seconds: float = Field(default=86_400.0, gt=0)
81
+ # Part-number lookup retry backoff (card recovery): a ficha whose lookup
82
+ # failed at the site (any error status, the error page, an undecodable
83
+ # answer, its own card unparseable, a transport error) or whose card could
84
+ # not be stored is looked up again after
85
+ # base * 2 ** (failures - 1), capped; a new site stamp resets it.
86
+ card_lookup_retry_base_seconds: float = Field(default=900.0, gt=0)
87
+ card_lookup_retry_cap_seconds: float = Field(default=86_400.0, gt=0)
88
+
89
+ @field_validator("http_user_agent")
90
+ @classmethod
91
+ def require_identifying_user_agent(cls, value: str) -> str:
92
+ value = value.strip()
93
+ if not value:
94
+ raise ValueError("http_user_agent cannot be blank")
95
+ if any(ord(char) < 0x20 or ord(char) == 0x7F for char in value):
96
+ raise ValueError("http_user_agent cannot contain control characters")
97
+ lowered = value.lower()
98
+ if "http://" not in lowered and "https://" not in lowered and "@" not in value:
99
+ raise ValueError("http_user_agent must include a contact URL or email address")
100
+ return value
101
+
102
+ @model_validator(mode="before")
103
+ @classmethod
104
+ def apply_ci_mock_defaults(cls, values: Any) -> Any:
105
+ if isinstance(values, dict) and values.get("profile") == "ci-mock":
106
+ values = values.copy()
107
+ values.setdefault("database_url", SecretStr("sqlite:///:memory:"))
108
+ values.setdefault("llm_provider", "mock")
109
+ values.setdefault("llm_model", "mock")
110
+ return values
111
+
112
+ @model_validator(mode="after")
113
+ def require_both_llm_rates(self) -> Settings:
114
+ if (self.llm_input_usd_per_mtok is None) != (self.llm_output_usd_per_mtok is None):
115
+ raise ValueError(
116
+ "set both PILOTO_LLM_INPUT_USD_PER_MTOK and PILOTO_LLM_OUTPUT_USD_PER_MTOK, "
117
+ "or neither"
118
+ )
119
+ return self
120
+
121
+ @model_validator(mode="after")
122
+ def require_retry_cap_at_least_base(self) -> Settings:
123
+ if self.enrichment_retry_cap_seconds < self.enrichment_retry_base_seconds:
124
+ raise ValueError(
125
+ "PILOTO_ENRICHMENT_RETRY_CAP_SECONDS must not be less than "
126
+ "PILOTO_ENRICHMENT_RETRY_BASE_SECONDS"
127
+ )
128
+ if self.card_lookup_retry_cap_seconds < self.card_lookup_retry_base_seconds:
129
+ raise ValueError(
130
+ "PILOTO_CARD_LOOKUP_RETRY_CAP_SECONDS must not be less than "
131
+ "PILOTO_CARD_LOOKUP_RETRY_BASE_SECONDS"
132
+ )
133
+ return self
134
+
135
+ @model_validator(mode="after")
136
+ def require_valid_snowflake_host(self) -> Settings:
137
+ # Only for the snowflake provider: SNOWFLAKE_HOST is a generic variable
138
+ # other tools set too, and must not affect or break other providers.
139
+ if self.llm_provider != "snowflake":
140
+ return self
141
+ # The SPCS fallback only for the SPCS session token: a PAT goes only to a
142
+ # host configured for it, never to whatever a generic variable names.
143
+ if self.llm_snowflake_host is None and self.llm_snowflake_auth == "spcs_oauth":
144
+ self.llm_snowflake_host = os.environ.get("SNOWFLAKE_HOST")
145
+ host = self.llm_snowflake_host
146
+ if host is not None and not SNOWFLAKE_HOST_RE.fullmatch(host):
147
+ raise ValueError(
148
+ "PILOTO_LLM_SNOWFLAKE_HOST (or SNOWFLAKE_HOST) must be a bare host name, "
149
+ "e.g. <org>-<account>.snowflakecomputing.com"
150
+ )
151
+ return self
152
+
153
+ @property
154
+ def llm_needs_api_key(self) -> bool:
155
+ """Whether the configured LLM provider authenticates with ``llm_api_key``."""
156
+ return self.llm_provider == "anthropic" or (
157
+ self.llm_provider == "snowflake" and self.llm_snowflake_auth == "pat"
158
+ )
159
+
160
+ @model_validator(mode="after")
161
+ def require_pilot_credentials(self) -> Settings:
162
+ if self.profile == "pilot":
163
+ missing = []
164
+ if self.database_url is None or not self.database_url.get_secret_value().strip():
165
+ missing.append("PILOTO_DATABASE_URL")
166
+ if self.llm_needs_api_key and (
167
+ self.llm_api_key is None or not self.llm_api_key.get_secret_value().strip()
168
+ ):
169
+ missing.append("PILOTO_LLM_API_KEY")
170
+ if self.llm_provider == "snowflake" and not self.llm_snowflake_host:
171
+ missing.append("PILOTO_LLM_SNOWFLAKE_HOST")
172
+ if missing:
173
+ raise ValueError(f"pilot profile requires {' and '.join(missing)}")
174
+ return self
@@ -0,0 +1,90 @@
1
+ """Build the Snowflake SQLAlchemy URL for the migration workflows.
2
+
3
+ Used by the pull-request migration check (``ci.yml``) and the migration deploy
4
+ (``migrations.yml``). Standard library only, so a workflow can run it with
5
+ ``python -I`` before or without the project's dependencies.
6
+
7
+ Reads ``SNOWFLAKE_PAT``, ``SNOWFLAKE_ACCOUNT``, ``SNOWFLAKE_DATABASE``,
8
+ ``SNOWFLAKE_WAREHOUSE``, ``SNOWFLAKE_USER`` and ``SNOWFLAKE_ROLE``, all required.
9
+ Prints GitHub ``add-mask`` commands for the URL-encoded PAT and the whole URL
10
+ (GitHub masks only a secret's exact value), then appends
11
+ ``PILOTO_DATABASE_URL=<url>`` to the ``GITHUB_ENV`` file.
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ from collections.abc import Mapping
17
+ from urllib.parse import quote, urlencode
18
+
19
+ REQUIRED = (
20
+ "SNOWFLAKE_PAT",
21
+ "SNOWFLAKE_ACCOUNT",
22
+ "SNOWFLAKE_DATABASE",
23
+ "SNOWFLAKE_WAREHOUSE",
24
+ "SNOWFLAKE_USER",
25
+ "SNOWFLAKE_ROLE",
26
+ "GITHUB_ENV",
27
+ )
28
+ SCHEMA = "cli"
29
+
30
+
31
+ class ConfigurationError(Exception):
32
+ """Required configuration is missing."""
33
+
34
+
35
+ def build_url(
36
+ *, pat: str, account: str, database: str, warehouse: str, user: str, role: str
37
+ ) -> str:
38
+ """Return the URL for a PAT-authenticated service user in the ``cli`` schema."""
39
+ query = urlencode(
40
+ {
41
+ "warehouse": warehouse,
42
+ "role": role,
43
+ "authenticator": "programmatic_access_token",
44
+ # The connector reads a PAT from `token`, not from the password.
45
+ "token": pat,
46
+ },
47
+ quote_via=quote,
48
+ )
49
+ return (
50
+ f"snowflake://{quote(user, safe='')}:{quote(pat, safe='')}"
51
+ f"@{quote(account, safe='')}/{quote(database, safe='')}/{SCHEMA}?{query}"
52
+ )
53
+
54
+
55
+ def run(environ: Mapping[str, str]) -> tuple[list[str], str]:
56
+ """Return the mask commands to print and the ``GITHUB_ENV`` line to append."""
57
+ missing = [name for name in REQUIRED if not environ.get(name, "").strip()]
58
+ if missing:
59
+ raise ConfigurationError(f"Missing Snowflake migration configuration: {', '.join(missing)}")
60
+ url = build_url(
61
+ pat=environ["SNOWFLAKE_PAT"],
62
+ account=environ["SNOWFLAKE_ACCOUNT"],
63
+ database=environ["SNOWFLAKE_DATABASE"],
64
+ warehouse=environ["SNOWFLAKE_WAREHOUSE"],
65
+ user=environ["SNOWFLAKE_USER"],
66
+ role=environ["SNOWFLAKE_ROLE"],
67
+ )
68
+ masks = [
69
+ f"::add-mask::{quote(environ['SNOWFLAKE_PAT'], safe='')}",
70
+ f"::add-mask::{url}",
71
+ ]
72
+ return masks, f"PILOTO_DATABASE_URL={url}\n"
73
+
74
+
75
+ def main() -> int:
76
+ try:
77
+ masks, env_line = run(os.environ)
78
+ except ConfigurationError as error:
79
+ print(f"::error::{error}", file=sys.stderr)
80
+ return 1
81
+ # Masks first: the runner must know them before the URL can reach a log.
82
+ for mask in masks:
83
+ print(mask, flush=True)
84
+ with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as github_env:
85
+ github_env.write(env_line)
86
+ return 0
87
+
88
+
89
+ if __name__ == "__main__":
90
+ raise SystemExit(main())
@@ -0,0 +1,53 @@
1
+ """Read the site's catalog stamp and refresh the agreement listing."""
2
+
3
+ from collections.abc import Callable
4
+ from datetime import UTC, datetime
5
+
6
+ from sqlalchemy.orm import Session
7
+
8
+ from piloto_ai_cli.connectors import get_home
9
+ from piloto_ai_cli.database import upsert
10
+ from piloto_ai_cli.http_client import HttpClient
11
+ from piloto_ai_cli.parsers import parse_home
12
+ from piloto_ai_cli.schema.models import Agreement
13
+
14
+
15
+ class StampService:
16
+ """Read the home-page stamp and upsert the agreements shown there."""
17
+
18
+ def __init__(
19
+ self,
20
+ session: Session,
21
+ client: HttpClient,
22
+ *,
23
+ now: Callable[[], datetime] | None = None,
24
+ ) -> None:
25
+ self._session = session
26
+ self._client = client
27
+ self._now = now or (lambda: datetime.now(UTC))
28
+
29
+ async def read(self) -> datetime:
30
+ """Fetch the home page, refresh its agreements, and return its site stamp."""
31
+ response = await get_home(self._client)
32
+ home = parse_home(response.text)
33
+ request_id = response.extensions["request_id"]
34
+ seen_at = self._now()
35
+ upsert(
36
+ self._session,
37
+ Agreement,
38
+ [
39
+ {
40
+ "agreement_id": agreement.agreement_id,
41
+ "name": agreement.name,
42
+ "status": agreement.status,
43
+ "type": agreement.type,
44
+ "ficha_count": agreement.ficha_count,
45
+ "filter_value": agreement.filter_value,
46
+ "last_request_id": request_id,
47
+ "first_seen_at": seen_at,
48
+ "last_seen_at": seen_at,
49
+ }
50
+ for agreement in home.agreements
51
+ ],
52
+ )
53
+ return home.stamp