nemo-compass 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 (105) hide show
  1. compass/__init__.py +2 -0
  2. compass/cli/__init__.py +2 -0
  3. compass/cli/artifacts.py +94 -0
  4. compass/cli/main.py +525 -0
  5. compass/cli/output.py +176 -0
  6. compass/compass_signals/__init__.py +2 -0
  7. compass/compass_signals/_trace.py +52 -0
  8. compass/compass_signals/anomaly_and_patterns/README.md +56 -0
  9. compass/compass_signals/anomaly_and_patterns/__init__.py +2 -0
  10. compass/compass_signals/anomaly_and_patterns/signal.py +1222 -0
  11. compass/compass_signals/builtins.py +89 -0
  12. compass/compass_signals/compass_signals.py +53 -0
  13. compass/compass_signals/ethos_divergence/ethos_divergence_detector.py +72 -0
  14. compass/compass_signals/grader_failure_patterns.py +139 -0
  15. compass/compass_signals/issue_detector.py +41 -0
  16. compass/compass_signals/registry.py +65 -0
  17. compass/compass_signals/tool_issues/README.md +60 -0
  18. compass/compass_signals/tool_issues/__init__.py +2 -0
  19. compass/compass_signals/tool_issues/coverage.py +460 -0
  20. compass/compass_signals/tool_issues/signal.py +834 -0
  21. compass/compass_signals/user_embedding/__init__.py +2 -0
  22. compass/compass_signals/user_embedding/embedding.py +226 -0
  23. compass/compass_signals/user_embedding/models/embedding.json +19 -0
  24. compass/compass_signals/user_embedding/models/embedding.npz +0 -0
  25. compass/compass_signals/user_sentiment/__init__.py +2 -0
  26. compass/compass_signals/user_sentiment/classifier.py +46 -0
  27. compass/compass_signals/user_sentiment/models/complaint.json +8 -0
  28. compass/compass_signals/user_sentiment/models/complaint.npz +0 -0
  29. compass/compass_signals/user_sentiment/signal.py +244 -0
  30. compass/config.py +338 -0
  31. compass/data/sample_corpus.jsonl +18 -0
  32. compass/insight.py +125 -0
  33. compass/insights_generation/__init__.py +2 -0
  34. compass/insights_generation/codebase.py +190 -0
  35. compass/insights_generation/confidence.py +98 -0
  36. compass/insights_generation/config.py +103 -0
  37. compass/insights_generation/defaults.py +6 -0
  38. compass/insights_generation/insight_compilation.py +369 -0
  39. compass/insights_generation/validation.py +98 -0
  40. compass/telemetry.py +97 -0
  41. compass/trace_loaders/__init__.py +56 -0
  42. compass/trace_loaders/atif.py +18 -0
  43. compass/trace_loaders/braintrust.py +23 -0
  44. compass/trace_loaders/fs.py +14 -0
  45. compass/trace_loaders/intake.py +22 -0
  46. compass/trace_loaders/langfuse.py +38 -0
  47. compass/trace_loaders/langsmith/__init__.py +32 -0
  48. compass/trace_loaders/langsmith/_normalization.py +24 -0
  49. compass/trace_loaders/langsmith/trace_export_file_loader.py +16 -0
  50. compass/trace_loaders/langsmith/trace_loader.py +22 -0
  51. compass/trace_loaders/mlflow.py +28 -0
  52. compass/trace_loaders/trace_loaders.py +14 -0
  53. compass/traces.py +26 -0
  54. compass/version.py +6 -0
  55. nemo_compass-0.1.0.dist-info/METADATA +170 -0
  56. nemo_compass-0.1.0.dist-info/RECORD +105 -0
  57. nemo_compass-0.1.0.dist-info/WHEEL +4 -0
  58. nemo_compass-0.1.0.dist-info/entry_points.txt +2 -0
  59. nemo_compass-0.1.0.dist-info/licenses/LICENSE +204 -0
  60. nemo_compass-0.1.0.dist-info/licenses/NOTICE +22 -0
  61. nemo_compass-0.1.0.dist-info/licenses/THIRD_PARTY_LICENSES.md +145 -0
  62. nemo_compass-0.1.0.dist-info/licenses/third_party/NOTICES.txt +30284 -0
  63. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/0BSD.txt +5 -0
  64. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/Apache-2.0.txt +73 -0
  65. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/BSD-2-Clause.txt +9 -0
  66. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/BSD-3-Clause.txt +11 -0
  67. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/BSL-1.0.txt +7 -0
  68. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/CC0-1.0.txt +121 -0
  69. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/CNRI-Python.txt +25 -0
  70. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/ISC.txt +7 -0
  71. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/LLVM-exception.txt +15 -0
  72. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/MIT-0.txt +16 -0
  73. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/MIT.txt +18 -0
  74. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/MPL-2.0.txt +373 -0
  75. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/PSF-2.0.txt +47 -0
  76. nemo_compass-0.1.0.dist-info/licenses/third_party/license_texts/Zlib.txt +11 -0
  77. nemo_compass-0.1.0.dist-info/licenses/third_party/licenses.jsonl +123 -0
  78. nemo_compass-0.1.0.dist-info/licenses/third_party/tau-bench-LICENSE.txt +21 -0
  79. trace_ingest/__init__.py +26 -0
  80. trace_ingest/loaders/__init__.py +62 -0
  81. trace_ingest/loaders/atif.py +358 -0
  82. trace_ingest/loaders/braintrust.py +409 -0
  83. trace_ingest/loaders/fs.py +97 -0
  84. trace_ingest/loaders/gym.py +520 -0
  85. trace_ingest/loaders/intake.py +793 -0
  86. trace_ingest/loaders/langfuse/__init__.py +40 -0
  87. trace_ingest/loaders/langfuse/client.py +44 -0
  88. trace_ingest/loaders/langfuse/config.py +125 -0
  89. trace_ingest/loaders/langfuse/file_io.py +45 -0
  90. trace_ingest/loaders/langfuse/filters.py +48 -0
  91. trace_ingest/loaders/langfuse/loader.py +71 -0
  92. trace_ingest/loaders/langfuse/normalization.py +516 -0
  93. trace_ingest/loaders/langfuse/v3.py +122 -0
  94. trace_ingest/loaders/langfuse/v3_file.py +103 -0
  95. trace_ingest/loaders/langfuse/v4.py +159 -0
  96. trace_ingest/loaders/langfuse/v4_file.py +137 -0
  97. trace_ingest/loaders/langfuse/v4_records.py +62 -0
  98. trace_ingest/loaders/langsmith/__init__.py +32 -0
  99. trace_ingest/loaders/langsmith/_normalization.py +420 -0
  100. trace_ingest/loaders/langsmith/trace_export_file_loader.py +494 -0
  101. trace_ingest/loaders/langsmith/trace_loader.py +296 -0
  102. trace_ingest/loaders/mlflow.py +737 -0
  103. trace_ingest/loaders/trace_loaders.py +31 -0
  104. trace_ingest/models.py +338 -0
  105. trace_ingest/source_links.py +44 -0
