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/cli.py ADDED
@@ -0,0 +1,1006 @@
1
+ """The `systemap` command: what the agent runs.
2
+
3
+ systemap init [--no-ci] configuration, starter model, the skill, a workflow
4
+ systemap extract [--check] read the facts out of the tree
5
+ systemap facts [--modules ...] read the facts back, one view at a time (never the JSON)
6
+ systemap place [--all] [--print] [--keep-order]
7
+ a position for every card without one; --all for every card
8
+ systemap render [--check] render the page from facts and model
9
+ systemap check every rule; exit 1 with each fix named
10
+ systemap figure ... --out FILE one figure from the same generator; --map ID for a sub-map
11
+ systemap refresh extract, check, render, figures
12
+ systemap judgement [--strict] the list the maintainer must confirm; --kind, --verbose
13
+ systemap delta --base REF what a change did to the map, each line with its fix
14
+ systemap suggest a first grouping from the facts, to argue with
15
+ systemap describe what a look at the picture would tell you, in numbers
16
+ systemap serve [--port N] serve the output directory over HTTP, print the URL
17
+ systemap skill [--dir PATH|--print] reinstall the skill directory, or print SKILL.md
18
+
19
+ Exit codes: 0 the map is current or the check passed; 1 the map is stale or
20
+ a check failed; 2 the configuration or the model cannot be used. Every
21
+ non-zero exit prints one line saying what to run.
22
+
23
+ Every command that reads the model walks the tree of maps (`nest`): the
24
+ top map, then the map inside each card that opens one. A sub-map's lines
25
+ carry its id in front, and its page is written under the output directory
26
+ at `<id>/index.html`.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import sys
33
+ from dataclasses import dataclass
34
+ from functools import partial
35
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
36
+ from pathlib import Path
37
+ from typing import Any
38
+
39
+ from systemap import (
40
+ __version__,
41
+ change,
42
+ check,
43
+ config,
44
+ delta,
45
+ describe,
46
+ extract,
47
+ figure,
48
+ judgement,
49
+ nest,
50
+ page,
51
+ place,
52
+ scaffold,
53
+ skill,
54
+ )
55
+ from systemap import facts as facts_mod
56
+ from systemap import suggest as suggest_mod
57
+ from systemap.config import Config, ConfigError
58
+ from systemap.model import Meaning, Model
59
+ from systemap.model import problems as model_problems
60
+
61
+ OK, STALE, BAD_CONFIG = 0, 1, 2
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Project:
66
+ """The configuration and the tree of maps under the configured model."""
67
+
68
+ cfg: Config
69
+ tree: nest.Tree
70
+
71
+ @property
72
+ def model(self) -> Model:
73
+ return self.tree.top.model
74
+
75
+ @property
76
+ def meaning(self) -> Meaning:
77
+ return self.tree.top.meaning
78
+
79
+ @property
80
+ def theme(self) -> dict[str, Any]:
81
+ return self.tree.top.theme
82
+
83
+
84
+ def say(*lines: str) -> None:
85
+ for line in lines:
86
+ print(line)
87
+
88
+
89
+ def warn(*lines: str) -> None:
90
+ for line in lines:
91
+ print(line, file=sys.stderr)
92
+
93
+
94
+ def _root(args: argparse.Namespace) -> Path:
95
+ if args.root:
96
+ return Path(args.root).resolve()
97
+ found = config.find_root(Path.cwd().resolve())
98
+ return found or Path.cwd().resolve()
99
+
100
+
101
+ def _project(args: argparse.Namespace) -> Project:
102
+ cfg = config.load(_root(args))
103
+ return Project(cfg, nest.load(cfg))
104
+
105
+
106
+ # ---- init ------------------------------------------------------------------
107
+
108
+
109
+ AGENT_SENTENCE = "Map this repository with systemap. Follow the systemap skill."
110
+ # The sentence for a repository that already has a map: the skill's "the
111
+ # code changed" path, with the ref the map is compared against.
112
+ MAINTENANCE_SENTENCE = (
113
+ "The code changed. Update the map with systemap: follow the systemap skill's "
114
+ "maintenance path, with base {base}."
115
+ )
116
+
117
+
118
+ def cmd_init(args: argparse.Namespace) -> int:
119
+ root = Path(args.root).resolve() if args.root else Path.cwd().resolve()
120
+ roots = config.discover_roots(root)
121
+ package = roots[0][1] if roots else "mypackage"
122
+ name = args.name or config.default_name(root)
123
+ say(*scaffold.write(root, name, package, roots, ci=not args.no_ci))
124
+ skill_path = skill.write(root / skill.DEFAULT_DIR)
125
+ references = len(skill.files()) - 1
126
+ say(
127
+ f"wrote {skill_path.parent.relative_to(root).as_posix()}/ "
128
+ f"({skill.FILE_NAME} and {references} references)"
129
+ )
130
+ say(*scaffold.TOOLING_NOTE)
131
+ say("next: give your coding agent this sentence:", f" {AGENT_SENTENCE}")
132
+ return OK
133
+
134
+
135
+ # ---- extract ---------------------------------------------------------------
136
+
137
+
138
+ def _require_roots(p: Project) -> None:
139
+ if not p.cfg.roots:
140
+ found = config.candidate_packages(p.cfg.root)
141
+ where = (
142
+ "directories holding an __init__.py: " + ", ".join(found)
143
+ if found
144
+ else f"no directory holding an __init__.py up to {config.CANDIDATE_DEPTH} deep"
145
+ )
146
+ raise ConfigError(
147
+ "no package roots found; set [package_roots] in systemap.toml "
148
+ f'("path" = "import name"); {where}'
149
+ )
150
+
151
+
152
+ def cmd_extract(args: argparse.Namespace) -> int:
153
+ p = _project(args)
154
+ _require_roots(p)
155
+ fresh = extract.build(p.cfg)
156
+ stored = extract.read_facts(p.cfg.facts_path)
157
+ if args.check:
158
+ problems = [
159
+ m.prefix + line
160
+ for m in p.tree.maps
161
+ for line in check.stale_facts(fresh, stored, m.model, p.cfg.prefixes)
162
+ ]
163
+ # The drift is the facts' own and is reported once, on the top map.
164
+ problems = list(dict.fromkeys(problems))
165
+ if problems:
166
+ noun = "problem" if len(problems) == 1 else "problems"
167
+ say(f"map is out of date ({len(problems)} {noun}):")
168
+ say(*(f" {line}" for line in problems[:25]))
169
+ if len(problems) > 25:
170
+ say(f" ... and {len(problems) - 25} more")
171
+ say("run: systemap extract")
172
+ return STALE
173
+ say(f"map is current: {len(fresh['components'])} modules match the tree")
174
+ return OK
175
+ extract.write_facts(p.cfg.facts_path, fresh)
176
+ say(*extract.summary(fresh))
177
+ for m in p.tree.maps:
178
+ for line in extract.mapping_drift(fresh, m.model, p.cfg.prefixes):
179
+ say(f" warning: {m.prefix}{line}")
180
+ say(f"written to {p.cfg.rel(p.cfg.facts_path)}")
181
+ return OK
182
+
183
+
184
+ # ---- facts -----------------------------------------------------------------
185
+
186
+
187
+ def cmd_facts(args: argparse.Namespace) -> int:
188
+ """Read the facts back one view at a time, so nobody opens the JSON.
189
+
190
+ With no option: the extract summary and the views. A module name the
191
+ facts do not have is one line with the closest they do, exit 1.
192
+ """
193
+ p = _project(args)
194
+ facts = _facts_or_stale(p)
195
+ if facts is None:
196
+ return STALE
197
+ try:
198
+ if args.modules:
199
+ lines = facts_mod.modules(facts)
200
+ elif args.docstrings:
201
+ lines = facts_mod.docstrings(facts)
202
+ elif args.module:
203
+ lines = facts_mod.module(facts, args.module)
204
+ elif args.names:
205
+ lines = facts_mod.names(facts, args.names)
206
+ elif args.entry_points:
207
+ lines = facts_mod.entry_points(facts)
208
+ elif args.external:
209
+ lines = facts_mod.external(facts)
210
+ elif args.imports:
211
+ lines = facts_mod.imports(facts, args.imports)
212
+ else:
213
+ lines = facts_mod.overview(extract.summary(facts))
214
+ except facts_mod.UnknownModule as exc:
215
+ hint = f"; closest: {exc.closest}" if exc.closest else ""
216
+ say(f"no module {exc.name} in the facts{hint}", "run: systemap facts --modules")
217
+ return STALE
218
+ say(*lines)
219
+ return OK
220
+
221
+
222
+ # ---- render ----------------------------------------------------------------
223
+
224
+
225
+ def _facts_or_stale(p: Project) -> dict[str, Any] | None:
226
+ facts = extract.read_facts(p.cfg.facts_path)
227
+ if not facts:
228
+ say(f"no facts at {p.cfg.rel(p.cfg.facts_path)}", "run: systemap extract")
229
+ return None
230
+ return facts
231
+
232
+
233
+ def _model_ok(p: Project, maps: list[nest.Map] | None = None) -> bool:
234
+ """Every map (or the ones given) free of its own contradictions, else said."""
235
+ ok = True
236
+ for m in maps if maps is not None else list(p.tree.maps):
237
+ problems = model_problems(m.model, m.meaning)
238
+ if problems:
239
+ say(*(m.prefix + line for line in problems), f"fix {m.rel}, then run: systemap check")
240
+ ok = False
241
+ return ok
242
+
243
+
244
+ def _render_page(p: Project, m: nest.Map, facts: dict[str, Any], args: argparse.Namespace) -> str:
245
+ ch: dict[str, Any] = {"has_change": False}
246
+ base = getattr(args, "base", "")
247
+ if base:
248
+ ch = change.compute(p.cfg, m.model, base, facts, getattr(args, "head", "HEAD"))
249
+ ch["pr"] = change.pr_meta(p.cfg.root, getattr(args, "pr", ""))
250
+ return page.build(
251
+ p.cfg,
252
+ m.model,
253
+ m.meaning,
254
+ m.theme,
255
+ facts,
256
+ ch,
257
+ nesting=page.nesting_of(p.cfg, p.tree, m, facts),
258
+ )
259
+
260
+
261
+ def cmd_render(args: argparse.Namespace) -> int:
262
+ p = _project(args)
263
+ facts = _facts_or_stale(p)
264
+ if facts is None:
265
+ return STALE
266
+ if not _model_ok(p):
267
+ return STALE
268
+ code = OK
269
+ for m in p.tree.maps:
270
+ html = _render_page(p, m, facts, args)
271
+ out = m.page_path(p.cfg)
272
+ if args.check:
273
+ current = out.read_text(encoding="utf-8") if out.is_file() else ""
274
+ if current != html:
275
+ say(f"{p.cfg.rel(out)} is stale: it differs from what systemap renders")
276
+ code = STALE
277
+ else:
278
+ say(f"{p.cfg.rel(out)} is current")
279
+ continue
280
+ out.parent.mkdir(parents=True, exist_ok=True)
281
+ out.write_text(html, encoding="utf-8", newline="\n")
282
+ say(f"wrote {p.cfg.rel(out)} ({out.stat().st_size / 1024:.0f} KB)")
283
+ if code == STALE:
284
+ say("run: systemap refresh")
285
+ return code
286
+
287
+
288
+ # ---- check -----------------------------------------------------------------
289
+
290
+
291
+ NO_COMPONENTS = "the model has no components yet; see the skill"
292
+
293
+
294
+ def _empty(p: Project) -> bool:
295
+ """An empty model has one thing to say, and nothing else can be judged."""
296
+ if p.model.components:
297
+ return False
298
+ say(NO_COMPONENTS)
299
+ return True
300
+
301
+
302
+ def _fix_line(p: Project, results: dict[str, check.Result]) -> str:
303
+ """The one line naming what to do first about a failed check.
304
+
305
+ The model's own contradictions come first, since nothing else can be
306
+ judged until they are gone; then the facts; then the rules that read
307
+ the two together; then the outputs, which refresh regenerates. The
308
+ top map's file is named first, then a sub-map's.
309
+ """
310
+ for m in p.tree.maps:
311
+ if results[m.id].problems:
312
+ return f"fix {m.rel}, then run: systemap check"
313
+ top = results[p.tree.top.id]
314
+ if not top.coverage.checked:
315
+ return "run: systemap extract"
316
+ if top.coverage.problems:
317
+ return (
318
+ f"map every module in {p.cfg.model}, or ignore it with a reason under "
319
+ "[coverage] in the configuration, then run: systemap check"
320
+ )
321
+ for m in p.tree.maps:
322
+ result = results[m.id]
323
+ if result.entry or result.interface or result.nesting:
324
+ return f"fix {m.rel}, then run: systemap check"
325
+ return "run: systemap refresh"
326
+
327
+
328
+ def _check_tree(p: Project, facts: dict[str, Any]) -> dict[str, check.Result]:
329
+ return check.run_tree(p.tree, facts, p.cfg.coverage_ignore, p.cfg.observed_by)
330
+
331
+
332
+ def _report_tree(p: Project, results: dict[str, check.Result], stale: list[str]) -> list[str]:
333
+ """Every map's report in tree order, then the stale group once."""
334
+ out: list[str] = []
335
+ for m in p.tree.maps:
336
+ out += check.report(m.model, results[m.id], m.rel, m.prefix)
337
+ return out + check.report_stale(stale)
338
+
339
+
340
+ def cmd_check(args: argparse.Namespace) -> int:
341
+ p = _project(args)
342
+ _require_roots(p)
343
+ if _empty(p):
344
+ return STALE
345
+ facts = extract.read_facts(p.cfg.facts_path)
346
+ results = _check_tree(p, facts)
347
+ stale = check.stale(p.cfg, p.tree)
348
+ say(*_report_tree(p, results, stale))
349
+ if not check.tree_ok(results) or stale:
350
+ say(_fix_line(p, results) if not check.tree_ok(results) else "run: systemap refresh")
351
+ return STALE
352
+ return OK
353
+
354
+
355
+ # ---- figure ----------------------------------------------------------------
356
+
357
+
358
+ def _ids(values: list[str] | None) -> tuple[str, ...]:
359
+ out: list[str] = []
360
+ for value in values or []:
361
+ out.extend(s.strip() for s in value.split(",") if s.strip())
362
+ return tuple(out)
363
+
364
+
365
+ def _map(p: Project, map_id: str) -> nest.Map:
366
+ """The map a `--map ID` names; the top map for none; unknown is refused."""
367
+ if not p.tree.has(map_id):
368
+ raise nest.unknown_map(p.tree, map_id)
369
+ return p.tree.get(map_id)
370
+
371
+
372
+ def cmd_figure(args: argparse.Namespace) -> int:
373
+ p = _project(args)
374
+ facts = _facts_or_stale(p)
375
+ if facts is None:
376
+ return STALE
377
+ m = _map(p, args.map or "")
378
+ if not _model_ok(p, [m]):
379
+ return STALE
380
+ html, collisions = figure.make(
381
+ p.cfg,
382
+ m.model,
383
+ m.meaning,
384
+ m.theme,
385
+ facts,
386
+ mode=args.mode or "",
387
+ components=_ids(args.components),
388
+ base=args.base or "",
389
+ head=args.head,
390
+ caption=args.caption or "",
391
+ svg_id=args.svg_id,
392
+ interactive=bool(args.interactive),
393
+ bare=bool(args.out) and args.out.endswith(".svg"),
394
+ layer=args.layer or "",
395
+ map_id=m.id,
396
+ opens=nest.opens(p.tree, m, links=False),
397
+ )
398
+ for line in collisions:
399
+ warn(line)
400
+ if args.out:
401
+ # Relative to the output directory, like a [[figures]] out; an
402
+ # absolute path is written where it says.
403
+ out = Path(args.out)
404
+ if not out.is_absolute():
405
+ out = p.cfg.out_path / out
406
+ out.parent.mkdir(parents=True, exist_ok=True)
407
+ out.write_text(html, encoding="utf-8", newline="\n")
408
+ say(f"wrote {p.cfg.rel(out)} ({len(html) / 1024:.0f} KB)")
409
+ else:
410
+ sys.stdout.write(html)
411
+ if collisions:
412
+ warn(f"fix {m.rel}, then run: systemap check")
413
+ return STALE
414
+ return OK
415
+
416
+
417
+ # ---- refresh ---------------------------------------------------------------
418
+
419
+ # Current means the page is what the renderer draws from the model's
420
+ # rendered fields and the stored facts, and the facts describe the tree.
421
+ ALREADY_CURRENT = "map: already current: the page matches the model's rendered fields and the facts"
422
+
423
+
424
+ def cmd_refresh(args: argparse.Namespace) -> int:
425
+ p = _project(args)
426
+ quiet = bool(args.quiet)
427
+
428
+ def note(line: str) -> None:
429
+ if not quiet:
430
+ say(line)
431
+
432
+ _require_roots(p)
433
+ if _empty(p):
434
+ return STALE
435
+ fresh = extract.build(p.cfg)
436
+ # Current means two things at once: nothing on disk is older than the
437
+ # tree or the model, and the check passes. A stale-free map that fails
438
+ # coverage is not current; it is incomplete.
439
+ stale_lines = check.stale(p.cfg, p.tree, fresh)
440
+ results = _check_tree(p, fresh)
441
+ if not stale_lines and check.tree_ok(results):
442
+ note(ALREADY_CURRENT)
443
+ return OK
444
+
445
+ note("map: refreshing against the working tree")
446
+ extract.write_facts(p.cfg.facts_path, fresh)
447
+ written = [p.cfg.rel(p.cfg.facts_path)]
448
+ if not check.tree_ok(results):
449
+ say(*_report_tree(p, results, []))
450
+ fix = _fix_line(p, results).replace("systemap check", "systemap refresh")
451
+ say(f"map: check failed; {fix}")
452
+ return STALE
453
+ for m in p.tree.maps:
454
+ html = _render_page(p, m, fresh, argparse.Namespace())
455
+ out = m.page_path(p.cfg)
456
+ out.parent.mkdir(parents=True, exist_ok=True)
457
+ out.write_text(html, encoding="utf-8", newline="\n")
458
+ written.append(p.cfg.rel(out))
459
+ for fig in p.cfg.figures:
460
+ html, collisions = figure.configured(p.cfg, p.tree, _map(p, fig.map), fresh, fig)
461
+ for line in collisions:
462
+ warn(line)
463
+ out = p.cfg.out_path / fig.out
464
+ out.parent.mkdir(parents=True, exist_ok=True)
465
+ out.write_text(html, encoding="utf-8", newline="\n")
466
+ written.append(p.cfg.rel(out))
467
+ # What was written is checked as `systemap check` would check it. A
468
+ # refresh that leaves the check failing is not a refresh, whatever it
469
+ # wrote; the exit code says so.
470
+ after = _check_tree(p, fresh)
471
+ stale_after = check.stale(p.cfg, p.tree, fresh)
472
+ if not check.tree_ok(after) or stale_after:
473
+ say(*_report_tree(p, after, stale_after))
474
+ fix = (
475
+ _fix_line(p, after) if not check.tree_ok(after) else "run: systemap refresh"
476
+ ).replace("systemap check", "systemap refresh")
477
+ say(f"map: check failed after the refresh; {fix}")
478
+ return STALE
479
+ note(f"map: updated {', '.join(written)}")
480
+ note(f"map: commit {p.cfg.out_dir}/ to record this state of the system")
481
+ return OK
482
+
483
+
484
+ # ---- judgement -------------------------------------------------------------
485
+
486
+
487
+ def cmd_judgement(args: argparse.Namespace) -> int:
488
+ """The list the maintainer confirms. A report, not a gate: exit 0.
489
+
490
+ Lines answered under `[judgement] answered` in the configuration are
491
+ suppressed and counted; an answer that matches no line is reported as
492
+ stale so it can be removed. With `--strict` the report is a gate for
493
+ a workflow: exit 1 while any line is open. A stale answer is reported
494
+ either way and fails neither.
495
+ """
496
+ p = _project(args)
497
+ if _empty(p):
498
+ return OK
499
+ facts = extract.read_facts(p.cfg.facts_path)
500
+ if not facts:
501
+ say(f"no facts at {p.cfg.rel(p.cfg.facts_path)}; the list below reads the model alone")
502
+ lines = judgement.run_tree(
503
+ p.tree,
504
+ facts,
505
+ judgement.sdk_list(p.cfg.model_sdks),
506
+ p.cfg.observed_by,
507
+ )
508
+ result = judgement.apply_answers(lines, p.cfg.judgement_answered)
509
+ detail = judgement.crossing_detail_tree(p.tree, facts) if args.verbose else None
510
+ say(*judgement.report(result, detail, args.kind or ""))
511
+ if args.strict and result.open:
512
+ say("answer every line in [judgement] answered in systemap.toml, or act on it")
513
+ return STALE
514
+ return OK
515
+
516
+
517
+ # ---- delta -----------------------------------------------------------------
518
+
519
+
520
+ def cmd_delta(args: argparse.Namespace) -> int:
521
+ """What a change did to the map, from the facts at two commits.
522
+
523
+ Both trees are read from git, never from the working copy; the model
524
+ is the one on disk. Exit 0 when nothing needs a person, 1 when a line
525
+ does, each line naming its fix; `--format markdown` prints the report
526
+ as a pull-request comment, with the committed map at the head commit
527
+ where a GitHub remote and a figure make that possible.
528
+ """
529
+ p = _project(args)
530
+ _require_roots(p)
531
+ if _empty(p):
532
+ return STALE
533
+ root = p.cfg.root
534
+ base_sha = delta.resolve(root, args.base)
535
+ head_sha = delta.resolve(root, args.head)
536
+ compared = delta.merge_base(root, base_sha, head_sha)
537
+ d = delta.compute_tree(
538
+ p.cfg,
539
+ p.tree,
540
+ delta.facts_at(p.cfg, compared),
541
+ delta.facts_at(p.cfg, head_sha),
542
+ base_ref=args.base,
543
+ head_ref=args.head,
544
+ )
545
+ if args.format == "markdown":
546
+ sys.stdout.write(delta.markdown(d, delta.figure_url(p.cfg, head_sha)))
547
+ else:
548
+ say(*delta.report(d))
549
+ return STALE if d.open else OK
550
+
551
+
552
+ # ---- suggest ---------------------------------------------------------------
553
+
554
+
555
+ def cmd_suggest(args: argparse.Namespace) -> int:
556
+ """A first grouping from the facts alone, to argue with; never the answer.
557
+
558
+ With a model that has cards, the tree is read too, for when a map is
559
+ past forty cards and which cards to open a map inside.
560
+ """
561
+ cfg = config.load(_root(args))
562
+ facts = extract.read_facts(cfg.facts_path)
563
+ if not facts:
564
+ say(f"no facts at {cfg.rel(cfg.facts_path)}", "run: systemap extract")
565
+ return STALE
566
+ say(*suggest_mod.lines(facts))
567
+ if cfg.model_path.is_file():
568
+ tree = nest.load(cfg)
569
+ if tree.top.model.components:
570
+ say(*suggest_mod.nesting_lines(tree, facts))
571
+ return OK
572
+
573
+
574
+ # ---- describe --------------------------------------------------------------
575
+
576
+
577
+ def cmd_describe(args: argparse.Namespace) -> int:
578
+ """The picture in numbers, for an agent that cannot open the page.
579
+
580
+ The drawing is made the way the page makes it and read back: cards
581
+ per region, bends and length per edge (worst first), seats per
582
+ gutter, cards and edges per reading. A model that contradicts itself
583
+ cannot be drawn, so that is reported instead, as `check` reports it.
584
+ """
585
+ p = _project(args)
586
+ if _empty(p):
587
+ return STALE
588
+ facts = extract.read_facts(p.cfg.facts_path)
589
+ code = OK
590
+ for m in p.tree.maps:
591
+ # A card without a position is placed for this look, as `systemap
592
+ # place` would place it, and the positions line says which; a
593
+ # whole layout searched the region order, and the order line says
594
+ # how many orders it tried.
595
+ placement = place.compute(m.model)
596
+ model = place.apply(m.model, placement) if placement.positions else m.model
597
+ problems = model_problems(model, m.meaning)
598
+ if problems:
599
+ say(*(m.prefix + line for line in problems), f"fix {m.rel}, then run: systemap check")
600
+ code = STALE
601
+ continue
602
+ lines = describe.run(
603
+ model,
604
+ m.meaning,
605
+ m.theme,
606
+ facts,
607
+ p.cfg.observed_by,
608
+ placement.placed,
609
+ searched=(placement.tried, placement.routed) if placement.fresh else None,
610
+ )
611
+ say(*(m.prefix + line for line in lines))
612
+ return code
613
+
614
+
615
+ # ---- place -----------------------------------------------------------------
616
+
617
+
618
+ def cmd_place(args: argparse.Namespace) -> int:
619
+ """A position for every card without one, written into the model.
620
+
621
+ A card with `x` and `y` is kept where it is; `--all` lays every card
622
+ out again and keeps only the cards marked `pinned=True`. With no card
623
+ kept the regions, the containers and the canvas are laid out too;
624
+ with any kept, the boxes stay as written and the other cards take
625
+ the free slots inside them; with none kept the region order is
626
+ searched (`--keep-order` lays them as listed) and the chosen order
627
+ and its score are printed. `--print` prints the positions instead
628
+ of writing them. The check decides, as before: run it next.
629
+ """
630
+ p = _project(args)
631
+ if _empty(p):
632
+ return STALE
633
+ wrote = False
634
+ for m in p.tree.maps:
635
+ placement = place.compute(
636
+ m.model, all_cards=bool(args.all), keep_order=bool(args.keep_order)
637
+ )
638
+ if args.print or not placement.positions:
639
+ say(*(m.prefix + line for line in place.lines(placement)))
640
+ continue
641
+ source = place.write(m.path, placement)
642
+ # The file is read back and compared with what was computed, so a
643
+ # card the edit could not reach is reported, never assumed written.
644
+ reloaded, _meaning = config.load_model(m.path, m.rel)
645
+ wrong = place.unwritten(reloaded, placement)
646
+ if wrong:
647
+ m.path.write_text(source, encoding="utf-8", newline="\n")
648
+ raise place.PlaceError(
649
+ f"could not write a position for {', '.join(wrong)} into {m.rel}: the card "
650
+ "is not a Component(id=...) call the file spells out; add x and y by hand from "
651
+ "systemap place --print"
652
+ )
653
+ laid = "; every box and the canvas laid out" if placement.fresh else ""
654
+ say(f"{m.prefix}place: wrote {m.rel}: {place.head(placement)}{laid}")
655
+ if placement.fresh:
656
+ say(f"{m.prefix} {place.order_line(placement)}")
657
+ wrote = True
658
+ if wrote:
659
+ say("run: systemap check")
660
+ return OK
661
+
662
+
663
+ # ---- serve -----------------------------------------------------------------
664
+
665
+
666
+ DEFAULT_PORT = 8765
667
+
668
+
669
+ def make_server(directory: Path, port: int) -> ThreadingHTTPServer:
670
+ """An HTTP server over `directory` on 127.0.0.1; port 0 picks a free one."""
671
+ handler = partial(SimpleHTTPRequestHandler, directory=str(directory))
672
+ return ThreadingHTTPServer(("127.0.0.1", port), handler)
673
+
674
+
675
+ def cmd_serve(args: argparse.Namespace) -> int:
676
+ """Serve the output directory, since the page's script does not run from file://.
677
+
678
+ The standard library's server, over the output directory alone, on the
679
+ loopback address. It runs until interrupted and prints the URL first,
680
+ so an agent can open it without knowing the port.
681
+ """
682
+ cfg = config.load(_root(args))
683
+ if not cfg.page_path.is_file():
684
+ say(f"no page at {cfg.rel(cfg.page_path)}", "run: systemap refresh")
685
+ return STALE
686
+ httpd = make_server(cfg.out_path, int(args.port))
687
+ port = httpd.server_address[1]
688
+ say(f"serving {cfg.rel(cfg.out_path)} at http://127.0.0.1:{port}/ (Ctrl-C to stop)")
689
+ try:
690
+ httpd.serve_forever()
691
+ except KeyboardInterrupt:
692
+ pass
693
+ finally:
694
+ httpd.server_close()
695
+ return OK
696
+
697
+
698
+ # ---- skill -----------------------------------------------------------------
699
+
700
+
701
+ def cmd_skill(args: argparse.Namespace) -> int:
702
+ if args.print:
703
+ sys.stdout.write(skill.text())
704
+ return OK
705
+ target = Path(args.dir).resolve() if args.dir else _root(args) / skill.DEFAULT_DIR
706
+ path = skill.write(target)
707
+ references = len(skill.files()) - 1
708
+ say(f"wrote {path}", f"wrote {target / skill.REFERENCES}/ ({references} files)")
709
+ return OK
710
+
711
+
712
+ # ---- the parser ------------------------------------------------------------
713
+
714
+
715
+ def build_parser() -> argparse.ArgumentParser:
716
+ parser = argparse.ArgumentParser(
717
+ prog="systemap",
718
+ description="A generated, interactive map of a Python system.",
719
+ )
720
+ parser.add_argument("--version", action="version", version=f"systemap {__version__}")
721
+ parser.add_argument(
722
+ "--root",
723
+ default="",
724
+ help="project root (default: the nearest directory with systemap.toml, "
725
+ "[tool.systemap] in pyproject.toml, or .git); accepted before or after the command",
726
+ )
727
+ sub = parser.add_subparsers(dest="command", required=True, metavar="command")
728
+
729
+ def add_root(s: argparse.ArgumentParser) -> None:
730
+ # The global --root, accepted after the subcommand as well. The
731
+ # subparser's default is suppressed so it never overwrites a --root
732
+ # given before the subcommand.
733
+ s.add_argument("--root", default=argparse.SUPPRESS, help=argparse.SUPPRESS)
734
+
735
+ s = sub.add_parser(
736
+ "init", help="write systemap.toml, a starter model, the agent skill and a workflow"
737
+ )
738
+ add_root(s)
739
+ s.add_argument(
740
+ "--name",
741
+ default="",
742
+ help="the page title (default: [project] name in pyproject.toml, then the git "
743
+ "repository's directory, then the directory name)",
744
+ )
745
+ s.add_argument(
746
+ "--no-ci", action="store_true", help="do not write .github/workflows/systemap.yml"
747
+ )
748
+ s.set_defaults(func=cmd_init)
749
+
750
+ s = sub.add_parser("extract", help="read the facts out of the tree")
751
+ add_root(s)
752
+ s.add_argument("--check", action="store_true", help="exit 1 if the stored facts are stale")
753
+ s.set_defaults(func=cmd_extract)
754
+
755
+ s = sub.add_parser(
756
+ "facts",
757
+ help="read the facts back one view at a time: --modules (one line per module: the "
758
+ "docstring's first sentence, then public names, imports and tests counted), "
759
+ "--docstrings (the first sentence only), --module NAME (its record, rendered), "
760
+ "--names NAME (its public names with kinds), --entry-points (with targets), "
761
+ "--external, --imports NAME; with no option, the extract summary",
762
+ )
763
+ add_root(s)
764
+ view = s.add_mutually_exclusive_group()
765
+ view.add_argument(
766
+ "--modules",
767
+ action="store_true",
768
+ help="one line per module: the first sentence of its docstring, then its public "
769
+ "names, imports and tests counted",
770
+ )
771
+ view.add_argument(
772
+ "--docstrings",
773
+ action="store_true",
774
+ help="one line per module: the first sentence of its docstring",
775
+ )
776
+ view.add_argument(
777
+ "--module",
778
+ default="",
779
+ metavar="NAME",
780
+ help="one module's record, rendered: docstring, public names with kinds, imports, "
781
+ "imported by, external imports, test count",
782
+ )
783
+ view.add_argument(
784
+ "--names",
785
+ default="",
786
+ metavar="NAME",
787
+ help="one module's public names with their kinds; a re-export names its module",
788
+ )
789
+ view.add_argument(
790
+ "--entry-points",
791
+ dest="entry_points",
792
+ action="store_true",
793
+ help="where a run can start, each named the way a person types it, with its target",
794
+ )
795
+ view.add_argument(
796
+ "--external",
797
+ action="store_true",
798
+ help="every third-party import, with the modules that import it",
799
+ )
800
+ view.add_argument(
801
+ "--imports",
802
+ default="",
803
+ metavar="NAME",
804
+ help="what one module imports from the package, and what imports it",
805
+ )
806
+ s.set_defaults(func=cmd_facts)
807
+
808
+ s = sub.add_parser(
809
+ "place",
810
+ help="write a position into the model for every card without one, keeping every "
811
+ "card that has one; --all lays every card out again and keeps only the cards "
812
+ "marked pinned=True (run it after adding or removing a card); with no card kept, "
813
+ "the regions, containers and canvas are laid out too, and the order of the regions "
814
+ "on the grid is searched: every order tried, the best routed, the one with the "
815
+ "fewest label collisions, refused routes, bends and length chosen; --keep-order "
816
+ "lays them as the model lists them; --print prints instead of writing",
817
+ )
818
+ add_root(s)
819
+ s.add_argument(
820
+ "--all",
821
+ action="store_true",
822
+ help="lay every card out again, keeping only the cards marked pinned=True",
823
+ )
824
+ s.add_argument("--print", action="store_true", help="print the positions; write nothing")
825
+ s.add_argument(
826
+ "--keep-order",
827
+ action="store_true",
828
+ help="lay the regions in the order the model lists them; skip the search",
829
+ )
830
+ s.set_defaults(func=cmd_place)
831
+
832
+ s = sub.add_parser("render", help="render the page from the facts and the model")
833
+ add_root(s)
834
+ s.add_argument("--check", action="store_true", help="exit 1 if the page is stale")
835
+ s.add_argument("--base", default="", help="also draw a change map of HEAD against this ref")
836
+ s.add_argument("--head", default="HEAD")
837
+ s.add_argument("--pr", default="", help="a pull request number, for the change map title")
838
+ s.set_defaults(func=cmd_render)
839
+
840
+ s = sub.add_parser(
841
+ "check",
842
+ help="every rule: placement, routes, labels, type size, meaning, wheels, coverage, "
843
+ "nesting, entry, stale outputs, on every map; exit 1 with each fix named",
844
+ )
845
+ add_root(s)
846
+ s.set_defaults(func=cmd_check)
847
+
848
+ s = sub.add_parser("figure", help="draw one figure with the same generator")
849
+ add_root(s)
850
+ kind = s.add_mutually_exclusive_group()
851
+ kind.add_argument("--interactive", action="store_true", help="carry the focus interaction")
852
+ kind.add_argument("--static", action="store_true", help="a plain figure (default)")
853
+ s.add_argument(
854
+ "--components",
855
+ nargs="*",
856
+ metavar="ID",
857
+ help="component ids a plan reaches (comma or space separated)",
858
+ )
859
+ s.add_argument("--mode", choices=["system", "change"], default="")
860
+ s.add_argument("--base", default="", help="the ref a change figure compares against")
861
+ s.add_argument("--head", default="HEAD")
862
+ s.add_argument(
863
+ "--layer",
864
+ default="",
865
+ metavar="ID",
866
+ help="one reading only: that layer's edges, every card, the legend reduced to it "
867
+ "(structure, system, data, control, or a layer of the model's own)",
868
+ )
869
+ s.add_argument(
870
+ "--map",
871
+ default="",
872
+ metavar="ID",
873
+ help="the map inside a card, by the card's id (Gateway, or Gateway/Routes for a map "
874
+ "inside a map); the top map when not given",
875
+ )
876
+ s.add_argument("--caption", default="")
877
+ s.add_argument("--svg-id", dest="svg_id", default="lessonmap")
878
+ s.add_argument(
879
+ "--out",
880
+ default="",
881
+ help="the file to write, relative to out_dir like a [[figures]] out (default: "
882
+ "stdout); a .svg name writes the drawing alone",
883
+ )
884
+ s.set_defaults(func=cmd_figure)
885
+
886
+ s = sub.add_parser("refresh", help="extract, check, render, and draw the configured figures")
887
+ add_root(s)
888
+ s.add_argument("--quiet", action="store_true")
889
+ s.set_defaults(func=cmd_refresh)
890
+
891
+ s = sub.add_parser(
892
+ "judgement",
893
+ help="print the list the maintainer must confirm: thin components, odd folds, "
894
+ "flows without a sentence, thin layers, entry points without a journey, imports "
895
+ "across a boundary with no flow, flows no import backs, model sdk imports outside "
896
+ "an agent; lines "
897
+ "answered under [judgement] in the configuration are suppressed and counted; "
898
+ "exit 0, or 1 with --strict while any line is open; --kind KIND prints one kind, "
899
+ "--verbose lists the imports behind each crossing-import line",
900
+ )
901
+ add_root(s)
902
+ s.add_argument(
903
+ "--strict", action="store_true", help="exit 1 while any line is unanswered, for CI"
904
+ )
905
+ s.add_argument(
906
+ "--kind",
907
+ default="",
908
+ metavar="KIND",
909
+ choices=config.LINE_KINDS,
910
+ help="print the open lines of one kind only (one of: "
911
+ + ", ".join(f'"{kind}"' for kind in config.LINE_KINDS)
912
+ + "); the head and the exit code still count every line",
913
+ )
914
+ s.add_argument(
915
+ "--verbose",
916
+ action="store_true",
917
+ help="under each crossing-import line, the imports it counts, one per line",
918
+ )
919
+ s.set_defaults(func=cmd_judgement)
920
+
921
+ s = sub.add_parser(
922
+ "delta",
923
+ help="what a change did to the map, from the facts at two commits read out of git: "
924
+ "modules added, removed and moved with the card each belongs to, entry and interface "
925
+ "names that vanished, new imports across a card boundary with no flow, flows the "
926
+ "code stopped backing; each line names its fix; exit 0 when nothing needs a person, "
927
+ "1 when something does",
928
+ )
929
+ add_root(s)
930
+ s.add_argument(
931
+ "--base", required=True, help="the commit, branch or tag the map is compared against"
932
+ )
933
+ s.add_argument("--head", default="HEAD", help="the commit under study (default HEAD)")
934
+ s.add_argument(
935
+ "--format",
936
+ choices=["text", "markdown"],
937
+ default="text",
938
+ help="markdown prints the report as a pull-request comment with the committed map",
939
+ )
940
+ s.set_defaults(func=cmd_delta)
941
+
942
+ s = sub.add_parser(
943
+ "suggest",
944
+ help="a first grouping to argue with, never the answer: one proposed card per "
945
+ "package with two or more modules, its modules, and the crossing imports between "
946
+ "proposals, from the facts alone",
947
+ )
948
+ add_root(s)
949
+ s.set_defaults(func=cmd_suggest)
950
+
951
+ s = sub.add_parser(
952
+ "describe",
953
+ help="what a look at the picture would tell you, in numbers: cards per region, "
954
+ "the region order and its score, bends and length per edge (worst first), seats "
955
+ "per gutter, cards and edges per reading; for an agent that cannot open the page",
956
+ )
957
+ add_root(s)
958
+ s.set_defaults(func=cmd_describe)
959
+
960
+ s = sub.add_parser(
961
+ "serve",
962
+ help="serve the output directory over HTTP on the loopback address and print the "
963
+ "URL; the page's script does not run from a file:// address",
964
+ )
965
+ add_root(s)
966
+ s.add_argument("--port", type=int, default=DEFAULT_PORT, help=f"default {DEFAULT_PORT}")
967
+ s.set_defaults(func=cmd_serve)
968
+
969
+ s = sub.add_parser(
970
+ "skill",
971
+ help="reinstall the agent skill directory (SKILL.md and references/) init installs, "
972
+ "or print SKILL.md",
973
+ )
974
+ add_root(s)
975
+ s.add_argument(
976
+ "--dir",
977
+ default="",
978
+ help=f"the directory to write the skill into (default: {skill.DEFAULT_DIR} under the root)",
979
+ )
980
+ s.add_argument("--print", action="store_true", help="write SKILL.md to stdout instead")
981
+ s.set_defaults(func=cmd_skill)
982
+ return parser
983
+
984
+
985
+ def main(argv: list[str] | None = None) -> int:
986
+ parser = build_parser()
987
+ args = parser.parse_args(argv)
988
+ try:
989
+ code = args.func(args)
990
+ except ConfigError as exc:
991
+ warn(f"systemap: {exc}", "fix systemap.toml or the model module, then run again")
992
+ return BAD_CONFIG
993
+ except figure.FigureError as exc:
994
+ warn(f"systemap: {exc}")
995
+ return STALE
996
+ except place.PlaceError as exc:
997
+ warn(f"systemap: {exc}")
998
+ return STALE
999
+ except delta.DeltaError as exc:
1000
+ warn(f"systemap: {exc}", "give delta a ref git can resolve, then run again")
1001
+ return BAD_CONFIG
1002
+ return int(code)
1003
+
1004
+
1005
+ if __name__ == "__main__":
1006
+ raise SystemExit(main())