stackdoctor-cli 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. stackdoctor/__init__.py +15 -0
  2. stackdoctor/__main__.py +6 -0
  3. stackdoctor/agent/__init__.py +5 -0
  4. stackdoctor/agent/compaction.py +66 -0
  5. stackdoctor/agent/diagnosis.py +398 -0
  6. stackdoctor/agent/loop.py +801 -0
  7. stackdoctor/agent/prompts.py +85 -0
  8. stackdoctor/agent/providers/__init__.py +295 -0
  9. stackdoctor/agent/providers/base.py +210 -0
  10. stackdoctor/agent/providers/claude.py +285 -0
  11. stackdoctor/agent/providers/gemini.py +312 -0
  12. stackdoctor/agent/providers/openai_compat.py +537 -0
  13. stackdoctor/agent/providers/prices.py +90 -0
  14. stackdoctor/benchmark/__init__.py +11 -0
  15. stackdoctor/benchmark/__main__.py +198 -0
  16. stackdoctor/benchmark/holmes.py +386 -0
  17. stackdoctor/benchmark/report.py +362 -0
  18. stackdoctor/benchmark/runner.py +710 -0
  19. stackdoctor/benchmark/scenarios.py +153 -0
  20. stackdoctor/benchmark/scoring.py +184 -0
  21. stackdoctor/cli.py +882 -0
  22. stackdoctor/dependencies.py +221 -0
  23. stackdoctor/discovery.py +361 -0
  24. stackdoctor/evidence.py +134 -0
  25. stackdoctor/github.py +168 -0
  26. stackdoctor/live.py +808 -0
  27. stackdoctor/mcp_server.py +233 -0
  28. stackdoctor/models.py +275 -0
  29. stackdoctor/pglog.py +55 -0
  30. stackdoctor/postgres.py +294 -0
  31. stackdoctor/probes.py +172 -0
  32. stackdoctor/py.typed +0 -0
  33. stackdoctor/redaction.py +215 -0
  34. stackdoctor/rules.py +303 -0
  35. stackdoctor/validation.py +61 -0
  36. stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
  37. stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
  38. stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
  39. stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
  40. stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,134 @@
