-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfig.py
More file actions
350 lines (284 loc) · 11.6 KB
/
Copy pathconfig.py
File metadata and controls
350 lines (284 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""TOML configuration loader for context-analyzer-tool."""
from __future__ import annotations
import logging
import os
import tomllib
from pathlib import Path
from typing import Any, get_origin
from pydantic import BaseModel, Field, model_validator
logger = logging.getLogger("context_analyzer_tool.config")
def get_config_dir() -> Path:
"""Return the config directory, respecting ``CAT_CONFIG_DIR`` env var."""
env_dir = os.environ.get("CAT_CONFIG_DIR")
if env_dir:
return Path(env_dir).expanduser()
return Path.home() / ".context-analyzer-tool"
def get_config_path() -> Path:
"""Return the path to ``config.toml``."""
return get_config_dir() / "config.toml"
# ---------------------------------------------------------------------------
# Pydantic config models
# ---------------------------------------------------------------------------
class CollectorConfig(BaseModel):
host: str = "127.0.0.1"
port: int = 7821
db_path: str = "~/.context-analyzer-tool/context_analyzer_tool.db"
class AnomalyConfig(BaseModel):
z_score_threshold: float = 2.0
min_sample_count: int = 5
cooldown_seconds: int = 60
task_types_ignored: list[str] = Field(default_factory=list)
baseline_window: int = 20 # number of recent samples for rolling stats
class ClassifierConfig(BaseModel):
enabled: bool = True
model: str = "claude-haiku-4-5-20251001"
max_tokens: int = 150
cache_results: bool = True
class NotificationsConfig(BaseModel):
statusline: bool = True
system_notification: bool = True
in_session_alert: bool = True
webhook_url: str = ""
class HooksConfig(BaseModel):
# Timeout in seconds for hook HTTP calls to the collector
timeout_seconds: float = 2.0
# Approximate characters per token for hook-side token estimation.
# This is a rough heuristic (~4 chars/token for English text).
chars_per_token_estimate: int = 4
# Token threshold above which a tool response triggers a large-output warning.
large_output_threshold: int = 5000
class ServerConfig(BaseModel):
# Session idle cleanup threshold in milliseconds (default: 1 hour)
session_idle_cleanup_ms: int = 3_600_000
# Session restore lookback window in milliseconds (default: 30 minutes)
session_restore_lookback_ms: int = 1_800_000
# Seconds between baseline update flushes
baseline_update_interval: int = 5
class RetentionConfig(BaseModel):
# Days to keep data (0 = keep forever)
retention_days: int = 30
class DashboardConfig(BaseModel):
# Seconds between TUI refreshes
refresh_rate: float = 2.0
_ENV_PREFIX = "CAT_"
class CATConfig(BaseModel):
"""Root configuration model. Maps 1:1 to config.toml sections."""
collector: CollectorConfig = Field(default_factory=CollectorConfig)
anomaly: AnomalyConfig = Field(default_factory=AnomalyConfig)
classifier: ClassifierConfig = Field(default_factory=ClassifierConfig)
notifications: NotificationsConfig = Field(default_factory=NotificationsConfig)
hooks: HooksConfig = Field(default_factory=HooksConfig)
server: ServerConfig = Field(default_factory=ServerConfig)
retention: RetentionConfig = Field(default_factory=RetentionConfig)
dashboard: DashboardConfig = Field(default_factory=DashboardConfig)
@model_validator(mode="after")
def _apply_env_overrides(self) -> CATConfig:
"""Override fields from environment variables.
Pattern: ``CAT_{SECTION}_{KEY}`` (uppercase).
For example ``CAT_COLLECTOR_PORT=7822`` sets
``collector.port`` to ``7822``.
"""
sections: dict[str, BaseModel] = {
"collector": self.collector,
"anomaly": self.anomaly,
"classifier": self.classifier,
"notifications": self.notifications,
"hooks": self.hooks,
"server": self.server,
"retention": self.retention,
"dashboard": self.dashboard,
}
for section_name, section in sections.items():
for field_name, field_info in type(section).model_fields.items():
env_key = f"{_ENV_PREFIX}{section_name.upper()}_{field_name.upper()}"
env_val = os.environ.get(env_key)
if env_val is None:
continue
annotation = field_info.annotation
if annotation is None:
continue
try:
coerced: Any
if annotation is bool:
coerced = env_val.lower() in ("1", "true", "yes")
elif annotation is int:
coerced = int(env_val)
elif annotation is float:
coerced = float(env_val)
elif get_origin(annotation) is list:
coerced = [
s.strip()
for s in env_val.split(",")
if s.strip()
]
else:
coerced = env_val
setattr(section, field_name, coerced)
logger.debug(
"Env override %s -> %s.%s = %r",
env_key,
section_name,
field_name,
coerced,
)
except (ValueError, TypeError) as exc:
logger.warning(
"Ignoring invalid env var %s=%r: %s",
env_key,
env_val,
exc,
)
return self
# ---------------------------------------------------------------------------
# Default TOML template (with comments)
# ---------------------------------------------------------------------------
_DEFAULT_TOML_TEMPLATE = """\
# context-analyzer-tool configuration
# Location: ~/.context-analyzer-tool/config.toml (or CAT_CONFIG_DIR)
# All values can be overridden via environment variables:
# CAT_{SECTION}_{KEY} (uppercase)
[collector]
# Host and port for the collector HTTP server
host = "127.0.0.1"
port = 7821
# Path to SQLite database (~ is expanded)
db_path = "~/.context-analyzer-tool/context_analyzer_tool.db"
[anomaly]
# Z-score threshold for anomaly detection
z_score_threshold = 2.0
# Minimum samples before anomaly detection activates
min_sample_count = 5
# Seconds before re-alerting for the same session
cooldown_seconds = 60
# Task types to exclude from anomaly detection
task_types_ignored = []
# Number of recent samples for rolling baseline
baseline_window = 20
[classifier]
# Enable LLM-based root cause classification (requires 'anthropic' package)
enabled = true
# Model to use for classification
model = "claude-haiku-4-5-20251001"
# Max tokens for classifier response
max_tokens = 150
# Cache classifier results to avoid redundant calls
cache_results = true
[notifications]
# Show context-analyzer-tool data in Claude Code statusline
statusline = true
# Fire OS-level notifications on anomalies
system_notification = true
# Inject alerts into Claude Code via additionalContext
in_session_alert = true
# Webhook URL for Slack/Discord/custom (empty = disabled)
webhook_url = ""
[hooks]
# Timeout in seconds for hook HTTP calls to the collector
timeout_seconds = 2.0
# Approximate characters per token for hook-side estimation.
# This is a rough heuristic (~4 chars/token for English text).
# The actual delta computation uses real statusline data, not this estimate.
chars_per_token_estimate = 4
# Token threshold above which a single tool response triggers a large-output warning.
large_output_threshold = 5000
[server]
# Session idle cleanup threshold in milliseconds (default: 1 hour)
session_idle_cleanup_ms = 3600000
# Session restore lookback window in milliseconds (default: 30 minutes)
session_restore_lookback_ms = 1800000
# Seconds between baseline update flushes
baseline_update_interval = 5
[retention]
# Days to keep data in the database (0 = keep forever)
retention_days = 30
[dashboard]
# Seconds between TUI dashboard refreshes
refresh_rate = 2.0
"""
# ---------------------------------------------------------------------------
# Public helpers
# ---------------------------------------------------------------------------
def load_default_config() -> CATConfig:
"""Return built-in defaults without ``CAT_*`` environment overrides."""
saved: dict[str, str | None] = {}
for key in list(os.environ):
if key.startswith(_ENV_PREFIX):
saved[key] = os.environ.pop(key)
try:
return CATConfig()
finally:
for key, value in saved.items():
if value is not None:
os.environ[key] = value
def config_to_toml(cfg: CATConfig) -> str:
"""Serialize *cfg* to a TOML-like string for display."""
lines: list[str] = []
for section_name, section in cfg.model_dump().items():
lines.append(f"[{section_name}]")
for key, value in section.items():
if isinstance(value, bool):
rendered = "true" if value else "false"
elif isinstance(value, str):
rendered = f'"{value}"'
elif isinstance(value, list):
if not value:
rendered = "[]"
else:
parts = [
f'"{item}"' if isinstance(item, str) else str(item)
for item in value
]
rendered = f"[{', '.join(parts)}]"
else:
rendered = str(value)
lines.append(f"{key} = {rendered}")
lines.append("")
return "\n".join(lines).rstrip() + "\n"
def load_config(config_path: Path | None = None) -> CATConfig:
"""Load config from a TOML file.
1. If *config_path* is ``None``, use :func:`get_config_path`.
2. If the file does not exist, return ``CATConfig()`` (all defaults).
3. Parse TOML, validate with Pydantic.
4. Expand ``~`` in ``db_path``.
Raises:
ValueError: If the TOML content is malformed.
"""
path = config_path if config_path is not None else get_config_path()
path = path.expanduser()
if not path.exists():
logger.info("Config file not found at %s — using defaults.", path)
return CATConfig()
logger.info("Loading config from %s", path)
try:
with open(path, "rb") as fh:
data = tomllib.load(fh)
except tomllib.TOMLDecodeError as exc:
raise ValueError(f"Malformed TOML in {path}: {exc}") from exc
return CATConfig.model_validate(data)
def ensure_config_dir() -> Path:
"""Create the config directory if it doesn't exist.
Returns:
The directory :class:`~pathlib.Path`.
"""
config_dir = get_config_dir()
config_dir.mkdir(parents=True, exist_ok=True)
logger.debug("Ensured config directory exists: %s", config_dir)
return config_dir
def get_db_path(config: CATConfig) -> str:
"""Resolve *db_path* from *config*, expanding ``~``.
Returns:
Absolute path string.
"""
return str(Path(config.collector.db_path).expanduser().resolve())
def write_default_config(path: Path | None = None) -> Path:
"""Write a default ``config.toml`` with comments to *path*.
If *path* is ``None``, writes to :func:`get_config_path`.
Returns:
The :class:`~pathlib.Path` that was written.
"""
target = path if path is not None else get_config_path()
target = target.expanduser()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(_DEFAULT_TOML_TEMPLATE, encoding="utf-8")
logger.info("Wrote default config to %s", target)
return target