Skip to content

Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.

feat(agent): read-only database tools for the agent (#193)

Karlo Kajba Šimanić20a6a5caa8ba
diff --git a/SECURITY.md b/SECURITY.md
index 2170eee..da87a08 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -82,6 +82,13 @@ marked recommended (`src/agent/safety.py`). Nothing the model writes is run. Tur
automatically" in Admin › Incident agent to send nothing unless someone asks; without a key nothing is sent
and incidents keep the rule-based diagnosis, which is worked out locally.
+**The agent's tools** (`src/agent/tools/`, used from #157 on) let it look up more of the same stored data: metrics,
+containers, filesystems, events, earlier incidents, availability results, listening ports and the firewall, from
+the last 90 days. The list is closed and every call is checked against the tool's schema before anything is read.
+No tool writes, contacts a collector or runs a command. Results are bounded and masked like the evidence pack; a
+check's target is sent without its credentials and query string; IP addresses, users, the audit log and enrolment
+are never returned, so a tool answers everyone the same and shows nothing the dashboard doesn't.
+
**Who sees the agent.** With "Show diagnoses to users" off, the backend leaves the agent's report out of every
incident, Overview line and notification for users who aren't admins. Chat access is "Admins only" by default; with
"Per user", only users an admin switched on in Admin › Users may chat, and the backend answers 403 to everyone
diff --git a/TESTS.md b/TESTS.md
index 95a579d..30e35c0 100644
--- a/TESTS.md
+++ b/TESTS.md
@@ -4,7 +4,7 @@ Infradeck ships with an automated test suite. This page explains how to run it,
covers (and what it doesn't), and what every single test is for, so you can decide
whether a failure matters before you upgrade or change your setup.
-- **1488 test cases** from 805 test functions, plus 38 small tests of the frontend helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).
+- **1537 test cases** from 828 test functions, plus 38 small tests of the frontend helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).
- **About two minutes** to run. No Docker, PostgreSQL, Redis, network or root access needed.
- **Safe to run next to a live install.** The tests use a throwaway in-memory database
and fakes; they never touch your running containers or your data. (Two collector
@@ -134,7 +134,7 @@ side and the backend's side in one file, because the feature only works when bot
| `tests/collectors/` | Adding and trusting collectors (enrollment, approval, pending servers, the dashboard's own machine), what they report and how it is validated, the filesystems they report, the read-only Docker proxy, and the version they report. |
| `tests/monitoring/` | What is watched and how it turns into incidents: the alert engine and its rules, system, container and network checks, the system helper and the container details. |
| `tests/history/` | Long-term history: rollups, the history API, statistics and the database indexes behind them. |
-| `tests/assistant/` | The AI assistant: its providers, fixed health checks, error messages and conversations. |
+| `tests/assistant/` | The AI assistant: its providers, read-only tools, fixed health checks, error messages and conversations. |
| `tests/security/` | Tests written from security reviews that cut across areas: request size limits, the second review's findings and the nginx security headers. |
`tests/conftest.py` (settings every test shares) and `tests/fakes.py` (the fake Redis) stay at the top.
@@ -151,6 +151,7 @@ The chart helper tests for the frontend are separate, in `src/frontend/tests/`.
| [`test_agent_providers.py`](#test_agent_providerspy) | 12 | The Claude provider, and how the chosen provider, model and encrypted API key are stored. |
| [`test_agent_tool_calls.py`](#test_agent_tool_callspy) | 24 | Tool calling with Claude, OpenAI and Gemini: calls, several at once, errors, masking, append-only history, forcing an answer. |
| [`test_agent_diagnosis.py`](#test_agent_diagnosispy) | 42 | The agent's diagnosis: the evidence pack, secret masking, dangerous commands, checking the model's answer, saving reports. |
+| [`test_agent_tools.py`](#test_agent_toolspy) | 49 | The agent's read-only tools: a closed list with strict schemas, checked arguments, bounded and masked results with fact IDs, no secrets or IP addresses, nothing written. |
| [`test_agent_watch.py`](#test_agent_watchpy) | 10 | Reusing a recent diagnosis, and watching the fix until the agent resolves the incident. |
| [`test_agent_worker.py`](#test_agent_workerpy) | 12 | The agent's job queue and worker: one job per opened or worsened incident after the commit, retries, time limit, restarts. |
| [`test_alerts.py`](#test_alertspy) | 10 | The incident engine: one incident per problem, resolve, container rules. |
@@ -385,6 +386,38 @@ Most tests run once per provider (Claude, OpenAI, Gemini), with fake clients.
| `test_without_a_key_the_worker_leaves_the_rule_based_diagnosis` | Without an API key the job is skipped and says why. |
| `test_with_automatic_diagnosis_off_only_a_request_is_diagnosed` | With automatic diagnosis off, only a requested diagnosis runs. |
+### test_agent_tools.py
+
+The tools run on a small database with a fixed clock: two days of check-ins, hourly summaries before the last week,
+a container killed for memory, events, incidents, an availability check with a password and token in its URL, ports
+and a firewall.
+
+| Test | What it checks |
+|---|---|
+| `test_every_tool_is_listed_once_with_a_strict_schema` | The eleven tools are each listed once, every schema is strict (all fields required, nothing extra allowed), and every host metric offered can be read. |
+| `test_an_unknown_tool_is_refused` | A call to a tool that isn't on the list (`run_shell`) is refused. |
+| `test_bad_arguments_are_refused_with_a_reason_the_model_can_act_on` *(17 inputs)* | Missing or extra arguments, wrong types, values outside a list, oversized text, bad or reversed times, windows older than 90 days, container snapshots older than 7 days, and unknown checks or containers are refused before anything is read, with a reason (and the names that do exist). |
+| `test_an_unknown_server_is_answered_with_the_known_ones` | An unknown hostname is answered with the servers that exist; a different letter case still finds the server. |
+| `test_host_metrics_reads_every_check_in_of_the_last_week_and_keeps_the_peak` | A window inside the last week is read from every check-in, a one-sample spike survives cutting the series to 40 points, and the label names the window. |
+| `test_the_window_defaults_to_the_last_24_hours_and_empty_metrics_to_the_usual_five` | Without `from` and `to` the window is the last 24 hours; without metrics, CPU, memory, swap, load and disk. |
+| `test_older_windows_are_read_from_the_hourly_summaries` | A window older than a week comes from the hourly summaries, with their averages and peaks. |
+| `test_no_data_in_the_window_says_so` | A server with no check-ins in the window gets a note and no facts. |
+| `test_server_info_has_the_machine_facts_and_no_ip_address` | Machine facts come back; the server's IP address does not. |
+| `test_list_containers_puts_the_ones_not_running_first` | Stopped containers come before running ones; an OOM kill is shown. |
+| `test_container_history_reports_restarts_and_oom_kills` | A restart with exit code 137 and an OOM kill show as one change at the right time, with the container's series and fact IDs. |
+| `test_disk_usage_estimates_growth_and_when_it_fills_up` | A disk growing 1 GB a day with 40 GB free is estimated to fill in about 40 days; an unknown mount is refused. |
+| `test_events_show_the_newest_thirty_oldest_first_and_filter_by_kind` | Of 42 events the newest 30 come back, oldest first, each labelled; filtering by kind works. |
+| `test_compare_to_baseline_sets_an_hour_against_the_same_hour_before` | An hour is compared with the same hour yesterday and over the previous 4 weeks, for a past hour and for the current one. |
+| `test_find_incidents_filters_by_server_and_kind` | Incidents filter by server and kind, newest first, with how long they lasted and how they were resolved. |
+| `test_fleet_snapshot_shows_every_server_now_and_at_an_earlier_moment` | Every server's online state, open incidents and failing checks, now and at an earlier moment; check results older than a week are reported as unknown. |
+| `test_check_results_show_downtime_and_errors_without_the_targets_secrets` | Down periods, error counts and response times come back; the target's password and token never do. |
+| `test_network_state_lists_ports_firewall_and_recent_changes` | Listening ports with who can reach them, the firewall state and the last week's port changes. |
+| `test_every_result_is_bounded_masked_free_of_ip_addresses_and_labelled` *(11 inputs)* | For every tool: the result fits the size limit, a password in the data is masked, no IP address appears, and the labels are exactly the fact IDs in the result. |
+| `test_a_result_too_large_is_shortened_and_loses_the_labels_of_what_was_cut` | A result over the limit drops its oldest entries, says it was truncated, and the dropped facts can't be cited. |
+| `test_a_long_series_is_thinned_keeping_its_peak` | A series over the limit is thinned by joining neighbours, and its peak survives. |
+| `test_the_same_question_gives_the_same_ids_and_a_second_window_joins_the_label` | The same call gives the same result and IDs; the same series read for another window keeps one ID whose label lists both windows. |
+| `test_tools_never_write_to_the_database` | After every tool, the database session has nothing new, changed or deleted. |
+
### test_agent_watch.py
| Test | What it checks |
diff --git a/docs/assistant.md b/docs/assistant.md
index dcc2524..08a5eff 100644
--- a/docs/assistant.md
+++ b/docs/assistant.md
@@ -113,6 +113,69 @@ container checks, point `DOCKER_SOCKET_PATH` at a hardened Docker API proxy that
endpoints. `daily_checkup` combines host and container checks; on a critical finding it POSTs an alert only to
`ADMIN_ALERT_WEBHOOK_URL`, and without it the result says `not_configured` and no request is made.
+## What the agent can look up
+
+Besides the evidence pack, the agent has eleven **read-only tools** (`src/agent/tools/`): questions it can ask
+Infradeck's database while it investigates, such as "how did CPU change on 3 November between 10:00 and 12:00" or
+"has this disk filled up before". The tools are ready; diagnoses and the chat start calling them, within a budget of
+calls, in the next step of the agent upgrade (#157). Until then the agent works from the evidence pack alone.
+
+| Tool | What it answers |
+|---|---|
+| `server_info` | What the machine is and how it is now: OS, kernel, CPU, memory, collector and Docker versions, last check-in, online, pending updates, uptime, reboot needed, clock sync, Docker and internet reachability. |
+| `host_metrics` | CPU, memory, swap, load, root disk, inodes, Docker API and collector timing over a window: min, max, average, first, last and up to 40 points per metric. |
+| `list_containers` | Every container at one check-in (last 7 days): status, health, CPU, memory and limit, restarts, exit code, OOM kill, image. Not running and largest first. |
+| `container_history` | One container over a window: CPU, memory and restart count, how much of the time it was not running, its memory limit, and (last 7 days) each change of status, health, exit code, OOM kill or image. |
+| `disk_usage` | Every filesystem (or one): used space and inodes now, usage over the last N days, growth in GB per day and in about how many days it fills up. |
+| `events` | What the machine recorded: reboots, OOM kills, kernel faults, image changes, containers added or removed, ports opened or closed, firewall changes, package updates. The newest 30. |
+| `compare_to_baseline` | A metric's average over one hour next to the same hour yesterday and that hour of the day over the previous 4 weeks, with the difference. |
+| `find_incidents` | Earlier incidents on one server or all of them, of one kind or any: how long they lasted and how they were resolved. |
+| `fleet_snapshot` | Every server at one moment: online, open incidents and the worst of them, failing availability checks. Tells one machine's problem from everyone's. |
+| `check_results` | Availability checks over a window: uptime, when they were down, the errors they got, response times. |
+| `network_state` | Listening ports (and whether other machines can reach them), the firewall, and port and firewall changes in the last 7 days. |
+
+**What they may read.** Only what Infradeck already stores. No tool writes anything, contacts a collector or runs a
+command, and the list is closed: a call to any other name, or with arguments that don't match the tool's schema
+(an unknown field, a wrong type, a value outside its list), is refused before anything is read. The agent names a
+server by its hostname and a container or check by its name; an unknown one is answered with the names it may use.
+
+**How far back.** Any window in the last **90 days**, given as `from` and `to` (UTC); without them, the last 24
+hours. The last 7 days come from every check-in; older windows from the hourly summaries, the same data as the
+charts on Statistics, so two hours from last month are two points. The agent is told to start wide and narrow down.
+
+**How much comes back.** Each series is cut to 40 points, each the highest value of its stretch, so a short peak
+is never averaged away; lists keep their newest 30 entries; text is clipped; a whole result stays under about
+12 KB. If it would be larger, the longest list is halved (a series by joining neighbouring points, keeping the
+higher one) and the result says `"truncated": true`.
+
+**What never comes back.** Every result is masked for secrets like the evidence pack (`masking.py`), and the
+interface masks it again before it is sent (`add_tool_results`). A check's target is always shown as non-admins
+see it, without credentials or query string, because it goes to the model provider. IP addresses, users, the audit
+log and enrolment are not readable by any tool. So a tool gives the same answer whoever asked, and a user who
+may chat learns nothing through it that the dashboard doesn't show them.
+
+**Fact IDs.** Every fact a tool returns has an ID that a diagnosis cites, as with the evidence pack. The ID says
+what the fact is, not when it was read, so the same question always gives the same ID; the window is in the label
+shown next to it ("CPU · web1 · 2026-11-03 10:00–12:00 UTC"). When the agent reads the same series twice with
+different windows, the label keeps both.
+
+| Fact | ID |
+|---|---|
+| a recorded event, an incident | `event:812`, `incident:31` (as in the evidence pack) |
+| a host metric, a filesystem | `metric:web1.cpu`, `metric:web1.disk:/var` |
+| a container, its metrics | `container:web1/nginx`, `metric:web1/nginx.memory_mb` |
+| a machine, its ports and firewall | `server:web1`, `network:web1` |
+| an hour against its usual level | `baseline:web1.cpu` |
+| an availability check | `uptime:7` (`check:N` in the evidence pack means the alert rule's own checks) |
+| a server in the fleet snapshot | `fleet:web1` |
+
+**Adding a tool.** Write the function in the module for its area (`servers.py`, `containers.py`, `activity.py`):
+it gets the database session, the checked arguments, the time and a `Facts` collector, and returns a dict whose
+facts each carry an `id` added with `facts.add`. Register it in `tools/__init__.py` with a description and a
+strict schema (every property required, `additionalProperties: false`, null for "not given"), and add tests to
+`tests/assistant/test_agent_tools.py`: the shared tests then check that it stays bounded, masked, labelled and
+read-only.
+
## What it costs
Every call to the model is recorded with the tokens the provider reports for it (see `agent_runs` in
diff --git a/src/agent/bounds.py b/src/agent/bounds.py
new file mode 100644
index 0000000..e151f35
--- /dev/null
+++ b/src/agent/bounds.py
@@ -0,0 +1,46 @@
+"""Keeps what the agent is told small: text clipped, series cut to a few dozen points with the peaks kept, numbers
+rounded. Shared by the evidence pack (evidence.py) and the read-only tools (tools/), so both read the same way.
+"""
+from __future__ import annotations
+
+import math
+from datetime import datetime, timezone
+
+SERIES_POINTS = 40
+MAX_TEXT = 300
+
+
+def utc(moment: datetime | None) -> datetime | None:
+ return None if moment is None else moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
+
+
+def stamp(moment: datetime | None) -> str | None:
+ """A time as the agent sees it everywhere: ISO 8601 in UTC, to the minute."""
+ return None if moment is None else utc(moment).isoformat(timespec="minutes")
+
+
+def clip(text: str | None, limit: int = MAX_TEXT) -> str:
+ text = (text or "").strip()
+ return text if len(text) <= limit else text[: limit - 1] + "…"
+
+
+def points(rows: list[tuple[datetime, float | None]], limit: int = SERIES_POINTS) -> list[list]:
+ """[[time, value], …] with at most ``limit`` points, keeping each group's highest value (peaks matter)."""
+ rows = [(moment, value) for moment, value in rows if value is not None]
+ if len(rows) > limit:
+ size = math.ceil(len(rows) / limit)
+ rows = [(rows[start][0], max(value for _, value in rows[start:start + size])) for start in range(0, len(rows), size)]
+ return [[stamp(moment), round(value, 2)] for moment, value in rows]
+
+
+def stats(values: list[float]) -> dict | None:
+ if not values:
+ return None
+ return {"min": round(min(values), 2), "max": round(max(values), 2), "avg": round(sum(values) / len(values), 2), "first": round(values[0], 2), "last": round(values[-1], 2)}
+
+
+def series(fact_id: str, label: str, unit: str, rows: list[tuple[datetime, float | None]], limit: float | None = None) -> dict | None:
+ values = [value for _, value in rows if value is not None]
+ if not values:
+ return None
+ return {"id": fact_id, "label": label, "unit": unit, "limit": limit, "stats": stats(values), "points": points(rows)}
diff --git a/src/agent/evidence.py b/src/agent/evidence.py
index 5108858..af8ec2e 100644
--- a/src/agent/evidence.py
+++ b/src/agent/evidence.py
@@ -8,55 +8,22 @@ before the pack is stored or sent anywhere.
"""
from __future__ import annotations
-import math
from datetime import datetime, timedelta, timezone
from src.backend import incidents
from src.backend.models import ContainerMetric, HostMetric, IncidentAlert, MountMetric, Server, SystemEvent
+from .bounds import clip as _clip, series as _series, utc as _utc
from .masking import mask
LEAD = timedelta(minutes=60)
-SERIES_POINTS = 40
MAX_EVENTS = 30
MAX_IMAGE_CHANGES = 10
MAX_SIMILAR = 5
-MAX_TEXT = 300
SIMILAR_DAYS = 90
IMAGE_HISTORY_DAYS = 30
-def _utc(moment: datetime | None) -> datetime | None:
- return None if moment is None else moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
-
-
-def _clip(text: str | None, limit: int = MAX_TEXT) -> str:
- text = (text or "").strip()
- return text if len(text) <= limit else text[: limit - 1] + "…"
-
-
-def _points(rows: list[tuple[datetime, float | None]], limit: int = SERIES_POINTS) -> list[list]:
- """[[time, value], …] with at most ``limit`` points, keeping each group's highest value (peaks matter)."""
- rows = [(moment, value) for moment, value in rows if value is not None]
- if len(rows) > limit:
- size = math.ceil(len(rows) / limit)
- rows = [(rows[start][0], max(value for _, value in rows[start:start + size])) for start in range(0, len(rows), size)]
- return [[_utc(moment).isoformat(timespec="minutes"), round(value, 2)] for moment, value in rows]
-
-
-def _stats(values: list[float]) -> dict | None:
- if not values:
- return None
- return {"min": round(min(values), 2), "max": round(max(values), 2), "avg": round(sum(values) / len(values), 2), "first": round(values[0], 2), "last": round(values[-1], 2)}
-
-
-def _series(fact_id: str, label: str, unit: str, rows: list[tuple[datetime, float | None]], limit: float | None = None) -> dict | None:
- values = [value for _, value in rows if value is not None]
- if not values:
- return None
- return {"id": fact_id, "label": label, "unit": unit, "limit": limit, "stats": _stats(values), "points": _points(rows)}
-
-
def build(db, incident: IncidentAlert, now: datetime | None = None) -> dict:
"""The pack for ``incident``: what it is, the machine, metrics around it, events, image changes, the rule's own
checks and similar incidents before it. Masked and bounded."""
diff --git a/src/agent/tools/__init__.py b/src/agent/tools/__init__.py
new file mode 100644
index 0000000..95e029d
--- /dev/null
+++ b/src/agent/tools/__init__.py
@@ -0,0 +1,173 @@
+"""The agent's read-only tools (#114): what it may look up in Infradeck's database while it investigates.
+
+Every tool reads data Infradeck already stores. None of them writes, and none contacts a collector or a monitored
+machine. The list is closed: ``run`` refuses any other name, and checks the arguments against the tool's schema
+before anything is read. What comes back is bounded (a few dozen points per series, the newest entries of lists,
+clipped text, about 12 KB in all), masked (masking.py), and carries fact IDs that a diagnosis can cite; ``labels``
+says what each ID is. Check targets are always shown without credentials or query string, as non-admins see them,
+because the result goes to the model provider; nothing that only admins can see (IP addresses, users, the audit log,
+enrolment) is returned, so a tool gives the same answer whoever is asking.
+
+The loop that offers these to the model, with its budget and audit log, is in #157. See docs/assistant.md.
+"""
+from __future__ import annotations
+
+import json
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import datetime, timezone
+
+from ..masking import mask, mask_text
+from ..providers.base import Tool
+from . import activity, containers, servers
+from .common import MAX_DAYS, Facts, ToolError, merge_labels
+
+__all__ = ["TOOLS", "Output", "ToolError", "merge_labels", "run"]
+
+MAX_RESULT_CHARS = 12000
+MAX_STRING = 200
+MAX_ITEMS = 12
+
+
+def _object(**properties) -> dict:
+ return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False}
+
+
+def _nullable(kind: str, description: str) -> dict:
+ return {"anyOf": [{"type": kind}, {"type": "null"}], "description": description}
+
+
+SERVER = {"type": "string", "description": "The server's hostname, as the evidence names it."}
+FROM = _nullable("string", "Start of the window, ISO 8601 in UTC (2026-11-07T10:00). null: 24 hours before `to`.")
+TO = _nullable("string", "End of the window, ISO 8601 in UTC. null: now.")
+AT = _nullable("string", "The moment to look at, ISO 8601 in UTC. null: now.")
+WINDOW_NOTE = (f" Any window within the last {MAX_DAYS} days: every check-in for the last 7 days, hourly averages and peaks before that."
+ " Start wide, then narrow down to the interesting hours.")
+
+
+@dataclass
+class Output:
+ content: str # JSON for the model
+ labels: dict[str, str] # fact ID -> what it is, for checking citations and showing them
+
+
+Handler = Callable[[object, dict, datetime, Facts], dict]
+
+_REGISTRY: dict[str, tuple[Tool, Handler]] = {tool.name: (tool, handler) for tool, handler in [
+ (Tool("server_info", "What a server is and how it is doing now: OS, kernel, CPU, memory, collector and Docker versions, last check-in, online or not, "
+ "pending updates, uptime, whether it needs a reboot, clock sync, Docker and internet reachability.", _object(server=SERVER)), servers.server_info),
+ (Tool("host_metrics", "A server's CPU, memory, swap, load, root disk and more over a window, with min, max, average and up to 40 points per metric. "
+ "Each point is the highest value of its stretch, so short peaks stay visible." + WINDOW_NOTE,
+ _object(server=SERVER, metrics={"type": "array", "items": {"type": "string", "enum": list(servers.HOST_METRICS)},
+ "description": "Which metrics. Empty: cpu, ram, swap, load and disk."}, **{"from": FROM, "to": TO})), servers.host_metrics),
+ (Tool("list_containers", "Every Docker container on a server at one check-in: status, health, CPU, memory and its limit, restarts, exit code, OOM kill, image. "
+ "Not running and the largest come first. Only for the last 7 days.", _object(server=SERVER, at=AT)), containers.list_containers),
+ (Tool("container_history", "One container over a window: CPU, memory and restart count as series, how much of the time it was not running, its memory limit, "
+ "and (for the last 7 days) each change of status, health, exit code, OOM kill or image." + WINDOW_NOTE,
+ _object(server=SERVER, container={"type": "string", "description": "The container's name."}, **{"from": FROM, "to": TO})), containers.container_history),
+ (Tool("disk_usage", "Every filesystem of a server (or one): used space and inodes now, usage over the last `days`, growth in GB per day and, when it grows, "
+ "in about how many days it fills up.", _object(server=SERVER, mount=_nullable("string", "One mount point such as /var. null: all of them."),
+ days={"type": "integer", "description": f"How many days back to look at, 1 to {MAX_DAYS}."})), servers.disk_usage),
+ (Tool("events", "What the server recorded in a window: reboots, OOM kills, kernel faults and errors, image changes, containers added or removed, ports "
+ "opened or closed, firewall changes, package updates. The newest 30, oldest first." + WINDOW_NOTE,
+ _object(server=SERVER, kinds={"type": "array", "items": {"type": "string", "enum": list(activity.EVENT_KINDS)}, "description": "Which kinds. Empty: all."},
+ **{"from": FROM, "to": TO})), activity.events),
+ (Tool("compare_to_baseline", "Whether a value is unusual: a host metric's average over one hour, next to the same hour yesterday and the average of "
+ "that hour of the day over the previous 4 weeks.", _object(server=SERVER, metric={"type": "string", "enum": list(servers.BASELINE_METRICS)}, at=AT)),
+ servers.compare_to_baseline),
+ (Tool("find_incidents", "Earlier incidents on one server or all of them: title, kind, severity, how long they lasted and how they were resolved. Newest "
+ "first. The window defaults to the last 30 days.",
+ _object(server=_nullable("string", "A hostname. null: every server."),
+ kind=_nullable("string", "Only this kind, as in the evidence's incident `kind` (host:disk, container:restart_loop, …). null: every kind."),
+ **{"from": _nullable("string", "Start of the window, ISO 8601 in UTC. null: 30 days before `to`."), "to": TO})), activity.find_incidents),
+ (Tool("fleet_snapshot", "Every server at one moment: online or not, open incidents and the worst of them, availability checks failing from it. "
+ "Shows whether a problem is on one machine or many.", _object(at=AT)), activity.fleet_snapshot),
+ (Tool("check_results", "Availability checks (HTTP, TCP, TLS, DNS, ping …) over a window: uptime, when they were down, the errors they got and response "
+ "times. Give one check by name, or a server for every check that runs from it." + WINDOW_NOTE,
+ _object(check=_nullable("string", "The check's name."), server=_nullable("string", "A hostname: every check run from it."), **{"from": FROM, "to": TO})),
+ activity.check_results),
+ (Tool("network_state", "A server's listening ports (and whether other machines can reach them), its firewall configuration, and port and firewall changes "
+ "in the last 7 days.", _object(server=SERVER)), servers.network_state),
+]}
+TOOLS: list[Tool] = [tool for tool, _ in _REGISTRY.values()]
+
+
+def _check(schema: dict, value, path: str) -> None:
+ """``value`` against the small part of JSON Schema the tools use. Raises ToolError naming the argument."""
+ if "anyOf" in schema:
+ for option in schema["anyOf"]:
+ try:
+ return _check(option, value, path)
+ except ToolError:
+ continue
+ raise ToolError(f"{path} has the wrong type.")
+ kind = schema["type"]
+ if kind == "null":
+ if value is not None:
+ raise ToolError(f"{path} must be null.")
+ elif kind == "object":
+ if not isinstance(value, dict) or set(value) != set(schema["properties"]):
+ raise ToolError(f"Give exactly these arguments: {', '.join(schema['properties'])}.")
+ for key, sub in schema["properties"].items():
+ _check(sub, value[key], key)
+ elif kind == "array":
+ if not isinstance(value, list) or len(value) > MAX_ITEMS:
+ raise ToolError(f"{path} must be a list of at most {MAX_ITEMS} items.")
+ for item in value:
+ _check(schema["items"], item, path)
+ elif kind == "string":
+ if not isinstance(value, str) or not value.strip() or len(value) > MAX_STRING:
+ raise ToolError(f"{path} must be a non-empty text of at most {MAX_STRING} characters.")
+ if "enum" in schema and value not in schema["enum"]:
+ raise ToolError(f"{path} must be one of: {', '.join(schema['enum'])}.")
+ elif kind == "integer":
+ if not isinstance(value, int) or isinstance(value, bool):
+ raise ToolError(f"{path} must be a whole number.")
+
+
+def _longest_list(value, best=None):
+ """The longest list anywhere in ``value`` (by its JSON size), to shorten first."""
+ if isinstance(value, list):
+ if len(value) > 1 and (best is None or len(json.dumps(value)) > len(json.dumps(best))):
+ best = value
+ for item in value:
+ best = _longest_list(item, best)
+ elif isinstance(value, dict):
+ for item in value.values():
+ best = _longest_list(item, best)
+ return best
+
+
+def _is_series(items: list) -> bool:
+ return all(isinstance(item, list) and len(item) == 2 and isinstance(item[0], str) for item in items)
+
+
+def _fit(content: dict) -> str:
+ """JSON of at most MAX_RESULT_CHARS. Until it fits, the longest list is halved: a series by joining neighbouring
+ points (keeping the higher value, so peaks survive), any other list by dropping its oldest half."""
+ text = json.dumps(content, ensure_ascii=False, separators=(",", ":"))
+ while len(text) > MAX_RESULT_CHARS:
+ longest = _longest_list(content)
+ if longest is None:
+ return json.dumps({"truncated": True, "note": "The result was too large. Ask for a narrower window or fewer items."})
+ if _is_series(longest):
+ longest[:] = [[longest[index][0], max(point[1] for point in longest[index:index + 2])] for index in range(0, len(longest), 2)]
+ else:
+ del longest[: len(longest) // 2]
+ content["truncated"] = True
+ text = json.dumps(content, ensure_ascii=False, separators=(",", ":"))
+ return text
+
+
+def run(db, name: str, arguments, now: datetime | None = None) -> Output:
+ """Run one tool. Raises ToolError for a call the model can correct (unknown tool, bad arguments, unknown server)."""
+ if name not in _REGISTRY:
+ raise ToolError(f"There is no tool named {str(name)[:60]!r}.")
+ tool, handler = _REGISTRY[name]
+ _check(tool.schema, arguments, "arguments")
+ now = now or datetime.now(timezone.utc)
+ facts = Facts()
+ text = _fit(mask(handler(db, arguments, now, facts)))
+ labels = {mask_text(fact_id): mask_text(label) for fact_id, label in facts.labels.items()}
+ # Only facts still in the result can be cited: a list shortened to fit loses its labels too.
+ return Output(text, {fact_id: label for fact_id, label in labels.items() if json.dumps(fact_id) in text})
diff --git a/src/agent/tools/activity.py b/src/agent/tools/activity.py
new file mode 100644
index 0000000..7147a3f
--- /dev/null
+++ b/src/agent/tools/activity.py
@@ -0,0 +1,158 @@
+"""Tools about what happened: events on a machine, earlier incidents, availability check results, and the state of
+the whole fleet at one moment."""
+from __future__ import annotations
+
+from collections import Counter
+from datetime import datetime, timedelta
+
+from sqlalchemy import or_
+
+from src.backend import availability, incidents
+from src.backend.models import Check, CheckResult, CheckRollup, HostMetric, IncidentAlert, Server, SystemEvent
+
+from ..bounds import clip, series as bounded_series, stamp, utc
+from .common import MAX_LIST, OFFLINE_AFTER_MISSED_CHECKS, Facts, ToolError, find_server, is_online, moment, span, window
+
+EVENT_KINDS = ("reboot", "oom_kill", "kernel_fault", "kernel_error", "image_changed", "container_added", "container_removed", "container_notice",
+ "port_opened", "port_closed", "firewall_changed", "firewall_allowed", "firewall_weakened", "packages_updated", "helper_notice")
+INCIDENT_WINDOW = timedelta(days=30)
+MAX_CHECKS = 10
+MAX_SERVERS = 50
+MAX_ERRORS = 5
+
+
+def _event_label(event: SystemEvent, hostname: str) -> str:
+ return f"{stamp(event.time)[5:16].replace('T', ' ')} {event.kind.replace('_', ' ')} · {hostname}"
+
+
+def events(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ since, until = window(arguments, now)
+ query = db.query(SystemEvent).filter(SystemEvent.server_id == server.id, SystemEvent.time >= since, SystemEvent.time < until)
+ if arguments["kinds"]:
+ query = query.filter(SystemEvent.kind.in_(arguments["kinds"]))
+ total = query.count()
+ newest = query.order_by(SystemEvent.time.desc()).limit(MAX_LIST).all()
+ return {"server": server.hostname, "from": stamp(since), "to": stamp(until), "total": total, "shown": len(newest),
+ "events": [{"id": facts.add(f"event:{event.id}", _event_label(event, server.hostname)), "time": stamp(event.time), "kind": event.kind, "text": clip(event.detail)}
+ for event in reversed(newest)]}
+
+
+def find_incidents(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"]) if arguments["server"] is not None else None
+ since, until = window(arguments, now, INCIDENT_WINDOW)
+ query = db.query(IncidentAlert).filter(IncidentAlert.created_at >= since, IncidentAlert.created_at < until)
+ if server:
+ query = query.filter(IncidentAlert.server_id == server.id)
+ found = [item for item in query.order_by(IncidentAlert.created_at.desc()).limit(2000) if arguments["kind"] is None or incidents.rule_kind(item.rule_key) == arguments["kind"]]
+ names = dict(db.query(Server.id, Server.hostname).all())
+ listed = []
+ for item in found[:MAX_LIST]:
+ reference = incidents.reference(item.id)
+ opened, resolved = utc(item.created_at), utc(item.resolved_at)
+ listed.append({"id": facts.add(f"incident:{item.id}", f"{reference} · {clip(item.title, 120)}"), "reference": reference, "server": names.get(item.server_id),
+ "kind": incidents.rule_kind(item.rule_key), "severity": item.severity, "title": clip(item.title), "state": incidents.state_of(item),
+ "opened_at": stamp(opened), "resolved_at": stamp(resolved), "lasted_minutes": round(((resolved or now) - opened).total_seconds() / 60),
+ "resolution": clip(item.resolution) if item.resolution else None})
+ return {"server": server.hostname if server else "all", "from": stamp(since), "to": stamp(until), "total": len(found), "incidents": listed}
+
+
+def _pick_checks(db, arguments: dict) -> list[Check]:
+ if (arguments["check"] is None) == (arguments["server"] is None):
+ raise ToolError("Give either check (its name) or server, not both.")
+ if arguments["check"] is not None:
+ name = arguments["check"].strip().lower()
+ checks = [check for check in db.query(Check).order_by(Check.name) if check.name.lower() == name]
+ if not checks:
+ known = [check_name for (check_name,) in db.query(Check.name).order_by(Check.name).limit(MAX_LIST)]
+ raise ToolError(f"No availability check is named {arguments['check']!r}. Checks: {', '.join(known) or 'none'}.")
+ return checks[:1]
+ server = find_server(db, arguments["server"])
+ return [check for check in db.query(Check).order_by(Check.name) if server.id in availability.servers_of(check)][:MAX_CHECKS]
+
+
+def _check_report(db, check: Check, since: datetime, until: datetime, now: datetime, names: dict[int, str], facts: Facts) -> dict:
+ """Up and down over the window: completed hours from the hourly summaries once raw results are gone, then every
+ result (which also tells when it was down and why)."""
+ total = down = 0
+ response: list[tuple[datetime, float | None]] = []
+ rolled = utc(check.rolled_until)
+ raw_from = since
+ if since < now - availability.RAW_KEPT and rolled:
+ raw_from = min(max(since, rolled), until)
+ for hour, slots_count, down_count, max_ms in db.query(CheckRollup.hour, CheckRollup.slots, CheckRollup.down_slots, CheckRollup.max_ms) \
+ .filter(CheckRollup.check_id == check.id, CheckRollup.hour >= since, CheckRollup.hour < raw_from).order_by(CheckRollup.hour):
+ total, down = total + slots_count, down + down_count
+ response.append((utc(hour), max_ms))
+ results = availability._results(db, check, raw_from, until) if raw_from < until else []
+ periods: list[list[datetime]] = [] # [start, end] of each run of down slots
+ step = timedelta(seconds=check.interval_seconds)
+ for slot in availability.slots(check, results):
+ start = datetime.fromisoformat(slot["start"])
+ total += 1
+ response.append((start, slot["response_ms"]))
+ if slot["status"] == "down":
+ down += 1
+ if periods and periods[-1][1] == start:
+ periods[-1][1] = start + step
+ else:
+ periods.append([start, start + step])
+ errors = Counter(clip(result.detail, 160) for result in results if not result.ok and result.detail)
+ fact_id = facts.add(f"uptime:{check.id}", f"check {clip(check.name, 60)} · {span(since, until)}")
+ return {
+ "id": fact_id, "name": check.name, "type": check.type, "target": availability.redacted_target(check.target), "state": check.state, "paused": check.paused,
+ "runs_from": [names.get(server, f"server {server}") for server in availability.servers_of(check)],
+ "uptime_pct": round(100 * (total - down) / total, 2) if total else None, "checks_in_window": total, "down": down,
+ "down_periods": [{"from": stamp(start), "to": stamp(end)} for start, end in periods[-MAX_LIST:]], "errors": [{"detail": detail, "count": count} for detail, count in errors.most_common(MAX_ERRORS)],
+ "response_ms": bounded_series(fact_id, "response time (each point the slowest of its stretch)", "ms", response),
+ }
+
+
+def check_results(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ checks = _pick_checks(db, arguments)
+ since, until = window(arguments, now)
+ names = dict(db.query(Server.id, Server.hostname).all())
+ return {"from": stamp(since), "to": stamp(until), "checks": [_check_report(db, check, since, until, now, names, facts) for check in checks],
+ "note": None if checks else "No availability checks run from this server."}
+
+
+def _failing(db, at: datetime) -> dict[int, list[str]]:
+ """Per server, the checks whose last result there before ``at`` failed."""
+ failing: dict[int, list[str]] = {}
+ for check in db.query(Check).filter(Check.paused.is_(False)):
+ recent = max(timedelta(minutes=10), timedelta(seconds=check.interval_seconds * (check.retries + 2)))
+ last: dict[int, bool] = {}
+ for result in db.query(CheckResult).filter(CheckResult.check_id == check.id, CheckResult.time > at - recent, CheckResult.time <= at).order_by(CheckResult.time):
+ last[result.server_id] = result.ok
+ for server_id, ok in last.items():
+ if not ok:
+ failing.setdefault(server_id, []).append(clip(check.name, 80))
+ return failing
+
+
+def fleet_snapshot(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ at = moment(arguments["at"], now)
+ servers = db.query(Server).order_by(Server.hostname).limit(MAX_SERVERS + 1).all()
+ open_then = db.query(IncidentAlert).filter(IncidentAlert.created_at <= at, or_(IncidentAlert.resolved_at.is_(None), IncidentAlert.resolved_at > at)) \
+ .order_by(IncidentAlert.created_at.desc()).limit(500).all()
+ checks_known = at >= now - availability.RAW_KEPT
+ failing = _failing(db, at) if checks_known else {}
+ output = []
+ for server in servers[:MAX_SERVERS]:
+ if at >= now - timedelta(minutes=1):
+ online = is_online(server, now)
+ else:
+ gap = timedelta(seconds=server.check_interval_seconds * OFFLINE_AFTER_MISSED_CHECKS)
+ online = db.query(HostMetric.id).filter(HostMetric.server_id == server.id, HostMetric.time > at - gap, HostMetric.time <= at).first() is not None
+ mine = [item for item in open_then if item.server_id == server.id]
+ for item in mine[:3]:
+ facts.add(f"incident:{item.id}", f"{incidents.reference(item.id)} · {clip(item.title, 120)}")
+ output.append({
+ "id": facts.add(f"fleet:{server.hostname}", f"{server.hostname} at {stamp(at)[5:16].replace('T', ' ')} UTC"),
+ "server": server.hostname, "online": online, "open_incidents": len(mine),
+ "worst": "CRITICAL" if any(item.severity == "CRITICAL" for item in mine) else "WARNING" if mine else None,
+ "newest_incidents": [{"id": f"incident:{item.id}", "title": clip(item.title, 120), "severity": item.severity} for item in mine[:3]],
+ "failing_checks": failing.get(server.id, []) if checks_known else None,
+ })
+ return {"at": stamp(at), "servers": output, "more_servers": max(0, len(servers) - MAX_SERVERS),
+ "note": None if checks_known else f"Check results older than {availability.RAW_KEPT.days} days are kept only as hourly totals, so failing checks are not known for that time."}
diff --git a/src/agent/tools/common.py b/src/agent/tools/common.py
new file mode 100644
index 0000000..e93e455
--- /dev/null
+++ b/src/agent/tools/common.py
@@ -0,0 +1,134 @@
+"""What every read-only tool shares: finding the server, the time window, reading a series at the right level of
+detail, and the fact IDs a diagnosis cites.
+
+Fact IDs say what a fact is, not when it was read (``metric:web1.cpu``, ``container:web1/nginx``), so the same
+question gives the same ID every time. The window goes into the label instead; when the agent reads the same series
+twice, the two labels are joined (``merge_labels``).
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+
+from sqlalchemy import func
+
+from src.backend import history, rollups
+from src.backend.models import Server
+from src.backend.retention import DETAILED_KEPT
+
+from ..bounds import points, stamp, utc
+
+MAX_DAYS = 90 # how far back any tool reads
+DEFAULT_WINDOW = timedelta(hours=24)
+MAX_LIST = 30 # newest entries of any list
+MAX_LABEL = 240
+OFFLINE_AFTER_MISSED_CHECKS = 3 # as in src/backend/main.py
+
+
+class ToolError(ValueError):
+ """A mistake in the call, told to the model so it can correct it. Never carries internal details."""
+
+
+class Facts:
+ """The fact IDs one call returns, each with a short label for checking citations and showing them."""
+
+ def __init__(self):
+ self.labels: dict[str, str] = {}
+
+ def add(self, fact_id: str, label: str) -> str:
+ self.labels[fact_id] = label[:MAX_LABEL]
+ return fact_id
+
+
+def merge_labels(known: dict[str, str], new: dict[str, str]) -> dict[str, str]:
+ """Labels of a whole conversation: a fact read again with another window keeps both windows in its label."""
+ merged = dict(known)
+ for fact_id, label in new.items():
+ old = merged.get(fact_id)
+ merged[fact_id] = label if old is None else old if label in old else f"{old}; {label}"[:MAX_LABEL]
+ return merged
+
+
+def parse_time(value: str | None, name: str) -> datetime | None:
+ if value is None:
+ return None
+ try:
+ return utc(datetime.fromisoformat(value.strip().replace("Z", "+00:00")))
+ except ValueError:
+ raise ToolError(f"{name} must be an ISO 8601 time such as 2026-11-07T10:00 (UTC), or null.") from None
+
+
+def oldest(now: datetime) -> datetime:
+ return now - timedelta(days=MAX_DAYS)
+
+
+def window(arguments: dict, now: datetime, default: timedelta = DEFAULT_WINDOW) -> tuple[datetime, datetime]:
+ """``from`` and ``to`` from the call: ``to`` defaults to now, ``from`` to ``default`` before ``to``. Both must lie
+ within the last MAX_DAYS days, and ``from`` before ``to``."""
+ until = min(parse_time(arguments.get("to"), "to") or now, now)
+ since = parse_time(arguments.get("from"), "from") or until - default
+ if since >= until:
+ raise ToolError("from must be earlier than to.")
+ if since < oldest(now):
+ raise ToolError(f"Tools read at most the last {MAX_DAYS} days: from must be after {stamp(oldest(now))}.")
+ return since, until
+
+
+def moment(value: str | None, now: datetime, name: str = "at") -> datetime:
+ """A single moment (``at``): now when null, otherwise within the last MAX_DAYS days."""
+ at = min(parse_time(value, name) or now, now)
+ if at < oldest(now):
+ raise ToolError(f"Tools read at most the last {MAX_DAYS} days: {name} must be after {stamp(oldest(now))}.")
+ return at
+
+
+def span(since: datetime, until: datetime) -> str:
+ """A window for a label: ``2026-11-03 10:00–12:00`` or ``2026-11-01 00:00 – 2026-11-07 00:00`` (UTC)."""
+ start, end = stamp(since).replace("T", " ")[:16], stamp(until).replace("T", " ")[:16]
+ return f"{start}–{end[11:]} UTC" if start[:10] == end[:10] else f"{start} – {end} UTC"
+
+
+def find_server(db, name: str) -> Server:
+ server = db.query(Server).filter(Server.hostname == name).first() or db.query(Server).filter(func.lower(Server.hostname) == name.lower()).first()
+ if server is None:
+ known = [hostname for (hostname,) in db.query(Server.hostname).order_by(Server.hostname).limit(MAX_LIST)]
+ raise ToolError(f"No server is named {name!r}. Servers: {', '.join(known) or 'none'}.")
+ return server
+
+
+def is_online(server: Server, at: datetime) -> bool:
+ last = utc(server.last_seen_at)
+ return last is not None and at - last < timedelta(seconds=server.check_interval_seconds * OFFLINE_AFTER_MISSED_CHECKS)
+
+
+def read(db, spec: history.Series, server_id: int, key: str | None, names, since: datetime, until: datetime, now: datetime):
+ """[(start, Agg)] for ``names`` between ``since`` and ``until``, and where it came from: every check-in while
+ those are kept (DETAILED_KEPT), hourly summaries for anything older."""
+ if since >= now - DETAILED_KEPT:
+ return history._raw_items(db, spec, list(names), server_id, key, since, until), "check-ins"
+ items, _ = history._tiered_items(db, spec, list(names), server_id, key, rollups.HOUR, since, until)
+ return [(start, agg) for start, agg in items if since <= start < until], "hourly summaries"
+
+
+def summary(fact_id: str, label: str, unit: str, items, name: str, source: str) -> dict | None:
+ """One metric of ``items`` as the agent sees it: min, max, average, first and last, and up to SERIES_POINTS
+ points that each keep the highest value of their stretch, so short peaks are not averaged away."""
+ rows = []
+ total = count = 0.0
+ peak = None
+ for start, agg in items:
+ value_total, value_count, value_max = agg.values.get(name, (0.0, 0, None))
+ average = value_total / value_count if value_count else None
+ rows.append((start, value_max if value_max is not None else average, average))
+ total, count = total + value_total, count + value_count
+ if value_max is not None and (peak is None or value_max > peak):
+ peak = value_max
+ averages = [average for _, _, average in rows if average is not None]
+ if not averages and peak is None:
+ return None
+ values = averages or [peak]
+ return {
+ "id": fact_id, "label": label, "unit": unit, "source": source,
+ "stats": {"min": round(min(values), 2), "max": round(peak if peak is not None else max(values), 2), "avg": round(total / count if count else sum(values) / len(values), 2),
+ "first": round(values[0], 2), "last": round(values[-1], 2)},
+ "points": points([(start, value) for start, value, _ in rows]),
+ }
diff --git a/src/agent/tools/containers.py b/src/agent/tools/containers.py
new file mode 100644
index 0000000..5f234e3
--- /dev/null
+++ b/src/agent/tools/containers.py
@@ -0,0 +1,107 @@
+"""Tools about a machine's Docker containers: every container at one check-in, and one container over time."""
+from __future__ import annotations
+
+from datetime import datetime
+
+from sqlalchemy import func
+
+from src.backend import history
+from src.backend.models import ContainerMetric, ContainerRollup
+from src.backend.retention import DETAILED_KEPT
+
+from ..bounds import clip, stamp, utc
+from .common import MAX_LIST, Facts, ToolError, find_server, moment, read, span, summary, window
+
+MAX_CONTAINERS = 40
+MAX_IDS = 5 # a container recreated more often than this in one window is read from its newest IDs
+SERIES = {"cpu": ("CPU", "%"), "memory_mb": ("memory", "MB"), "restarts": ("restart count (running total)", "")}
+
+
+def list_containers(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ at = moment(arguments["at"], now)
+ if at < now - DETAILED_KEPT:
+ raise ToolError(f"Snapshots of every container are kept for {DETAILED_KEPT.days} days. For older times use container_history.")
+ taken = db.query(func.max(ContainerMetric.time)).filter(ContainerMetric.server_id == server.id, ContainerMetric.time <= at, ContainerMetric.time >= now - DETAILED_KEPT).scalar()
+ rows = db.query(ContainerMetric).filter(ContainerMetric.server_id == server.id, ContainerMetric.time == taken).all() if taken else []
+ rows.sort(key=lambda row: (row.status == "running", -(row.memory_used_mb or 0)))
+ output = []
+ for row in rows[:MAX_CONTAINERS]:
+ fact_id = facts.add(f"container:{server.hostname}/{row.name}", f"{row.name} on {server.hostname} at {stamp(taken)[5:16].replace('T', ' ')} UTC")
+ output.append({"id": fact_id, "name": row.name, "image": clip(row.image, 120), "project": row.project, "status": row.status, "health": row.healthcheck_status,
+ "cpu_pct": row.cpu_pct, "memory_mb": row.memory_used_mb, "memory_limit_mb": row.memory_limit_mb, "memory_pct": row.memory_pct,
+ "restarts": row.restart_count, "exit_code": row.exit_code, "oom_killed": row.oom_killed, "started_at": row.started_at})
+ return {"server": server.hostname, "at": stamp(taken), "containers": output, "more_containers": max(0, len(rows) - MAX_CONTAINERS),
+ "note": None if rows else "No container data from this server at or before that time."}
+
+
+def _ids(db, server_id: int, name: str, since: datetime, until: datetime) -> list[str]:
+ """The Docker IDs the container had in the window, newest first (it gets a new one each time it is recreated)."""
+ raw = db.query(ContainerMetric.container_id, func.max(ContainerMetric.time)).filter(ContainerMetric.server_id == server_id, ContainerMetric.name == name,
+ ContainerMetric.time >= since, ContainerMetric.time < until).group_by(ContainerMetric.container_id).all()
+ rolled = db.query(ContainerRollup.container_id, func.max(ContainerRollup.bucket_start)).filter(ContainerRollup.server_id == server_id, ContainerRollup.name == name,
+ ContainerRollup.bucket_start >= since, ContainerRollup.bucket_start < until).group_by(ContainerRollup.container_id).all()
+ newest: dict[str, datetime] = {}
+ for container_id, last in raw + rolled:
+ newest[container_id] = max(newest.get(container_id, utc(last)), utc(last))
+ return sorted(newest, key=newest.get, reverse=True)[:MAX_IDS]
+
+
+def _changes(db, server_id: int, name: str, since: datetime, until: datetime) -> list[dict]:
+ """Moments its state changed: status, health, restarts, exit code, OOM kill, image. Only from check-ins."""
+ rows = db.query(ContainerMetric).filter(ContainerMetric.server_id == server_id, ContainerMetric.name == name, ContainerMetric.time >= since, ContainerMetric.time < until) \
+ .order_by(ContainerMetric.time).limit(50_000).all()
+ changes, previous = [], None
+ for row in rows:
+ if previous is not None:
+ what = []
+ if row.status != previous.status:
+ what.append(f"status {previous.status} → {row.status}")
+ if row.healthcheck_status != previous.healthcheck_status:
+ what.append(f"health {previous.healthcheck_status or 'none'} → {row.healthcheck_status or 'none'}")
+ if row.restart_count > previous.restart_count:
+ what.append(f"restarted {row.restart_count - previous.restart_count}×")
+ if row.exit_code is not None and row.exit_code != previous.exit_code:
+ what.append(f"exit code {row.exit_code}")
+ if row.oom_killed and not previous.oom_killed:
+ what.append("killed for running out of memory")
+ if row.image_id and previous.image_id and row.image_id != previous.image_id:
+ what.append("now runs a different image build")
+ if what:
+ changes.append({"time": stamp(row.time), "change": ", ".join(what)})
+ previous = row
+ return changes[-MAX_LIST:]
+
+
+def container_history(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ name = arguments["container"]
+ since, until = window(arguments, now)
+ ids = _ids(db, server.id, name, since, until)
+ if not ids:
+ known = [found for (found,) in db.query(ContainerMetric.name).filter(ContainerMetric.server_id == server.id, ContainerMetric.time >= now - DETAILED_KEPT).distinct().order_by(ContainerMetric.name).limit(MAX_LIST)]
+ raise ToolError(f"No container {name!r} on {server.hostname} in that window. Containers seen there this week: {', '.join(known) or 'none'}.")
+ items, source = [], "check-ins"
+ for container_id in ids:
+ found, source = read(db, history.CONTAINER, server.id, container_id, list(SERIES), since, until, now)
+ items += found
+ items.sort(key=lambda item: item[0])
+ series = []
+ for metric, (label, unit) in SERIES.items():
+ fact_id = f"metric:{server.hostname}/{name}.{metric}"
+ found = summary(fact_id, f"{name} {label} · {server.hostname} · {span(since, until)}", unit, items, metric, source)
+ if found:
+ facts.add(fact_id, found["label"])
+ series.append(found)
+ samples, down = sum(agg.samples for _, agg in items), sum(agg.down for _, agg in items)
+ latest = db.query(ContainerMetric).filter(ContainerMetric.server_id == server.id, ContainerMetric.name == name, ContainerMetric.time < until).order_by(ContainerMetric.time.desc()).first()
+ raw_from = max(since, now - DETAILED_KEPT)
+ return {
+ "id": facts.add(f"container:{server.hostname}/{name}", f"{name} on {server.hostname} · {span(since, until)}"),
+ "server": server.hostname, "container": name, "from": stamp(since), "to": stamp(until), "recreated": len(ids) > 1,
+ "not_running_pct": round(100 * down / samples, 1) if samples else None,
+ "memory_limit_mb": latest.memory_limit_mb if latest else None, "image": clip(latest.image, 120) if latest else None,
+ "series": series,
+ "changes": _changes(db, server.id, name, raw_from, until) if raw_from < until else [],
+ "changes_from": stamp(raw_from) if raw_from < until else None,
+ }
diff --git a/src/agent/tools/servers.py b/src/agent/tools/servers.py
new file mode 100644
index 0000000..53c6fb0
--- /dev/null
+++ b/src/agent/tools/servers.py
@@ -0,0 +1,148 @@
+"""Tools about one machine: what it is, its metrics over time, its disks, how a value compares with its usual level,
+and its open ports and firewall."""
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+
+from src.backend import history, rollups
+from src.backend.models import FirewallState, HostMetric, HostRollup, ListenerState, MountMetric, SystemEvent
+
+from ..bounds import clip, stamp, utc
+from .common import MAX_LIST, Facts, ToolError, find_server, is_online, moment, read, span, summary, window
+
+HOST_METRICS = { # name: (label, unit)
+ "cpu": ("CPU", "%"), "ram": ("memory", "%"), "swap": ("swap", "%"), "load": ("load (1 min)", ""), "disk": ("root disk", "%"),
+ "inodes": ("root disk inodes", "%"), "docker_ms": ("Docker API response", "ms"), "collect_ms": ("collector check-in time", "ms"),
+}
+BASELINE_METRICS = ("cpu", "ram", "swap", "load", "disk", "inodes")
+BASELINE_WEEKS = 4
+MAX_MOUNTS = 12
+NETWORK_EVENTS = ("port_opened", "port_closed", "firewall_changed", "firewall_allowed", "firewall_weakened")
+NETWORK_DAYS = 7
+
+
+def server_info(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ system = json.loads(server.system_info) if server.system_info else {}
+ latest = db.query(HostMetric).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc()).first()
+ return {
+ "id": facts.add(f"server:{server.hostname}", f"{server.hostname}: machine facts"),
+ "hostname": server.hostname, "online": is_online(server, now), "last_check_in": stamp(server.last_seen_at), "check_every_seconds": server.check_interval_seconds,
+ "runs_the_dashboard": server.is_dashboard_host, "os": server.os_info, "kernel": system.get("kernel"), "arch": system.get("arch"), "cpu_model": system.get("cpu_model"),
+ "cpu_cores": server.cpu_cores, "memory_gb": round(server.total_ram_gb, 1) if server.total_ram_gb else None, "swap_gb": system.get("swap_total_gb"),
+ "collector_version": system.get("collector_version"), "docker_version": system.get("docker_version"),
+ "updates_pending": system.get("updates_pending"), "security_updates_pending": system.get("updates_security"), "automatic_updates": system.get("auto_updates"),
+ "uptime_hours": round(latest.system_uptime_seconds / 3600, 1) if latest and latest.system_uptime_seconds else None,
+ "reboot_required": latest.reboot_required if latest else None, "clock_synced": latest.ntp_synced if latest else None,
+ "docker": latest.docker_status if latest else None, "internet": latest.internet_status if latest else None,
+ }
+
+
+def host_metrics(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ since, until = window(arguments, now)
+ names = list(dict.fromkeys(arguments["metrics"])) or list(history.DEFAULT_HOST_METRICS)
+ items, source = read(db, history.HOST, server.id, None, names, since, until, now)
+ series = []
+ for name in names:
+ label, unit = HOST_METRICS[name]
+ fact_id = f"metric:{server.hostname}.{name}"
+ found = summary(fact_id, f"{label} · {server.hostname} · {span(since, until)}", unit, items, name, source)
+ if found:
+ series.append(found)
+ facts.add(fact_id, found["label"])
+ return {"server": server.hostname, "from": stamp(since), "to": stamp(until), "series": series,
+ "note": None if series else "No check-ins from this server in that window."}
+
+
+def _growth_per_day(rows: list[tuple[datetime, float]]) -> float | None:
+ """Least-squares slope of used space in GB per day; None with too little data to tell."""
+ if len(rows) < 3 or (rows[-1][0] - rows[0][0]) < timedelta(hours=6):
+ return None
+ xs = [(moment - rows[0][0]).total_seconds() / 86400 for moment, _ in rows]
+ ys = [value for _, value in rows]
+ mean_x, mean_y = sum(xs) / len(xs), sum(ys) / len(ys)
+ spread = sum((x - mean_x) ** 2 for x in xs)
+ return sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys)) / spread if spread else None
+
+
+def disk_usage(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ days = arguments["days"]
+ if not 1 <= days <= 90:
+ raise ToolError("days must be between 1 and 90.")
+ since = now - timedelta(days=days)
+ latest = db.query(MountMetric.time).filter(MountMetric.server_id == server.id).order_by(MountMetric.time.desc()).limit(1).scalar()
+ mounts = db.query(MountMetric).filter(MountMetric.server_id == server.id, MountMetric.time == latest).order_by(MountMetric.mount).all() if latest else []
+ if arguments["mount"] is not None:
+ mounts = [mount for mount in mounts if mount.mount == arguments["mount"]]
+ if not mounts:
+ raise ToolError(f"{server.hostname} reports no mount {arguments['mount']!r}. Leave mount null to see them all.")
+ output = []
+ for mount in mounts[:MAX_MOUNTS]:
+ items, source = read(db, history.MOUNT, server.id, mount.mount, ["used_pct", "used_gb"], since, now, now)
+ used = [(start, agg.values["used_gb"][0] / agg.values["used_gb"][1]) for start, agg in items if agg.values.get("used_gb", (0, 0))[1]]
+ growth = _growth_per_day(used)
+ free = (mount.total_gb or 0) - (mount.used_gb or 0)
+ fact_id = f"metric:{server.hostname}.disk:{mount.mount}"
+ usage = summary(fact_id, f"{mount.mount} used · {server.hostname} · last {days} d", "%", items, "used_pct", source)
+ facts.add(fact_id, usage["label"] if usage else f"{mount.mount} on {server.hostname}")
+ output.append({
+ "id": fact_id, "mount": mount.mount, "filesystem": mount.fs_type, "used_pct": mount.used_pct, "used_gb": mount.used_gb, "total_gb": mount.total_gb, "inodes_pct": mount.inodes_pct,
+ "growth_gb_per_day": round(growth, 2) if growth is not None else None,
+ "full_in_days": round(free / growth, 1) if growth and growth > 0.01 and free > 0 else None,
+ "usage": usage,
+ })
+ return {"server": server.hostname, "measured_at": stamp(latest), "mounts": output, "more_mounts": max(0, len(mounts) - MAX_MOUNTS)}
+
+
+def _hour_average(db, server_id: int, name: str, start: datetime, now: datetime) -> float | None:
+ """The metric's average over the hour from ``start`` (so far, for the current hour)."""
+ items, _ = read(db, history.HOST, server_id, None, [name], start, min(start + timedelta(hours=1), now + timedelta(seconds=1)), now)
+ total = sum(agg.values.get(name, (0.0, 0, None))[0] for _, agg in items)
+ count = sum(agg.values.get(name, (0.0, 0, None))[1] for _, agg in items)
+ return total / count if count else None
+
+
+def compare_to_baseline(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ name = arguments["metric"]
+ at = moment(arguments["at"], now)
+ hour = rollups.floor(rollups.HOUR, at)
+ value = _hour_average(db, server.id, name, hour, now)
+ yesterday = _hour_average(db, server.id, name, hour - timedelta(days=1), now)
+ column = history.HOST_METRICS[name].avg
+ rows = db.query(HostRollup.bucket_start, getattr(HostRollup, column)).filter(
+ HostRollup.server_id == server.id, HostRollup.tier == rollups.HOUR, HostRollup.bucket_start >= hour - timedelta(weeks=BASELINE_WEEKS), HostRollup.bucket_start < hour).all()
+ same_hour = [average for start, average in rows if utc(start).hour == hour.hour and average is not None]
+ usual = sum(same_hour) / len(same_hour) if same_hour else None
+ label, unit = HOST_METRICS[name]
+ fact_id = facts.add(f"baseline:{server.hostname}.{name}", f"{label} at {stamp(hour)[11:16]} UTC vs usual · {server.hostname} · {stamp(hour)[:10]}")
+ rounded = lambda number: None if number is None else round(number, 2) # noqa: E731
+ return {
+ "id": fact_id, "server": server.hostname, "metric": name, "unit": unit, "hour": stamp(hour),
+ "value": rounded(value), "same_hour_yesterday": rounded(yesterday),
+ "usual_for_this_hour": rounded(usual), "usual_from_days": len(same_hour),
+ "difference": rounded(value - usual) if value is not None and usual is not None else None,
+ "difference_pct": round(100 * (value - usual) / usual, 1) if value is not None and usual else None,
+ }
+
+
+def network_state(db, arguments: dict, now: datetime, facts: Facts) -> dict:
+ server = find_server(db, arguments["server"])
+ listeners = db.query(ListenerState).filter(ListenerState.server_id == server.id).order_by(ListenerState.port, ListenerState.proto).all()
+ firewalls = db.query(FirewallState).filter(FirewallState.server_id == server.id).order_by(FirewallState.name).all()
+ changes = db.query(SystemEvent).filter(SystemEvent.server_id == server.id, SystemEvent.kind.in_(NETWORK_EVENTS), SystemEvent.time >= now - timedelta(days=NETWORK_DAYS)) \
+ .order_by(SystemEvent.time.desc()).limit(MAX_LIST).all()
+ for event in changes:
+ facts.add(f"event:{event.id}", f"{stamp(event.time)[5:16].replace('T', ' ')} {event.kind.replace('_', ' ')} · {server.hostname}")
+ return {
+ "id": facts.add(f"network:{server.hostname}", f"{server.hostname}: open ports and firewall"),
+ "server": server.hostname,
+ "listening": [{"proto": item.proto, "port": item.port, "reachable_from": {"any": "other machines", "loopback": "this machine only"}.get(item.scope, "one address"),
+ "since": stamp(item.first_seen)} for item in listeners[:MAX_LIST * 2]],
+ "more_listening": max(0, len(listeners) - MAX_LIST * 2),
+ "firewall": [{"name": item.name, "rules": item.rules, "enabled": item.enabled, "changed_at": stamp(item.updated_at)} for item in firewalls],
+ "changes_last_7_days": [{"id": f"event:{event.id}", "time": stamp(event.time), "kind": event.kind, "text": clip(event.detail)} for event in reversed(changes)],
+ }
diff --git a/tests/assistant/test_agent_diagnosis.py b/tests/assistant/test_agent_diagnosis.py
index b41baf7..3d3a08f 100644
--- a/tests/assistant/test_agent_diagnosis.py
+++ b/tests/assistant/test_agent_diagnosis.py
@@ -8,7 +8,7 @@ from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
-from src.agent import diagnosis, evidence, masking, safety, worker
+from src.agent import bounds, diagnosis, evidence, masking, safety, worker
from src.agent.providers import Completion
from src.backend.models import AgentReport, AgentRun, Base, ContainerMetric, HostMetric, IncidentAlert, Server, SystemEvent
@@ -83,7 +83,7 @@ def test_the_pack_has_an_id_on_every_fact_and_stays_small(db):
labels = evidence.index(pack)
assert {"incident:42", "metric:main", "metric:host.cpu", "metric:container.restarts", "event:812", "event:813", "check:1", "incident:31"} <= set(labels)
- assert all(len(metric["points"]) <= evidence.SERIES_POINTS for metric in pack["metrics"])
+ assert all(len(metric["points"]) <= bounds.SERIES_POINTS for metric in pack["metrics"])
main = next(metric for metric in pack["metrics"] if metric["id"] == "metric:main")
assert main["limit"] == 4096 and main["stats"]["max"] >= 3900
assert pack["similar_incidents"][0]["resolution"] == "Marked resolved by Karlo"
diff --git a/tests/assistant/test_agent_tools.py b/tests/assistant/test_agent_tools.py
new file mode 100644
index 0000000..c667d83
--- /dev/null
+++ b/tests/assistant/test_agent_tools.py
@@ -0,0 +1,315 @@
+"""The agent's read-only tools (#114): a closed list with strict schemas, arguments checked before anything is read,
+every check-in for the last week and hourly summaries before that, bounded and masked results with fact IDs, check
+targets without secrets, no IP addresses, and nothing ever written."""
+import json
+from datetime import datetime, timedelta, timezone
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.pool import StaticPool
+
+from src.agent import tools
+from src.agent.tools import common, servers
+from src.backend import history, rollups
+from src.backend.models import (AppSetting, Base, Check, CheckResult, ContainerMetric, FirewallState, HostMetric, HostRollup, IncidentAlert, ListenerState,
+ MountMetric, Server, SystemEvent)
+
+NOW = datetime(2026, 11, 7, 12, 0, tzinfo=timezone.utc)
+SPIKE = NOW - timedelta(hours=5)
+
+
+def db():
+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ system = {"kernel": "6.8.0", "collector_version": "0.10.0", "updates_pending": 4, "updates_security": 1}
+ session.add(Server(id=1, owner_id=1, hostname="web1", ip_address="10.0.0.5", os_info="Debian 12", cpu_cores=4, total_ram_gb=16.0, check_interval_seconds=600,
+ last_seen_at=NOW, system_info=json.dumps(system)))
+ session.add(Server(id=2, owner_id=1, hostname="db1", ip_address="10.0.0.6", check_interval_seconds=600, last_seen_at=NOW - timedelta(days=2)))
+ # Every 10 minutes for two days: CPU around 10 % with one peak, the root disk filling up by 1 GB a day.
+ for step in range(2 * 24 * 6):
+ moment = NOW - timedelta(minutes=10 * step)
+ session.add(HostMetric(server_id=1, time=moment, cpu_utilization_pct=97.0 if moment == SPIKE else 10 + step % 3, ram_pct=50, swap_pct=5, load_1m=0.4, disk_usage_pct=60))
+ session.add(MountMetric(server_id=1, time=moment, mount="/", fs_type="ext4", total_gb=100, used_gb=60 - step * 10 / 1440, used_pct=60 - step * 10 / 1440, inodes_pct=10))
+ # Hourly summaries before the last week: CPU averaging 5 % at 12:00 UTC, 30 % at other hours.
+ for hours in range(8 * 24, 40 * 24):
+ start = rollups.floor(rollups.HOUR, NOW) - timedelta(hours=hours)
+ average = 5.0 if start.hour == 12 else 30.0
+ session.add(HostRollup(server_id=1, tier=rollups.HOUR, bucket_start=start, samples=6, avg_cpu=average, n_cpu=6, max_cpu=average + 10))
+ session.add(AppSetting(key=rollups.WATERMARK_PREFIX + rollups.HOUR, value=(NOW - timedelta(days=7)).isoformat()))
+ # nginx: running, then killed for memory and restarted.
+ for step in range(12):
+ moment = NOW - timedelta(minutes=10 * (11 - step))
+ session.add(ContainerMetric(server_id=1, container_id="n" * 64, name="nginx", image="nginx:1.27", status="running", restart_count=0 if step < 6 else 1,
+ cpu_pct=2, memory_used_mb=100 + step, memory_limit_mb=256, exit_code=137 if step >= 6 else None, oom_killed=step >= 6, time=moment))
+ session.add(ContainerMetric(server_id=1, container_id="w" * 64, name="worker", image="app:2", status="exited", restart_count=0, time=moment))
+ session.add(SystemEvent(id=500, server_id=1, time=NOW - timedelta(hours=1), kind="oom_kill", detail="Killed nginx DATABASE_URL=postgres://app:hunter2@db/app"))
+ session.add(SystemEvent(id=501, server_id=1, time=NOW - timedelta(hours=2), kind="port_opened", detail="Listener opened: tcp/8080 on all addresses"))
+ for index in range(40):
+ session.add(SystemEvent(id=600 + index, server_id=1, time=NOW - timedelta(hours=3, minutes=index), kind="packages_updated", detail=f"{index} packages updated"))
+ session.add(IncidentAlert(id=31, server_id=1, severity="CRITICAL", title="Disk usage on web1:/ is 95%", description="d", status="resolved", rule_key="host:disk:/",
+ created_at=NOW - timedelta(days=10), resolved_at=NOW - timedelta(days=10) + timedelta(hours=2), resolution="Marked resolved by Ana"))
+ session.add(IncidentAlert(id=32, server_id=1, severity="WARNING", title="Container nginx restarted", description="d", status="active", rule_key="container:nginx:restart_loop",
+ created_at=NOW - timedelta(hours=1)))
+ session.add(IncidentAlert(id=33, server_id=2, severity="CRITICAL", title="db1 is offline", description="d", status="active", rule_key="server_offline", created_at=NOW - timedelta(days=2)))
+ session.add(Check(id=7, name="Shop", type="http", target="https://shop:[email protected]/health?token=abc123", server_ids="[1]", interval_seconds=60, retries=0,
+ state="up", created_at=NOW - timedelta(days=30)))
+ for minute in range(120):
+ failing = 30 <= minute < 35
+ session.add(CheckResult(check_id=7, server_id=1, time=NOW - timedelta(minutes=120 - minute), ok=not failing, response_ms=None if failing else 40 + minute % 5,
+ detail="HTTP 503" if failing else None))
+ session.add(ListenerState(server_id=1, proto="tcp", port=443, scope="any", first_seen=NOW - timedelta(days=20), last_seen=NOW))
+ session.add(ListenerState(server_id=1, proto="tcp", port=5432, scope="loopback", first_seen=NOW - timedelta(days=20), last_seen=NOW))
+ session.add(FirewallState(server_id=1, name="ufw-conf", sha="abc", rules=3, enabled=True, updated_at=NOW - timedelta(days=1)))
+ session.commit()
+ yield session
+ session.close()
+
+
+def call(db, name, **arguments):
+ output = tools.run(db, name, arguments, now=NOW)
+ return json.loads(output.content), output.labels
+
+
+WINDOW = {"from": None, "to": None}
+EVERY_CALL = [
+ ("server_info", {"server": "web1"}),
+ ("host_metrics", {"server": "web1", "metrics": [], **WINDOW}),
+ ("list_containers", {"server": "web1", "at": None}),
+ ("container_history", {"server": "web1", "container": "nginx", **WINDOW}),
+ ("disk_usage", {"server": "web1", "mount": None, "days": 2}),
+ ("events", {"server": "web1", "kinds": [], **WINDOW}),
+ ("compare_to_baseline", {"server": "web1", "metric": "cpu", "at": None}),
+ ("find_incidents", {"server": None, "kind": None, **WINDOW}),
+ ("fleet_snapshot", {"at": None}),
+ ("check_results", {"check": "Shop", "server": None, **WINDOW}),
+ ("network_state", {"server": "web1"}),
+]
+
+
+# --- the list and its arguments ---------------------------------------------------------------------------------
+
+def _strict(schema: dict) -> bool:
+ if "anyOf" in schema:
+ return all(_strict(option) for option in schema["anyOf"])
+ if schema["type"] == "object":
+ return schema["additionalProperties"] is False and schema["required"] == list(schema["properties"]) and all(_strict(sub) for sub in schema["properties"].values())
+ if schema["type"] == "array":
+ return _strict(schema["items"])
+ return True
+
+
+def test_every_tool_is_listed_once_with_a_strict_schema():
+ names = [tool.name for tool in tools.TOOLS]
+ assert sorted(names) == sorted(name for name, _ in EVERY_CALL) and len(names) == 11
+ assert all(_strict(tool.schema) for tool in tools.TOOLS)
+ assert set(servers.HOST_METRICS) <= set(history.HOST_METRICS)
+
+
+def test_an_unknown_tool_is_refused(db):
+ with pytest.raises(tools.ToolError, match="no tool named"):
+ tools.run(db, "run_shell", {"command": "rm -rf /"}, now=NOW)
+
+
[email protected]("name, arguments, message", [
+ ("events", {"server": "web1"}, "exactly these arguments"),
+ ("events", {"server": "web1", "kinds": [], "from": None, "to": None, "sql": "drop table"}, "exactly these arguments"),
+ ("events", {"server": 1, "kinds": [], "from": None, "to": None}, "server must be"),
+ ("events", {"server": "web1", "kinds": ["everything"], "from": None, "to": None}, "kinds must be one of"),
+ ("events", {"server": "web1", "kinds": ["reboot"] * 13, "from": None, "to": None}, "at most 12"),
+ ("events", {"server": "x" * 201, "kinds": [], "from": None, "to": None}, "at most 200"),
+ ("events", {"server": "web1", "kinds": [], "from": "yesterday", "to": None}, "ISO 8601"),
+ ("events", {"server": "web1", "kinds": [], "from": "2026-11-07T10:00", "to": "2026-11-07T09:00"}, "earlier than"),
+ ("events", {"server": "web1", "kinds": [], "from": "2026-01-01T00:00", "to": None}, "last 90 days"),
+ ("disk_usage", {"server": "web1", "mount": None, "days": True}, "whole number"),
+ ("disk_usage", {"server": "web1", "mount": None, "days": 365}, "between 1 and 90"),
+ ("compare_to_baseline", {"server": "web1", "metric": "temperature", "at": None}, "one of"),
+ ("list_containers", {"server": "web1", "at": "2026-10-01T00:00"}, "kept for 7 days"),
+ ("check_results", {"check": "Shop", "server": "web1", "from": None, "to": None}, "not both"),
+ ("check_results", {"check": None, "server": None, "from": None, "to": None}, "not both"),
+ ("check_results", {"check": "Bank", "server": None, "from": None, "to": None}, "Checks: Shop"),
+ ("container_history", {"server": "web1", "container": "redis", "from": None, "to": None}, "nginx, worker"),
+])
+def test_bad_arguments_are_refused_with_a_reason_the_model_can_act_on(db, name, arguments, message):
+ with pytest.raises(tools.ToolError, match=message):
+ tools.run(db, name, arguments, now=NOW)
+
+
+def test_an_unknown_server_is_answered_with_the_known_ones(db):
+ with pytest.raises(tools.ToolError, match="Servers: db1, web1"):
+ tools.run(db, "server_info", {"server": "mail"}, now=NOW)
+ assert call(db, "server_info", server="WEB1")[0]["hostname"] == "web1"
+
+
+# --- what each tool returns -------------------------------------------------------------------------------------
+
+def test_host_metrics_reads_every_check_in_of_the_last_week_and_keeps_the_peak(db):
+ content, labels = call(db, "host_metrics", server="web1", metrics=["cpu"], **{"from": "2026-11-07T00:00", "to": "2026-11-07T12:00"})
+ cpu = content["series"][0]
+ assert cpu["id"] == "metric:web1.cpu" and cpu["source"] == "check-ins"
+ assert cpu["stats"]["max"] == 97.0 and max(value for _, value in cpu["points"]) == 97.0
+ assert len(cpu["points"]) <= 40
+ assert labels["metric:web1.cpu"] == "CPU · web1 · 2026-11-07 00:00–12:00 UTC"
+
+
+def test_the_window_defaults_to_the_last_24_hours_and_empty_metrics_to_the_usual_five(db):
+ content, _ = call(db, "host_metrics", server="web1", metrics=[], **WINDOW)
+ assert (content["from"], content["to"]) == ("2026-11-06T12:00+00:00", "2026-11-07T12:00+00:00")
+ assert [series["id"] for series in content["series"]] == [f"metric:web1.{name}" for name in history.DEFAULT_HOST_METRICS]
+
+
+def test_older_windows_are_read_from_the_hourly_summaries(db):
+ content, _ = call(db, "host_metrics", server="web1", metrics=["cpu"], **{"from": "2026-10-01T00:00", "to": "2026-10-20T00:00"})
+ cpu = content["series"][0]
+ assert cpu["source"] == "hourly summaries"
+ assert cpu["stats"]["min"] == 5.0 and cpu["stats"]["max"] == 40.0 and len(cpu["points"]) <= 40
+
+
+def test_no_data_in_the_window_says_so(db):
+ content, labels = call(db, "host_metrics", server="db1", metrics=[], **WINDOW)
+ assert content["series"] == [] and "No check-ins" in content["note"] and labels == {}
+
+
+def test_server_info_has_the_machine_facts_and_no_ip_address(db):
+ content, labels = call(db, "server_info", server="web1")
+ assert content["online"] is True and content["kernel"] == "6.8.0" and content["security_updates_pending"] == 1
+ assert labels == {"server:web1": "web1: machine facts"}
+ assert "10.0.0.5" not in json.dumps(content)
+
+
+def test_list_containers_puts_the_ones_not_running_first(db):
+ content, labels = call(db, "list_containers", server="web1", at=None)
+ assert [item["name"] for item in content["containers"]] == ["worker", "nginx"]
+ assert content["containers"][1]["oom_killed"] is True and "container:web1/nginx" in labels
+
+
+def test_container_history_reports_restarts_and_oom_kills(db):
+ content, labels = call(db, "container_history", server="web1", container="nginx", **WINDOW)
+ assert content["changes"] == [{"time": "2026-11-07T11:10+00:00", "change": "restarted 1×, exit code 137, killed for running out of memory"}]
+ assert {"metric:web1/nginx.cpu", "metric:web1/nginx.memory_mb", "metric:web1/nginx.restarts", "container:web1/nginx"} <= set(labels)
+ assert content["memory_limit_mb"] == 256 and content["not_running_pct"] == 0.0
+
+
+def test_disk_usage_estimates_growth_and_when_it_fills_up(db):
+ content, labels = call(db, "disk_usage", server="web1", mount="/", days=2)
+ root = content["mounts"][0]
+ assert root["growth_gb_per_day"] == pytest.approx(1.0, abs=0.05)
+ assert root["full_in_days"] == pytest.approx(40, abs=2)
+ assert "metric:web1.disk:/" in labels
+ with pytest.raises(tools.ToolError, match="no mount '/data'"):
+ tools.run(db, "disk_usage", {"server": "web1", "mount": "/data", "days": 2}, now=NOW)
+
+
+def test_events_show_the_newest_thirty_oldest_first_and_filter_by_kind(db):
+ content, labels = call(db, "events", server="web1", kinds=[], **WINDOW)
+ assert content["total"] == 42 and content["shown"] == 30
+ times = [event["time"] for event in content["events"]]
+ assert times == sorted(times) and content["events"][-1]["id"] == "event:500"
+ assert set(labels) == {event["id"] for event in content["events"]}
+ only, _ = call(db, "events", server="web1", kinds=["oom_kill", "port_opened"], **WINDOW)
+ assert [event["id"] for event in only["events"]] == ["event:501", "event:500"]
+
+
+def test_compare_to_baseline_sets_an_hour_against_the_same_hour_before(db):
+ content, labels = call(db, "compare_to_baseline", server="web1", metric="cpu", at="2026-10-20T12:30")
+ assert content["hour"] == "2026-10-20T12:00+00:00" and content["value"] == 5.0
+ assert content["same_hour_yesterday"] == 5.0 and content["usual_for_this_hour"] == 5.0 and content["difference"] == 0.0
+ later, _ = call(db, "compare_to_baseline", server="web1", metric="cpu", at=None)
+ assert later["usual_for_this_hour"] == 5.0 and later["value"] > later["usual_for_this_hour"]
+ assert "baseline:web1.cpu" in labels
+
+
+def test_find_incidents_filters_by_server_and_kind(db):
+ content, labels = call(db, "find_incidents", server="web1", kind="host:disk", **WINDOW)
+ assert [item["id"] for item in content["incidents"]] == ["incident:31"]
+ assert content["incidents"][0]["lasted_minutes"] == 120 and content["incidents"][0]["resolution"] == "Marked resolved by Ana"
+ assert labels == {"incident:31": "INC-0031 · Disk usage on web1:/ is 95%"}
+ everything, _ = call(db, "find_incidents", server=None, kind=None, **WINDOW)
+ assert [item["id"] for item in everything["incidents"]] == ["incident:32", "incident:33", "incident:31"]
+
+
+def test_fleet_snapshot_shows_every_server_now_and_at_an_earlier_moment(db):
+ content, labels = call(db, "fleet_snapshot", at=None)
+ by_name = {item["server"]: item for item in content["servers"]}
+ assert by_name["web1"]["online"] is True and by_name["db1"]["online"] is False
+ assert by_name["db1"]["worst"] == "CRITICAL" and by_name["web1"]["open_incidents"] == 1
+ assert by_name["web1"]["failing_checks"] == []
+ assert {"fleet:web1", "fleet:db1", "incident:32", "incident:33"} <= set(labels)
+ during, _ = call(db, "fleet_snapshot", at="2026-11-07T10:32")
+ assert {item["server"]: item for item in during["servers"]}["web1"]["failing_checks"] == ["Shop"]
+ long_ago, _ = call(db, "fleet_snapshot", at="2026-10-01T00:00")
+ assert long_ago["servers"][0]["failing_checks"] is None and "hourly totals" in long_ago["note"]
+
+
+def test_check_results_show_downtime_and_errors_without_the_targets_secrets(db):
+ content, labels = call(db, "check_results", check="shop", server=None, **WINDOW)
+ shop = content["checks"][0]
+ assert shop["target"] == "https://shop.example.org/health?…"
+ assert "s3cret" not in json.dumps(content) and "abc123" not in json.dumps(content)
+ assert shop["down"] == 5 and shop["down_periods"] == [{"from": "2026-11-07T10:30+00:00", "to": "2026-11-07T10:35+00:00"}]
+ assert shop["errors"] == [{"detail": "HTTP 503", "count": 5}] and shop["runs_from"] == ["web1"]
+ assert labels["uptime:7"].startswith("check Shop")
+ by_server, _ = call(db, "check_results", check=None, server="web1", **WINDOW)
+ assert [check["name"] for check in by_server["checks"]] == ["Shop"]
+
+
+def test_network_state_lists_ports_firewall_and_recent_changes(db):
+ content, labels = call(db, "network_state", server="web1")
+ assert [(item["port"], item["reachable_from"]) for item in content["listening"]] == [(443, "other machines"), (5432, "this machine only")]
+ assert content["firewall"] == [{"name": "ufw-conf", "rules": 3, "enabled": True, "changed_at": "2026-11-06T12:00+00:00"}]
+ assert [event["id"] for event in content["changes_last_7_days"]] == ["event:501"] and "network:web1" in labels
+
+
+# --- rules every result follows ---------------------------------------------------------------------------------
+
[email protected]("name, arguments", EVERY_CALL)
+def test_every_result_is_bounded_masked_free_of_ip_addresses_and_labelled(db, name, arguments):
+ output = tools.run(db, name, arguments, now=NOW)
+ assert len(output.content) <= tools.MAX_RESULT_CHARS
+ assert "hunter2" not in output.content and "10.0.0." not in output.content
+ cited = set()
+
+ def ids(value):
+ if isinstance(value, dict):
+ if isinstance(value.get("id"), str):
+ cited.add(value["id"])
+ for item in value.values():
+ ids(item)
+ elif isinstance(value, list):
+ for item in value:
+ ids(item)
+ ids(json.loads(output.content))
+ assert cited == set(output.labels)
+
+
+def test_a_result_too_large_is_shortened_and_loses_the_labels_of_what_was_cut(db, monkeypatch):
+ monkeypatch.setattr(tools, "MAX_RESULT_CHARS", 1500)
+ content, labels = call(db, "events", server="web1", kinds=[], **WINDOW)
+ assert content["truncated"] is True and len(content["events"]) < 30
+ assert set(labels) == {event["id"] for event in content["events"]}
+ assert content["events"][-1]["id"] == "event:500" # the oldest went first
+
+
+def test_a_long_series_is_thinned_keeping_its_peak(db, monkeypatch):
+ monkeypatch.setattr(tools, "MAX_RESULT_CHARS", 900)
+ content, _ = call(db, "host_metrics", server="web1", metrics=["cpu"], **{"from": "2026-11-07T00:00", "to": "2026-11-07T12:00"})
+ points = content["series"][0]["points"]
+ assert content["truncated"] is True and len(points) < 40 and max(value for _, value in points) == 97.0
+
+
+def test_the_same_question_gives_the_same_ids_and_a_second_window_joins_the_label(db):
+ first = tools.run(db, "host_metrics", {"server": "web1", "metrics": ["cpu"], "from": "2026-11-07T00:00", "to": "2026-11-07T06:00"}, now=NOW)
+ again = tools.run(db, "host_metrics", {"server": "web1", "metrics": ["cpu"], "from": "2026-11-07T00:00", "to": "2026-11-07T06:00"}, now=NOW)
+ later = tools.run(db, "host_metrics", {"server": "web1", "metrics": ["cpu"], "from": "2026-11-07T06:00", "to": "2026-11-07T12:00"}, now=NOW)
+ assert first.content == again.content and set(first.labels) == set(later.labels) == {"metric:web1.cpu"}
+ merged = common.merge_labels(tools.merge_labels({}, first.labels), later.labels)
+ assert merged["metric:web1.cpu"] == "CPU · web1 · 2026-11-07 00:00–06:00 UTC; CPU · web1 · 2026-11-07 06:00–12:00 UTC"
+ assert common.merge_labels(merged, first.labels) == merged
+
+
+def test_tools_never_write_to_the_database(db):
+ for name, arguments in EVERY_CALL:
+ tools.run(db, name, arguments, now=NOW)
+ assert not db.new and not db.dirty and not db.deleted, name