1
+ """Evidence: collected data items, and references from findings to them.
2
+
3
+ Every finding must cite evidence, and every citation must resolve. Collected
4
+ data is wrapped in an `EvidenceItem` (the Compose configuration is the item
5
+ ``config``; live checks add more). Rules create references with
6
+ `make_evidence` (into the configuration) or `make_item_evidence` (into any
7
+ item); both resolve the path first and record the value found there.
8
+ `check_report` resolves every reference in a report again, independently, so
9
+ a report cannot cite data that does not exist or says something else.
10
+
11
+ A resolvable reference shows that the cited data exists and says what it
12
+ says; it does not by itself prove the finding's conclusion.
13
+ """
14
+
15
+ import json
16
+ from collections.abc import Mapping
17
+ from typing import Any
18
+
19
+ from stackdoctor.models import (
20
+ CONFIG_EVIDENCE_ID,
21
+ ComposeProject,
22
+ EvidenceItem,
23
+ EvidenceRef,
24
+ ValidationReport,
25
+ )
26
+
27
+
28
+ class EvidenceError(LookupError):
29
+ """An evidence reference does not resolve, or does not match its excerpt."""
30
+
31
+
32
+ def config_item(project: ComposeProject) -> EvidenceItem:
33
+ """The discovered Compose configuration as an evidence item.
34
+
35
+ Services, their ``depends_on`` entries and top-level networks are keyed by
36
+ name, the way Compose itself keys them; lists (such as ``ports``) are
37
+ addressed by index.
38
+ """
39
+ return EvidenceItem(
40
+ id=CONFIG_EVIDENCE_ID,
41
+ source="compose_config",
42
+ description="docker compose config --format json (allowlisted fields, redacted)",
43
+ data=_keyed(project),
44
+ )
45
+
46
+
47
+ def resolve_path(data: Any, path: tuple[str | int, ...]) -> Any:
48
+ """Return the value at ``path`` inside ``data``.
49
+
50
+ Raises:
51
+ EvidenceError: if any part of the path does not exist.
52
+ """
53
+ node = data
54
+ for depth, segment in enumerate(path):
55
+ by_key = isinstance(node, dict) and isinstance(segment, str) and segment in node
56
+ by_index = isinstance(node, list) and isinstance(segment, int) and 0 <= segment < len(node)
57
+ if not (by_key or by_index):
58
+ where = format_path(path[: depth + 1])
59
+ raise EvidenceError(f"Evidence path does not resolve: {where}")
60
+ node = node[segment]
61
+ return node
62
+
63
+
64
+ def resolve_evidence(project: ComposeProject, path: tuple[str | int, ...]) -> Any:
65
+ """Return the value at ``path`` in the project's ``config`` evidence item."""
66
+ return resolve_path(config_item(project).data, path)
67
+
68
+
69
+ def make_evidence(project: ComposeProject, *path: str | int) -> EvidenceRef:
70
+ """Create a reference into the Compose configuration."""
71
+ return make_item_evidence(config_item(project), *path)
72
+
73
+
74
+ def make_item_evidence(item: EvidenceItem, *path: str | int) -> EvidenceRef:
75
+ """Create a reference to ``path`` in ``item``, recording the value found there."""
76
+ return EvidenceRef(item=item.id, path=path, excerpt=format_value(resolve_path(item.data, path)))
77
+
78
+
79
+ def check_report(report: ValidationReport) -> None:
80
+ """Resolve every evidence reference in ``report`` against its own items.
81
+
82
+ Raises:
83
+ EvidenceError: if a reference names a missing item, does not resolve,
84
+ or resolves to a value other than its excerpt.
85
+ """
86
+ items: Mapping[str, EvidenceItem] = {item.id: item for item in report.evidence}
87
+ for finding in report.findings:
88
+ for ref in finding.evidence:
89
+ item = items.get(ref.item)
90
+ if item is None:
91
+ raise EvidenceError(f"{finding.rule_id}: evidence item {ref.item!r} is missing")
92
+ if format_value(resolve_path(item.data, ref.path)) != ref.excerpt:
93
+ where = f"{ref.item}:{format_path(ref.path)}"
94
+ raise EvidenceError(f"{finding.rule_id}: evidence {where} does not match")
95
+
96
+
97
+ def format_value(value: Any) -> str:
98
+ """Render an evidence value as text, the same way every time."""
99
+ if value is None:
100
+ return "(none)"
101
+ if value == "":
102
+ return '""'
103
+ if isinstance(value, str):
104
+ return value
105
+ if isinstance(value, list) and all(isinstance(item, str) for item in value):
106
+ return ", ".join(value) if value else "(empty)"
107
+ return json.dumps(value, sort_keys=True)
108
+
109
+
110
+ def format_path(path: tuple[str | int, ...]) -> str:
111
+ """Render a path for people, for example ``services.api.ports[0]``."""
112
+ text = ""
113
+ for segment in path:
114
+ text += f"[{segment}]" if isinstance(segment, int) else f".{segment}"
115
+ return text.lstrip(".")
116
+
117
+
118
+ def format_ref(ref: EvidenceRef) -> str:
119
+ """Render a reference for people; the ``config`` item is implied."""
120
+ where = format_path(ref.path)
121
+ return where if ref.item == CONFIG_EVIDENCE_ID else f"{ref.item}:{where}"
122
+
123
+
124
+ def _keyed(project: ComposeProject) -> dict[str, Any]:
125
+ data = project.model_dump(mode="json")
126
+ services: dict[str, Any] = {}
127
+ for service in data["services"]:
128
+ service["depends_on"] = {entry["service"]: entry for entry in service["depends_on"]}
129
+ services[service["name"]] = service
130
+ return {
131
+ "name": data["name"],
132
+ "services": services,
133
+ "networks": {network["name"]: network for network in data["networks"]},
134
+ }
stackdoctor/github.py ADDED
@@ -0,0 +1,168 @@
1
+ """GitHub Actions output for `stackdoctor validate --github`.
2
+
3
+ Findings become workflow annotations (``::error`` and ``::warning`` lines on
4
+ stdout), and a Markdown table goes to the job summary (the file named by
5
+ ``GITHUB_STEP_SUMMARY``).
6
+
7
+ Everything shown comes from the report, which is already redacted, but its
8
+ text is untrusted: a configuration value can contain anything. So:
9
+
10
+ - annotation text and properties are escaped as GitHub's toolkit escapes them
11
+ (``%``, CR and LF; also ``:`` and ``,`` in properties), so a value cannot end
12
+ the annotation or start a workflow command of its own;
13
+ - the human-readable report printed after the annotations is wrapped in
14
+ ``::stop-commands::`` with a random token, so no line of it is read as a
15
+ workflow command;
16
+ - summary cells are HTML-escaped and Markdown's special characters are
17
+ escaped, so a value cannot add links, images or layout.
18
+
19
+ The Compose project is discovered from ``docker compose config``, which keeps
20
+ no line numbers, so annotations name the Compose file but no line.
21
+ """
22
+
23
+ import html
24
+ import os
25
+ import re
26
+ import secrets
27
+ from collections.abc import Sequence
28
+ from pathlib import Path
29
+
30
+ from stackdoctor.evidence import format_ref
31
+ from stackdoctor.models import Finding, Severity, ValidationReport
32
+
33
+ # Compose's own lookup order for the default file in a project directory.
34
+ DEFAULT_COMPOSE_FILES = ("compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml")
35
+ # Longest annotation message, in characters; GitHub shows the start of it.
36
+ MAX_MESSAGE = 4000
37
+
38
+ # Markdown characters that can format, link or end a table cell. "<" and "&"
39
+ # are HTML-escaped first; "#" is left alone so those escapes stay intact.
40
+ _MARKDOWN_SPECIAL = re.compile(r"([\\`*_\[\]|~])")
41
+
42
+
43
+ def escape_data(text: str) -> str:
44
+ """Escape an annotation's message, as @actions/core escapes command data."""
45
+ return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
46
+
47
+
48
+ def escape_property(text: str) -> str:
49
+ """Escape an annotation property (file, title), as @actions/core does."""
50
+ return escape_data(text).replace(":", "%3A").replace(",", "%2C")
51
+
52
+
53
+ def annotation_file(
54
+ project_dir: Path, files: Sequence[Path], workspace: Path | None = None
55
+ ) -> str | None:
56
+ """The Compose file to annotate, relative to the workspace, or None.
57
+
58
+ The first ``--file`` if any were given, otherwise the first file of
59
+ Compose's default lookup that exists. None if there is none, or it is
60
+ outside the workspace (GitHub could not show it).
61
+ """
62
+ directory = project_dir.resolve()
63
+ if files:
64
+ chosen: Path | None = (directory / files[0]).resolve()
65
+ else:
66
+ chosen = next(
67
+ (directory / name for name in DEFAULT_COMPOSE_FILES if (directory / name).is_file()),
68
+ None,
69
+ )
70
+ if chosen is None:
71
+ return None
72
+ base = (workspace or Path.cwd()).resolve()
73
+ try:
74
+ return chosen.resolve().relative_to(base).as_posix()
75
+ except ValueError:
76
+ return None
77
+
78
+
79
+ def workspace() -> Path | None:
80
+ """The workflow's workspace, where annotated files are looked up."""
81
+ value = os.environ.get("GITHUB_WORKSPACE")
82
+ return Path(value) if value else None
83
+
84
+
85
+ def annotations(report: ValidationReport, file: str | None) -> list[str]:
86
+ """One workflow command per finding."""
87
+ lines = []
88
+ for finding in report.findings:
89
+ command = "error" if finding.severity is Severity.ERROR else "warning"
90
+ properties = [f"title={escape_property(_title(finding))}"]
91
+ if file is not None:
92
+ properties.insert(0, f"file={escape_property(file)}")
93
+ message = _message(finding)[:MAX_MESSAGE]
94
+ lines.append(f"::{command} {','.join(properties)}::{escape_data(message)}")
95
+ return lines
96
+
97
+
98
+ def _title(finding: Finding) -> str:
99
+ service = f" ({finding.service})" if finding.service else ""
100
+ return f"StackDoctor {finding.rule_id}{service}: {finding.title}"
101
+
102
+
103
+ def _message(finding: Finding) -> str:
104
+ parts = [finding.message]
105
+ if finding.hint:
106
+ parts.append(f"Hint: {finding.hint}")
107
+ parts += [f"Evidence: {format_ref(ref)} = {ref.excerpt}" for ref in finding.evidence]
108
+ return "\n".join(parts)
109
+
110
+
111
+ def stop_commands_token() -> str:
112
+ """A random token for ``::stop-commands::``; it must not be guessable."""
113
+ return secrets.token_hex(16)
114
+
115
+
116
+ def without_commands(text: str, token: str) -> list[str]:
117
+ """Lines that print ``text`` with workflow commands turned off around it."""
118
+ return [f"::stop-commands::{token}", text, f"::{token}::"]
119
+
120
+
121
+ def summary(report: ValidationReport) -> str:
122
+ """The job summary, in Markdown."""
123
+ title = f"## StackDoctor: `{_cell(report.project)}`"
124
+ if not report.findings:
125
+ return f"{title}\n\nNo problems found.\n"
126
+ counts = (
127
+ f"{report.error_count} error{'' if report.error_count == 1 else 's'}, "
128
+ f"{report.warning_count} warning{'' if report.warning_count == 1 else 's'}"
129
+ )
130
+ lines = [
131
+ title,
132
+ "",
133
+ f"Findings: {counts}.",
134
+ "",
135
+ "| Severity | Rule | Service | Finding | Evidence |",
136
+ "|---|---|---|---|---|",
137
+ ]
138
+ for finding in report.findings:
139
+ evidence = "<br>".join(
140
+ _cell(f"{format_ref(ref)} = {ref.excerpt}") for ref in finding.evidence
141
+ )
142
+ lines.append(
143
+ f"| {finding.severity.value} | {_cell(finding.rule_id)} | "
144
+ f"{_cell(finding.service or '')} | "
145
+ f"**{_cell(finding.title)}**<br>{_cell(finding.message)} | {evidence} |"
146
+ )
147
+ lines += [
148
+ "",
149
+ "Findings cite the redacted configuration; secret values never appear.",
150
+ "",
151
+ ]
152
+ return "\n".join(lines)
153
+
154
+
155
+ def _cell(text: str) -> str:
156
+ """Untrusted text as plain text inside a Markdown table cell."""
157
+ flat = " ".join(text.split())
158
+ return _MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(flat, quote=True))
159
+
160
+
161
+ def write_summary(text: str) -> bool:
162
+ """Append to the job summary, if this runs in GitHub Actions. True if written."""
163
+ path = os.environ.get("GITHUB_STEP_SUMMARY")
164
+ if not path:
165
+ return False
166
+ with open(path, "a", encoding="utf-8") as file:
167
+ file.write(text)
168
+ return True