systemap 1.0.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.
systemap/config.py ADDED
@@ -0,0 +1,710 @@
1
+ """Project configuration: `systemap.toml` at the repo root, or `[tool.systemap]`.
2
+
3
+ Everything project-specific the engine needs lives here, so the engine
4
+ itself holds no literal that belongs to one project: where the packages
5
+ are, where the tests are, where the model module is, where the output
6
+ goes, and the theme.
7
+
8
+ name the page title; defaults to [project] name in
9
+ pyproject.toml, then the name of the directory holding
10
+ the git repository (the main checkout, even from a
11
+ worktree), then the directory's name
12
+ package_roots table of path = import name; default: every top-level
13
+ directory (or src/<dir>) that holds an __init__.py, in
14
+ the root and in every [tool.uv.workspace] member
15
+ tests_dir where test_*.py files live: one directory or a list;
16
+ default: every directory named tests or test under the
17
+ root, outside the skipped directories
18
+ model the module exporting MODEL and MEANING (default
19
+ "map/model.py")
20
+ out_dir where the facts, the page and the figures are written
21
+ (default "docs/map")
22
+ facts_file the facts file's name inside out_dir (default "map.json")
23
+ spec_path optional document whose ##-headings become spec sections
24
+ planes optional list of second-level package names that count as
25
+ their own architectural plane in the facts
26
+ outside_label the index heading for actors outside every region
27
+ [theme] tokens laid over the default scheme; `scheme` names
28
+ the default ("warm", "graphite" or "paper"), and
29
+ `[theme.<scheme>]` lays tokens over one scheme
30
+ [[figures]] figures `systemap refresh` regenerates: out, mode
31
+ ("system" or "reach"), components, caption, interactive,
32
+ layer (one reading's id: only that layer's edges), map
33
+ (the id of a map inside a card, for a figure of it)
34
+ [coverage] ignore = [{module = "pkg.mod", reason = "..."}]: modules
35
+ the coverage rule of `systemap check` may leave unmapped;
36
+ every entry needs a reason, since an unexplained hole in
37
+ the map is the thing the rule exists to refuse
38
+ [facts] model_sdks = [...]: import names, added to the built-in
39
+ list, that mark a module as calling a model; the
40
+ judgement asks about each in a component that is not
41
+ an agent. A leading `-` removes a built-in name
42
+ ("-google.adk")
43
+ [flows] observed_by = [...]: the mechanisms other than an
44
+ import that join this repository's parts (a
45
+ subprocess, a queue, a file); a flow whose sentence or
46
+ artifact names one is observed by it rather than
47
+ declared
48
+ [judgement] answered = [{item = "<a judgement line>", reason = "..."}]:
49
+ the lines of `systemap judgement` the maintainer has
50
+ answered, each with why; an answered line is suppressed
51
+ and counted, an answer that matches no line is
52
+ reported as stale, and an answer without a reason is an
53
+ error. `items = [...]` answers several exact lines with
54
+ one reason; `crossing = ["A", "B", ...]` every crossing
55
+ import between any two of the ids, in either direction;
56
+ `crossing_into = "A"` every crossing import into A and
57
+ `crossing_from = "A"` every one out of it; `kind =
58
+ "single module"` every line of that kind; `module_sdk
59
+ = "google.adk"` every model sdk line for that import
60
+
61
+ Unknown keys are a configuration error: a misspelt key that silently did
62
+ nothing would be worse than a refusal.
63
+ """
64
+
65
+ from __future__ import annotations
66
+
67
+ import dataclasses
68
+ import os
69
+ import subprocess
70
+ import sys
71
+ import tomllib
72
+ import types
73
+ from dataclasses import dataclass, field
74
+ from pathlib import Path
75
+ from typing import Any
76
+
77
+ from systemap.model import Meaning, Model
78
+
79
+ CONFIG_FILE = "systemap.toml"
80
+ SKIP_DIRS = {".git", ".venv", "node_modules", "__pycache__", "build", "dist", "tests", "docs"}
81
+ # What a walk for tests directories or package candidates never enters:
82
+ # the skipped directories minus `tests` itself, plus a plain `venv`.
83
+ SKIP_WALK = (SKIP_DIRS - {"tests"}) | {"venv"}
84
+ TEST_DIR_NAMES = ("tests", "test")
85
+ CANDIDATE_DEPTH = 4
86
+
87
+ KNOWN_KEYS = {
88
+ "name",
89
+ "package_roots",
90
+ "tests_dir",
91
+ "model",
92
+ "out_dir",
93
+ "facts_file",
94
+ "spec_path",
95
+ "planes",
96
+ "outside_label",
97
+ "theme",
98
+ "figures",
99
+ "coverage",
100
+ "facts",
101
+ "judgement",
102
+ "flows",
103
+ }
104
+ FACTS_KEYS = {"model_sdks"}
105
+ FLOWS_KEYS = {"observed_by"}
106
+ FIGURE_KEYS = {"out", "mode", "components", "caption", "interactive", "svg_id", "layer", "map"}
107
+ COVERAGE_KEYS = {"ignore"}
108
+ IGNORE_KEYS = {"module", "reason"}
109
+ JUDGEMENT_KEYS = {"answered"}
110
+ ANSWER_FORMS = ("item", "items", "crossing", "crossing_into", "crossing_from", "kind", "module_sdk")
111
+ ANSWER_KEYS = {*ANSWER_FORMS, "reason"}
112
+ # The kinds of line `systemap judgement` prints, as `kind = "..."` names them.
113
+ LINE_KINDS = (
114
+ "single module",
115
+ "possible mis-fold",
116
+ "no sentence",
117
+ "thin layer",
118
+ "entry point",
119
+ "crossing import",
120
+ "declared flow",
121
+ "model sdk",
122
+ )
123
+
124
+
125
+ class ConfigError(Exception):
126
+ """The configuration cannot be used; the message says what to fix."""
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class Figure:
131
+ """One figure `systemap refresh` regenerates beside the page."""
132
+
133
+ out: str
134
+ mode: str = "system"
135
+ components: tuple[str, ...] = ()
136
+ caption: str = ""
137
+ interactive: bool = True
138
+ svg_id: str = "lessonmap"
139
+ layer: str = ""
140
+ map: str = ""
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class Ignore:
145
+ """One module the coverage rule may leave unmapped, and why.
146
+
147
+ `module` is an exact module name or a package with `.*` for its
148
+ subtree, the same convention `implemented_by` uses.
149
+ """
150
+
151
+ module: str
152
+ reason: str
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class Answer:
157
+ """One or more judgement lines the maintainer has answered, and why.
158
+
159
+ `items` are the lines exactly as `systemap judgement` prints them
160
+ (without the two-space indent). The bulk forms answer a family with
161
+ one reason: `crossing` every crossing-import line between any two of
162
+ its ids (two or more) in either direction, `crossing_into` every one
163
+ whose imported module belongs to the named card, `crossing_from`
164
+ every one whose importing module does, `kind` every line of one kind,
165
+ `module_sdk` every model sdk line for one import. Exactly one form
166
+ is set. The answer is the hand-back: it lives in the repository
167
+ beside the model, not in a conversation.
168
+ """
169
+
170
+ items: tuple[str, ...]
171
+ reason: str
172
+ crossing: tuple[str, ...] | None = None
173
+ kind: str = ""
174
+ module_sdk: str = ""
175
+ crossing_into: str = ""
176
+ crossing_from: str = ""
177
+
178
+ @property
179
+ def label(self) -> str:
180
+ """The answer as the configuration wrote it, for the stale report."""
181
+ if self.crossing is not None:
182
+ return "crossing = [" + ", ".join(f'"{cid}"' for cid in self.crossing) + "]"
183
+ if self.crossing_into:
184
+ return f'crossing_into = "{self.crossing_into}"'
185
+ if self.crossing_from:
186
+ return f'crossing_from = "{self.crossing_from}"'
187
+ if self.kind:
188
+ return f'kind = "{self.kind}"'
189
+ if self.module_sdk:
190
+ return f'module_sdk = "{self.module_sdk}"'
191
+ return self.items[0] if len(self.items) == 1 else f"items = {list(self.items)}"
192
+
193
+
194
+ @dataclass(frozen=True)
195
+ class Config:
196
+ root: Path
197
+ name: str
198
+ package_roots: tuple[tuple[str, str], ...]
199
+ tests_dirs: tuple[str, ...] = ()
200
+ model: str = "map/model.py"
201
+ out_dir: str = "docs/map"
202
+ facts_file: str = "map.json"
203
+ spec_path: str = ""
204
+ planes: tuple[str, ...] = ()
205
+ outside_label: str = "OUTSIDE THE SYSTEM"
206
+ theme: dict[str, Any] = field(default_factory=dict)
207
+ figures: tuple[Figure, ...] = ()
208
+ coverage_ignore: tuple[Ignore, ...] = ()
209
+ judgement_answered: tuple[Answer, ...] = ()
210
+ model_sdks: tuple[str, ...] = ()
211
+ observed_by: tuple[str, ...] = ()
212
+ source: str = ""
213
+
214
+ @property
215
+ def model_path(self) -> Path:
216
+ return self.root / self.model
217
+
218
+ @property
219
+ def out_path(self) -> Path:
220
+ return self.root / self.out_dir
221
+
222
+ @property
223
+ def facts_path(self) -> Path:
224
+ return self.out_path / self.facts_file
225
+
226
+ @property
227
+ def page_path(self) -> Path:
228
+ return self.out_path / "index.html"
229
+
230
+ @property
231
+ def roots(self) -> list[tuple[Path, str]]:
232
+ """(package directory, import name) for every package root that exists."""
233
+ out: list[tuple[Path, str]] = []
234
+ for rel, name in self.package_roots:
235
+ pkg = self.root / rel
236
+ if pkg.is_dir():
237
+ out.append((pkg, name))
238
+ return out
239
+
240
+ @property
241
+ def prefixes(self) -> set[str]:
242
+ return {name for _, name in self.package_roots}
243
+
244
+ @property
245
+ def test_dirs(self) -> tuple[str, ...]:
246
+ """The directories test files are read from: configured, else discovered."""
247
+ return self.tests_dirs or tuple(discover_tests(self.root))
248
+
249
+ def rel(self, path: Path) -> str:
250
+ """A path shown to the user, relative to the root when it is under it."""
251
+ try:
252
+ return path.relative_to(self.root).as_posix()
253
+ except ValueError:
254
+ return str(path)
255
+
256
+
257
+ def find_root(start: Path) -> Path | None:
258
+ """The nearest ancestor (or `start`) holding a configuration or a .git."""
259
+ for candidate in (start, *start.parents):
260
+ if (candidate / CONFIG_FILE).is_file():
261
+ return candidate
262
+ pyproject = candidate / "pyproject.toml"
263
+ if pyproject.is_file() and "[tool.systemap]" in pyproject.read_text(encoding="utf-8"):
264
+ return candidate
265
+ if (candidate / ".git").exists():
266
+ return candidate
267
+ return None
268
+
269
+
270
+ def _pyproject(root: Path) -> dict[str, Any]:
271
+ path = root / "pyproject.toml"
272
+ if not path.is_file():
273
+ return {}
274
+ try:
275
+ return tomllib.loads(path.read_text(encoding="utf-8"))
276
+ except (OSError, tomllib.TOMLDecodeError):
277
+ return {}
278
+
279
+
280
+ def workspace_members(root: Path) -> list[Path]:
281
+ """The directories `[tool.uv.workspace] members` names, by its globs."""
282
+ workspace = _pyproject(root).get("tool", {}).get("uv", {}).get("workspace", {})
283
+ members = workspace.get("members", []) if isinstance(workspace, dict) else []
284
+ out: list[Path] = []
285
+ for pattern in members:
286
+ if not isinstance(pattern, str):
287
+ continue
288
+ for path in sorted(root.glob(pattern)):
289
+ if path.is_dir() and path.resolve() != root.resolve() and path not in out:
290
+ out.append(path)
291
+ return out
292
+
293
+
294
+ def discover_roots(root: Path) -> list[tuple[str, str]]:
295
+ """Every top-level directory holding an __init__.py, plus src/<pkg> layouts.
296
+
297
+ The root is searched, then every workspace member (`packages/<m>/src/<pkg>`
298
+ and `packages/<m>/<pkg>`), so a uv workspace needs no configuration.
299
+ """
300
+ found: list[tuple[str, str]] = []
301
+ for base in (root, *workspace_members(root)):
302
+ for parent in (base, base / "src"):
303
+ if not parent.is_dir():
304
+ continue
305
+ for child in sorted(parent.iterdir()):
306
+ if not child.is_dir() or child.name in SKIP_DIRS or child.name.startswith("."):
307
+ continue
308
+ if (child / "__init__.py").is_file():
309
+ entry = (child.relative_to(root).as_posix(), child.name)
310
+ if entry not in found:
311
+ found.append(entry)
312
+ return found
313
+
314
+
315
+ def _walk(root: Path, depth: int | None = None) -> list[Path]:
316
+ """Every directory under `root`, skipping what a walk never enters."""
317
+ out: list[Path] = []
318
+ for dirpath, dirnames, _files in os.walk(root):
319
+ here = Path(dirpath)
320
+ level = len(here.relative_to(root).parts)
321
+ dirnames[:] = sorted(d for d in dirnames if d not in SKIP_WALK and not d.startswith("."))
322
+ if depth is not None and level >= depth:
323
+ dirnames[:] = []
324
+ if here != root:
325
+ out.append(here)
326
+ return out
327
+
328
+
329
+ def discover_tests(root: Path) -> list[str]:
330
+ """Every directory named tests or test under the root, relative, in walk order.
331
+
332
+ A found directory is not entered again: its subdirectories are its own.
333
+ """
334
+ out: list[str] = []
335
+ for dirpath, dirnames, _files in os.walk(root):
336
+ here = Path(dirpath)
337
+ keep: list[str] = []
338
+ for d in sorted(dirnames):
339
+ if d in SKIP_WALK or d.startswith("."):
340
+ continue
341
+ if d in TEST_DIR_NAMES:
342
+ out.append((here / d).relative_to(root).as_posix())
343
+ else:
344
+ keep.append(d)
345
+ dirnames[:] = keep
346
+ return out
347
+
348
+
349
+ def candidate_packages(root: Path, depth: int = CANDIDATE_DEPTH) -> list[str]:
350
+ """Directories holding an __init__.py up to `depth` below the root, relative.
351
+
352
+ Listed when discovery finds no package root, so the fix names what is
353
+ there rather than asking the reader to search.
354
+ """
355
+ return [
356
+ d.relative_to(root).as_posix() for d in _walk(root, depth) if (d / "__init__.py").is_file()
357
+ ]
358
+
359
+
360
+ def default_name(root: Path) -> str:
361
+ """`[project] name`, else the git repository's directory, else the root's name.
362
+
363
+ The repository's directory is the one holding the common git dir, so
364
+ a worktree is named after the checkout it belongs to, not after the
365
+ worktree's own directory.
366
+ """
367
+ project = _pyproject(root).get("project", {})
368
+ name = project.get("name") if isinstance(project, dict) else None
369
+ if isinstance(name, str) and name.strip():
370
+ return name.strip()
371
+ try:
372
+ proc = subprocess.run(
373
+ ["git", "rev-parse", "--git-common-dir"],
374
+ cwd=root,
375
+ capture_output=True,
376
+ text=True,
377
+ timeout=10,
378
+ )
379
+ except (OSError, subprocess.SubprocessError):
380
+ proc = None
381
+ if proc is not None and proc.returncode == 0 and proc.stdout.strip():
382
+ common = (root / proc.stdout.strip()).resolve()
383
+ holder = common.parent.name if common.name == ".git" else common.name.removesuffix(".git")
384
+ if holder:
385
+ return holder
386
+ return root.name
387
+
388
+
389
+ def read_raw(root: Path) -> tuple[dict[str, Any], str]:
390
+ """The raw table and where it came from: systemap.toml first, then pyproject."""
391
+ toml = root / CONFIG_FILE
392
+ if toml.is_file():
393
+ try:
394
+ return tomllib.loads(toml.read_text(encoding="utf-8")), CONFIG_FILE
395
+ except tomllib.TOMLDecodeError as exc:
396
+ raise ConfigError(f"{CONFIG_FILE}: {exc}") from exc
397
+ pyproject = root / "pyproject.toml"
398
+ if pyproject.is_file():
399
+ try:
400
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
401
+ except tomllib.TOMLDecodeError as exc:
402
+ raise ConfigError(f"pyproject.toml: {exc}") from exc
403
+ section = data.get("tool", {}).get("systemap")
404
+ if isinstance(section, dict):
405
+ return section, "pyproject.toml [tool.systemap]"
406
+ return {}, ""
407
+
408
+
409
+ def _str(raw: dict[str, Any], key: str, default: str, source: str) -> str:
410
+ value = raw.get(key, default)
411
+ if not isinstance(value, str):
412
+ raise ConfigError(f"{source}: {key} must be a string")
413
+ return value
414
+
415
+
416
+ def _str_list(raw: dict[str, Any], key: str, source: str) -> tuple[str, ...]:
417
+ value = raw.get(key, [])
418
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
419
+ raise ConfigError(f"{source}: {key} must be a list of strings")
420
+ return tuple(value)
421
+
422
+
423
+ def load(root: Path) -> Config:
424
+ """The configuration for the project at `root`, defaults filled in."""
425
+ root = root.resolve()
426
+ raw, source = read_raw(root)
427
+ where = source or "defaults"
428
+ unknown = sorted(set(raw) - KNOWN_KEYS)
429
+ if unknown:
430
+ raise ConfigError(
431
+ f"{where}: unknown key{'s' if len(unknown) > 1 else ''}: {', '.join(unknown)}"
432
+ )
433
+
434
+ roots_raw = raw.get("package_roots")
435
+ if roots_raw is None:
436
+ package_roots = tuple(discover_roots(root))
437
+ elif isinstance(roots_raw, dict) and all(
438
+ isinstance(k, str) and isinstance(v, str) for k, v in roots_raw.items()
439
+ ):
440
+ package_roots = tuple((k, v) for k, v in roots_raw.items())
441
+ else:
442
+ raise ConfigError(f'{where}: package_roots must be a table of "path" = "name"')
443
+
444
+ theme = raw.get("theme", {})
445
+ if not isinstance(theme, dict):
446
+ raise ConfigError(f"{where}: theme must be a table")
447
+
448
+ figures: list[Figure] = []
449
+ for k, item in enumerate(raw.get("figures", []), start=1):
450
+ if not isinstance(item, dict):
451
+ raise ConfigError(f"{where}: figures[{k}] must be a table")
452
+ bad = sorted(set(item) - FIGURE_KEYS)
453
+ if bad:
454
+ raise ConfigError(f"{where}: figures[{k}] has unknown key: {', '.join(bad)}")
455
+ out = item.get("out")
456
+ if not isinstance(out, str) or not out:
457
+ raise ConfigError(f"{where}: figures[{k}] needs an out file name")
458
+ mode = _str(item, "mode", "system", where)
459
+ if mode not in ("system", "reach"):
460
+ raise ConfigError(f'{where}: figures[{k}] mode must be "system" or "reach"')
461
+ components = _str_list(item, "components", where)
462
+ if mode == "reach" and not components:
463
+ raise ConfigError(f"{where}: figures[{k}] is a reach figure with no components")
464
+ interactive = item.get("interactive", True)
465
+ if not isinstance(interactive, bool):
466
+ raise ConfigError(f"{where}: figures[{k}] interactive must be true or false")
467
+ figures.append(
468
+ Figure(
469
+ out=out,
470
+ mode=mode,
471
+ components=components,
472
+ caption=_str(item, "caption", "", where),
473
+ interactive=interactive,
474
+ svg_id=_str(item, "svg_id", "lessonmap", where),
475
+ layer=_str(item, "layer", "", where),
476
+ map=_str(item, "map", "", where),
477
+ )
478
+ )
479
+
480
+ tests_raw = raw.get("tests_dir", [])
481
+ if isinstance(tests_raw, str):
482
+ tests_dirs: tuple[str, ...] = (tests_raw,) if tests_raw else ()
483
+ elif isinstance(tests_raw, list) and all(isinstance(v, str) for v in tests_raw):
484
+ tests_dirs = tuple(tests_raw)
485
+ else:
486
+ raise ConfigError(f"{where}: tests_dir must be a directory or a list of directories")
487
+
488
+ return Config(
489
+ coverage_ignore=_coverage_ignore(raw, where),
490
+ judgement_answered=_judgement_answered(raw, where),
491
+ model_sdks=_facts(raw, where),
492
+ observed_by=_flows(raw, where),
493
+ root=root,
494
+ name=_str(raw, "name", "", where) or default_name(root),
495
+ package_roots=package_roots,
496
+ tests_dirs=tests_dirs,
497
+ model=_str(raw, "model", "map/model.py", where),
498
+ out_dir=_str(raw, "out_dir", "docs/map", where),
499
+ facts_file=_str(raw, "facts_file", "map.json", where),
500
+ spec_path=_str(raw, "spec_path", "", where),
501
+ planes=_str_list(raw, "planes", where),
502
+ outside_label=_str(raw, "outside_label", "OUTSIDE THE SYSTEM", where),
503
+ theme=theme,
504
+ figures=tuple(figures),
505
+ source=source,
506
+ )
507
+
508
+
509
+ def _coverage_ignore(raw: dict[str, Any], where: str) -> tuple[Ignore, ...]:
510
+ """The `[coverage] ignore` list; an entry without a reason is refused."""
511
+ coverage = raw.get("coverage", {})
512
+ if not isinstance(coverage, dict):
513
+ raise ConfigError(f"{where}: coverage must be a table")
514
+ bad = sorted(set(coverage) - COVERAGE_KEYS)
515
+ if bad:
516
+ raise ConfigError(f"{where}: coverage has unknown key: {', '.join(bad)}")
517
+ entries = coverage.get("ignore", [])
518
+ if not isinstance(entries, list):
519
+ raise ConfigError(f"{where}: coverage.ignore must be a list of tables")
520
+ out: list[Ignore] = []
521
+ for k, item in enumerate(entries, start=1):
522
+ if not isinstance(item, dict):
523
+ raise ConfigError(
524
+ f"{where}: coverage.ignore[{k}] must be a table with module and reason"
525
+ )
526
+ bad = sorted(set(item) - IGNORE_KEYS)
527
+ if bad:
528
+ raise ConfigError(f"{where}: coverage.ignore[{k}] has unknown key: {', '.join(bad)}")
529
+ module = item.get("module")
530
+ if not isinstance(module, str) or not module:
531
+ raise ConfigError(f"{where}: coverage.ignore[{k}] needs a module name")
532
+ reason = item.get("reason")
533
+ if not isinstance(reason, str) or not reason.strip():
534
+ raise ConfigError(
535
+ f"{where}: coverage.ignore[{k}] ({module}) needs a reason: "
536
+ "say why the map may leave this module unmapped"
537
+ )
538
+ out.append(Ignore(module=module, reason=reason))
539
+ return tuple(out)
540
+
541
+
542
+ def _facts(raw: dict[str, Any], where: str) -> tuple[str, ...]:
543
+ """The `[facts]` table: `model_sdks` extends the judgement's built-in list."""
544
+ facts = raw.get("facts", {})
545
+ if not isinstance(facts, dict):
546
+ raise ConfigError(f"{where}: facts must be a table")
547
+ bad = sorted(set(facts) - FACTS_KEYS)
548
+ if bad:
549
+ raise ConfigError(f"{where}: facts has unknown key: {', '.join(bad)}")
550
+ return _str_list(facts, "model_sdks", f"{where}: facts")
551
+
552
+
553
+ def _flows(raw: dict[str, Any], where: str) -> tuple[str, ...]:
554
+ """The `[flows]` table: `observed_by` names the non-import mechanisms."""
555
+ flows = raw.get("flows", {})
556
+ if not isinstance(flows, dict):
557
+ raise ConfigError(f"{where}: flows must be a table")
558
+ bad = sorted(set(flows) - FLOWS_KEYS)
559
+ if bad:
560
+ raise ConfigError(f"{where}: flows has unknown key: {', '.join(bad)}")
561
+ names = _str_list(flows, "observed_by", f"{where}: flows")
562
+ if any(not name.strip() for name in names):
563
+ raise ConfigError(f"{where}: flows.observed_by must name each mechanism with a word")
564
+ return tuple(name.strip() for name in names)
565
+
566
+
567
+ def _judgement_answered(raw: dict[str, Any], where: str) -> tuple[Answer, ...]:
568
+ """The `[judgement] answered` list; an entry without a reason is refused."""
569
+ judgement = raw.get("judgement", {})
570
+ if not isinstance(judgement, dict):
571
+ raise ConfigError(f"{where}: judgement must be a table")
572
+ bad = sorted(set(judgement) - JUDGEMENT_KEYS)
573
+ if bad:
574
+ raise ConfigError(f"{where}: judgement has unknown key: {', '.join(bad)}")
575
+ entries = judgement.get("answered", [])
576
+ if not isinstance(entries, list):
577
+ raise ConfigError(f"{where}: judgement.answered must be a list of tables")
578
+ out: list[Answer] = []
579
+ for k, entry in enumerate(entries, start=1):
580
+ if not isinstance(entry, dict):
581
+ raise ConfigError(
582
+ f"{where}: judgement.answered[{k}] must be a table with item (or items) and reason"
583
+ )
584
+ bad = sorted(set(entry) - ANSWER_KEYS)
585
+ if bad:
586
+ raise ConfigError(f"{where}: judgement.answered[{k}] has unknown key: {', '.join(bad)}")
587
+ forms = [form for form in ANSWER_FORMS if entry.get(form) is not None]
588
+ if len(forms) != 1:
589
+ raise ConfigError(
590
+ f"{where}: judgement.answered[{k}] needs exactly one of item (one line), "
591
+ "items (a list), crossing (two or more component ids), crossing_into or "
592
+ "crossing_from (one component id), kind (a line kind) or module_sdk (an "
593
+ f"import name); it has {len(forms)}"
594
+ )
595
+ (form,) = forms
596
+ value = entry[form]
597
+ lines: tuple[str, ...] = ()
598
+ crossing: tuple[str, ...] | None = None
599
+ kind = ""
600
+ module_sdk = ""
601
+ crossing_into = ""
602
+ crossing_from = ""
603
+ if form == "item":
604
+ if not isinstance(value, str) or not value.strip():
605
+ raise ConfigError(f"{where}: judgement.answered[{k}] item must be a line")
606
+ lines = (value.strip(),)
607
+ elif form == "items":
608
+ if (
609
+ not isinstance(value, list)
610
+ or not value
611
+ or not all(isinstance(v, str) and v.strip() for v in value)
612
+ ):
613
+ raise ConfigError(
614
+ f"{where}: judgement.answered[{k}] items must be a non-empty list of lines"
615
+ )
616
+ lines = tuple(v.strip() for v in value)
617
+ elif form == "crossing":
618
+ ids = [v.strip() for v in value] if isinstance(value, list) else []
619
+ if (
620
+ len(ids) < 2
621
+ or not all(isinstance(v, str) and v for v in ids)
622
+ or len(set(ids)) != len(ids)
623
+ ):
624
+ raise ConfigError(
625
+ f"{where}: judgement.answered[{k}] crossing must name two or more "
626
+ 'different component ids, ["A", "B"]'
627
+ )
628
+ crossing = tuple(ids)
629
+ elif form in ("crossing_into", "crossing_from"):
630
+ if not isinstance(value, str) or not value.strip():
631
+ raise ConfigError(
632
+ f"{where}: judgement.answered[{k}] {form} must name one component id"
633
+ )
634
+ if form == "crossing_into":
635
+ crossing_into = value.strip()
636
+ else:
637
+ crossing_from = value.strip()
638
+ elif form == "kind":
639
+ if not isinstance(value, str) or value.strip() not in LINE_KINDS:
640
+ raise ConfigError(
641
+ f"{where}: judgement.answered[{k}] kind must be one of {', '.join(LINE_KINDS)}"
642
+ )
643
+ kind = value.strip()
644
+ else:
645
+ if not isinstance(value, str) or not value.strip():
646
+ raise ConfigError(
647
+ f"{where}: judgement.answered[{k}] module_sdk must be an import name"
648
+ )
649
+ module_sdk = value.strip()
650
+ reason = entry.get("reason")
651
+ answer = Answer(
652
+ items=lines,
653
+ reason="",
654
+ crossing=crossing,
655
+ kind=kind,
656
+ module_sdk=module_sdk,
657
+ crossing_into=crossing_into,
658
+ crossing_from=crossing_from,
659
+ )
660
+ if not isinstance(reason, str) or not reason.strip():
661
+ raise ConfigError(
662
+ f"{where}: judgement.answered[{k}] ({answer.label}) needs a reason: "
663
+ "say why the line is answered rather than acted on"
664
+ )
665
+ out.append(dataclasses.replace(answer, reason=reason))
666
+ return tuple(out)
667
+
668
+
669
+ def load_model(path: Path, label: str = "") -> tuple[Model, Meaning]:
670
+ """Import the model module by path and return its MODEL and MEANING.
671
+
672
+ `label` is the name the messages call the module by (the configured
673
+ `model`, `map/model.py`); the path itself when not given. A name the
674
+ module could not import or does not know is reported as such, with
675
+ the fix: the starter imports every schema name, and an agent that
676
+ trims the import and then uses `Layer` gets one line, not a traceback.
677
+
678
+ The source is compiled and run directly rather than through the
679
+ import system's loader: that loader keeps bytecode under
680
+ `__pycache__` keyed by the source's size and whole-second mtime, so an
681
+ edit that changes neither (a moved card, one name for another of the
682
+ same length, within the same second as the last run) would be read
683
+ back as the old model. An agent runs the check after every edit;
684
+ the model it checks must be the one on disk.
685
+ """
686
+ if not path.is_file():
687
+ raise ConfigError(f"model module not found: {path}")
688
+ label = label or str(path)
689
+ name = f"systemap_model_{abs(hash(str(path)))}"
690
+ module = types.ModuleType(name)
691
+ module.__file__ = str(path)
692
+ sys.modules[name] = module
693
+ try:
694
+ source = path.read_text(encoding="utf-8")
695
+ exec(compile(source, str(path), "exec"), module.__dict__) # noqa: S102 - the model is code
696
+ except (ImportError, NameError) as exc:
697
+ raise ConfigError(
698
+ f"{label} failed to import: {exc}; add the missing name to the import from systemap"
699
+ ) from exc
700
+ except Exception as exc: # noqa: BLE001 - the consumer's module may fail any way
701
+ raise ConfigError(f"{label} failed to import: {type(exc).__name__}: {exc}") from exc
702
+ finally:
703
+ sys.modules.pop(name, None)
704
+ model = getattr(module, "MODEL", None)
705
+ meaning = getattr(module, "MEANING", None)
706
+ if not isinstance(model, Model):
707
+ raise ConfigError(f"{label}: MODEL must be a systemap.Model")
708
+ if not isinstance(meaning, Meaning):
709
+ raise ConfigError(f"{label}: MEANING must be a systemap.Meaning")
710
+ return model, meaning