md2site-cli 0.2.0__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.
md2site/config.py ADDED
@@ -0,0 +1,444 @@
1
+ """Configuration schema, loading, and validation for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path, PurePosixPath
8
+ from typing import Any
9
+
10
+ SOURCE_LINK_MODES = frozenset({"relative", "editor", "remote", "auto"})
11
+ THEME_MODES = frozenset({"system", "light", "dark"})
12
+
13
+
14
+ class ConfigError(ValueError):
15
+ """Raised when configuration loading or validation fails."""
16
+
17
+
18
+ DEFAULT_MAX_HIGHLIGHT_BYTES = 262144
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class SearchConfig:
23
+ """Search index configuration."""
24
+
25
+ enabled: bool = True
26
+ body_chars: int = 6000
27
+ max_index_bytes: int = 0
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ThemePaletteConfig:
32
+ """Color palette tokens for a single theme mode."""
33
+
34
+ bg_primary: str
35
+ bg_sidebar: str
36
+ text_primary: str
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ThemeConfig:
41
+ """Theme and typography configuration."""
42
+
43
+ default_mode: str = "system"
44
+ accent_color: str = "#7c3aed"
45
+ accent_color_dark: str = "#a78bfa"
46
+ code_theme_light: str = "default"
47
+ code_theme_dark: str = "github-dark"
48
+ light: ThemePaletteConfig = field(
49
+ default_factory=lambda: ThemePaletteConfig(
50
+ bg_primary="#ffffff",
51
+ bg_sidebar="#f8fafc",
52
+ text_primary="#0f172a",
53
+ )
54
+ )
55
+ dark: ThemePaletteConfig = field(
56
+ default_factory=lambda: ThemePaletteConfig(
57
+ bg_primary="#0b0f19",
58
+ bg_sidebar="#111827",
59
+ text_primary="#f1f5f9",
60
+ )
61
+ )
62
+ font_sans: str = "system-ui, -apple-system, sans-serif"
63
+ font_mono: str = "'JetBrains Mono', 'Fira Code', monospace"
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class NavConfigEntry:
68
+ """Explicit navigation entry configured under ``nav`` in ``md2site.config.json``."""
69
+
70
+ path: str | None = None
71
+ label: str | None = None
72
+ children: tuple[NavConfigEntry, ...] = ()
73
+ is_dir_auto: bool = False
74
+ has_children: bool = False
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Config:
79
+ """Resolved md2site configuration."""
80
+
81
+ site_title: str = "Project Documentation"
82
+ docs_dir: Path = field(default_factory=lambda: Path("."))
83
+ output_dir: Path = field(default_factory=lambda: Path("_site"))
84
+ repo_root: Path = field(default_factory=lambda: Path("."))
85
+ exclude: tuple[str, ...] = ()
86
+ source_link_mode: str = "relative"
87
+ remote_repo_url: str = ""
88
+ remote_branch: str = "main"
89
+ editor_scheme: str = "vscode"
90
+ autolink_code_paths: bool = False
91
+ wikilinks: bool = True
92
+ allow_html: bool = True
93
+ mermaid: bool = True
94
+ max_highlight_bytes: int = DEFAULT_MAX_HIGHLIGHT_BYTES
95
+ search: SearchConfig = field(default_factory=SearchConfig)
96
+ theme: ThemeConfig = field(default_factory=ThemeConfig)
97
+ nav: tuple[NavConfigEntry, ...] | None = None
98
+ config_path: Path | None = None
99
+ warnings: tuple[str, ...] = ()
100
+
101
+
102
+ def default_config_dict() -> dict[str, Any]:
103
+ """Return a fresh dictionary matching the PRD §7 default config schema."""
104
+ return {
105
+ "site_title": "Project Documentation",
106
+ "docs_dir": ".",
107
+ "output_dir": "_site",
108
+ "repo_root": "auto",
109
+ "exclude": [],
110
+ "source_link_mode": "relative",
111
+ "remote_repo_url": "",
112
+ "remote_branch": "main",
113
+ "editor_scheme": "vscode",
114
+ "autolink_code_paths": False,
115
+ "wikilinks": True,
116
+ "allow_html": True,
117
+ "mermaid": True,
118
+ "max_highlight_bytes": DEFAULT_MAX_HIGHLIGHT_BYTES,
119
+ "nav": None,
120
+ "search": {"enabled": True, "body_chars": 6000, "max_index_bytes": 0},
121
+ "theme": {
122
+ "default_mode": "system",
123
+ "accent_color": "#7c3aed",
124
+ "accent_color_dark": "#a78bfa",
125
+ "code_theme_light": "default",
126
+ "code_theme_dark": "github-dark",
127
+ "light": {
128
+ "bg_primary": "#ffffff",
129
+ "bg_sidebar": "#f8fafc",
130
+ "text_primary": "#0f172a",
131
+ },
132
+ "dark": {
133
+ "bg_primary": "#0b0f19",
134
+ "bg_sidebar": "#111827",
135
+ "text_primary": "#f1f5f9",
136
+ },
137
+ "font_sans": "system-ui, -apple-system, sans-serif",
138
+ "font_mono": "'JetBrains Mono', 'Fira Code', monospace",
139
+ },
140
+ }
141
+
142
+
143
+ def _find_git_root(start: Path) -> Path | None:
144
+ """Return nearest ancestor (including start) containing ``.git``, else None."""
145
+ resolved = start.resolve()
146
+ for candidate in (resolved, *resolved.parents):
147
+ if (candidate / ".git").exists():
148
+ return candidate
149
+ return None
150
+
151
+
152
+ def _deep_merge_and_collect_unknown(
153
+ defaults: dict[str, Any],
154
+ overrides: dict[str, Any],
155
+ prefix: str,
156
+ warnings: list[str],
157
+ ) -> dict[str, Any]:
158
+ """Deep-merge overrides onto defaults while recording unknown keys."""
159
+ merged: dict[str, Any] = dict(defaults)
160
+ for key in sorted(overrides):
161
+ dotted = f"{prefix}.{key}" if prefix else key
162
+ if key not in defaults:
163
+ warnings.append(f"Unknown config key '{dotted}' will be ignored")
164
+ continue
165
+ default_val = defaults[key]
166
+ override_val = overrides[key]
167
+ if isinstance(default_val, dict):
168
+ if not isinstance(override_val, dict):
169
+ raise ConfigError(
170
+ f"Invalid type for '{dotted}': expected object, "
171
+ f"got {type(override_val).__name__}"
172
+ )
173
+ merged[key] = _deep_merge_and_collect_unknown(
174
+ default_val, override_val, dotted, warnings
175
+ )
176
+ else:
177
+ merged[key] = override_val
178
+ return merged
179
+
180
+
181
+ def _require_str(data: dict[str, Any], key: str, prefix: str = "") -> str:
182
+ dotted = f"{prefix}.{key}" if prefix else key
183
+ val = data[key]
184
+ if not isinstance(val, str):
185
+ raise ConfigError(f"Invalid type for '{dotted}': expected string, got {type(val).__name__}")
186
+ return val
187
+
188
+
189
+ def _require_bool(data: dict[str, Any], key: str, prefix: str = "") -> bool:
190
+ dotted = f"{prefix}.{key}" if prefix else key
191
+ val = data[key]
192
+ if not isinstance(val, bool):
193
+ raise ConfigError(
194
+ f"Invalid type for '{dotted}': expected boolean, got {type(val).__name__}"
195
+ )
196
+ return val
197
+
198
+
199
+ def _require_int(data: dict[str, Any], key: str, prefix: str = "") -> int:
200
+ dotted = f"{prefix}.{key}" if prefix else key
201
+ val = data[key]
202
+ if not isinstance(val, int) or isinstance(val, bool):
203
+ raise ConfigError(
204
+ f"Invalid type for '{dotted}': expected integer, got {type(val).__name__}"
205
+ )
206
+ return val
207
+
208
+
209
+ def _normalize_nav_rel(raw: str, dotted: str, *, allow_trailing_slash: bool) -> tuple[str, bool]:
210
+ """Validate and normalize a nav relative POSIX path entry."""
211
+ val = raw.strip().replace("\\", "/")
212
+ if not val:
213
+ raise ConfigError(f"Invalid value for '{dotted}': must be a non-empty string")
214
+ if val.startswith("/"):
215
+ raise ConfigError(f"Invalid value for '{dotted}': path cannot be absolute ({raw!r})")
216
+ is_dir_auto = val.endswith("/")
217
+ if is_dir_auto and not allow_trailing_slash:
218
+ raise ConfigError(
219
+ f"Invalid value for '{dotted}': 'page' cannot be a directory path ({raw!r})"
220
+ )
221
+ trimmed = val.rstrip("/")
222
+ if not trimmed:
223
+ raise ConfigError(f"Invalid value for '{dotted}': invalid directory path ({raw!r})")
224
+ norm_path = PurePosixPath(trimmed)
225
+ if ".." in norm_path.parts:
226
+ raise ConfigError(f"Invalid value for '{dotted}': path cannot contain '..' ({raw!r})")
227
+ norm = norm_path.as_posix()
228
+ if norm == ".":
229
+ raise ConfigError(f"Invalid value for '{dotted}': invalid path ({raw!r})")
230
+ return norm, is_dir_auto
231
+
232
+
233
+ def _parse_nav_entry(raw: Any, dotted: str) -> NavConfigEntry:
234
+ if isinstance(raw, str):
235
+ norm, is_dir_auto = _normalize_nav_rel(raw, dotted, allow_trailing_slash=True)
236
+ return NavConfigEntry(path=norm, is_dir_auto=is_dir_auto)
237
+
238
+ if isinstance(raw, dict):
239
+ allowed_keys = {"label", "page", "children"}
240
+ for key in sorted(raw):
241
+ if key not in allowed_keys:
242
+ raise ConfigError(f"Unknown key '{dotted}.{key}' in nav entry")
243
+
244
+ label: str | None = None
245
+ if "label" in raw and raw["label"] is not None:
246
+ if not isinstance(raw["label"], str) or not raw["label"].strip():
247
+ raise ConfigError(f"Invalid value for '{dotted}.label': expected non-empty string")
248
+ label = raw["label"].strip()
249
+
250
+ page_path: str | None = None
251
+ if "page" in raw and raw["page"] is not None:
252
+ if not isinstance(raw["page"], str):
253
+ raise ConfigError(f"Invalid type for '{dotted}.page': expected string")
254
+ page_path, _ = _normalize_nav_rel(
255
+ raw["page"], f"{dotted}.page", allow_trailing_slash=False
256
+ )
257
+
258
+ children: tuple[NavConfigEntry, ...] = ()
259
+ has_children = "children" in raw and raw["children"] is not None
260
+ if has_children:
261
+ children = _parse_nav_list(raw["children"], f"{dotted}.children")
262
+
263
+ if page_path is None and not has_children:
264
+ raise ConfigError(f"Invalid nav object at '{dotted}': expected 'page' or 'children'")
265
+ if page_path is None and label is None:
266
+ raise ConfigError(
267
+ f"Invalid nav object at '{dotted}': section without 'page' requires 'label'"
268
+ )
269
+ return NavConfigEntry(
270
+ path=page_path,
271
+ label=label,
272
+ children=children,
273
+ is_dir_auto=False,
274
+ has_children=has_children,
275
+ )
276
+
277
+ raise ConfigError(
278
+ f"Invalid type for '{dotted}': expected string or object, got {type(raw).__name__}"
279
+ )
280
+
281
+
282
+ def _parse_nav_list(raw: Any, dotted: str) -> tuple[NavConfigEntry, ...]:
283
+ if not isinstance(raw, list):
284
+ raise ConfigError(f"Invalid type for '{dotted}': expected list, got {type(raw).__name__}")
285
+ return tuple(_parse_nav_entry(item, f"{dotted}[{idx}]") for idx, item in enumerate(raw))
286
+
287
+
288
+ def load_config(
289
+ path_or_dir: Path | str = ".",
290
+ *,
291
+ config_file: Path | str | None = None,
292
+ ) -> Config:
293
+ """Load md2site configuration from a directory or config file.
294
+
295
+ When ``config_file`` is provided, it is loaded directly. Otherwise, if
296
+ ``path_or_dir`` is a file it is loaded as the config file; if it is a
297
+ directory, ``md2site.config.json`` inside that directory is loaded if
298
+ present (without walking upward). When no config file is found, defaults
299
+ are used with ``docs_dir`` set to ``path_or_dir``.
300
+ """
301
+ target = Path(path_or_dir)
302
+ if config_file is not None:
303
+ cfg_path = Path(config_file)
304
+ if not cfg_path.is_file():
305
+ raise ConfigError(f"Config file not found: {cfg_path}")
306
+ resolved_cfg_path: Path | None = cfg_path.resolve()
307
+ base_dir = resolved_cfg_path.parent
308
+ elif target.is_file():
309
+ resolved_cfg_path = target.resolve()
310
+ base_dir = resolved_cfg_path.parent
311
+ elif target.is_dir():
312
+ base_dir = target.resolve()
313
+ candidate = base_dir / "md2site.config.json"
314
+ resolved_cfg_path = candidate if candidate.is_file() else None
315
+ else:
316
+ raise ConfigError(f"Path does not exist or is not a file/directory: {path_or_dir}")
317
+
318
+ warnings: list[str] = []
319
+ defaults = default_config_dict()
320
+
321
+ if resolved_cfg_path is not None:
322
+ try:
323
+ raw_text = resolved_cfg_path.read_text(encoding="utf-8-sig")
324
+ raw_data = json.loads(raw_text)
325
+ except OSError as exc:
326
+ raise ConfigError(f"Unable to read config file {resolved_cfg_path}: {exc}") from exc
327
+ except json.JSONDecodeError as exc:
328
+ raise ConfigError(f"Invalid JSON in config file {resolved_cfg_path}: {exc}") from exc
329
+
330
+ if not isinstance(raw_data, dict):
331
+ raise ConfigError(f"Invalid config root in {resolved_cfg_path}: expected JSON object")
332
+ merged = _deep_merge_and_collect_unknown(defaults, raw_data, "", warnings)
333
+ else:
334
+ merged = defaults
335
+
336
+ site_title = _require_str(merged, "site_title")
337
+ docs_dir_raw = _require_str(merged, "docs_dir")
338
+ output_dir_raw = _require_str(merged, "output_dir")
339
+ repo_root_raw = _require_str(merged, "repo_root")
340
+
341
+ exclude_raw = merged["exclude"]
342
+ if not isinstance(exclude_raw, list) or not all(isinstance(item, str) for item in exclude_raw):
343
+ raise ConfigError("Invalid type for 'exclude': expected list of strings")
344
+ exclude = tuple(exclude_raw)
345
+
346
+ source_link_mode = _require_str(merged, "source_link_mode")
347
+ if source_link_mode not in SOURCE_LINK_MODES:
348
+ allowed = ", ".join(sorted(SOURCE_LINK_MODES))
349
+ raise ConfigError(
350
+ f"Invalid value for 'source_link_mode': {source_link_mode!r} "
351
+ f"(expected one of: {allowed})"
352
+ )
353
+
354
+ remote_repo_url = _require_str(merged, "remote_repo_url")
355
+ remote_branch = _require_str(merged, "remote_branch")
356
+ editor_scheme = _require_str(merged, "editor_scheme")
357
+ if not editor_scheme.strip():
358
+ raise ConfigError("Invalid value for 'editor_scheme': must be a non-empty string")
359
+
360
+ autolink_code_paths = _require_bool(merged, "autolink_code_paths")
361
+ wikilinks = _require_bool(merged, "wikilinks")
362
+ allow_html = _require_bool(merged, "allow_html")
363
+ mermaid = _require_bool(merged, "mermaid")
364
+ max_highlight_bytes = _require_int(merged, "max_highlight_bytes")
365
+ if max_highlight_bytes < 0:
366
+ raise ConfigError("Invalid value for 'max_highlight_bytes': must be >= 0")
367
+
368
+ search_dict = merged["search"]
369
+ search_enabled = _require_bool(search_dict, "enabled", "search")
370
+ search_body_chars = _require_int(search_dict, "body_chars", "search")
371
+ if search_body_chars < 0:
372
+ raise ConfigError("Invalid value for 'search.body_chars': must be >= 0")
373
+ search_max_index_bytes = _require_int(search_dict, "max_index_bytes", "search")
374
+ if search_max_index_bytes < 0:
375
+ raise ConfigError("Invalid value for 'search.max_index_bytes': must be >= 0")
376
+ search_cfg = SearchConfig(
377
+ enabled=search_enabled,
378
+ body_chars=search_body_chars,
379
+ max_index_bytes=search_max_index_bytes,
380
+ )
381
+
382
+ theme_dict = merged["theme"]
383
+ default_mode = _require_str(theme_dict, "default_mode", "theme")
384
+ if default_mode not in THEME_MODES:
385
+ allowed = ", ".join(sorted(THEME_MODES))
386
+ raise ConfigError(
387
+ f"Invalid value for 'theme.default_mode': {default_mode!r} (expected one of: {allowed})"
388
+ )
389
+
390
+ light_dict = theme_dict["light"]
391
+ light_cfg = ThemePaletteConfig(
392
+ bg_primary=_require_str(light_dict, "bg_primary", "theme.light"),
393
+ bg_sidebar=_require_str(light_dict, "bg_sidebar", "theme.light"),
394
+ text_primary=_require_str(light_dict, "text_primary", "theme.light"),
395
+ )
396
+ dark_dict = theme_dict["dark"]
397
+ dark_cfg = ThemePaletteConfig(
398
+ bg_primary=_require_str(dark_dict, "bg_primary", "theme.dark"),
399
+ bg_sidebar=_require_str(dark_dict, "bg_sidebar", "theme.dark"),
400
+ text_primary=_require_str(dark_dict, "text_primary", "theme.dark"),
401
+ )
402
+ theme_cfg = ThemeConfig(
403
+ default_mode=default_mode,
404
+ accent_color=_require_str(theme_dict, "accent_color", "theme"),
405
+ accent_color_dark=_require_str(theme_dict, "accent_color_dark", "theme"),
406
+ code_theme_light=_require_str(theme_dict, "code_theme_light", "theme"),
407
+ code_theme_dark=_require_str(theme_dict, "code_theme_dark", "theme"),
408
+ light=light_cfg,
409
+ dark=dark_cfg,
410
+ font_sans=_require_str(theme_dict, "font_sans", "theme"),
411
+ font_mono=_require_str(theme_dict, "font_mono", "theme"),
412
+ )
413
+
414
+ raw_nav = merged["nav"]
415
+ nav_cfg = _parse_nav_list(raw_nav, "nav") if raw_nav is not None else None
416
+
417
+ docs_dir = (base_dir / docs_dir_raw).resolve()
418
+ output_dir = (base_dir / output_dir_raw).resolve()
419
+ if repo_root_raw == "auto":
420
+ repo_root = _find_git_root(base_dir) or base_dir
421
+ else:
422
+ repo_root = (base_dir / repo_root_raw).resolve()
423
+
424
+ return Config(
425
+ site_title=site_title,
426
+ docs_dir=docs_dir,
427
+ output_dir=output_dir,
428
+ repo_root=repo_root,
429
+ exclude=exclude,
430
+ source_link_mode=source_link_mode,
431
+ remote_repo_url=remote_repo_url,
432
+ remote_branch=remote_branch,
433
+ editor_scheme=editor_scheme,
434
+ autolink_code_paths=autolink_code_paths,
435
+ wikilinks=wikilinks,
436
+ allow_html=allow_html,
437
+ mermaid=mermaid,
438
+ max_highlight_bytes=max_highlight_bytes,
439
+ search=search_cfg,
440
+ theme=theme_cfg,
441
+ nav=nav_cfg,
442
+ config_path=resolved_cfg_path,
443
+ warnings=tuple(warnings),
444
+ )
md2site/diagnostics.py ADDED
@@ -0,0 +1,167 @@
1
+ """Structured diagnostics collection and JSON/terminal formatting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import json
7
+ from collections.abc import Sequence
8
+
9
+ from md2site.model import Diagnostic
10
+
11
+ MD2S001 = "MD2S001" # broken Markdown link (target .md not found)
12
+ MD2S002 = "MD2S002" # broken file/asset link
13
+ MD2S003 = "MD2S003" # ambiguous wikilink (resolved to nearest)
14
+ MD2S004 = "MD2S004" # unresolved wikilink
15
+ MD2S005 = "MD2S005" # broken anchor
16
+ MD2S006 = "MD2S006" # case mismatch (works here, breaks on case-sensitive FS)
17
+ MD2S007 = "MD2S007" # target escapes repo_root
18
+ MD2S008 = "MD2S008" # output path / slug collision
19
+ MD2S009 = "MD2S009" # bad front matter
20
+ MD2S010 = "MD2S010" # remote/auto mode without remote_repo_url
21
+ MD2S011 = "MD2S011" # cross-filesystem relative repo_file fallback
22
+
23
+ CODE_DESCRIPTIONS: dict[str, str] = {
24
+ MD2S001: "broken Markdown link (target .md not found)",
25
+ MD2S002: "broken file/asset link",
26
+ MD2S003: "ambiguous wikilink (resolved to nearest)",
27
+ MD2S004: "unresolved wikilink",
28
+ MD2S005: "broken anchor",
29
+ MD2S006: "case mismatch (works here, breaks on case-sensitive FS)",
30
+ MD2S007: "target escapes repo_root",
31
+ MD2S008: "output path / slug collision",
32
+ MD2S009: "bad front matter",
33
+ MD2S010: "remote/auto mode without remote_repo_url",
34
+ MD2S011: "relative source_link_mode fell back across filesystems",
35
+ }
36
+
37
+
38
+ def sort_key(diag: Diagnostic) -> tuple[str, int, str, str, str]:
39
+ """Deterministic sort key for diagnostics."""
40
+ return (
41
+ diag.file,
42
+ diag.line if diag.line is not None else 0,
43
+ diag.code,
44
+ diag.message,
45
+ diag.target or "",
46
+ )
47
+
48
+
49
+ class Collector:
50
+ """Mutable collector for diagnostics during a build or check run."""
51
+
52
+ def __init__(self, initial: Sequence[Diagnostic] = ()) -> None:
53
+ self._items: list[Diagnostic] = list(initial)
54
+
55
+ def append(self, diag: Diagnostic) -> None:
56
+ """Append a single diagnostic."""
57
+ self._items.append(diag)
58
+
59
+ def extend(self, diags: Sequence[Diagnostic]) -> None:
60
+ """Append multiple diagnostics."""
61
+ self._items.extend(diags)
62
+
63
+ def add(
64
+ self,
65
+ *,
66
+ level: str = "warning",
67
+ code: str,
68
+ file: str,
69
+ line: int | None,
70
+ message: str,
71
+ target: str | None = None,
72
+ suggestion: str | None = None,
73
+ ) -> Diagnostic:
74
+ """Create, append, and return a new diagnostic."""
75
+ diag = Diagnostic(
76
+ level=level,
77
+ code=code,
78
+ file=file,
79
+ line=line,
80
+ message=message,
81
+ target=target,
82
+ suggestion=suggestion,
83
+ )
84
+ self._items.append(diag)
85
+ return diag
86
+
87
+ def sorted_items(self) -> list[Diagnostic]:
88
+ """Return all diagnostics in deterministic order."""
89
+ return sorted(self._items, key=sort_key)
90
+
91
+ @property
92
+ def error_count(self) -> int:
93
+ return sum(1 for item in self._items if item.level == "error")
94
+
95
+ @property
96
+ def warning_count(self) -> int:
97
+ return sum(1 for item in self._items if item.level == "warning")
98
+
99
+ @property
100
+ def has_errors(self) -> bool:
101
+ return self.error_count > 0
102
+
103
+ @property
104
+ def has_diagnostics(self) -> bool:
105
+ return len(self._items) > 0
106
+
107
+
108
+ def suggest_match(
109
+ target: str,
110
+ candidates: Sequence[str],
111
+ *,
112
+ cutoff: float = 0.6,
113
+ ) -> str | None:
114
+ """Return the closest matching candidate string via difflib, or None."""
115
+ if not target or not candidates:
116
+ return None
117
+ matches = difflib.get_close_matches(target, list(candidates), n=1, cutoff=cutoff)
118
+ return matches[0] if matches else None
119
+
120
+
121
+ def format_diagnostic(diag: Diagnostic) -> str:
122
+ """Format a diagnostic for human-readable terminal output."""
123
+ loc = f"{diag.file}:{diag.line}" if diag.line is not None else diag.file
124
+ line = f"{loc} {diag.code} {diag.message}"
125
+ if diag.suggestion:
126
+ line += f" → did you mean {diag.suggestion}"
127
+ return line
128
+
129
+
130
+ def format_diagnostics(diagnostics: Sequence[Diagnostic]) -> str:
131
+ """Format a sequence of diagnostics sorted deterministically."""
132
+ ordered = sorted(diagnostics, key=sort_key)
133
+ return "\n".join(format_diagnostic(d) for d in ordered)
134
+
135
+
136
+ def to_json(
137
+ diagnostics: Sequence[Diagnostic],
138
+ *,
139
+ pages: int,
140
+ duration_ms: int,
141
+ ) -> str:
142
+ """Serialize summary and diagnostics to the PRD §6.4 JSON document."""
143
+ ordered = sorted(diagnostics, key=sort_key)
144
+ errors = sum(1 for d in ordered if d.level == "error")
145
+ warnings = sum(1 for d in ordered if d.level == "warning")
146
+ payload = {
147
+ "version": 1,
148
+ "summary": {
149
+ "pages": pages,
150
+ "errors": errors,
151
+ "warnings": warnings,
152
+ "duration_ms": duration_ms,
153
+ },
154
+ "diagnostics": [
155
+ {
156
+ "level": d.level,
157
+ "code": d.code,
158
+ "file": d.file,
159
+ "line": d.line,
160
+ "message": d.message,
161
+ "target": d.target,
162
+ "suggestion": d.suggestion,
163
+ }
164
+ for d in ordered
165
+ ],
166
+ }
167
+ return json.dumps(payload, indent=2)