Metadata-Version: 2.5
Name: dockmedic
Version: 0.1.5
Summary: Safe, bounded, resumable diagnosis of local Docker container failures
Project-URL: Homepage, https://github.com/ammarfitwalla/dockmedic
Project-URL: Repository, https://github.com/ammarfitwalla/dockmedic
Project-URL: Issues, https://github.com/ammarfitwalla/dockmedic/issues
Project-URL: Releases, https://github.com/ammarfitwalla/dockmedic/releases
Project-URL: Changelog, https://github.com/ammarfitwalla/dockmedic/releases
Author: DockMedic contributors
License: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: docker>=7.1
Requires-Dist: langgraph-checkpoint-sqlite>=2.0
Requires-Dist: langgraph>=0.2
Requires-Dist: pydantic>=2.8
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: rich>=13.7
Requires-Dist: typer>=0.12
Provides-Extra: gemini
Requires-Dist: langchain-google-genai>=2.0; extra == 'gemini'
Description-Content-Type: text/markdown

# DockMedic

[![CI](https://github.com/ammarfitwalla/dockmedic/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/ammarfitwalla/dockmedic/actions/workflows/ci.yml?query=branch%3Amaster)
[![Tag](https://img.shields.io/github/v/tag/ammarfitwalla/dockmedic)](https://github.com/ammarfitwalla/dockmedic/tags)

**Bounded, reviewable, resumable, measured.** DockMedic is a local CLI that
diagnoses Docker container failures with a single-agent triage inside a
deterministic pipeline. The LLM proposes a root cause and one of three small
actions; code decides what is actually allowed to happen, asks for approval,
and records the outcome in an execution ledger.

This is a portfolio project for local Docker development hosts, not a paid
product and not a production safety guarantee. See `project_overview.md` for a
plain-language overview and `dockmedic_v0_1_0_engineering_plan.md` (Rev 2) for
the engineering plan.

**v0.1.5 note:** this release fixes the stale-approval regression (a committed
intent is not consent to retry unless container state proves the action ran),
adds a bounded fresh-approval prompt loop, expands best-effort secret redaction,
makes verification wait for `verify_window_seconds`, widens the intentional-stop
window to 15 s, isolates per-incident watcher errors, reconnects the Docker event
stream, supports Python 3.13, adds a dependency audit, and publishes with PyPI
Trusted Publishing attestations. The replay figures below are unchanged because
replay uses the offline stub and no live model was called.

## Why it exists

Log diagnosis alone is a commodity. The interesting engineering problem is:
what happens when the model is wrong, compromised, or interrupted half-way
through an action? DockMedic answers that with four pieces of code that do not
trust the model:

1. A strict action schema: the LLM cannot name a container, a command, or an
   extra field.
2. A deterministic policy: allowlist, opt-in stop, code-attached target, and
   bounded read-only fetch-count, token, and stage-time breakers. There is no
   LLM tool loop; fetch count is the three fixed read-only calls in ingest.
3. An approval screen that prints the validated action object, plus a hash/TTL
   binding so approval cannot be replayed against a different state.
4. A SQLite ledger: an fsynced intent is written before Docker is touched, and
   resume reconciles from that record.

## Install

Python 3.11+ is required. Install from PyPI:

```bash
python -m pip install dockmedic
```

With the optional Gemini provider dependencies:

```bash
python -m pip install "dockmedic[gemini]"
```

Using [uv](https://docs.astral.sh/uv/) instead of `pip`:

```bash
uv tool install dockmedic
uv tool install "dockmedic[gemini]"
```

To install an unreleased tagged commit directly from GitHub instead:

```bash
python -m pip install "dockmedic @ git+https://github.com/ammarfitwalla/dockmedic.git@v0.1.5"
```

## Quickstart

After installation:

```bash
dockmedic init
dockmedic demo --yes    # offline OOM fixture; uses the stub, no Docker/API key
dockmedic diagnose /path/to/your/container.log --yes  # saved log, no Docker needed
dockmedic watch         # needs Docker, Gemini access and GOOGLE_API_KEY
dockmedic incidents
dockmedic status <incident-id-prefix>
dockmedic resume <incident-id-prefix>
```

From a source clone, prefix each command with `uv run` after `uv sync --locked`:

```bash
uv sync --locked
uv run dockmedic init
uv run dockmedic demo --yes
uv run dockmedic diagnose demo/sample_container.log --yes
uv run dockmedic eval --mode replay --runs 3
```

`dockmedic demo` and `watch` will prompt before any restart. `stop_container`
is disabled unless `allow_stop: true` is set in `dockmedic.yaml`.

### LLM provider

`watch` and `resume` use the configured provider from `dockmedic.yaml`; the
default is `gemini` with `model: gemini-2.5-flash`. Install the provider extra
and export a key before running them:

```bash
python -m pip install "dockmedic[gemini]"
export GOOGLE_API_KEY="..."
```

Set `provider: stub` in the config to run entirely offline without a key. The
`demo` and `diagnose` commands default to `--provider stub` so they stay
reproducible; pass `--provider gemini` to exercise the real client against the
same fixture. `dockmedic eval --mode replay` always uses the stub; `--mode live`
uses Gemini with a hard `--usd-cap`. Gemini is the only real provider, behind
`LLMClient`.

`dockmedic diagnose <log-file>` runs the whole pipeline against a saved log with
no Docker daemon. It infers a small synthetic inspect snapshot from the text
(`exit_code`, `restart_count`, OOM flag), so it is a replay/demo aid, not a
substitute for live Docker state. The sample in `demo/sample_container.log`
includes a URL credential that the scrubber redacts before the LLM sees it.

## Pipeline

```mermaid
flowchart LR
    E[Docker events] --> W[Watch: bounded reconciliation,\nintentional-stop filter,\ndedupe + cooldown]
    W --> I[Ingest: scrub, sanitise,\ntruncate, delimit]
    I --> T[Triage: LLM, read-only]
    T --> P[Plan: strict IncidentReport]
    P --> Q[Policy: allowlist,\ncode target, breakers]
    Q --> A{Approve\ninterrupt}
    A -->|yes| X[Execute: ledger intent,\nstate guard, Docker call]
    A -->|no| R[Report only]
    X --> V[Verify + ledger outcome]
```

Execution is **at-least-once delivery of idempotent, state-guarded actions** —
not exactly-once. If the process dies after Docker ran but before the ledger was
updated, resume sees the container state and skips the duplicate call.

## What the tests prove

| Claim | Evidence |
| --- | --- |
| Best-effort secret redaction | Labelled corpus gate in `tests/security/`; every labelled secret is removed. No "zero leakage" claim. |
| Control/bidi/ANSI text is neutralised | `tests/test_sanitize.py`. |
| Policy rejects malicious plans | Mock-LLM malicious-plan corpus (smuggled target, shell string, extra keys, out-of-enum action) plus Hypothesis invariants: for any action object the target equals the incident container and nothing outside the allowlist reaches Docker. |
| Approvals are bound and expire | `tests/policy/test_approval.py` (action, container, `started_at`, policy version, TTL). |
| Stale approvals cannot silently retry | Expired-TTL kill-point tests: state must prove the action ran, otherwise a bounded fresh-approval prompt is required. |
| Verification observes a window | `tests/graph/test_verify.py`; `verify_window_seconds` is enforced with an injectable clock. |
| Watcher survives bad incidents and stream drops | `tests/watch/` and `tests/tools/` cover per-incident error isolation and bounded event-stream reconnect. |
| Crash-safe execution | Four kill-point scenarios: before intent, after intent/before Docker, after Docker/before executed write, after executed. |
| Red-team behaviour | Five red-team scenarios recorded as counts and labelled a smoke test, not a measured attack rate. |
| Replay harness check | Graph vs baseline on fixed fixtures with scenario-level uncertainty (see below). |

The deterministic mock-LLM tests are the primary security evidence. Live-model
runs would be supporting evidence, not a substitute.

## Evaluation

`evals/` contains a taxonomy, author-written labels, 10 functional scenarios,
5 red-team scenarios, recorded `logs`/`inspect`/`stats` fixtures, a pinned model
ID and price table. `dockmedic eval --mode replay` runs a harness check: the
graph and a naive baseline (one structured call on raw logs, no read-only
fetches and no policy) over the same corpus, 3 runs per scenario by default.
It validates code paths on fixed fixtures, not live model quality.

Result generated 2026-11-28 with `uv run dockmedic eval --mode replay --runs 3`
(stub LLM, offline; the model ID is a pinned config label, **no live model was
called**). Full artefacts: `eval_results/results.json`, `results.md`,
`result.yaml`.

| Arm | Accuracy | 95% CI |
| --- | ---: | ---: |
| Graph | 100.0% | [100.0%, 100.0%] |
| Baseline | 86.7% | [66.7%, 100.0%] |
| Delta (graph − baseline) | +13.3% | [+0.0%, +33.3%] |

Counts rather than percentages: graph 30/30 correct, baseline 26/30 correct.
The graph wins on `oom-basic` (3/3 vs 0/3) and `crash-loop` (3/3 vs 0/3)
because it can read structured signals the baseline never receives.

Red-team smoke test: 5 scenarios x 3 runs, **0 policy bypasses** in the replay
harness. This is a count on a malicious-plan corpus, not a claim about all
possible prompts.

Uncertainty uses a percentile bootstrap over **scenarios**, with the 3 correlated
runs collapsed into one scenario accuracy first. Wilson intervals on individual
runs would overstate the sample size because runs within a scenario are not
independent. With 15 scenarios the intervals are wide; treat the delta as
directional, not precise.

Cost and latency are recorded for both arms in the artefacts. Replay spend is
$0.0000 because the stub makes no network calls. `--mode live` uses Gemini with
a hard `--usd-cap`; actual prompt/completion tokens are settled where the
provider reports them, and structured-output calls use a length estimate from
the pinned price table ($0.30/M input, $2.50/M output for `gemini-2.5-flash`).
Live eval **never runs in CI**. Temperature is 0 but providers are not
deterministic and retire models, so results are dated, not eternal.

## Limitations

- Docker-only, intended for developer hosts; no cluster or remote daemon support.
- Small corpus (15 scenarios), labelled by one author: no independent annotator.
- The stub LLM is rule-based; replay validates the harness and code paths, not
  real model quality. Live numbers require a separate dated run with an API key.
  `watch`/`resume` default to Gemini, so they do spend tokens and need network
  access unless the config is switched to `provider: stub`.
- Best-effort scrubber: known patterns only, no guarantee against novel secrets.
- `stop_container` is opt-in, and semantic harm from an allowed action on the
  intended container is out of scope.
- Live watch/DoD cannot be exercised in environments without Docker; the
  offline demo, `diagnose` and replay suite cover the same code paths with a
  fake client and a log-derived snapshot.
- A dated live eval with equal inputs for graph and baseline is still pending;
  the numbers below are a replay harness check only.

## Development

```bash
uv run ruff check .
uv run mypy src
uv export --format requirements-txt --no-hashes --no-emit-project -o requirements.txt
uv run pip-audit --strict --disable-pip --no-deps -r requirements.txt
uv run pytest          # 72 tests
```

CI syncs `uv.lock` with `uv sync --locked`, runs lint, strict mypy, a dependency
audit, all tests, and the replay eval. Actions are pinned by commit SHA,
permissions are least-privilege, and Dependabot is enabled. Releases are
published to PyPI from a protected environment using PyPI Trusted Publishing;
PEP 740 attestations are generated automatically and no token is stored in the
repo. There is no `litellm` dependency:
its PyPI package shipped credential-stealing releases after a CI compromise in
March 2026.
