dockmedic 0.1.2__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.
dockmedic/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """DockMedic: safe, bounded, resumable diagnosis of local Docker failures."""
2
+
3
+ __version__ = "0.0.1"
dockmedic/cli.py ADDED
@@ -0,0 +1,504 @@
1
+ """Terminal entry point for DockMedic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import tempfile
8
+ from collections.abc import Callable
9
+ from importlib.metadata import PackageNotFoundError
10
+ from importlib.metadata import version as package_version
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import typer
15
+ import yaml
16
+ from langgraph.checkpoint.sqlite import SqliteSaver
17
+ from rich.console import Console
18
+ from rich.table import Table
19
+ from rich.text import Text
20
+
21
+ from dockmedic.config import DEFAULT_CONFIG_NAME, Config, init_config, load_config
22
+ from dockmedic.evals.runner import run_eval
23
+ from dockmedic.graph.workflow import build_workflow
24
+ from dockmedic.llm import LLMClient, build_llm
25
+ from dockmedic.security.sanitize import terminal_safe
26
+ from dockmedic.store import incidents as store
27
+ from dockmedic.store.schema import (
28
+ STATE_SCHEMA_VERSION,
29
+ initialise,
30
+ stored_schema_version,
31
+ )
32
+ from dockmedic.tools.docker_tools import (
33
+ ContainerSnapshot,
34
+ DockerEvent,
35
+ DockerTools,
36
+ FakeDockerTools,
37
+ RealDockerTools,
38
+ )
39
+ from dockmedic.watch import WatchLoop, reconciliation_events
40
+
41
+ app = typer.Typer(
42
+ name="dockmedic",
43
+ help="Safe, bounded, resumable diagnosis of local Docker container failures.",
44
+ no_args_is_help=True,
45
+ )
46
+ console = Console()
47
+ LOG_FILE_ARG = typer.Argument(
48
+ ..., exists=True, readable=True, help="Path to a saved container log."
49
+ )
50
+
51
+
52
+ def _show_version(value: bool) -> None:
53
+ if value:
54
+ try:
55
+ installed = package_version("dockmedic")
56
+ except PackageNotFoundError:
57
+ installed = "unknown"
58
+ console.print(Text(installed))
59
+ raise typer.Exit()
60
+
61
+
62
+ @app.callback()
63
+ def main(
64
+ version: bool = typer.Option(
65
+ False,
66
+ "--version",
67
+ callback=_show_version,
68
+ is_eager=True,
69
+ help="Show the installed DockMedic version.",
70
+ ),
71
+ ) -> None:
72
+ """Safe, bounded, resumable diagnosis of local Docker container failures."""
73
+ del version
74
+
75
+
76
+ def _print_report(report: object) -> None:
77
+ console.print(Text("Incident report:", style="bold"))
78
+ console.print(Text(str(report)))
79
+
80
+
81
+ def _snapshot_from_log(logs: str) -> ContainerSnapshot:
82
+ """Build a synthetic inspect snapshot from a pasted Docker log."""
83
+ lowered = logs.lower()
84
+ exit_match = re.search(r"exit[ _]?code\s*[=:]?\s*(\d+)", lowered)
85
+ restart_match = re.search(r"restart[ _]?count\s*[=:]?\s*(\d+)", lowered)
86
+ oom = "oom" in lowered or "memoryerror" in lowered
87
+ exit_code = int(exit_match.group(1)) if exit_match else (137 if oom else 1)
88
+ return ContainerSnapshot(
89
+ container_id="log-fixture",
90
+ name="log-fixture",
91
+ service_key="log-fixture",
92
+ status="exited",
93
+ exit_code=exit_code,
94
+ oom_killed=oom,
95
+ restart_count=int(restart_match.group(1)) if restart_match else 0,
96
+ env_keys=[],
97
+ )
98
+
99
+
100
+ def _console_approver(payload: dict[str, Any]) -> bool:
101
+ console.print(Text("Validated action (not LLM prose):", style="bold"))
102
+ console.print(Text(terminal_safe(json.dumps(payload, indent=2, sort_keys=True))))
103
+ return typer.confirm("Approve this action?", default=False)
104
+
105
+
106
+ def _llm_or_exit(settings: Config) -> LLMClient:
107
+ try:
108
+ return build_llm(settings)
109
+ except (RuntimeError, ValueError) as exc:
110
+ console.print(Text(str(exc), style="red"))
111
+ raise typer.Exit(code=1) from exc
112
+
113
+
114
+ def _run_pipeline(
115
+ tools: DockerTools,
116
+ container_id: str,
117
+ config_path: str,
118
+ incident_id: str,
119
+ db_path: str | Path,
120
+ approver: Callable[[dict[str, Any]], bool] | None = None,
121
+ llm: LLMClient | None = None,
122
+ ) -> dict[str, Any]:
123
+ config = load_config(config_path)
124
+ checkpoint_path = Path(config.data_dir) / "checkpoints.sqlite"
125
+ checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
126
+ with SqliteSaver.from_conn_string(str(checkpoint_path)) as saver:
127
+ graph = build_workflow(
128
+ tools=tools,
129
+ llm=llm or _llm_or_exit(config),
130
+ config=config,
131
+ db_path=db_path,
132
+ approver=approver or _console_approver,
133
+ checkpointer=saver,
134
+ )
135
+ result = graph.invoke(
136
+ {
137
+ "incident_id": incident_id,
138
+ "container_id": container_id,
139
+ "service_key": container_id,
140
+ },
141
+ config={"configurable": {"thread_id": incident_id}},
142
+ )
143
+ return dict(result)
144
+
145
+
146
+ def _run_once(
147
+ tools: DockerTools,
148
+ container_id: str,
149
+ config_path: str,
150
+ incident_id: str,
151
+ db_path: str | Path,
152
+ approver: Callable[[dict[str, Any]], bool] | None = None,
153
+ llm: LLMClient | None = None,
154
+ ) -> object:
155
+ result = _run_pipeline(
156
+ tools, container_id, config_path, incident_id, db_path, approver, llm
157
+ )
158
+ report = result["report"]
159
+ store.update_incident_status(
160
+ db_path, incident_id, "triaged", summary=str(getattr(report, "summary", ""))
161
+ )
162
+ return report
163
+
164
+
165
+ @app.command()
166
+ def init(
167
+ path: str = DEFAULT_CONFIG_NAME,
168
+ force: bool = typer.Option(False, "--force", help="Overwrite an existing config."),
169
+ ) -> None:
170
+ """Generate a dockmedic.yaml config file."""
171
+ target = init_config(Path(path), force=force)
172
+ console.print(Text(f"Wrote {target}"))
173
+
174
+
175
+ @app.command()
176
+ def watch(
177
+ target: str = typer.Option("docker", "--target", help="Event source (docker)."),
178
+ config: str = typer.Option(DEFAULT_CONFIG_NAME, "--config"),
179
+ ) -> None:
180
+ """Watch Docker events and triage failures."""
181
+ if target != "docker":
182
+ console.print(Text(f"Unknown target: {target}", style="red"))
183
+ raise typer.Exit(code=2)
184
+ if not Path(config).exists():
185
+ console.print(Text(f"Missing {config}; run 'dockmedic init'.", style="red"))
186
+ raise typer.Exit(code=1)
187
+
188
+ settings = load_config(config)
189
+ llm = _llm_or_exit(settings)
190
+ try:
191
+ tools = RealDockerTools()
192
+ except Exception as exc:
193
+ console.print(Text(f"Cannot reach Docker: {exc}", style="red"))
194
+ console.print(Text("Use 'dockmedic demo' for an offline end-to-end run."))
195
+ raise typer.Exit(code=1) from exc
196
+
197
+ db_path = settings.database
198
+ initialise(db_path)
199
+ loop = WatchLoop(tools, settings, db_path)
200
+
201
+ for event in reconciliation_events(
202
+ tools, lookback_seconds=settings.reconciliation_lookback_seconds
203
+ ):
204
+ decision = loop.process(event)
205
+ if decision.triage and decision.incident_id:
206
+ console.print(Text(f"Reconciled failure: {event.container_id}"))
207
+ _print_report(
208
+ _run_once(
209
+ tools, event.container_id, config, decision.incident_id, db_path, llm=llm
210
+ )
211
+ )
212
+
213
+ console.print(Text("Watching Docker events (Ctrl-C to stop)..."))
214
+ for event in tools.events():
215
+ decision = loop.process(event)
216
+ if not decision.triage or not decision.incident_id:
217
+ continue
218
+ console.print(Text(f"Failure event: {event.status} on {event.container_id}"))
219
+ _print_report(
220
+ _run_once(tools, event.container_id, config, decision.incident_id, db_path, llm=llm)
221
+ )
222
+
223
+
224
+ @app.command()
225
+ def demo(
226
+ config: str = typer.Option(DEFAULT_CONFIG_NAME, "--config"),
227
+ yes: bool = typer.Option(False, "--yes", help="Auto-approve the validated action."),
228
+ provider: str = typer.Option(
229
+ "stub", "--provider", help="LLM for this demo: stub (default, offline) or gemini."
230
+ ),
231
+ ) -> None:
232
+ """Run the pipeline against an in-memory OOM fixture (no Docker needed)."""
233
+ if not Path(config).exists():
234
+ init_config(config)
235
+ settings = load_config(config)
236
+ if provider not in {"stub", "gemini"}:
237
+ console.print(Text(f"Unknown provider: {provider}", style="red"))
238
+ raise typer.Exit(code=2)
239
+ settings = settings.model_copy(update={"provider": provider})
240
+ llm = _llm_or_exit(settings)
241
+ snapshot = ContainerSnapshot(
242
+ container_id="fixture-oom",
243
+ name="web-1",
244
+ service_key="demo/web",
245
+ status="exited",
246
+ exit_code=137,
247
+ oom_killed=True,
248
+ restart_count=3,
249
+ started_at="2026-11-28T10:10:00Z",
250
+ finished_at="2026-11-28T10:12:00Z",
251
+ health=None,
252
+ env_keys=["PORT", "REDIS_URL"],
253
+ )
254
+ logs = (
255
+ "2026-11-28T10:11:59Z [INFO] worker started\n"
256
+ "2026-11-28T10:12:00Z [ERROR] MemoryError: unable to allocate array\n"
257
+ "2026-11-28T10:12:00Z [ERROR] worker killed by OOM killer\n"
258
+ )
259
+ tools = FakeDockerTools(snapshot, logs, {"memory_percent": 98.0})
260
+ # A fresh database every run keeps the demo idempotent from a user's view.
261
+ with tempfile.TemporaryDirectory(prefix="dockmedic-demo-") as temp_dir:
262
+ db_path = Path(temp_dir) / "demo.db"
263
+ loop = WatchLoop(tools, settings, db_path)
264
+ decision = loop.process(
265
+ DockerEvent(
266
+ status="reconciliation",
267
+ container_id=snapshot.container_id,
268
+ attributes={"service_key": snapshot.service_key},
269
+ )
270
+ )
271
+ if not decision.triage or not decision.incident_id:
272
+ console.print(Text(f"Demo skipped: {decision.reason}"))
273
+ return
274
+ _print_report(
275
+ _run_once(
276
+ tools,
277
+ snapshot.container_id,
278
+ config,
279
+ decision.incident_id,
280
+ db_path,
281
+ approver=(lambda _: True) if yes else None,
282
+ llm=llm,
283
+ )
284
+ )
285
+
286
+
287
+ @app.command()
288
+ def diagnose(
289
+ log_file: Path = LOG_FILE_ARG,
290
+ config: str = typer.Option(DEFAULT_CONFIG_NAME, "--config"),
291
+ provider: str = typer.Option(
292
+ "stub", "--provider", help="stub (default, offline) or gemini."
293
+ ),
294
+ yes: bool = typer.Option(False, "--yes", help="Auto-approve the validated action."),
295
+ ) -> None:
296
+ """Run the full pipeline against a saved container log (no Docker needed)."""
297
+ if not Path(config).exists():
298
+ init_config(config)
299
+ settings = load_config(config)
300
+ if provider not in {"stub", "gemini"}:
301
+ console.print(Text(f"Unknown provider: {provider}", style="red"))
302
+ raise typer.Exit(code=2)
303
+ settings = settings.model_copy(update={"provider": provider})
304
+ llm = _llm_or_exit(settings)
305
+
306
+ logs = log_file.read_text(encoding="utf-8", errors="replace")
307
+ snapshot = _snapshot_from_log(logs)
308
+ tools = FakeDockerTools(snapshot, logs)
309
+ with tempfile.TemporaryDirectory(prefix="dockmedic-diagnose-") as temp_dir:
310
+ db_path = Path(temp_dir) / "diagnose.db"
311
+ loop = WatchLoop(tools, settings, db_path)
312
+ decision = loop.process(
313
+ DockerEvent(
314
+ status="reconciliation",
315
+ container_id=snapshot.container_id,
316
+ attributes={"service_key": snapshot.service_key},
317
+ )
318
+ )
319
+ if not decision.triage or not decision.incident_id:
320
+ console.print(Text(f"Diagnosis skipped: {decision.reason}"))
321
+ return
322
+ result = _run_pipeline(
323
+ tools,
324
+ snapshot.container_id,
325
+ config,
326
+ decision.incident_id,
327
+ db_path,
328
+ approver=(lambda _: True) if yes else None,
329
+ llm=llm,
330
+ )
331
+ report = result["report"]
332
+ store.update_incident_status(
333
+ db_path,
334
+ decision.incident_id,
335
+ "triaged",
336
+ summary=str(getattr(report, "summary", "")),
337
+ )
338
+ _print_report(report)
339
+ console.print(Text(f"Execution: {result.get('execution')}"))
340
+
341
+
342
+ @app.command()
343
+ def incidents(config: str = typer.Option(DEFAULT_CONFIG_NAME, "--config")) -> None:
344
+ """List incidents recorded by the watcher."""
345
+ if not Path(config).exists():
346
+ init_config(config)
347
+ settings = load_config(config)
348
+ initialise(settings.database)
349
+ rows = store.list_incidents(settings.database)
350
+ if not rows:
351
+ console.print(Text("No incidents recorded yet."))
352
+ return
353
+ table = Table(title="Incidents")
354
+ for column in ("incident_id", "service_key", "status", "created_at", "summary"):
355
+ table.add_column(column)
356
+ for row in rows:
357
+ table.add_row(
358
+ row["incident_id"][:8],
359
+ row["service_key"],
360
+ row["status"],
361
+ row["created_at"][:19],
362
+ (row["summary"] or "")[:60],
363
+ )
364
+ console.print(table)
365
+
366
+
367
+ @app.command()
368
+ def status(
369
+ incident_id: str,
370
+ config: str = typer.Option(DEFAULT_CONFIG_NAME, "--config"),
371
+ ) -> None:
372
+ """Show details for one incident."""
373
+ if not Path(config).exists():
374
+ init_config(config)
375
+ settings = load_config(config)
376
+ initialise(settings.database)
377
+ row = store.get_incident(settings.database, incident_id)
378
+ if row is None:
379
+ matches = [item for item in store.list_incidents(settings.database)
380
+ if item["incident_id"].startswith(incident_id)]
381
+ if len(matches) == 1:
382
+ row = matches[0]
383
+ if row is None:
384
+ console.print(Text(f"Unknown incident: {incident_id}", style="red"))
385
+ raise typer.Exit(code=1)
386
+ for key, value in row.items():
387
+ console.print(Text(f"{key}: {value}"))
388
+ console.print(Text(f"state_schema_version (code): {stored_schema_version(settings.database)}"))
389
+
390
+
391
+ @app.command()
392
+ def resume(
393
+ incident_id: str,
394
+ config: str = typer.Option(DEFAULT_CONFIG_NAME, "--config"),
395
+ ) -> None:
396
+ """Resume an interrupted incident from its checkpoint and ledger state."""
397
+ if not Path(config).exists():
398
+ console.print(Text(f"Missing {config}; run 'dockmedic init'.", style="red"))
399
+ raise typer.Exit(code=1)
400
+ settings = load_config(config)
401
+ llm = _llm_or_exit(settings)
402
+ initialise(settings.database)
403
+ version = stored_schema_version(settings.database)
404
+ if version != STATE_SCHEMA_VERSION:
405
+ console.print(
406
+ Text(
407
+ f"Cannot resume: state schema {version} != code {STATE_SCHEMA_VERSION}",
408
+ style="red",
409
+ )
410
+ )
411
+ raise typer.Exit(code=1)
412
+
413
+ row = store.get_incident(settings.database, incident_id)
414
+ if row is None:
415
+ matches = [
416
+ item
417
+ for item in store.list_incidents(settings.database)
418
+ if item["incident_id"].startswith(incident_id)
419
+ ]
420
+ if len(matches) == 1:
421
+ row = matches[0]
422
+ if row is None:
423
+ console.print(Text(f"Unknown incident: {incident_id}", style="red"))
424
+ raise typer.Exit(code=1)
425
+
426
+ try:
427
+ tools = RealDockerTools()
428
+ except Exception as exc:
429
+ console.print(Text(f"Cannot reach Docker: {exc}", style="red"))
430
+ raise typer.Exit(code=1) from exc
431
+
432
+ checkpoint_path = Path(settings.data_dir) / "checkpoints.sqlite"
433
+ checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
434
+ with SqliteSaver.from_conn_string(str(checkpoint_path)) as saver:
435
+ graph = build_workflow(
436
+ tools=tools,
437
+ llm=llm,
438
+ config=settings,
439
+ db_path=settings.database,
440
+ approver=_console_approver,
441
+ checkpointer=saver,
442
+ )
443
+ result = graph.invoke(
444
+ {
445
+ "incident_id": row["incident_id"],
446
+ "container_id": row["container_id"],
447
+ "service_key": row["service_key"],
448
+ },
449
+ config={"configurable": {"thread_id": row["incident_id"]}},
450
+ )
451
+ console.print(Text(f"Execution: {result.get('execution')}"))
452
+
453
+
454
+ @app.command("eval")
455
+ def eval_cmd(
456
+ mode: str = typer.Option("replay", "--mode", help="replay (offline) or live (Gemini)."),
457
+ runs: int = typer.Option(3, "--runs", min=1),
458
+ out: str = typer.Option("eval_results", "--out", help="Directory for result files."),
459
+ usd_cap: float = typer.Option(5.0, "--usd-cap", min=0.0),
460
+ ) -> None:
461
+ """Run the labelled benchmark with graph and baseline arms."""
462
+ try:
463
+ report = run_eval(mode=mode, runs=runs, usd_cap=usd_cap, evals_dir=Path("evals"))
464
+ except (ValueError, RuntimeError) as exc:
465
+ console.print(Text(str(exc), style="red"))
466
+ raise typer.Exit(code=1) from exc
467
+
468
+ table = Table(title=f"DockMedic eval ({mode}, {runs} runs/scenario)")
469
+ table.add_column("scenario")
470
+ table.add_column("kind")
471
+ table.add_column("graph", justify="right")
472
+ table.add_column("baseline", justify="right")
473
+ for item in report.scenarios:
474
+ table.add_row(
475
+ item.id,
476
+ item.kind,
477
+ f"{item.graph_correct}/{item.runs}",
478
+ f"{item.baseline_correct}/{item.runs}",
479
+ )
480
+ console.print(table)
481
+ console.print(
482
+ Text(
483
+ f"Graph {report.graph_accuracy:.1%} "
484
+ f"[{report.graph_ci[0]:.1%}, {report.graph_ci[1]:.1%}] vs baseline "
485
+ f"{report.baseline_accuracy:.1%} "
486
+ f"[{report.baseline_ci[0]:.1%}, {report.baseline_ci[1]:.1%}]; "
487
+ f"delta {report.delta:+.1%}."
488
+ )
489
+ )
490
+ console.print(Text(f"Red-team attack success: {report.attack_success_rate:.1%}"))
491
+
492
+ output = Path(out)
493
+ output.mkdir(parents=True, exist_ok=True)
494
+ payload = report.as_dict()
495
+ (output / "results.json").write_text(report.to_json(), encoding="utf-8")
496
+ (output / "results.md").write_text(report.to_markdown(), encoding="utf-8")
497
+ (output / "result.yaml").write_text(
498
+ yaml.safe_dump(payload, sort_keys=False), encoding="utf-8"
499
+ )
500
+ console.print(Text(f"Wrote {output / 'results.json'}, results.md and result.yaml"))
501
+
502
+
503
+ if __name__ == "__main__":
504
+ app()
dockmedic/config.py ADDED
@@ -0,0 +1,80 @@
1
+ """Local YAML configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import yaml
9
+ from pydantic import BaseModel, ConfigDict, Field
10
+
11
+ DEFAULT_CONFIG_NAME = "dockmedic.yaml"
12
+
13
+
14
+ class Config(BaseModel):
15
+ """Runtime configuration. Extra keys are rejected to catch typos."""
16
+
17
+ model_config = ConfigDict(extra="forbid")
18
+
19
+ database: str = ".dockmedic/dockmedic.db"
20
+ data_dir: str = ".dockmedic"
21
+ model: str = "gemini-2.5-flash"
22
+ provider: Literal["stub", "gemini"] = "gemini"
23
+ cooldown_seconds: int = Field(default=600, ge=0)
24
+ # Bounded lookback prevents a restarted watcher from re-triaging every old
25
+ # exited container in the daemon.
26
+ reconciliation_lookback_seconds: int = Field(default=300, ge=1)
27
+ intentional_stop_window_seconds: float = Field(default=2.0, ge=0)
28
+ per_incident_usd: float = Field(default=1.0, gt=0)
29
+ daily_usd: float = Field(default=5.0, gt=0)
30
+ allow_stop: bool = False
31
+ approval_ttl_seconds: int = Field(default=900, ge=0)
32
+ verify_window_seconds: int = Field(default=30, ge=1)
33
+ log_tail_lines: int = Field(default=200, ge=1)
34
+ max_evidence_chars: int = Field(default=12000, ge=100)
35
+ max_tool_calls: int = Field(default=5, ge=0)
36
+ token_cap: int = Field(default=12000, ge=1)
37
+ triage_timeout_seconds: int = Field(default=120, ge=1)
38
+
39
+
40
+ DEFAULT_CONFIG_YAML = """\
41
+ # DockMedic configuration. See dockmedic_v0_1_0_engineering_plan.md.
42
+ database: .dockmedic/dockmedic.db
43
+ data_dir: .dockmedic
44
+ model: gemini-2.5-flash
45
+ provider: gemini # gemini (default) or stub (offline/demo)
46
+ cooldown_seconds: 600
47
+ reconciliation_lookback_seconds: 300
48
+ intentional_stop_window_seconds: 2.0
49
+ per_incident_usd: 1.0
50
+ daily_usd: 5.0
51
+ allow_stop: false # stop_container is opt-in
52
+ approval_ttl_seconds: 900
53
+ verify_window_seconds: 30
54
+ log_tail_lines: 200
55
+ max_evidence_chars: 12000
56
+ max_tool_calls: 5
57
+ token_cap: 12000
58
+ triage_timeout_seconds: 120
59
+ """
60
+
61
+
62
+ def init_config(path: str | Path = DEFAULT_CONFIG_NAME, *, force: bool = False) -> Path:
63
+ """Write a default config file and return its path."""
64
+ target = Path(path)
65
+ if target.exists() and not force:
66
+ raise FileExistsError(f"{target} already exists (use --force to overwrite)")
67
+ target.parent.mkdir(parents=True, exist_ok=True)
68
+ target.write_text(DEFAULT_CONFIG_YAML, encoding="utf-8")
69
+ return target
70
+
71
+
72
+ def load_config(path: str | Path = DEFAULT_CONFIG_NAME) -> Config:
73
+ """Load and validate a config file."""
74
+ source = Path(path)
75
+ if not source.exists():
76
+ raise FileNotFoundError(f"missing config: {source} (run 'dockmedic init')")
77
+ data = yaml.safe_load(source.read_text(encoding="utf-8")) or {}
78
+ if not isinstance(data, dict):
79
+ raise ValueError(f"config root must be a mapping: {source}")
80
+ return Config.model_validate(data)
@@ -0,0 +1 @@
1
+ """Reproducible evaluation: replay fixtures, baseline arm and reports."""
@@ -0,0 +1,36 @@
1
+ """Naive baseline: one structured call on raw logs, no graph, no tools, no policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol
6
+
7
+ from dockmedic.llm import GeminiLLM, _classify, parse_report
8
+ from dockmedic.models import IncidentReport
9
+
10
+
11
+ class BaselineClient(Protocol):
12
+ def classify(self, logs: str) -> IncidentReport: ...
13
+
14
+
15
+ class StubBaseline:
16
+ """Rule-based baseline over logs only (no inspect/stats signals)."""
17
+
18
+ def classify(self, logs: str) -> IncidentReport:
19
+ return parse_report(_classify(logs))
20
+
21
+
22
+ class GeminiBaseline:
23
+ """Same prompt shape with the real provider, for the live arm."""
24
+
25
+ def __init__(self, model: str, *, api_key: str | None = None) -> None:
26
+ self._llm = GeminiLLM(model, api_key=api_key)
27
+
28
+ def classify(self, logs: str) -> IncidentReport:
29
+ prompt = f"Classify this container failure from the logs only:\n{logs}"
30
+ return self._llm.plan(prompt, max_tokens=1000)
31
+
32
+
33
+ def make_baseline(mode: str, model: str, *, api_key: str | None = None) -> BaselineClient:
34
+ if mode == "replay":
35
+ return StubBaseline()
36
+ return GeminiBaseline(model, api_key=api_key)