atif-sql 0.2.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 (164) hide show
  1. atif_analytics/__init__.py +9 -0
  2. atif_analytics/application/__init__.py +3 -0
  3. atif_analytics/application/analyze.py +158 -0
  4. atif_analytics/application/prompts.py +750 -0
  5. atif_analytics/application/use_cases/__init__.py +3 -0
  6. atif_analytics/application/use_cases/_shared.py +264 -0
  7. atif_analytics/application/use_cases/classify.py +430 -0
  8. atif_analytics/application/use_cases/conflicts.py +448 -0
  9. atif_analytics/application/use_cases/friction.py +634 -0
  10. atif_analytics/application/use_cases/perceived.py +451 -0
  11. atif_analytics/domain/__init__.py +3 -0
  12. atif_analytics/domain/authorship.py +166 -0
  13. atif_analytics/domain/config.py +30 -0
  14. atif_analytics/domain/costs.py +50 -0
  15. atif_analytics/domain/friction.py +117 -0
  16. atif_analytics/domain/layout.py +94 -0
  17. atif_analytics/domain/models.py +385 -0
  18. atif_analytics/domain/ports.py +100 -0
  19. atif_analytics/domain/transcript.py +359 -0
  20. atif_analytics/infrastructure/__init__.py +3 -0
  21. atif_analytics/infrastructure/corpus_reader.py +546 -0
  22. atif_analytics/infrastructure/parquet_cache.py +186 -0
  23. atif_analytics/infrastructure/settings.py +114 -0
  24. atif_analytics/infrastructure/sqlite_state/__init__.py +3 -0
  25. atif_analytics/infrastructure/sqlite_state/checkpointer.py +326 -0
  26. atif_analytics/infrastructure/sqlite_state/retry_queue.py +296 -0
  27. atif_analytics/py.typed +0 -0
  28. atif_cli/__init__.py +3 -0
  29. atif_cli/__main__.py +8 -0
  30. atif_cli/app.py +2459 -0
  31. atif_cli/converter_adapter.py +151 -0
  32. atif_cli/corpus.py +409 -0
  33. atif_cli/cron.py +311 -0
  34. atif_cli/duck_errors.py +97 -0
  35. atif_cli/embed_lake.py +101 -0
  36. atif_cli/errors.py +89 -0
  37. atif_cli/lake.py +373 -0
  38. atif_cli/lake_sessions.py +270 -0
  39. atif_cli/output.py +297 -0
  40. atif_cli/py.typed +0 -0
  41. atif_converter/__init__.py +3 -0
  42. atif_converter/application/__init__.py +3 -0
  43. atif_converter/application/convert_and_audit.py +294 -0
  44. atif_converter/application/convert_codex.py +210 -0
  45. atif_converter/domain/__init__.py +9 -0
  46. atif_converter/domain/agents.py +40 -0
  47. atif_converter/domain/atif/__init__.py +55 -0
  48. atif_converter/domain/atif/agent.py +37 -0
  49. atif_converter/domain/atif/content.py +161 -0
  50. atif_converter/domain/atif/final_metrics.py +45 -0
  51. atif_converter/domain/atif/metrics.py +49 -0
  52. atif_converter/domain/atif/observation.py +21 -0
  53. atif_converter/domain/atif/observation_result.py +47 -0
  54. atif_converter/domain/atif/step.py +144 -0
  55. atif_converter/domain/atif/subagent_trajectory_ref.py +90 -0
  56. atif_converter/domain/atif/tool_call.py +36 -0
  57. atif_converter/domain/atif/trajectory.py +211 -0
  58. atif_converter/domain/atif/trajectory_validator.py +299 -0
  59. atif_converter/domain/blobs.py +510 -0
  60. atif_converter/domain/claude_code_conversion.py +1077 -0
  61. atif_converter/domain/codex_conversion.py +1036 -0
  62. atif_converter/domain/codex_edges.py +192 -0
  63. atif_converter/domain/codex_enrichment.py +419 -0
  64. atif_converter/domain/codex_fidelity.py +124 -0
  65. atif_converter/domain/codex_nested_calls.py +165 -0
  66. atif_converter/domain/edges.py +113 -0
  67. atif_converter/domain/enrichment.py +412 -0
  68. atif_converter/domain/errors.py +60 -0
  69. atif_converter/domain/fidelity.py +171 -0
  70. atif_converter/domain/model_prices.json +8538 -0
  71. atif_converter/domain/pricing.py +790 -0
  72. atif_converter/domain/result_signals.py +774 -0
  73. atif_converter/domain/schema_version.py +90 -0
  74. atif_converter/domain/session_events.py +408 -0
  75. atif_converter/infrastructure/__init__.py +3 -0
  76. atif_converter/infrastructure/census.py +89 -0
  77. atif_converter/infrastructure/claude_code_converter.py +127 -0
  78. atif_converter/infrastructure/codex_adapter.py +132 -0
  79. atif_converter/infrastructure/codex_census.py +100 -0
  80. atif_converter/infrastructure/codex_converter.py +82 -0
  81. atif_converter/infrastructure/harbor_adapter.py +187 -0
  82. atif_converter/infrastructure/raw_records.py +426 -0
  83. atif_converter/infrastructure/source_archive.py +154 -0
  84. atif_converter/py.typed +0 -0
  85. atif_corpus/__init__.py +13 -0
  86. atif_corpus/application/__init__.py +7 -0
  87. atif_corpus/application/materialize.py +1826 -0
  88. atif_corpus/domain/__init__.py +9 -0
  89. atif_corpus/domain/agents.py +33 -0
  90. atif_corpus/domain/generation.py +34 -0
  91. atif_corpus/domain/layout.py +168 -0
  92. atif_corpus/domain/ports.py +175 -0
  93. atif_corpus/domain/session_id.py +68 -0
  94. atif_corpus/domain/sessions.py +228 -0
  95. atif_corpus/domain/slug.py +72 -0
  96. atif_corpus/domain/source_layout.py +143 -0
  97. atif_corpus/domain/watermark.py +76 -0
  98. atif_corpus/infrastructure/__init__.py +7 -0
  99. atif_corpus/infrastructure/atomic.py +266 -0
  100. atif_corpus/infrastructure/compress_artifacts.py +161 -0
  101. atif_corpus/infrastructure/fake_converter.py +174 -0
  102. atif_corpus/infrastructure/scanner.py +316 -0
  103. atif_corpus/infrastructure/settings.py +130 -0
  104. atif_corpus/infrastructure/source_archive.py +202 -0
  105. atif_corpus/py.typed +0 -0
  106. atif_duck/__init__.py +43 -0
  107. atif_duck/domain/__init__.py +32 -0
  108. atif_duck/domain/artifacts.py +66 -0
  109. atif_duck/domain/authorship.py +165 -0
  110. atif_duck/domain/catalog.py +626 -0
  111. atif_duck/domain/columnar.py +149 -0
  112. atif_duck/domain/embedding_guard.py +88 -0
  113. atif_duck/domain/examples.py +265 -0
  114. atif_duck/domain/lake.py +427 -0
  115. atif_duck/domain/lake_sessions.py +97 -0
  116. atif_duck/domain/raw_readers.py +140 -0
  117. atif_duck/domain/session_id.py +69 -0
  118. atif_duck/domain/sql_literal.py +50 -0
  119. atif_duck/infrastructure/__init__.py +34 -0
  120. atif_duck/infrastructure/analytics.py +469 -0
  121. atif_duck/infrastructure/authorship.py +139 -0
  122. atif_duck/infrastructure/columnar.py +641 -0
  123. atif_duck/infrastructure/lake.py +1383 -0
  124. atif_duck/infrastructure/lake_sessions.py +194 -0
  125. atif_duck/infrastructure/lake_settings.py +63 -0
  126. atif_duck/infrastructure/lake_steps.py +225 -0
  127. atif_duck/infrastructure/projections.py +221 -0
  128. atif_duck/infrastructure/registry.py +2194 -0
  129. atif_duck/infrastructure/stored_artifacts.py +115 -0
  130. atif_duck/py.typed +0 -0
  131. atif_embed/__init__.py +12 -0
  132. atif_embed/application/__init__.py +3 -0
  133. atif_embed/application/embed.py +293 -0
  134. atif_embed/application/prune.py +80 -0
  135. atif_embed/domain/__init__.py +3 -0
  136. atif_embed/domain/discovery.py +70 -0
  137. atif_embed/domain/embedding_guard.py +83 -0
  138. atif_embed/domain/errors.py +94 -0
  139. atif_embed/domain/ports.py +223 -0
  140. atif_embed/domain/sql_literal.py +49 -0
  141. atif_embed/domain/text_stamp.py +71 -0
  142. atif_embed/infrastructure/__init__.py +3 -0
  143. atif_embed/infrastructure/cohere_bedrock.py +433 -0
  144. atif_embed/infrastructure/corpus_text_rows.py +273 -0
  145. atif_embed/infrastructure/gemma_local.py +355 -0
  146. atif_embed/infrastructure/lake_text_rows.py +203 -0
  147. atif_embed/infrastructure/lance_store.py +440 -0
  148. atif_embed/infrastructure/providers.py +30 -0
  149. atif_embed/infrastructure/settings.py +154 -0
  150. atif_embed/py.typed +0 -0
  151. atif_models/__init__.py +14 -0
  152. atif_models/domain/__init__.py +9 -0
  153. atif_models/domain/ports.py +143 -0
  154. atif_models/domain/registry.py +151 -0
  155. atif_models/domain/schema.py +109 -0
  156. atif_models/infrastructure/__init__.py +8 -0
  157. atif_models/infrastructure/openai_bedrock.py +314 -0
  158. atif_models/infrastructure/settings.py +85 -0
  159. atif_models/py.typed +0 -0
  160. atif_sql-0.2.0.dist-info/METADATA +272 -0
  161. atif_sql-0.2.0.dist-info/RECORD +164 -0
  162. atif_sql-0.2.0.dist-info/WHEEL +4 -0
  163. atif_sql-0.2.0.dist-info/entry_points.txt +2 -0
  164. atif_sql-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,314 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+