compass/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,2 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,94 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Write CLI artifacts as JSON-safe structures.
5
+
6
+ Two things in the engine outputs are not natively serialisable:
7
+
8
+ * ``run_anomaly_and_patterns`` returns ``PreparedTrace`` dataclasses under ``"prepared"``, which
9
+ carry extracted features and evidence.
10
+ * The tool-issue signal's ``MISSING`` sentinel is a bare ``object()``. It should never reach
11
+ ``json.dumps``, and if it somehow does we want ``"<missing>"`` in the output
12
+ rather than a crash three hours into a batch run.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import dataclasses
18
+ import json
19
+ from collections.abc import Iterable, Mapping
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from pydantic import BaseModel, JsonValue
24
+
25
+ from compass.compass_signals.anomaly_and_patterns.signal import PreparedTrace
26
+ from compass.compass_signals.tool_issues.signal import MISSING
27
+
28
+ __all__ = ["dump_json", "jsonable", "prepared_features", "write_json"]
29
+
30
+ MISSING_MARKER = "<missing>"
31
+
32
+
33
+ def jsonable(value: object) -> JsonValue:
34
+ """Recursively convert ``value`` into JSON-safe primitives."""
35
+
36
+ if value is MISSING:
37
+ return MISSING_MARKER
38
+ if value is None or isinstance(value, (str, bool, int)):
39
+ return value
40
+ if isinstance(value, float):
41
+ # JSON has no NaN/Infinity; emit null rather than invalid JSON.
42
+ return value if value == value and value not in (float("inf"), float("-inf")) else None
43
+ if isinstance(value, BaseModel):
44
+ return jsonable(value.model_dump(mode="python"))
45
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
46
+ return {f.name: jsonable(getattr(value, f.name)) for f in dataclasses.fields(value)}
47
+ if isinstance(value, Mapping):
48
+ return {str(k): jsonable(v) for k, v in value.items()}
49
+ if isinstance(value, (list, tuple, set, frozenset)):
50
+ items = sorted(value, key=repr) if isinstance(value, (set, frozenset)) else value
51
+ return [jsonable(item) for item in items]
52
+ item = getattr(value, "item", None)
53
+ if callable(item) and hasattr(value, "dtype"): # numpy scalar
54
+ return jsonable(item())
55
+ tolist = getattr(value, "tolist", None)
56
+ if callable(tolist): # numpy array
57
+ return jsonable(tolist())
58
+ return str(value)
59
+
60
+
61
+ def dump_json(value: object, *, indent: int | None = 2) -> str:
62
+ return json.dumps(jsonable(value), indent=indent, ensure_ascii=False, sort_keys=False) + "\n"
63
+
64
+
65
+ def write_json(path: str | Path, value: object, *, indent: int | None = 2) -> Path:
66
+ path = Path(path)
67
+ path.parent.mkdir(parents=True, exist_ok=True)
68
+ path.write_text(dump_json(value, indent=indent), encoding="utf-8")
69
+ return path
70
+
71
+
72
+ def prepared_features(prepared: Iterable[PreparedTrace]) -> list[dict[str, Any]]:
73
+ """Flatten ``run_anomaly_and_patterns``'s ``prepared`` list into per-trace feature rows.
74
+
75
+ Keeps the numeric vector, the trajectory tokens and the source pointer —
76
+ everything an analyst needs to see why a trace was scored the way it was —
77
+ without echoing the entire input corpus back into the output directory.
78
+ """
79
+
80
+ rows = []
81
+ for item in prepared:
82
+ features = item.features
83
+ rows.append(
84
+ {
85
+ "trace_id": features.trace_id,
86
+ "numeric": jsonable(features.numeric),
87
+ "sequence_tokens": list(features.sequence_tokens),
88
+ "tool_names": list(item.tool_names),
89
+ "failure_event_count": len(item.failure_events),
90
+ "last_agent_excerpt": item.last_agent_excerpt,
91
+ "source_pointer": jsonable(features.source_pointer),
92
+ }
93
+ )
94
+ return rows
compass/cli/main.py ADDED
@@ -0,0 +1,525 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Analyze your agent's behavior and surface actionable insights from its traces.
5
+
6
+ After configuring your model and credentials, run:
7
+ compass --config config.yaml
8
+
9
+ Start with your trace source (Braintrust, LangSmith, Langfuse, MLflow, Intake, or files):
10
+ https://github.com/NVIDIA-NeMo/labs-nemo-compass/blob/main/README.md#start-here
11
+
12
+ Understand your results:
13
+ https://github.com/NVIDIA-NeMo/labs-nemo-compass/blob/main/docs/results.md
14
+
15
+ Use --help-all for every setting. CLI options override individual YAML values.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import os
22
+ import sys
23
+ from argparse import SUPPRESS, Action, ArgumentParser
24
+ from collections.abc import Callable, Sequence
25
+ from datetime import datetime, timezone
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ import yaml
30
+ from nooa.unifiedllm import CompletionClient, UnifiedLLM
31
+ from pydantic_settings import CliSettingsSource
32
+ from rich.console import Console
33
+
34
+ from compass.cli.output import RunOutput, RunResult, display_name
35
+ from compass.compass_signals.builtins import registered_builtin_signals
36
+ from compass.compass_signals.compass_signals import CompassSignalResult, Problem
37
+ from compass.config import CompassSignalsConfig, RunConfig, TraceConfig
38
+ from compass.insight import Insight, load_insights, resolve_trace_links
39
+ from compass.insights_generation.confidence import InsightConfidence
40
+ from compass.insights_generation.config import (
41
+ ENV_API_BASE,
42
+ ENV_API_KEY,
43
+ ENV_MODEL,
44
+ load_dotenv,
45
+ resolve,
46
+ )
47
+ from compass.insights_generation.defaults import DEFAULT_MAX_TOKENS, DEFAULT_MODEL
48
+ from compass.insights_generation.insight_compilation import InsightCompilation
49
+ from compass.insights_generation.validation import ProblemValidation
50
+ from compass.telemetry import span, telemetry_session
51
+ from compass.trace_loaders.atif import ATIFTraceLoader
52
+ from compass.trace_loaders.braintrust import (
53
+ BRAINTRUST_DEFAULT_MAX_TRACES,
54
+ BraintrustTraceConfig,
55
+ BraintrustTraceLoader,
56
+ )
57
+ from compass.trace_loaders.fs import FSDataLoader
58
+ from compass.trace_loaders.intake import IntakeTraceLoader
59
+ from compass.trace_loaders.langfuse import (
60
+ LANGFUSE_DEFAULT_MAX_TRACES,
61
+ LangfuseFileTraceConfig,
62
+ LangfuseTraceConfig,
63
+ LangfuseTraceLoader,
64
+ LangfuseV3FileTraceLoader,
65
+ LangfuseV4FileTraceConfig,
66
+ LangfuseV4FileTraceLoader,
67
+ )
68
+ from compass.trace_loaders.langsmith import (
69
+ LANGSMITH_DEFAULT_MAX_TRACES,
70
+ LangSmithTraceConfig,
71
+ LangSmithTraceExportFileConfig,
72
+ LangSmithTraceExportFileLoader,
73
+ LangSmithTraceLoader,
74
+ )
75
+ from compass.trace_loaders.mlflow import (
76
+ MLFLOW_DEFAULT_MAX_TRACES,
77
+ MLflowFileTraceConfig,
78
+ MLflowFileTraceLoader,
79
+ MLflowTraceConfig,
80
+ MLflowTraceLoader,
81
+ )
82
+ from compass.trace_loaders.trace_loaders import TraceLoader
83
+ from compass.traces import Trace, TraceSnapshot
84
+ from trace_ingest.loaders.gym import GymTraceLoader
85
+
86
+ EXIT_OK = 0
87
+ EXIT_SETUP = 2
88
+ DEFAULT_REASONING_EFFORT = "high"
89
+
90
+
91
+ class SetupError(ValueError):
92
+ """Required settings are missing from the environment for this run."""
93
+
94
+
95
+ def _check_environment(config: RunConfig) -> str:
96
+ """Check the selected integrations before constructing clients or loading traces."""
97
+
98
+ load_dotenv()
99
+ api_key = resolve(ENV_API_KEY)
100
+ required = {f"{ENV_API_KEY} — API key for the configured model": api_key}
101
+ if config.trace.langsmith is not None:
102
+ # Match the LangSmith SDK's legacy alias without importing the optional SDK.
103
+ required["LANGSMITH_API_KEY — API key for LangSmith"] = os.environ.get(
104
+ "LANGSMITH_API_KEY", ""
105
+ ).strip() or os.environ.get("LANGCHAIN_API_KEY")
106
+ if config.trace.braintrust is not None:
107
+ required["BRAINTRUST_API_KEY — API key for Braintrust"] = os.environ.get(
108
+ "BRAINTRUST_API_KEY"
109
+ )
110
+ if config.trace.langfuse is not None:
111
+ for name in ("LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY"):
112
+ required[f"{name} — Langfuse project credentials"] = os.environ.get(name)
113
+ if not (config.trace.langfuse.base_url or "").strip():
114
+ required["LANGFUSE_BASE_URL — Langfuse URL; or set trace.langfuse.base_url"] = (
115
+ os.environ.get("LANGFUSE_BASE_URL")
116
+ )
117
+ sentiment = config.compass_signals.user_sentiment
118
+ if sentiment is not None and sentiment.litellm is not None and sentiment.litellm.api_key_env:
119
+ name = sentiment.litellm.api_key_env
120
+ hint = "API key named by compass_signals.user_sentiment.litellm.api_key_env"
121
+ required[f"{name} — {hint}"] = os.environ.get(name)
122
+
123
+ missing = [f" {label}" for label, value in required.items() if not (value or "").strip()]
124
+ if missing:
125
+ raise SetupError(
126
+ "Missing required environment settings:\n"
127
+ + "\n".join(missing)
128
+ + "\n\nSet these in .env in your working directory (NAME=value),\n"
129
+ "or export them in your shell, then rerun the command.\n"
130
+ "Setup: https://github.com/NVIDIA-NeMo/labs-nemo-compass/blob/main/docs/model-access.md"
131
+ )
132
+ assert api_key is not None
133
+ return api_key
134
+
135
+
136
+ def _configured_trace_loader(config: TraceConfig) -> TraceLoader:
137
+ """Construct the trace loader selected by the run configuration."""
138
+
139
+ if config.filesystem is not None:
140
+ return FSDataLoader(config.filesystem.path)
141
+ if config.gym is not None:
142
+ return GymTraceLoader(config.gym)
143
+ if config.atif is not None:
144
+ return ATIFTraceLoader(config.atif)
145
+ if config.intake is not None:
146
+ source = config.intake
147
+ if config.max_traces is not None:
148
+ query = source.query.model_copy(update={"max_traces": config.max_traces})
149
+ source = source.model_copy(update={"query": query})
150
+ return IntakeTraceLoader(config=source)
151
+ if config.braintrust is not None:
152
+ source = config.braintrust
153
+ return BraintrustTraceLoader(
154
+ BraintrustTraceConfig(
155
+ project_id=source.project_id,
156
+ experiment_id=source.experiment_id,
157
+ org_name=source.org_name,
158
+ app_url=source.app_url,
159
+ api_url=source.api_url,
160
+ from_timestamp=source.from_timestamp,
161
+ to_timestamp=source.to_timestamp,
162
+ max_traces=config.max_traces or BRAINTRUST_DEFAULT_MAX_TRACES,
163
+ )
164
+ )
165
+ if config.langfuse is not None:
166
+ source = config.langfuse
167
+ return LangfuseTraceLoader(
168
+ LangfuseTraceConfig(
169
+ base_url=source.base_url,
170
+ from_timestamp=source.from_timestamp,
171
+ to_timestamp=source.to_timestamp,
172
+ filter_string=source.filter,
173
+ max_traces=config.max_traces or LANGFUSE_DEFAULT_MAX_TRACES,
174
+ )
175
+ )
176
+ if config.langfuse_trace_export_file is not None:
177
+ source = config.langfuse_trace_export_file
178
+ if source.api_version == "v4":
179
+ return LangfuseV4FileTraceLoader(
180
+ LangfuseV4FileTraceConfig(
181
+ path=source.path,
182
+ scores_path=source.scores_path,
183
+ base_url=source.base_url,
184
+ max_traces=config.max_traces or LANGFUSE_DEFAULT_MAX_TRACES,
185
+ )
186
+ )
187
+ return LangfuseV3FileTraceLoader(
188
+ LangfuseFileTraceConfig(
189
+ path=source.path,
190
+ max_traces=config.max_traces or LANGFUSE_DEFAULT_MAX_TRACES,
191
+ )
192
+ )
193
+ if config.langsmith is not None:
194
+ source = config.langsmith
195
+ return LangSmithTraceLoader(
196
+ LangSmithTraceConfig(
197
+ project_name=source.project,
198
+ api_url=source.api_url,
199
+ filter=source.filter,
200
+ tree_filter=source.tree_filter,
201
+ start_time=source.start_time,
202
+ max_traces=config.max_traces or LANGSMITH_DEFAULT_MAX_TRACES,
203
+ )
204
+ )
205
+ if config.langsmith_trace_export_file is not None:
206
+ return LangSmithTraceExportFileLoader(
207
+ LangSmithTraceExportFileConfig(
208
+ path=config.langsmith_trace_export_file.path,
209
+ max_traces=config.max_traces or LANGSMITH_DEFAULT_MAX_TRACES,
210
+ )
211
+ )
212
+ if config.mlflow_experiment is not None:
213
+ source = config.mlflow_experiment
214
+ return MLflowTraceLoader(
215
+ MLflowTraceConfig(
216
+ experiment_name=source.experiment,
217
+ tracking_uri=source.tracking_uri,
218
+ filter_string=source.filter,
219
+ max_traces=config.max_traces or MLFLOW_DEFAULT_MAX_TRACES,
220
+ )
221
+ )
222
+ assert config.mlflow_export is not None
223
+ return MLflowFileTraceLoader(
224
+ MLflowFileTraceConfig(
225
+ path=config.mlflow_export.path,
226
+ max_traces=config.max_traces or MLFLOW_DEFAULT_MAX_TRACES,
227
+ )
228
+ )
229
+
230
+
231
+ async def _run_compass_signals(
232
+ config: CompassSignalsConfig,
233
+ snapshot: TraceSnapshot,
234
+ llm_factory: Callable[[], UnifiedLLM] | None = None,
235
+ progress: Callable[[Sequence[str]], None] | None = None,
236
+ ) -> list[CompassSignalResult]:
237
+ """Run the configured Compass Signals concurrently in registration order."""
238
+
239
+ registry = registered_builtin_signals(
240
+ anomaly_and_patterns=config.anomaly_and_patterns,
241
+ tool_issues=config.tool_issues,
242
+ ethos_divergence=config.ethos_divergence,
243
+ user_sentiment=config.user_sentiment,
244
+ grader_failure_patterns=config.grader_failure_patterns,
245
+ llm_factory=llm_factory,
246
+ )
247
+
248
+ active: set[str] = set()
249
+
250
+ def changed() -> None:
251
+ if progress is not None:
252
+ progress(tuple(name for name in registry.names if name in active))
253
+
254
+ async def analyze(name: str) -> CompassSignalResult:
255
+ def started() -> None:
256
+ active.add(name)
257
+ changed()
258
+
259
+ try:
260
+ with span(f"evidence.{name}") as record:
261
+ result = await registry.analyze(name, snapshot, on_start=started)
262
+ record.set_output(result)
263
+ return result
264
+ finally:
265
+ if name in active:
266
+ active.remove(name)
267
+ changed()
268
+
269
+ # Cancel sibling work on failure; no analysis outlives this run.
270
+ async with asyncio.TaskGroup() as group:
271
+ tasks = [group.create_task(analyze(name)) for name in registry.names]
272
+ return [task.result() for task in tasks]
273
+
274
+
275
+ async def _validate_evidence_with_code(
276
+ evidence: list[CompassSignalResult],
277
+ snapshot: TraceSnapshot,
278
+ code_base_path: Path,
279
+ llm: UnifiedLLM,
280
+ ) -> list[CompassSignalResult]:
281
+ """Keep only Problems that the supplied codebase supports."""
282
+
283
+ code_base_path = code_base_path.expanduser().resolve()
284
+ if not code_base_path.is_dir():
285
+ raise ValueError(f"code_base must be an existing directory: {code_base_path}")
286
+ validator = ProblemValidation(code_base_path, llm)
287
+
288
+ async def validate_problem(
289
+ problem: Problem, supporting_traces: tuple[Trace, ...]
290
+ ) -> bool | None:
291
+ with span("validate_problem") as record:
292
+ record.set_input({"problem": problem, "code_base": str(code_base_path)})
293
+ decision = await validator.is_supported(problem, supporting_traces)
294
+ record.set_output({"supported": decision})
295
+ return decision
296
+
297
+ async def validate_result(result: CompassSignalResult) -> CompassSignalResult:
298
+ validations = []
299
+ for problem in result.problems:
300
+ supporting_traces = tuple(
301
+ snapshot.get_trace_by_id(trace_id) for trace_id in problem.supporting_trace_ids
302
+ )
303
+ validations.append(validate_problem(problem, supporting_traces))
304
+
305
+ decisions = await asyncio.gather(*validations)
306
+ retained_problems = tuple(
307
+ problem
308
+ for problem, decision in zip(result.problems, decisions, strict=True)
309
+ if decision is not False
310
+ )
311
+ return result.model_copy(update={"problems": retained_problems})
312
+
313
+ return list(await asyncio.gather(*(validate_result(result) for result in evidence)))
314
+
315
+
316
+ async def _rate_confidence_with_code(
317
+ insights: list[Insight],
318
+ snapshot: TraceSnapshot,
319
+ code_base_path: Path,
320
+ llm: UnifiedLLM,
321
+ ) -> list[Insight]:
322
+ """Rate each insight's confidence against the supplied codebase."""
323
+
324
+ code_base_path = code_base_path.expanduser().resolve()
325
+ if not code_base_path.is_dir():
326
+ raise ValueError(f"code_base must be an existing directory: {code_base_path}")
327
+ rater = InsightConfidence(code_base_path, llm)
328
+
329
+ def supporting_trace(ref: str) -> Trace | None:
330
+ try:
331
+ return snapshot.get_trace_by_id(ref)
332
+ except KeyError:
333
+ return None
334
+
335
+ async def rate_insight(insight: Insight) -> Insight:
336
+ supporting_traces = tuple(
337
+ trace
338
+ for trace in (supporting_trace(item.trace_id) for item in insight.evidence)
339
+ if trace is not None
340
+ )
341
+ rating = await rater.rate(insight, supporting_traces)
342
+ return insight.model_copy(update={"confidence": rating})
343
+
344
+ return list(await asyncio.gather(*(rate_insight(insight) for insight in insights)))
345
+
346
+
347
+ def _build_llm(config: RunConfig, api_key: str) -> CompletionClient:
348
+ """Construct an LLM client with the run's shared model settings."""
349
+
350
+ model = config.model or resolve(ENV_MODEL) or DEFAULT_MODEL
351
+ api_base = config.api_base or os.environ.get(ENV_API_BASE)
352
+ # A gateway configured for OpenAI must not redirect native provider routes.
353
+ if not api_base and not model.startswith(("anthropic/", "openrouter/")):
354
+ api_base = resolve(ENV_API_BASE)
355
+
356
+ return CompletionClient(
357
+ model=model,
358
+ api_base=api_base or None,
359
+ api_key=api_key,
360
+ max_tokens=config.max_tokens or DEFAULT_MAX_TOKENS,
361
+ reasoning_effort=DEFAULT_REASONING_EFFORT,
362
+ # Anthropic needs LiteLLM's native translation, not raw OpenAI fields.
363
+ allowed_openai_params=[]
364
+ if model.startswith("anthropic/")
365
+ else ["tool_choice", "reasoning_effort"],
366
+ drop_params=True,
367
+ )
368
+
369
+
370
+ async def _generate_insights(config: RunConfig, output: RunOutput) -> RunResult:
371
+ api_key = _check_environment(config)
372
+ async with output.progress():
373
+ with span("ingestion") as record:
374
+ record.set_input(config.trace)
375
+ snapshot = await asyncio.to_thread(_configured_trace_loader(config.trace).load)
376
+ record.set_output({"trace_count": len(snapshot)})
377
+ output.trace_count = len(snapshot)
378
+ output.activity = "Checking prerequisites"
379
+
380
+ def progress(active: Sequence[str]) -> None:
381
+ output.activity = (
382
+ "Analyzing: " + ", ".join(display_name(name).lower() for name in active)
383
+ if active
384
+ else "Checking prerequisites"
385
+ )
386
+
387
+ evidence = await _run_compass_signals(
388
+ config.compass_signals,
389
+ snapshot,
390
+ lambda: _build_llm(config, api_key),
391
+ progress,
392
+ )
393
+ existing = load_insights(config.existing_insights) if config.existing_insights else []
394
+ result = RunResult(
395
+ trace_count=len(snapshot),
396
+ evidence=evidence,
397
+ insights=list(existing),
398
+ existing_insights=existing,
399
+ )
400
+ if any(item.problems for item in evidence):
401
+ run_timestamp = datetime.now(timezone.utc)
402
+ result.insights = await _compile_evidence(
403
+ config, api_key, snapshot, result, output, run_timestamp
404
+ )
405
+ result.insights = resolve_trace_links(result.insights, snapshot, existing)
406
+ if config.code_base is not None and result.insights:
407
+ output.activity = "Investigating insight confidence against the codebase"
408
+ async with _build_llm(config, api_key) as llm:
409
+ result.insights = await _rate_confidence_with_code(
410
+ result.insights, snapshot, config.code_base, llm
411
+ )
412
+ return result
413
+
414
+
415
+ async def _compile_evidence(
416
+ config: RunConfig,
417
+ api_key: str,
418
+ snapshot: TraceSnapshot,
419
+ result: RunResult,
420
+ output: RunOutput,
421
+ run_timestamp: datetime,
422
+ ) -> list[Insight]:
423
+ evidence = result.evidence
424
+ async with _build_llm(config, api_key) as llm:
425
+ if config.code_base is not None:
426
+ output.activity = "Checking candidate issues against the codebase"
427
+ evidence = await _validate_evidence_with_code(evidence, snapshot, config.code_base, llm)
428
+ result.rejected_by_code = sum(len(item.problems) for item in result.evidence) - sum(
429
+ len(item.problems) for item in evidence
430
+ )
431
+ if not any(item.problems for item in evidence):
432
+ return result.existing_insights
433
+ output.activity = "Reviewing candidate issues for actionable insights"
434
+ with span("compilation") as record:
435
+ record.set_input({"evidence": evidence, "existing_insights": result.existing_insights})
436
+ insights = await InsightCompilation(llm=llm).compile_insights(
437
+ evidence,
438
+ snapshot,
439
+ result.existing_insights,
440
+ run_timestamp,
441
+ )
442
+ record.set_output({"insights": insights})
443
+ return insights
444
+
445
+
446
+ def _render_insights(insights: Sequence[Insight]) -> str:
447
+ return yaml.safe_dump(
448
+ [insight.model_dump() for insight in insights],
449
+ allow_unicode=True,
450
+ sort_keys=False,
451
+ )
452
+
453
+
454
+ def _write_insights(output_path: Path, rendered: str) -> None:
455
+ if output_path == Path("-"):
456
+ return
457
+ output_path.parent.mkdir(parents=True, exist_ok=True)
458
+ output_path.write_text(rendered, encoding="utf-8")
459
+
460
+
461
+ def get_config(argv: Sequence[str] | None = None) -> RunConfig:
462
+ """Load run settings from optional YAML and generated CLI arguments."""
463
+
464
+ return RunConfig(_cli_parse_args=list(sys.argv[1:] if argv is None else argv))
465
+
466
+
467
+ # Pydantic hooks accept parser/group objects and argparse's heterogeneous keyword arguments.
468
+ def _add_common_argument(parser: Any, *args: str, **kwargs: Any) -> Action: # noqa: ANN401
469
+ if (
470
+ kwargs.get("dest") not in ("config", "output_path", "model")
471
+ and kwargs.get("action") != "help"
472
+ ):
473
+ kwargs["help"] = SUPPRESS
474
+ return parser.add_argument(*args, **kwargs)
475
+
476
+
477
+ def _add_common_group(parser: Any, **kwargs: Any) -> Any: # noqa: ANN401
478
+ kwargs["description"] = None
479
+ return parser.add_argument_group(**kwargs)
480
+
481
+
482
+ def _print_help(*, full: bool) -> None:
483
+ parser = CliSettingsSource(
484
+ RunConfig,
485
+ add_argument_method=ArgumentParser.add_argument if full else _add_common_argument,
486
+ add_argument_group_method=ArgumentParser.add_argument_group if full else _add_common_group,
487
+ ).root_parser
488
+ parser.description = __doc__
489
+ parser.add_argument("--help-all", action="help", help="Show all configuration options")
490
+ parser.print_help()
491
+
492
+
493
+ def main(argv: Sequence[str] | None = None) -> int:
494
+ argv = list(sys.argv[1:] if argv is None else argv)
495
+ if not argv or any(arg in argv for arg in ("-h", "--help", "--help-all")):
496
+ _print_help(full="--help-all" in argv)
497
+ return EXIT_OK
498
+
499
+ output = RunOutput(Console(stderr=True, markup=False, highlight=False))
500
+ try:
501
+ config = get_config(argv)
502
+ _check_environment(config)
503
+ with telemetry_session(config) as record:
504
+ result = asyncio.run(_generate_insights(config, output))
505
+ rendered = _render_insights(result.insights)
506
+ if result.insights:
507
+ _write_insights(config.output_path, rendered)
508
+ if config.output_path == Path("-") or not sys.stdout.isatty():
509
+ print(rendered, end="")
510
+ output.report(result, config.output_path)
511
+ record.set_output(
512
+ {
513
+ "trace_count": result.trace_count,
514
+ "insights": result.insights,
515
+ "rejected_by_code": result.rejected_by_code,
516
+ },
517
+ )
518
+ return EXIT_OK
519
+ except SetupError as error:
520
+ output.console.print(str(error), soft_wrap=True)
521
+ return EXIT_SETUP
522
+
523
+
524
+ if __name__ == "__main__":
525
+ raise SystemExit(main())