3
+ """OpenAI GPT-5.6 structured-output adapter on bedrock-runtime (the default).
4
+
5
+ Implements :class:`atif_models.domain.ports.LlmStructuredProvider` with the
6
+ OpenAI chat-completions body shape on ``invoke_model``:
7
+
8
+ .. code-block:: json
9
+
10
+ {"messages": [{"role": "system", ...}, {"role": "user", ...}],
11
+ "max_completion_tokens": 32000,
12
+ "reasoning_effort": "high",
13
+ "response_format": {"type": "json_schema",
14
+ "json_schema": {"name": ..., "strict": true, "schema": ...}}}
15
+
16
+ Retry policy: tenacity owns the semantic loop (10 attempts, exponential
17
+ 2..60s) over :data:`RETRY_CODES` + network errors; botocore's own retries
18
+ are OFF (``max_attempts=0``) so tenacity sees every error immediately. The
19
+ blocking ``invoke_model`` call is dispatched via ``anyio.to_thread`` under
20
+ an ``anyio.CapacityLimiter`` so cancellation scopes propagate.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import threading
27
+ from typing import Any
28
+
29
+ import anyio
30
+ import anyio.to_thread
31
+ import boto3
32
+ from botocore.config import Config as BotoConfig
33
+ from botocore.exceptions import (
34
+ ClientError,
35
+ ConnectionError as BotoConnectionError,
36
+ EndpointConnectionError,
37
+ ReadTimeoutError,
38
+ SSLError,
39
+ )
40
+ from loguru import logger
41
+ from pydantic import ValidationError
42
+ from tenacity import (
43
+ retry,
44
+ retry_if_exception,
45
+ stop_after_attempt,
46
+ wait_exponential,
47
+ )
48
+
49
+ from atif_models.domain.ports import (
50
+ CallUsage,
51
+ ProviderUnavailable,
52
+ RefusalError,
53
+ SchemaT,
54
+ UsageAccumulator,
55
+ )
56
+ from atif_models.domain.registry import ModelSpec
57
+ from atif_models.domain.schema import to_openai_strict
58
+
59
+ #: Bedrock error codes worth retrying. TWIN of
60
+ #: ``atif_embed.infrastructure.cohere_bedrock.RETRY_CODES`` — the two
61
+ #: packages may not import each other (independence contract), so each pins
62
+ #: this set against the same literal in its own test suite.
63
+ RETRY_CODES: frozenset[str] = frozenset(
64
+ {
65
+ "ThrottlingException",
66
+ "ServiceUnavailableException",
67
+ "ModelTimeoutException",
68
+ "ModelErrorException",
69
+ "ProvisionedThroughputExceededException",
70
+ "TooManyRequestsException",
71
+ "InternalServerException",
72
+ "InternalFailure",
73
+ }
74
+ )
75
+
76
+ #: finish_reason values that mean "the model declined" (terminal).
77
+ _REFUSAL_FINISH_REASONS = {"content_filter", "refusal"}
78
+
79
+ #: One-step reasoning_effort degradation ladder for the finish_reason=length
80
+ #: retry. Truncation is DETERMINISTIC for a fixed (prompt, parameters) pair —
81
+ #: resending the same request would truncate identically and just double the
82
+ #: bill — so the single retry changes a parameter: less reasoning leaves more
83
+ #: of the completion budget for the answer. Efforts at "low" or below don't
84
+ #: retry (nothing left to degrade to).
85
+ _EFFORT_DEGRADE: dict[str, str] = {
86
+ "max": "xhigh",
87
+ "xhigh": "high",
88
+ "high": "medium",
89
+ "medium": "low",
90
+ }
91
+
92
+
93
+ class _LengthTruncation(ProviderUnavailable):
94
+ """Internal marker for ``finish_reason=length``.
95
+
96
+ Callers only ever see :class:`ProviderUnavailable`;
97
+ :meth:`OpenAiBedrockProvider.classify_structured` catches this one to run
98
+ the one-shot effort-degrade retry.
99
+ """
100
+
101
+
102
+ def _is_retryable(exc: BaseException) -> bool:
103
+ """True for throttle/service ``ClientError`` codes + network errors."""
104
+ if isinstance(exc, SSLError | BotoConnectionError | EndpointConnectionError | ReadTimeoutError):
105
+ return True
106
+ if not isinstance(exc, ClientError):
107
+ return False
108
+ code = exc.response.get("Error", {}).get("Code")
109
+ return code in RETRY_CODES
110
+
111
+
112
+ def _log_before_sleep(retry_state: Any) -> None:
113
+ """Log one WARNING per backoff (loguru — stdlib logging is banned)."""
114
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
115
+ logger.warning(
116
+ "bedrock invoke retry {}/10 in {:.1f}s after {}: {}",
117
+ retry_state.attempt_number,
118
+ getattr(retry_state.next_action, "sleep", 0.0),
119
+ type(exc).__name__ if exc else "?",
120
+ exc,
121
+ )
122
+
123
+
124
+ def extract_usage(payload: dict[str, Any]) -> CallUsage:
125
+ """Pull :class:`CallUsage` out of one chat-completions response.
126
+
127
+ GPT-5.6 on Bedrock reports ``usage.prompt_tokens`` /
128
+ ``usage.completion_tokens`` plus ``completion_tokens_details.reasoning_tokens``
129
+ and ``prompt_tokens_details.cached_tokens``. Missing fields default to 0.
130
+ """
131
+ usage = payload.get("usage") or {}
132
+ completion_details = usage.get("completion_tokens_details") or {}
133
+ prompt_details = usage.get("prompt_tokens_details") or {}
134
+ return CallUsage(
135
+ input_tokens=int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0),
136
+ output_tokens=int(usage.get("completion_tokens") or usage.get("output_tokens") or 0),
137
+ reasoning_tokens=int(completion_details.get("reasoning_tokens") or 0),
138
+ cached_tokens=int(prompt_details.get("cached_tokens") or 0),
139
+ )
140
+
141
+
142
+ class OpenAiBedrockProvider:
143
+ """The default :class:`~atif_models.domain.ports.LlmStructuredProvider`.
144
+
145
+ Everything provider-specific is fixed at construction: the resolved
146
+ :class:`~atif_models.domain.registry.ModelSpec`, the AWS region, the
147
+ concurrency ceiling, and (optionally) a shared per-pipeline
148
+ :class:`~atif_models.domain.ports.UsageAccumulator`.
149
+ """
150
+
151
+ def __init__(
152
+ self,
153
+ spec: ModelSpec,
154
+ *,
155
+ region: str,
156
+ concurrency: int = 16,
157
+ usage: UsageAccumulator | None = None,
158
+ ) -> None:
159
+ self._spec = spec
160
+ self._region = region
161
+ self._limiter = anyio.CapacityLimiter(concurrency)
162
+ self.usage = usage if usage is not None else UsageAccumulator()
163
+ self._client_lock = threading.Lock()
164
+ self._client: Any = None
165
+ self._pool_size = max(32, concurrency * 2)
166
+
167
+ @property
168
+ def provider(self) -> str:
169
+ """Stable provider tag for logs and store stamps."""
170
+ return "openai-bedrock"
171
+
172
+ @property
173
+ def spec(self) -> ModelSpec:
174
+ """The resolved model spec this adapter is bound to."""
175
+ return self._spec
176
+
177
+ def _get_client(self) -> Any:
178
+ """Lazily build one shared thread-safe ``bedrock-runtime`` client.
179
+
180
+ botocore retries are OFF (``max_attempts=0``) — the tenacity
181
+ decorator on :meth:`_invoke_sync` owns the retry policy. Pool
182
+ sized to 2× concurrency with a floor of 32; ``read_timeout=600``
183
+ because high reasoning effort can hold the connection well past
184
+ botocore's 60s default.
185
+ """
186
+ with self._client_lock:
187
+ if self._client is None:
188
+ boto_cfg = BotoConfig(
189
+ region_name=self._region,
190
+ retries={"max_attempts": 0, "mode": "standard"},
191
+ max_pool_connections=self._pool_size,
192
+ connect_timeout=10,
193
+ read_timeout=600,
194
+ )
195
+ self._client = boto3.client("bedrock-runtime", config=boto_cfg)
196
+ return self._client
197
+
198
+ def build_body(self, *, system: str, prompt: str, schema: type[SchemaT]) -> dict[str, Any]:
199
+ """Return the exact ``invoke_model`` body for one call (pure; unit-testable)."""
200
+ return {
201
+ "messages": [
202
+ {"role": "system", "content": system},
203
+ {"role": "user", "content": prompt},
204
+ ],
205
+ "max_completion_tokens": self._spec.max_completion_tokens,
206
+ "reasoning_effort": self._spec.reasoning_effort,
207
+ "response_format": {
208
+ "type": "json_schema",
209
+ "json_schema": {
210
+ "name": schema.__name__,
211
+ "strict": True,
212
+ "schema": to_openai_strict(schema),
213
+ },
214
+ },
215
+ }
216
+
217
+ async def classify_structured(
218
+ self, *, system: str, prompt: str, schema: type[SchemaT]
219
+ ) -> SchemaT:
220
+ """One structured-output call under the concurrency limiter.
221
+
222
+ ``finish_reason=length`` retries ONCE with ``reasoning_effort``
223
+ degraded one step (high→medium→low): truncation is deterministic
224
+ for a fixed (prompt, parameters) pair, so the second chance must
225
+ change a parameter, not resend. Still-truncated (or already at the
226
+ floor) raises :class:`ProviderUnavailable` for the retry queue.
227
+ """
228
+ body = self.build_body(system=system, prompt=prompt, schema=schema)
229
+ async with self._limiter:
230
+ payload = await anyio.to_thread.run_sync(lambda: self._invoke_sync(body))
231
+ try:
232
+ return self._parse_payload(payload, schema)
233
+ except _LengthTruncation as first:
234
+ degraded = _EFFORT_DEGRADE.get(str(body.get("reasoning_effort")))
235
+ if degraded is None:
236
+ raise ProviderUnavailable(str(first)) from first
237
+ logger.warning(
238
+ "bedrock invoke: finish_reason=length at effort={} — "
239
+ "retrying once at effort={} (deterministic truncation "
240
+ "needs a parameter change, not a resend)",
241
+ body.get("reasoning_effort"),
242
+ degraded,
243
+ )
244
+ retry_body = {**body, "reasoning_effort": degraded}
245
+ payload = await anyio.to_thread.run_sync(lambda: self._invoke_sync(retry_body))
246
+ try:
247
+ return self._parse_payload(payload, schema)
248
+ except _LengthTruncation as second:
249
+ raise ProviderUnavailable(str(second)) from second
250
+
251
+ @retry(
252
+ stop=stop_after_attempt(10),
253
+ wait=wait_exponential(multiplier=2, min=2, max=60),
254
+ retry=retry_if_exception(_is_retryable),
255
+ before_sleep=_log_before_sleep,
256
+ reraise=True,
257
+ )
258
+ def _invoke_sync(self, body: dict[str, Any]) -> dict[str, Any]:
259
+ """One blocking ``invoke_model`` call; returns the parsed JSON payload."""
260
+ client = self._get_client()
261
+ resp = client.invoke_model(
262
+ modelId=self._spec.model_id,
263
+ body=json.dumps(body),
264
+ contentType="application/json",
265
+ accept="application/json",
266
+ )
267
+ return json.loads(resp["body"].read())
268
+
269
+ def _parse_payload(self, payload: dict[str, Any], schema: type[SchemaT]) -> SchemaT:
270
+ """choices[0].message.content → json → ``schema.model_validate``.
271
+
272
+ Usage is accumulated FIRST (even a length-truncated call billed
273
+ tokens), then finish_reason gates: ``length`` →
274
+ :class:`ProviderUnavailable` with a hint, ``content_filter`` /
275
+ ``refusal`` → :class:`RefusalError`.
276
+ """
277
+ self.usage.add(extract_usage(payload))
278
+ choices = payload.get("choices") or []
279
+ if not choices:
280
+ msg = f"no choices in response (keys: {sorted(payload.keys())})"
281
+ raise ProviderUnavailable(msg)
282
+ choice = choices[0]
283
+ finish_reason = choice.get("finish_reason")
284
+ if finish_reason in _REFUSAL_FINISH_REASONS:
285
+ msg = f"model declined the input (finish_reason={finish_reason})"
286
+ raise RefusalError(msg)
287
+ message = choice.get("message") or {}
288
+ if message.get("refusal"):
289
+ msg = f"model refused: {message['refusal']}"
290
+ raise RefusalError(msg)
291
+ if finish_reason == "length":
292
+ msg = (
293
+ "response truncated (finish_reason=length) — raise "
294
+ f"max_completion_tokens (currently {self._spec.max_completion_tokens}), "
295
+ "lower reasoning_effort, or shrink the prompt"
296
+ )
297
+ raise _LengthTruncation(msg)
298
+ content = message.get("content")
299
+ if not isinstance(content, str) or not content:
300
+ msg = f"no message content (finish_reason={finish_reason!r})"
301
+ raise ProviderUnavailable(msg)
302
+ try:
303
+ data = json.loads(content)
304
+ except json.JSONDecodeError as exc:
305
+ msg = f"content is not valid JSON: {exc}"
306
+ raise ProviderUnavailable(msg) from exc
307
+ try:
308
+ return schema.model_validate(data)
309
+ except ValidationError as exc:
310
+ msg = f"strict output failed pydantic validation: {exc}"
311
+ raise ProviderUnavailable(msg) from exc
312
+
313
+
314
+ __all__ = ["RETRY_CODES", "OpenAiBedrockProvider", "extract_usage"]
@@ -0,0 +1,85 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+
3
+ """Env-driven LLM settings for atif-models (CONTRACT-V2 §Model registry).
4
+
5
+ Pydantic v2 ``BaseSettings`` under the workspace-wide ``ATIF_SQL_`` prefix.
6
+ Carries the family/region/concurrency knobs plus the per-pipeline size
7
+ overrides — ``ATIF_SQL_LLM_SIZE_CLASSIFY`` and friends. Reading process env
8
+ is I/O, so this lives in ``infrastructure``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import cast
14
+
15
+ from pydantic import field_validator
16
+ from pydantic_settings import BaseSettings, SettingsConfigDict
17
+
18
+ from atif_models.domain.registry import DEFAULT_FAMILY, Family, ModelSpec, Size, resolve
19
+
20
+ #: Families with a wired provider adapter. The registry knows every family's
21
+ #: model ids, but only these can actually be called: an unwired family
22
+ #: resolves a model id and then sends it the OpenAI chat-completions body
23
+ #: (``response_format`` / ``reasoning_effort``), which is a Bedrock 400 on
24
+ #: every call. Rejecting at settings load turns that into a startup refusal.
25
+ RUNNABLE_FAMILIES: frozenset[Family] = frozenset({"openai"})
26
+
27
+
28
+ class LlmSettings(BaseSettings):
29
+ """Env-driven model selection for the LLM analytics pipelines."""
30
+
31
+ model_config = SettingsConfigDict(
32
+ env_prefix="ATIF_SQL_",
33
+ env_file=".env",
34
+ extra="ignore",
35
+ )
36
+
37
+ llm_family: Family = DEFAULT_FAMILY
38
+ llm_region: str = "us-east-1"
39
+ llm_concurrency: int = 16
40
+
41
+ @field_validator("llm_family")
42
+ @classmethod
43
+ def _family_must_be_runnable(cls, value: Family) -> Family:
44
+ """Refuse a family that has no provider adapter behind it."""
45
+ if value in RUNNABLE_FAMILIES:
46
+ return value
47
+ runnable = ", ".join(sorted(RUNNABLE_FAMILIES))
48
+ msg = (
49
+ f"llm_family={value!r} has no provider adapter, so every pipeline call "
50
+ f"would send an OpenAI chat-completions body to a {value} model id and "
51
+ f"get a Bedrock 400. Runnable families: {runnable}. "
52
+ f"Unset ATIF_SQL_LLM_FAMILY or set it to one of those."
53
+ )
54
+ raise ValueError(msg)
55
+
56
+ # Per-pipeline size assignments (CONTRACT-V2 §Pipeline size assignments):
57
+ # conflicts is the hardest judgment task (sol), friction is a
58
+ # per-message enum (luna). classify moved to luna on 2026-09-27 when its
59
+ # schema shrank to work category + goal; the trajectory pipeline (and its
60
+ # size) left the same day.
61
+ llm_size_classify: Size = "small"
62
+ llm_size_conflicts: Size = "large"
63
+ llm_size_friction: Size = "small"
64
+ # perceived judges user-visible evidence over full transcripts — medium
65
+ # (terra). Env: ATIF_SQL_LLM_SIZE_PERCEIVED.
66
+ llm_size_perceived: Size = "medium"
67
+
68
+ def size_for(self, pipeline: str) -> Size:
69
+ """The configured size alias for ``pipeline``.
70
+
71
+ Pipelines: classify / conflicts / friction / perceived.
72
+ """
73
+ try:
74
+ size = getattr(self, f"llm_size_{pipeline}")
75
+ except AttributeError:
76
+ msg = f"unknown pipeline {pipeline!r} — no llm_size_{pipeline} setting"
77
+ raise KeyError(msg) from None
78
+ return cast("Size", size)
79
+
80
+ def spec_for(self, pipeline: str) -> ModelSpec:
81
+ """Resolve ``pipeline`` to its :class:`~atif_models.domain.registry.ModelSpec`."""
82
+ return resolve(self.size_for(pipeline), self.llm_family)
83
+
84
+
85
+ __all__ = ["LlmSettings"]
atif_models/py.typed ADDED
File without changes
@@ -0,0 +1,272 @@
1
+ Metadata-Version: 2.5
2
+ Name: atif-sql
3
+ Version: 0.2.0
4
+ Summary: ATIF-native analytics over Claude Code agent trajectories: convert, materialize, and query agent sessions with DuckDB.
5
+ Project-URL: Homepage, https://github.com/laithalsaadoon/atif-sql
6
+ Project-URL: Repository, https://github.com/laithalsaadoon/atif-sql
7
+ Project-URL: Issues, https://github.com/laithalsaadoon/atif-sql/issues
8
+ Project-URL: Changelog, https://github.com/laithalsaadoon/atif-sql/blob/main/CHANGELOG.md
9
+ Author: Laith Al-Saadoon
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.13
20
+ Requires-Dist: anyio>=4.11.0
21
+ Requires-Dist: boto3>=1.42.91
22
+ Requires-Dist: cyclopts>=5.1.1
23
+ Requires-Dist: duckdb<2,>=1.5.2
24
+ Requires-Dist: imagesize>=2.0
25
+ Requires-Dist: lancedb<0.40,>=0.30
26
+ Requires-Dist: loguru>=0.7.3
27
+ Requires-Dist: polars>=1.40.0
28
+ Requires-Dist: pyarrow>=23.0.1
29
+ Requires-Dist: pydantic-settings>=2.13.1
30
+ Requires-Dist: pydantic>=2.13.2
31
+ Requires-Dist: pytz>=2024.1
32
+ Requires-Dist: tenacity>=9.1.4
33
+ Requires-Dist: zstandard>=0.25.0
34
+ Provides-Extra: local
35
+ Requires-Dist: pillow>=12.3.0; extra == 'local'
36
+ Requires-Dist: sentence-transformers>=6.1.0; extra == 'local'
37
+ Requires-Dist: torch>=2.14; extra == 'local'
38
+ Requires-Dist: torchvision>=0.29; extra == 'local'
39
+ Requires-Dist: transformers>=5.19.0; extra == 'local'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # atif-sql
43
+
44
+ [![CI](https://github.com/laithalsaadoon/atif-sql/actions/workflows/check.yml/badge.svg?branch=main)](https://github.com/laithalsaadoon/atif-sql/actions/workflows/check.yml)
45
+ [![security](https://github.com/laithalsaadoon/atif-sql/actions/workflows/security.yml/badge.svg?branch=main)](https://github.com/laithalsaadoon/atif-sql/actions/workflows/security.yml)
46
+ [![CodeQL](https://github.com/laithalsaadoon/atif-sql/actions/workflows/codeql.yml/badge.svg?branch=main)](https://github.com/laithalsaadoon/atif-sql/actions/workflows/codeql.yml)
47
+ [![Scorecard](https://github.com/laithalsaadoon/atif-sql/actions/workflows/scorecard.yml/badge.svg?branch=main)](https://github.com/laithalsaadoon/atif-sql/actions/workflows/scorecard.yml)
48
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/laithalsaadoon/atif-sql/badge)](https://scorecard.dev/viewer/?uri=github.com/laithalsaadoon/atif-sql)
49
+ ![Python 3.13+](https://img.shields.io/badge/python-3.13%2B-blue.svg)
50
+ [![License Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
51
+
52
+ ATIF-native analytics over agent trajectories.
53
+
54
+ Claude Code sessions (`~/.claude/projects/**/*.jsonl`) and Codex CLI rollouts
55
+ (`~/.codex/sessions/**/rollout-*.jsonl`) are converted to ATIF (Harbor's Agent
56
+ Trajectory Interchange Format, see the Harbor ATIF RFC: RFC-0001 in
57
+ <https://github.com/laude-institute/harbor>), materialized as a corpus, and
58
+ queried through DuckDB views. Converting once at the boundary (with an
59
+ explicit, tested fidelity policy for what upstream drops) beats re-deriving
60
+ trajectory semantics inside every SQL view. Both agents land in the same views,
61
+ and `sessions.agent` says which one a row came from.
62
+
63
+ ## Install
64
+
65
+ One command, one package, every capability. Conversion, materialization, the DuckDB surface,
66
+ the LLM analytics pipelines, and semantic search are all in the box, and nothing has to be
67
+ installed afterwards to make a command work.
68
+
69
+ ```bash
70
+ uv tool install atif-sql # the CLI on PATH
71
+ uvx atif-sql schema # or run it without installing
72
+ ```
73
+
74
+ To keep semantic search on your own machine, add the one optional extra, `local`. It runs
75
+ Google's EmbeddingGemma 2 for `embed` and `search` in place of Cohere on Bedrock (see
76
+ [Search without sending text off the machine](#search-without-sending-text-off-the-machine)).
77
+ On Linux, `--torch-backend cpu` installs PyTorch's CPU build rather than PyPI's CUDA build and
78
+ its gigabytes of NVIDIA libraries:
79
+
80
+ ```bash
81
+ uv tool install 'atif-sql[local]' --torch-backend cpu
82
+ ```
83
+
84
+ Python 3.13 or newer. The install is substantial and deliberately so, because the analytics and
85
+ vector paths carry `polars`, `pyarrow`, `lancedb`, and `duckdb`. Conversion itself needs none of
86
+ that weight: the ATIF models are vendored from Harbor and step pricing reads a vendored copy of
87
+ litellm's price data, so neither `harbor` nor `litellm` is installed. Prebuilt wheels cover CPython
88
+ 3.13 on manylinux x86_64 and aarch64, macOS arm64, and Windows x86_64. Alpine and other musl targets
89
+ are not supported. [RELEASING.md](RELEASING.md) says how to measure the install.
90
+
91
+ `atif-sql analyze`, `atif-sql embed`, and `atif-sql search` call Amazon Bedrock and cost money.
92
+ `analyze` is a dry run until you pass `--no-dry-run`, `embed` refuses to run without `--limit` or
93
+ `--all` (and `--dry-run` previews it), and `search` embeds one query per call. With
94
+ `ATIF_SQL_EMBED_PROVIDER=gemma`, `embed` and `search` run on this machine instead and cost
95
+ nothing. Nothing else in the tool needs a credential.
96
+
97
+ ## What you can do
98
+
99
+ Start with the question you want to answer or the work you want to keep. Each command links
100
+ to its flags and exit codes in [the CLI reference](docs/reference/cli.md).
101
+
102
+ Analysis, embedding, and text search use Amazon Bedrock. `analyze` previews by default;
103
+ `embed` needs `--dry-run` to preview an explicit scope; `search` charges for a query embedding
104
+ on each successful call. Rows marked **costs money** describe paid execution; embedding and
105
+ search on this machine are free.
106
+
107
+ | Task | Command | Outcome |
108
+ | --- | --- | --- |
109
+ | Keep a history of your Claude Code work | [`atif-sql materialize`](docs/reference/cli.md#materialize) | Saves quiet sessions for later queries and keeps them when source transcripts disappear. Re-runs update changed sessions and those with an older converter generation. |
110
+ | Bring your Codex work into the same analysis workflow | [`atif-sql materialize --agent codex`](docs/reference/cli.md#materialize) | Saves Codex rollouts in a separate corpus with the same query surface as Claude Code. |
111
+ | Inspect or share one conversation as ATIF | [`atif-sql convert <session.jsonl>`](docs/reference/cli.md#convert) | Prints its trajectory and loss report. Add `--trajectory-out` to save the trajectory and adjacent `edges.jsonl` file. |
112
+ | Know whether your recent work is included | [`atif-sql status`](docs/reference/cli.md#status) | Shows corpus freshness, session counts, and what another `materialize` pass would update, without changing data. |
113
+ | Query a large history without rereading every transcript | [`atif-sql lake rebuild`](docs/reference/cli.md#lake-rebuild) | Builds the shared DuckLake query store. Later `materialize` passes keep it current. |
114
+ | Check that query results match your saved conversations | [`atif-sql lake verify`](docs/reference/cli.md#lake-verify) | Compares stored rows with session artifacts and exits 65 if they differ. |
115
+ | Diagnose missing or stale query data | [`atif-sql lake status`](docs/reference/cli.md#lake-status) | Shows whether the lake exists, is current, and contains the expected corpora, plus its last write. |
116
+ | Recover disk space from query storage | [`atif-sql lake compact`](docs/reference/cli.md#lake-compact) | Merges small files, expires old snapshots, and removes unreferenced files while keeping current rows. |
117
+ | Find the fields you need to answer a question | [`atif-sql schema`](docs/reference/cli.md#schema) | Lists columns and macro signatures, tagged by required data: `core`, `analytics`, or `vss`. No corpus needed. |
118
+ | Start with a query that already works | [`atif-sql examples`](docs/reference/cli.md#examples) | Gives tested queries to copy or adapt. Filters select the required data and query type. |
119
+ | Answer your own question about past sessions | [`atif-sql query '<sql>'`](docs/reference/cli.md#query) | Returns a table to read or JSON to pipe into another tool, through a read-only sandboxed connection. |
120
+ | Compare work across Claude Code and Codex | [`atif-sql query --all-corpora 'SELECT agent, count(*) FROM sessions GROUP BY agent'`](docs/reference/cli.md#query) | Counts sessions by agent across all corpora in the lake. Other queries can use `sessions.corpus` to identify each source. Needs the lake. |
121
+ | See which tools your agents rely on most | [`atif-sql query 'SELECT * FROM tool_rank(30) LIMIT 10'`](docs/reference/cli.md#query) | Ranks tool use by call count over the last 30 days. |
122
+ | Estimate the cost of a session | [`atif-sql query 'SELECT * FROM cost_estimate((SELECT session_id FROM sessions LIMIT 1)) LIMIT 10'`](docs/reference/cli.md#query) | Gives a lower-bound USD estimate and priced/unpriced step counts. Unpriced steps and cache-read charges are excluded. Replace the subquery to choose a session. |
123
+ | Find recurring moments when you correct your agents | [`atif-sql query 'SELECT * FROM friction_counts(30) LIMIT 10'`](docs/reference/cli.md#query) | Counts detected friction labels over the last 30 days, after paid analysis has run. |
124
+ | Plan a review of agent interactions before paying | [`atif-sql analyze`](docs/reference/cli.md#analyze) | Previews the work and estimated cost. **Costs money** with `--no-dry-run`, which fills the classifications, conflicts, user friction, and perceived errors views. |
125
+ | Preview how much history to prepare for semantic search | [`atif-sql embed --limit 100 --dry-run`](docs/reference/cli.md#embed) | Previews embedding up to 100 steps. Removing `--dry-run` **costs money** and prepares those steps for search. |
126
+ | Find prior work when you remember the topic, not the words | [`atif-sql search '<text>'`](docs/reference/cli.md#search) | **Costs money** for one query embedding. Finds similar steps with session identifiers and snippets. Needs existing embeddings from `embed`. |
127
+ | Search your sessions without sending text off the machine | [`atif-sql embed --limit 200`](docs/reference/cli.md#embed) | With `ATIF_SQL_EMBED_PROVIDER=gemma` and the `local` extra, embeds 200 steps with EmbeddingGemma 2 on this machine, free, into a store of its own; `search` then reads that store. The first run downloads 1.5 GB. |
128
+ | Find related work across both agent histories | [`atif-sql search --all-corpora '<text>'`](docs/reference/cli.md#search) | **Costs money.** Searches all corpora's embedding stores and identifies each result's corpus. Needs the lake and existing embeddings. |
129
+ | Free space in a corpus from an older version | [`atif-sql corpus slim`](docs/reference/cli.md#corpus-slim) | Previews byte savings. `--no-dry-run` compresses JSON and removes old parquet only after lake verification succeeds. |
130
+ | Keep your history refreshed without remembering each run | [`atif-sql cron install --script <refresh-script>`](docs/reference/cli.md#cron-install) | Prints a schedule to review and install manually. The schedule includes paid embedding and analytics. Obtain `scripts/atif-sql-refresh.sh` from a repo checkout; packaged installs need its explicit path. |
131
+ | Check whether scheduled refreshes ran | [`atif-sql cron status --script <refresh-script>`](docs/reference/cli.md#cron-status) | Shows each lane's last completion, skip, and current lock holder from the refresh script's logs. |
132
+
133
+ ## How the source is organized
134
+
135
+ The directories under `packages/` are internal structure, not separate installs. They
136
+ exist so `import-linter` can enforce the layer and independence contracts at the source level;
137
+ the only thing documented as installable is the `atif-sql` CLI above.
138
+
139
+ | Directory | What |
140
+ | --- | --- |
141
+ | `atif-converter` | Claude Code and Codex CLI transcript → ATIF converters (ours, built on Harbor's ATIF models, vendored) + per-agent fidelity policy (loss accounting per session) |
142
+ | `atif-corpus` | Corpus materialization: discovery, watermarks, quiescence, atomic artifact writes |
143
+ | `atif-duck` | DuckDB views + macros over the materialized corpus (core surface plus the v2 analytics surface) |
144
+ | `atif-models` | Model alias registry + structured-output LLM client; no other package hardcodes a model id |
145
+ | `atif-analytics` | the LLM pipelines `atif-sql analyze` runs: classify, conflicts, friction, and perceived |
146
+ | `atif-embed` | Cohere Embed v4 on Bedrock or EmbeddingGemma 2 on this machine + LanceDB vector store + embedding backfill |
147
+ | `atif-cli` | the composition root, and the source of the `atif-sql` command (see [What you can do](#what-you-can-do)) |
148
+
149
+ ## Quick start
150
+
151
+ Build the corpus from the local transcripts, then query it:
152
+
153
+ ```bash
154
+ atif-sql materialize # discover sessions, convert, write the corpus
155
+ atif-sql lake rebuild # load every corpus into the DuckLake once
156
+ atif-sql status # corpus and lake freshness, read-only
157
+ atif-sql query 'SELECT * FROM sessions LIMIT 5'
158
+ ```
159
+
160
+ The lake lives at `~/.atif-sql/lake/` (`ATIF_SQL_LAKE_ROOT` moves it) and holds every corpus. Without
161
+ one, `query` warns once and reads the per-session files.
162
+
163
+ Each session is stored once. `materialize` writes the ATIF document as `trajectory.json.zst`,
164
+ and `edges.jsonl` and `session_events.jsonl` compressed the same way, beside a plain `meta.json`,
165
+ `loss_report.json`, and the raw source archive. The lake holds the queryable rows, and it loads a
166
+ session from its compressed trajectory. `zstd -dc trajectory.json.zst` prints the plain ATIF
167
+ document. Without a lake, `query --no-lake` still works, but it parses every session's trajectory
168
+ on each run, so it's slow on a large corpus.
169
+
170
+ A corpus written by an earlier version keeps working as it is; `status` counts its sessions under
171
+ `layout`, and `atif-sql corpus slim` converts it.
172
+
173
+ `materialize` converts sessions across a process pool, `min(8, cpu_count)` workers by default.
174
+ `--workers N` (or `ATIF_SQL_MATERIALIZE_WORKERS`) sets the size, and `--workers 1` runs the
175
+ single-process path. The pool doesn't change a byte of output: every worker writes the same
176
+ artifacts through the same per-session staging directory and atomic rename.
177
+
178
+ ### Codex CLI transcripts
179
+
180
+ `convert`, `materialize`, and `status` all take `--agent claude-code|codex`,
181
+ defaulting to `claude-code`. Pick `codex` and both roots move with it: the source
182
+ becomes `$CODEX_HOME` (default `~/.codex`) `/sessions`, and the corpus becomes
183
+ `~/.atif-sql/corpus/codex`. An explicit `--source-root`, `--corpus-root`, or the
184
+ matching `ATIF_SQL_*` env var still wins.
185
+
186
+ ```bash
187
+ atif-sql materialize --agent codex
188
+ atif-sql status --agent codex
189
+ atif-sql query "SELECT agent, count(*) FROM sessions GROUP BY 1"
190
+ ```
191
+
192
+ One corpus holds one agent, so a Codex corpus and a Claude Code corpus stay
193
+ separate directories, and one `query` reads one of them. Pass `--corpus-root` to
194
+ pick which, or `--agent codex` to get the Codex default. `--all-corpora` reads
195
+ every corpus the lake holds at once, and `sessions.corpus` says which one a
196
+ row came from.
197
+
198
+ ### Search without sending text off the machine
199
+
200
+ Set `ATIF_SQL_EMBED_PROVIDER=gemma` and `embed` and `search` use Google's
201
+ [EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2) on this machine: step text
202
+ and queries stay local, and nothing bills an AWS account. It needs the `local` extra (see
203
+ [Install](#install)); in a checkout, `uv sync --all-packages --extra local`.
204
+
205
+ ```bash
206
+ export ATIF_SQL_EMBED_PROVIDER=gemma
207
+ atif-sql embed --limit 200 --dry-run # the plan names the provider, model, width and store
208
+ atif-sql embed --limit 200 # downloads the model on first use, then embeds
209
+ atif-sql search 'the flaky watermark test'
210
+ ```
211
+
212
+ - **The first run downloads about 1.5 GB.** The model goes into the Hugging Face cache once,
213
+ and later runs read it from there; `HF_HUB_OFFLINE=1` keeps every run off the network. Only
214
+ the 270M-parameter text tower loads, in about 4 GB of memory on a CPU.
215
+ - **A CPU embeds about one step a second on a real corpus.** 200 steps of a Claude Code corpus
216
+ took 156 s on a shared 16-core machine: short steps run at about 30 a second, and the few
217
+ long ones (up to the model's 8,192-token window) take most of the time. A CUDA GPU with
218
+ bfloat16 is faster; the lockfile installs PyTorch's CPU build, so install a CUDA torch build
219
+ to use one.
220
+ - **Each provider keeps its own store.** Gemma writes `<corpus_root>/embeddings_lance_gemma`
221
+ beside Cohere's `embeddings_lance`, so switching back and forth never mixes the two vector
222
+ spaces, and `search` reads the store of the provider selected when it runs.
223
+ - **The width is 768 by default.** `ATIF_SQL_OUTPUT_DIMENSION` takes 512, 256, or 128 for a
224
+ smaller store at some cost in ranking quality; a store keeps the width it was written at.
225
+
226
+ Working on `atif-sql` itself is a different setup: a clone, `mise`, and `mise run check` as the
227
+ definition of done. `CONTRIBUTING.md` has it.
228
+
229
+ ## Agent workflow: schema → examples → query
230
+
231
+ ```bash
232
+ atif-sql schema # every view + macro signature (<50 ms)
233
+ atif-sql examples # tested example queries, grouped core/analytics/vss
234
+ atif-sql query 'SELECT * FROM tool_rank(30) LIMIT 10'
235
+ ```
236
+
237
+ `atif-sql examples` (or `atif-sql query --examples`) emits runnable queries
238
+ derived from the catalog, not hardcoded strings, and every one is executed
239
+ by the test suite against a fixture corpus, so the listing cannot rot.
240
+ Piped output is JSON; filter with `--requires core|analytics|vss` and
241
+ `--category view|table-macro|scalar-macro`.
242
+
243
+ ## Contributing
244
+
245
+ Setup, the gates `mise run check` runs, the import-linter contracts you will trip, and the
246
+ Conventional Commit rule the `commit-msg` hook enforces: **[CONTRIBUTING.md](CONTRIBUTING.md)**.
247
+
248
+ Releases are cut by commitizen and published to PyPI over OIDC Trusted Publishing;
249
+ **[RELEASING.md](RELEASING.md)** covers the flow, the versioning model, and the install-weight
250
+ measurements.
251
+
252
+ ## Security
253
+
254
+ Report a vulnerability privately through
255
+ [GitHub's advisory form](https://github.com/laithalsaadoon/atif-sql/security/advisories/new),
256
+ not in a public issue. Supported versions, the disclosure expectations, and what counts as a
257
+ vulnerability in a tool that reads local transcripts are in
258
+ **[SECURITY.md](SECURITY.md)**.
259
+
260
+ `atif-sql query` runs agent-composed SQL, so it runs it in a box: sized to the host before the
261
+ corpus is registered (override with `ATIF_SQL_QUERY_MEMORY_LIMIT` and `ATIF_SQL_QUERY_THREADS`),
262
+ a private spill directory outside the corpus that's removed on exit, no extension installs at
263
+ query time (`atif-sql embed --install-extension` is where the lance extension comes from), file
264
+ facing statements (`COPY`, `EXPORT`, `ATTACH`, `INSTALL`, `LOAD`, `PREPARE`, `EXECUTE`) refused
265
+ before they run, and a refusal to run as root unless `ATIF_SQL_ALLOW_ROOT=1` says so. The details
266
+ and the one accepted disclosure (`duckdb_settings()` lists the granted paths) are in
267
+ [docs/reference/cli.md](docs/reference/cli.md#query).
268
+
269
+ ## License
270
+
271
+ [Apache License 2.0](LICENSE). Each module directory carries the same license
272
+ file, so a published distribution ships it too.