stewardkit 0.1.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.
stewardkit/cli.py ADDED
@@ -0,0 +1,1110 @@
1
+ """Command-line interface for `stewardkit`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from collections.abc import Sequence
7
+ import json
8
+ from pathlib import Path
9
+ import sys
10
+ from typing import Any
11
+
12
+ from stewardkit import __version__
13
+ from stewardkit.config import (
14
+ CONFIG_FILENAME,
15
+ DEFAULT_SPECIALIST_CATALOG,
16
+ LOCAL_CONFIG_FILENAME,
17
+ VALID_CLOCK_FORMATS,
18
+ VALID_DELIVERY_MODES,
19
+ VALID_MERGE_STRATEGIES,
20
+ VALID_ORCHESTRATION_MODES,
21
+ VALID_PROFILES,
22
+ VALID_STATE_MODES,
23
+ ConfigError,
24
+ config_to_dict,
25
+ detect_git_context,
26
+ external_state_dir,
27
+ find_repo_root,
28
+ load_config,
29
+ load_user_config_data,
30
+ resolve_config_with_sources,
31
+ resolve_path_strict_cycles,
32
+ resolve_timezone,
33
+ user_config_path,
34
+ write_user_config,
35
+ )
36
+ from stewardkit.doctor import has_failures, run_doctor
37
+ from stewardkit.harnesses import HARNESS_SPECS, resolve_harness_paths
38
+ from stewardkit.installer import (
39
+ find_kit_root,
40
+ init_repo,
41
+ install_global,
42
+ sync_repo,
43
+ uninstall_repo,
44
+ )
45
+ from stewardkit.markers import MarkerError
46
+ from stewardkit.test_parity import check_tests_parity, find_doc_reader_tests
47
+
48
+
49
+ def _flatten_csv(values: Sequence[str] | None) -> list[str] | None:
50
+ if values is None:
51
+ return None
52
+ out: list[str] = []
53
+ for item in values:
54
+ for part in item.split(","):
55
+ cleaned = part.strip()
56
+ if cleaned:
57
+ out.append(cleaned)
58
+ return out
59
+
60
+
61
+ def _print_table(rows: Sequence[tuple[str, str, str]]) -> None:
62
+ if not rows:
63
+ return
64
+ col1 = max(len(r[0]) for r in rows)
65
+ col2 = max(len(r[1]) for r in rows)
66
+ for status, label, detail in rows:
67
+ print(f"{status:<{col1}} {label:<{col2}} {detail}")
68
+
69
+
70
+ def _emit_json(payload: dict[str, Any]) -> None:
71
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
72
+
73
+
74
+ def _emit_error(command: str, exc: Exception, *, as_json: bool) -> int:
75
+ if as_json:
76
+ _emit_json({"ok": False, "error": str(exc)})
77
+ else:
78
+ print(f"FAIL {command} {exc}", file=sys.stderr)
79
+ return 1
80
+
81
+
82
+ def _cmd_install_global(args: argparse.Namespace) -> int:
83
+ try:
84
+ if args.all and args.harnesses:
85
+ raise ValueError("cannot combine --all with --harnesses")
86
+ home_dir = (
87
+ resolve_path_strict_cycles(Path(args.home).expanduser())
88
+ if args.home
89
+ else Path.home()
90
+ )
91
+ if args.kit_root:
92
+ kit_root = resolve_path_strict_cycles(Path(args.kit_root).expanduser())
93
+ else:
94
+ try:
95
+ kit_root = find_kit_root()
96
+ except FileNotFoundError:
97
+ if not args.uninstall:
98
+ raise
99
+ installed_plugin = resolve_harness_paths(
100
+ HARNESS_SPECS["antigravity"], home=home_dir
101
+ ).global_dir
102
+ if installed_plugin.is_dir():
103
+ kit_root = resolve_path_strict_cycles(installed_plugin)
104
+ else:
105
+ kit_root = home_dir / ".stewardkit-uninstall-noop"
106
+ harnesses = _flatten_csv(args.harnesses)
107
+ actions = install_global(
108
+ kit_root=kit_root,
109
+ home_dir=home_dir,
110
+ harnesses=harnesses,
111
+ mode=args.mode,
112
+ with_global_rules=args.with_global_rules,
113
+ uninstall=args.uninstall,
114
+ dry_run=args.dry_run,
115
+ install_all=args.all,
116
+ )
117
+ except (ConfigError, MarkerError, FileNotFoundError, ValueError, OSError, RuntimeError) as exc:
118
+ return _emit_error("install-global", exc, as_json=args.json)
119
+
120
+ if args.json:
121
+ _emit_json(
122
+ {
123
+ "ok": True,
124
+ "mode": args.mode,
125
+ "dry_run": bool(args.dry_run),
126
+ "uninstall": bool(args.uninstall),
127
+ "actions": [
128
+ {
129
+ "harness": a.harness,
130
+ "action": a.action,
131
+ "path": str(a.target),
132
+ "detail": a.detail,
133
+ }
134
+ for a in actions
135
+ ],
136
+ }
137
+ )
138
+ return 0
139
+
140
+ prefix = "[dry-run] " if args.dry_run else ""
141
+ rows = [
142
+ ("PASS", f"{a.harness}:{a.action}", f"{prefix}{a.target} ({a.detail})")
143
+ for a in actions
144
+ ]
145
+ _print_table(rows)
146
+ return 0
147
+
148
+
149
+ def _cmd_init(args: argparse.Namespace) -> int:
150
+ try:
151
+ repo = resolve_path_strict_cycles(Path(args.repo).expanduser())
152
+ report = init_repo(
153
+ repo_root=repo,
154
+ harnesses=_flatten_csv(args.harnesses),
155
+ antigravity_file=args.antigravity_file,
156
+ junie_legacy_guidelines=args.junie_legacy_guidelines,
157
+ copilot_apply_to=args.copilot_apply_to,
158
+ recommended_specialist_catalog=args.recommended_specialist_catalog,
159
+ profile=args.profile,
160
+ orchestration_mode=args.orchestration_mode,
161
+ delivery_mode=args.delivery_mode,
162
+ require_tests_doc_parity=args.require_tests_doc_parity,
163
+ real_cases_only=args.real_cases_only,
164
+ default_branch=args.default_branch,
165
+ merge_strategy=args.merge_strategy,
166
+ min_free_disk_gb=args.min_free_disk_gb,
167
+ disk_check_path=args.disk_check_path,
168
+ timezone=args.timezone,
169
+ clock_format=args.clock_format,
170
+ nits_dir=args.nits_dir,
171
+ test_roots=_flatten_csv(args.test_roots),
172
+ scaffold_docs=args.scaffold_docs,
173
+ dry_run=args.dry_run,
174
+ force=args.force,
175
+ full=args.full,
176
+ update_gitignore=args.update_gitignore,
177
+ )
178
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
179
+ return _emit_error("init", exc, as_json=args.json)
180
+
181
+ if args.json:
182
+ _emit_json(
183
+ {
184
+ "ok": report.ok,
185
+ "repo": str(repo),
186
+ "profile": args.profile,
187
+ "config": str(repo / CONFIG_FILENAME),
188
+ "dry_run": bool(args.dry_run),
189
+ "scaffolded": list(report.scaffolded),
190
+ "gitignore_status": report.gitignore_status,
191
+ "actions": [
192
+ {
193
+ "path": res.rel_path,
194
+ "action": res.status,
195
+ "byte_size": res.bytes_size,
196
+ }
197
+ for res in report.results
198
+ ],
199
+ "errors": list(report.errors),
200
+ }
201
+ )
202
+ return 0 if report.ok else 1
203
+
204
+ prefix = "[dry-run] " if args.dry_run else ""
205
+ rows: list[tuple[str, str, str]] = [
206
+ ("PASS", CONFIG_FILENAME, f"{prefix}configured"),
207
+ ]
208
+ for doc in report.scaffolded:
209
+ rows.append(("PASS", doc, f"{prefix}scaffolded"))
210
+ if report.gitignore_status is not None:
211
+ rows.append(
212
+ (
213
+ "PASS",
214
+ ".gitignore",
215
+ f"{prefix}{report.gitignore_status} ({LOCAL_CONFIG_FILENAME})",
216
+ )
217
+ )
218
+ for res in report.results:
219
+ status = "FAIL" if res.status == "error" else "PASS"
220
+ rows.append((status, res.rel_path, f"{prefix}{res.status} ({res.bytes_size} bytes)"))
221
+ for err in report.errors:
222
+ rows.append(("FAIL", "error", err))
223
+ _print_table(rows)
224
+ return 0 if report.ok else 1
225
+
226
+
227
+ def _cmd_sync(args: argparse.Namespace) -> int:
228
+ try:
229
+ repo = find_repo_root(Path(args.repo))
230
+ report = sync_repo(repo_root=repo, check=args.check, dry_run=args.dry_run)
231
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
232
+ return _emit_error("sync", exc, as_json=args.json)
233
+
234
+ if args.json:
235
+ _emit_json(
236
+ {
237
+ "ok": report.ok,
238
+ "repo": str(repo),
239
+ "check": bool(args.check),
240
+ "dry_run": bool(args.dry_run),
241
+ "actions": [
242
+ {
243
+ "path": res.rel_path,
244
+ "action": res.status,
245
+ "byte_size": res.bytes_size,
246
+ }
247
+ for res in report.results
248
+ ],
249
+ "errors": list(report.errors),
250
+ }
251
+ )
252
+ return 0 if report.ok else 1
253
+
254
+ prefix = "[dry-run] " if args.dry_run else ""
255
+ rows: list[tuple[str, str, str]] = []
256
+ for res in report.results:
257
+ status = "FAIL" if res.status in {"drift", "error"} else "PASS"
258
+ rows.append((status, res.rel_path, f"{prefix}{res.status} ({res.bytes_size} bytes)"))
259
+ for err in report.errors:
260
+ rows.append(("FAIL", "error", err))
261
+ _print_table(rows)
262
+ return 0 if report.ok else 1
263
+
264
+
265
+ def _cmd_uninstall_repo(args: argparse.Namespace) -> int:
266
+ try:
267
+ repo = find_repo_root(Path(args.repo))
268
+ actions = uninstall_repo(
269
+ repo_root=repo,
270
+ remove_config=args.remove_config,
271
+ dry_run=args.dry_run,
272
+ )
273
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
274
+ return _emit_error("uninstall-repo", exc, as_json=args.json)
275
+
276
+ if args.json:
277
+ _emit_json(
278
+ {
279
+ "ok": True,
280
+ "repo": str(repo),
281
+ "dry_run": bool(args.dry_run),
282
+ "remove_config": bool(args.remove_config),
283
+ "actions": [
284
+ {
285
+ "path": a.rel_path,
286
+ "action": a.action,
287
+ "byte_size": a.byte_size,
288
+ }
289
+ for a in actions
290
+ ],
291
+ }
292
+ )
293
+ return 0
294
+
295
+ prefix = "[dry-run] " if args.dry_run else ""
296
+ rows = [
297
+ ("PASS", a.rel_path, f"{prefix}{a.action} ({a.byte_size} bytes)")
298
+ for a in actions
299
+ ]
300
+ _print_table(rows)
301
+ return 0
302
+
303
+
304
+ def _cmd_check_tests(args: argparse.Namespace) -> int:
305
+ try:
306
+ if args.doc_readers_only and args.no_doc_reader_check:
307
+ raise ValueError("cannot combine --doc-readers-only with --no-doc-reader-check")
308
+ repo = find_repo_root(Path(args.repo))
309
+ docs_tests = args.tests_doc
310
+ test_roots = _flatten_csv(args.test_roots)
311
+ ignore_globs = _flatten_csv(args.ignore_globs)
312
+ check_doc_readers: bool | None = False if args.no_doc_reader_check else None
313
+
314
+ cfg_file = repo / CONFIG_FILENAME
315
+ if cfg_file.exists() or cfg_file.is_symlink():
316
+ cfg = load_config(repo, include_local=False, include_user=False)
317
+ if docs_tests is None:
318
+ docs_tests = cfg.docs.tests
319
+ if test_roots is None:
320
+ test_roots = cfg.tests.roots
321
+ if ignore_globs is None:
322
+ ignore_globs = cfg.tests.ignore_globs
323
+ if check_doc_readers is None:
324
+ check_doc_readers = cfg.tests.check_doc_readers
325
+
326
+ test_roots = test_roots or ["tests"]
327
+ ignore_globs = ignore_globs or []
328
+
329
+ if args.doc_readers_only:
330
+ if not repo.exists() or not repo.is_dir():
331
+ raise ConfigError(f"repository directory does not exist: {repo}")
332
+ parse_errors: list[str] = []
333
+ doc_readers = find_doc_reader_tests(
334
+ repo,
335
+ test_roots=test_roots,
336
+ ignore_globs=ignore_globs,
337
+ parse_errors=parse_errors,
338
+ )
339
+ ok = not doc_readers and not parse_errors
340
+ if args.json:
341
+ _emit_json(
342
+ {
343
+ "ok": ok,
344
+ "mode": "doc-readers-only",
345
+ "repo": str(repo),
346
+ "doc_readers": [
347
+ {
348
+ "file": dr.file,
349
+ "test_name": dr.test_name,
350
+ "line": dr.line,
351
+ "doc_ref": dr.doc_ref,
352
+ }
353
+ for dr in doc_readers
354
+ ],
355
+ "parse_errors": parse_errors,
356
+ }
357
+ )
358
+ return 0 if ok else 1
359
+
360
+ summary = f"doc_readers={len(doc_readers)} parse_errors={len(parse_errors)}"
361
+ rows: list[tuple[str, str, str]] = [
362
+ ("PASS" if ok else "FAIL", "doc_readers", summary)
363
+ ]
364
+ for err in parse_errors:
365
+ rows.append(("FAIL", "parse_error", err))
366
+ for dr in doc_readers:
367
+ rows.append(
368
+ (
369
+ "FAIL",
370
+ "doc_reader",
371
+ f"{dr.file}::{dr.test_name} (line {dr.line}) reads {dr.doc_ref}",
372
+ )
373
+ )
374
+ _print_table(rows)
375
+ return 0 if ok else 1
376
+
377
+ docs_tests = docs_tests or "docs/tests.md"
378
+ check_doc_readers = True if check_doc_readers is None else check_doc_readers
379
+
380
+ report = check_tests_parity(
381
+ repo_root=repo,
382
+ docs_tests_path=docs_tests,
383
+ test_roots=test_roots,
384
+ check_doc_readers=check_doc_readers,
385
+ ignore_globs=ignore_globs,
386
+ )
387
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
388
+ return _emit_error("check-tests", exc, as_json=args.json)
389
+
390
+ if args.json:
391
+ _emit_json(
392
+ {
393
+ "ok": report.ok,
394
+ "repo": str(repo),
395
+ "tests_doc": docs_tests,
396
+ "discovered": report.discovered_count,
397
+ "documented": report.documented_count,
398
+ "missing": list(report.missing),
399
+ "extra": list(report.extra),
400
+ "wrong_section": [
401
+ {
402
+ "name": ws.name,
403
+ "actual_file": ws.actual_file,
404
+ "documented_file": ws.documented_file,
405
+ "doc_line": ws.doc_line,
406
+ }
407
+ for ws in report.wrong_section
408
+ ],
409
+ "duplicates": list(report.duplicates),
410
+ "doc_readers": [
411
+ {
412
+ "file": dr.file,
413
+ "test_name": dr.test_name,
414
+ "line": dr.line,
415
+ "doc_ref": dr.doc_ref,
416
+ }
417
+ for dr in report.doc_readers
418
+ ],
419
+ "parse_errors": list(report.parse_errors),
420
+ "unsupported_test_files": list(report.unsupported_test_files),
421
+ }
422
+ )
423
+ return 0 if report.ok else 1
424
+
425
+ summary = (
426
+ f"discovered={report.discovered_count} documented={report.documented_count} "
427
+ f"missing={len(report.missing)} extra={len(report.extra)} "
428
+ f"wrong_section={len(report.wrong_section)} duplicates={len(report.duplicates)} "
429
+ f"doc_readers={len(report.doc_readers)}"
430
+ )
431
+ rows: list[tuple[str, str, str]] = [
432
+ ("PASS" if report.ok else "FAIL", "tests_parity", summary)
433
+ ]
434
+ for err in report.parse_errors:
435
+ rows.append(("FAIL", "parse_error", err))
436
+ for item in report.missing:
437
+ rows.append(("FAIL", "missing", item))
438
+ for item in report.extra:
439
+ rows.append(("FAIL", "extra", item))
440
+ for ws in report.wrong_section:
441
+ rows.append(
442
+ (
443
+ "FAIL",
444
+ "wrong_section",
445
+ f"{ws.name}: code={ws.actual_file}, doc={ws.documented_file} (line {ws.doc_line})",
446
+ )
447
+ )
448
+ for dup in report.duplicates:
449
+ rows.append(("FAIL", "duplicate", dup))
450
+ for dr in report.doc_readers:
451
+ rows.append(
452
+ (
453
+ "FAIL",
454
+ "doc_reader",
455
+ f"{dr.file}::{dr.test_name} (line {dr.line}) reads {dr.doc_ref}",
456
+ )
457
+ )
458
+ if report.discovered_count == 0 and report.unsupported_test_files:
459
+ sample = ", ".join(report.unsupported_test_files[:3])
460
+ rows.append(
461
+ (
462
+ "WARN",
463
+ "unsupported_lang",
464
+ f"0 Python/JS tests discovered, but {len(report.unsupported_test_files)} "
465
+ f"non-Python/JS test file(s) found ({sample}); check-tests currently parses "
466
+ "Python and JS/TS/TSX (disable parity checks via bar.require_tests_doc_parity = false)",
467
+ )
468
+ )
469
+ _print_table(rows)
470
+ return 0 if report.ok else 1
471
+
472
+
473
+ def _flatten_config_items(data: dict[str, Any], prefix: str = "") -> list[tuple[str, Any]]:
474
+ items: list[tuple[str, Any]] = []
475
+ for key, val in data.items():
476
+ dotted = f"{prefix}.{key}" if prefix else key
477
+ if isinstance(val, dict):
478
+ items.extend(_flatten_config_items(val, dotted))
479
+ else:
480
+ items.append((dotted, val))
481
+ return items
482
+
483
+
484
+ def _format_config_value(value: Any) -> str:
485
+ if isinstance(value, bool):
486
+ return "true" if value else "false"
487
+ if isinstance(value, list):
488
+ return json.dumps(value, ensure_ascii=False)
489
+ if value == "":
490
+ return '""'
491
+ return str(value)
492
+
493
+
494
+ def _cmd_config(args: argparse.Namespace) -> int:
495
+ try:
496
+ home_dir = (
497
+ resolve_path_strict_cycles(Path(args.home).expanduser()) if args.home else None
498
+ )
499
+ repo = find_repo_root(Path(args.repo))
500
+ cfg, sources = resolve_config_with_sources(repo, home_dir=home_dir)
501
+ resolved_tz = resolve_timezone(cfg.docs.timezone)
502
+ is_git_repo, inferred_default_branch = detect_git_context(repo)
503
+ ext_state = (
504
+ str(external_state_dir(repo, home=home_dir))
505
+ if cfg.mode == "global" and cfg.projectless.state_mode == "external"
506
+ else None
507
+ )
508
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
509
+ return _emit_error("config", exc, as_json=args.json)
510
+
511
+ cfg_dict = config_to_dict(cfg)
512
+ if args.json:
513
+ payload = {
514
+ "mode": cfg.mode,
515
+ "git_repo": is_git_repo,
516
+ "inferred_default_branch": inferred_default_branch,
517
+ "user_config": cfg.user_config_path or None,
518
+ "projectless": {
519
+ "state_mode": cfg.projectless.state_mode,
520
+ "exclude_paths": list(cfg.projectless.exclude_paths),
521
+ "external_state_dir": ext_state,
522
+ },
523
+ "profile": cfg.profile,
524
+ "resolved_timezone": resolved_tz,
525
+ "user_overrides": list(cfg.user_overrides),
526
+ "local_overrides": list(cfg.local_overrides),
527
+ "warnings": list(cfg.config_warnings),
528
+ "config": cfg_dict,
529
+ "sources": sources,
530
+ }
531
+ _emit_json(payload)
532
+ return 0
533
+
534
+ rows: list[tuple[str, str, str]] = [
535
+ ("KEY", "VALUE", "SOURCE"),
536
+ ("mode", cfg.mode, "detected"),
537
+ ("git_repo", _format_config_value(is_git_repo), "detected"),
538
+ ("inferred_default_branch", inferred_default_branch, "detected"),
539
+ ("user_config", cfg.user_config_path or "(none)", "user" if cfg.user_config_path else "none"),
540
+ (
541
+ "projectless.state_mode",
542
+ cfg.projectless.state_mode,
543
+ sources.get("projectless.state_mode", "default"),
544
+ ),
545
+ (
546
+ "projectless.exclude_paths",
547
+ _format_config_value(cfg.projectless.exclude_paths),
548
+ sources.get("projectless.exclude_paths", "default"),
549
+ ),
550
+ ]
551
+ if ext_state is not None:
552
+ rows.append(("projectless.external_state_dir", ext_state, "computed"))
553
+ for dotted, val in _flatten_config_items(cfg_dict):
554
+ rows.append((dotted, _format_config_value(val), sources.get(dotted, "default")))
555
+ rows.append(("resolved_timezone", resolved_tz, "computed"))
556
+ rows.append(
557
+ (
558
+ "user_overrides",
559
+ ", ".join(cfg.user_overrides) if cfg.user_overrides else "(none)",
560
+ "user" if cfg.user_overrides else "none",
561
+ )
562
+ )
563
+ rows.append(
564
+ (
565
+ "local_overrides",
566
+ ", ".join(cfg.local_overrides) if cfg.local_overrides else "(none)",
567
+ "local" if cfg.local_overrides else "none",
568
+ )
569
+ )
570
+ if cfg.config_warnings:
571
+ rows.append(("warnings", "; ".join(cfg.config_warnings), "warning"))
572
+ _print_table(rows)
573
+ return 0
574
+
575
+
576
+ def _cmd_user_config_init(args: argparse.Namespace) -> int:
577
+ try:
578
+ home_dir = (
579
+ resolve_path_strict_cycles(Path(args.home).expanduser()) if args.home else None
580
+ )
581
+ target = user_config_path(home=home_dir)
582
+ existed = target.exists() and not target.is_symlink()
583
+ written = write_user_config(
584
+ target,
585
+ profile=args.profile,
586
+ orchestration_mode=args.orchestration_mode,
587
+ delivery_mode=args.delivery_mode,
588
+ timezone=args.timezone,
589
+ clock_format=args.clock_format,
590
+ min_free_disk_gb=args.min_free_disk_gb,
591
+ state_mode=args.state_mode,
592
+ exclude_paths=args.exclude_path,
593
+ force=args.force,
594
+ )
595
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
596
+ return _emit_error("user-config", exc, as_json=args.json)
597
+
598
+ action = "overwritten" if existed else "created"
599
+ if args.json:
600
+ _emit_json({"ok": True, "path": str(written), "action": action})
601
+ return 0
602
+ _print_table([("PASS", "user-config", f"{action} {written}")])
603
+ return 0
604
+
605
+
606
+ def _cmd_user_config_path(args: argparse.Namespace) -> int:
607
+ try:
608
+ home_dir = (
609
+ resolve_path_strict_cycles(Path(args.home).expanduser()) if args.home else None
610
+ )
611
+ target = user_config_path(home=home_dir)
612
+ exists = target.exists() or target.is_symlink()
613
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
614
+ return _emit_error("user-config", exc, as_json=args.json)
615
+
616
+ if args.json:
617
+ _emit_json({"ok": True, "path": str(target), "exists": exists})
618
+ return 0
619
+ print(target)
620
+ return 0
621
+
622
+
623
+ def _cmd_user_config_show(args: argparse.Namespace) -> int:
624
+ try:
625
+ home_dir = (
626
+ resolve_path_strict_cycles(Path(args.home).expanduser()) if args.home else None
627
+ )
628
+ target = user_config_path(home=home_dir)
629
+ data = load_user_config_data(home_dir=home_dir)
630
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
631
+ return _emit_error("user-config", exc, as_json=args.json)
632
+
633
+ if data is None:
634
+ if args.json:
635
+ _emit_json(
636
+ {
637
+ "ok": True,
638
+ "path": str(target),
639
+ "exists": False,
640
+ "config": None,
641
+ "warnings": [],
642
+ }
643
+ )
644
+ return 0
645
+ _print_table(
646
+ [
647
+ (
648
+ "PASS",
649
+ "user-config",
650
+ f"no user config at {target} (run `stewardkit user-config init`)",
651
+ )
652
+ ]
653
+ )
654
+ return 0
655
+
656
+ cfg_dict = data.to_dict()
657
+ if args.json:
658
+ _emit_json(
659
+ {
660
+ "ok": True,
661
+ "path": str(data.path),
662
+ "exists": True,
663
+ "config": cfg_dict,
664
+ "warnings": list(data.warnings),
665
+ }
666
+ )
667
+ return 0
668
+
669
+ rows: list[tuple[str, str, str]] = [
670
+ ("KEY", "VALUE", "SOURCE"),
671
+ ("path", str(data.path), "user"),
672
+ ]
673
+ for dotted, val in _flatten_config_items(cfg_dict):
674
+ rows.append((dotted, _format_config_value(val), "user"))
675
+ if data.warnings:
676
+ rows.append(("warnings", "; ".join(data.warnings), "warning"))
677
+ _print_table(rows)
678
+ return 0
679
+
680
+
681
+ def _cmd_doctor(args: argparse.Namespace) -> int:
682
+ try:
683
+ repo = find_repo_root(Path(args.repo))
684
+ home_dir = (
685
+ resolve_path_strict_cycles(Path(args.home).expanduser()) if args.home else None
686
+ )
687
+ kit_root = (
688
+ resolve_path_strict_cycles(Path(args.kit_root).expanduser())
689
+ if args.kit_root
690
+ else None
691
+ )
692
+ results = run_doctor(
693
+ repo_root=repo,
694
+ home_dir=home_dir,
695
+ kit_root=kit_root,
696
+ min_free_gb=args.min_free_disk_gb,
697
+ )
698
+ except (ConfigError, MarkerError, ValueError, OSError, RuntimeError) as exc:
699
+ return _emit_error("doctor", exc, as_json=args.json)
700
+
701
+ ok = not has_failures(results)
702
+ if args.json:
703
+ _emit_json(
704
+ {
705
+ "ok": ok,
706
+ "repo": str(repo),
707
+ "checks": [
708
+ {"name": r.name, "status": r.status, "detail": r.detail}
709
+ for r in results
710
+ ],
711
+ }
712
+ )
713
+ return 0 if ok else 1
714
+
715
+ _print_table([(r.status, r.name, r.detail) for r in results])
716
+ return 0 if ok else 1
717
+
718
+
719
+ def build_parser() -> argparse.ArgumentParser:
720
+ parser = argparse.ArgumentParser(
721
+ prog="stewardkit",
722
+ description="Multi-harness workflow orchestration, sweep, and test-parity toolkit.",
723
+ )
724
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
725
+ sub = parser.add_subparsers(dest="command", required=True)
726
+
727
+ # install-global
728
+ p_inst = sub.add_parser(
729
+ "install-global",
730
+ help="Install or uninstall stewardkit globally across coding harnesses.",
731
+ )
732
+ p_inst.add_argument("--kit-root", help="Path to stewardkit repo root.")
733
+ p_inst.add_argument("--home", help="Override user home directory (useful for testing).")
734
+ p_inst.add_argument(
735
+ "--harnesses",
736
+ nargs="+",
737
+ help="Target harnesses (antigravity, claude, codex, copilot, junie, opencode, pi, qwen, deepseek, goose).",
738
+ )
739
+ p_inst.add_argument(
740
+ "--all",
741
+ action="store_true",
742
+ help="Install across all 10 supported harnesses instead of only auto-detected ones.",
743
+ )
744
+ p_inst.add_argument(
745
+ "--mode",
746
+ choices=("auto", "symlink", "copy"),
747
+ default="auto",
748
+ help=(
749
+ "Install mode (default: auto — copy on Windows or bundled wheel _kit_data; "
750
+ "symlink with copy fallback on macOS/Linux source checkouts)."
751
+ ),
752
+ )
753
+ p_inst.add_argument(
754
+ "--with-global-rules",
755
+ action="store_true",
756
+ help="Also upsert managed workflow rules into global harness rules files.",
757
+ )
758
+ p_inst.add_argument(
759
+ "--uninstall",
760
+ action="store_true",
761
+ help=(
762
+ "Remove stewardkit's global plugin and workflow skills and strip managed workflow "
763
+ "blocks from global harness rules files (deleting empty ones while preserving user "
764
+ "rules and skipping symlinked rules files) without touching other skills."
765
+ ),
766
+ )
767
+ p_inst.add_argument("--dry-run", action="store_true", help="Print actions without writing.")
768
+ p_inst.add_argument(
769
+ "--json",
770
+ action="store_true",
771
+ help="Output install-global actions as JSON.",
772
+ )
773
+ p_inst.set_defaults(func=_cmd_install_global)
774
+
775
+ # init
776
+ p_init = sub.add_parser(
777
+ "init",
778
+ help="Initialize .stewardkit.toml and managed harness rule files in a repository.",
779
+ )
780
+ p_init.add_argument("repo", nargs="?", default=".", help="Target repository directory.")
781
+ p_init.add_argument(
782
+ "--harnesses",
783
+ nargs="+",
784
+ help="Enabled harnesses (antigravity, claude, codex, copilot, junie, opencode, pi, qwen, deepseek, goose).",
785
+ )
786
+ p_init.add_argument(
787
+ "--antigravity-file",
788
+ choices=("AGENTS.md", "GEMINI.md"),
789
+ default="AGENTS.md",
790
+ help="Antigravity repo rule file (default: AGENTS.md).",
791
+ )
792
+ p_init.add_argument(
793
+ "--junie-legacy-guidelines",
794
+ action="store_true",
795
+ help="Also manage legacy .junie/guidelines.md.",
796
+ )
797
+ p_init.add_argument(
798
+ "--copilot-apply-to",
799
+ default="**",
800
+ help="applyTo glob for .github/instructions/stewardkit.instructions.md (default: **).",
801
+ )
802
+ p_init.add_argument(
803
+ "--profile",
804
+ choices=VALID_PROFILES,
805
+ default="standard",
806
+ help="Workflow profile preset (light, standard, strict; default: standard).",
807
+ )
808
+ p_init.add_argument(
809
+ "--orchestration-mode",
810
+ choices=VALID_ORCHESTRATION_MODES,
811
+ default=None,
812
+ help="Orchestration mode override (auto, subagents, single-agent; default: from profile).",
813
+ )
814
+ p_init.add_argument(
815
+ "--delivery-mode",
816
+ choices=VALID_DELIVERY_MODES,
817
+ default=None,
818
+ help="Git delivery mode override (pull-request, direct-merge; default: from profile).",
819
+ )
820
+ p_init.add_argument(
821
+ "--require-tests-doc-parity",
822
+ action=argparse.BooleanOptionalAction,
823
+ default=None,
824
+ help="Enable or disable 1:1 tests doc parity enforcement (default: from profile).",
825
+ )
826
+ p_init.add_argument(
827
+ "--recommended-specialist-catalog",
828
+ default=DEFAULT_SPECIALIST_CATALOG,
829
+ help="Optional recommended specialist skills catalog URL (empty string disables).",
830
+ )
831
+ p_init.add_argument(
832
+ "--real-cases-only",
833
+ action="store_true",
834
+ default=None,
835
+ help="Enable the Real Cases Only gate in .stewardkit.toml (bar.real_cases_only).",
836
+ )
837
+ p_init.add_argument(
838
+ "--default-branch",
839
+ default="main",
840
+ help="Default repository branch name (default: main).",
841
+ )
842
+ p_init.add_argument(
843
+ "--merge-strategy",
844
+ choices=VALID_MERGE_STRATEGIES,
845
+ default="no-ff",
846
+ help="Preferred merge strategy after a clean sweep (default: no-ff).",
847
+ )
848
+ p_init.add_argument(
849
+ "--min-free-disk-gb",
850
+ type=float,
851
+ default=5.0,
852
+ help="Minimum free disk space in GB (0 disables check; default: 5.0).",
853
+ )
854
+ p_init.add_argument(
855
+ "--disk-check-path",
856
+ default="",
857
+ help="Optional explicit filesystem path to check for free disk space.",
858
+ )
859
+ p_init.add_argument(
860
+ "--timezone",
861
+ default="local",
862
+ help="Timezone for user-facing docs/reports ('local' or IANA name; default: local).",
863
+ )
864
+ p_init.add_argument(
865
+ "--clock-format",
866
+ choices=VALID_CLOCK_FORMATS,
867
+ default="12h",
868
+ help="Clock format for user-facing timestamps (default: 12h).",
869
+ )
870
+ p_init.add_argument(
871
+ "--nits-dir",
872
+ default=None,
873
+ help="Relative directory for categorized out-of-bar nits (empty string disables; default: docs/nits).",
874
+ )
875
+ p_init.add_argument(
876
+ "--test-roots",
877
+ nargs="+",
878
+ help="Relative directories containing tests (default: tests).",
879
+ )
880
+ p_init.add_argument(
881
+ "--scaffold-docs",
882
+ action="store_true",
883
+ help=(
884
+ "Create missing starter workflow docs (intent and how-it-works on all profiles; "
885
+ "findings and categorized nits README when enabled on standard/strict; and tests "
886
+ "when parity is enabled)."
887
+ ),
888
+ )
889
+ p_init.add_argument(
890
+ "--force",
891
+ action="store_true",
892
+ help="Overwrite an existing .stewardkit.toml instead of failing closed.",
893
+ )
894
+ p_init.add_argument(
895
+ "--full",
896
+ action="store_true",
897
+ help="Emit all profile-governed keys explicitly in .stewardkit.toml.",
898
+ )
899
+ p_init.add_argument(
900
+ "--update-gitignore",
901
+ action="store_true",
902
+ help="Idempotently append .stewardkit.local.toml to .gitignore.",
903
+ )
904
+ p_init.add_argument("--dry-run", action="store_true", help="Preview without writing.")
905
+ p_init.add_argument(
906
+ "--json",
907
+ action="store_true",
908
+ help="Output init results as JSON.",
909
+ )
910
+ p_init.set_defaults(func=_cmd_init)
911
+
912
+ # config
913
+ p_cfg = sub.add_parser(
914
+ "config",
915
+ help="Show effective resolved configuration, mode, timezone, overrides, and provenance.",
916
+ )
917
+ p_cfg.add_argument("repo", nargs="?", default=".", help="Target repository directory.")
918
+ p_cfg.add_argument("--home", help="Override user home directory.")
919
+ p_cfg.add_argument(
920
+ "--json",
921
+ action="store_true",
922
+ help="Output resolved configuration and provenance as JSON.",
923
+ )
924
+ p_cfg.set_defaults(func=_cmd_config)
925
+
926
+ # user-config
927
+ p_uc = sub.add_parser(
928
+ "user-config",
929
+ help="Initialize, locate, or inspect user-level stewardkit defaults.",
930
+ )
931
+ uc_sub = p_uc.add_subparsers(dest="user_config_command", required=True)
932
+
933
+ p_uc_init = uc_sub.add_parser(
934
+ "init",
935
+ help="Create user-level config.toml with personal and Global Mode defaults.",
936
+ )
937
+ p_uc_init.add_argument(
938
+ "--profile",
939
+ choices=VALID_PROFILES,
940
+ default="standard",
941
+ help="Default Global Mode profile (light, standard, strict; default: standard).",
942
+ )
943
+ p_uc_init.add_argument(
944
+ "--orchestration-mode",
945
+ choices=VALID_ORCHESTRATION_MODES,
946
+ default=None,
947
+ help="Preferred orchestration mode (auto, subagents, single-agent).",
948
+ )
949
+ p_uc_init.add_argument(
950
+ "--delivery-mode",
951
+ choices=VALID_DELIVERY_MODES,
952
+ default=None,
953
+ help="Default Global Mode git delivery mode (pull-request, direct-merge).",
954
+ )
955
+ p_uc_init.add_argument(
956
+ "--timezone",
957
+ default="local",
958
+ help="Preferred timezone ('local' or IANA name; default: local).",
959
+ )
960
+ p_uc_init.add_argument(
961
+ "--clock-format",
962
+ choices=VALID_CLOCK_FORMATS,
963
+ default="12h",
964
+ help="Preferred clock format (default: 12h).",
965
+ )
966
+ p_uc_init.add_argument(
967
+ "--min-free-disk-gb",
968
+ type=float,
969
+ default=5.0,
970
+ help="Minimum free disk space in GB (0 disables check; default: 5.0).",
971
+ )
972
+ p_uc_init.add_argument(
973
+ "--state-mode",
974
+ choices=VALID_STATE_MODES,
975
+ default="chat",
976
+ help="Global Mode state storage mode (chat or external; default: chat).",
977
+ )
978
+ p_uc_init.add_argument(
979
+ "--exclude-path",
980
+ action="append",
981
+ default=None,
982
+ help="Directory path to exclude from Global Mode (repeatable).",
983
+ )
984
+ p_uc_init.add_argument("--home", help="Override user home directory.")
985
+ p_uc_init.add_argument(
986
+ "--force",
987
+ action="store_true",
988
+ help="Overwrite an existing user config file instead of failing closed.",
989
+ )
990
+ p_uc_init.add_argument("--json", action="store_true", help="Output result as JSON.")
991
+ p_uc_init.set_defaults(func=_cmd_user_config_init)
992
+
993
+ p_uc_path = uc_sub.add_parser(
994
+ "path",
995
+ help="Print the resolved path to the user-level config.toml file.",
996
+ )
997
+ p_uc_path.add_argument("--home", help="Override user home directory.")
998
+ p_uc_path.add_argument("--json", action="store_true", help="Output path as JSON.")
999
+ p_uc_path.set_defaults(func=_cmd_user_config_path)
1000
+
1001
+ p_uc_show = uc_sub.add_parser(
1002
+ "show",
1003
+ help="Display the validated user-level config.toml settings.",
1004
+ )
1005
+ p_uc_show.add_argument("--home", help="Override user home directory.")
1006
+ p_uc_show.add_argument("--json", action="store_true", help="Output config as JSON.")
1007
+ p_uc_show.set_defaults(func=_cmd_user_config_show)
1008
+
1009
+ # sync
1010
+ p_sync = sub.add_parser(
1011
+ "sync",
1012
+ help="Idempotently update managed workflow blocks across configured harness files.",
1013
+ )
1014
+ p_sync.add_argument("repo", nargs="?", default=".", help="Target repository directory.")
1015
+ p_sync.add_argument(
1016
+ "--check",
1017
+ action="store_true",
1018
+ help="Report drift without writing and exit 1 if out of sync.",
1019
+ )
1020
+ p_sync.add_argument("--dry-run", action="store_true", help="Preview without writing.")
1021
+ p_sync.add_argument("--json", action="store_true", help="Output sync results as JSON.")
1022
+ p_sync.set_defaults(func=_cmd_sync)
1023
+
1024
+ # uninstall-repo
1025
+ p_uninst = sub.add_parser(
1026
+ "uninstall-repo",
1027
+ help="Remove stewardkit managed blocks from repo harness files (and optionally .stewardkit.toml).",
1028
+ )
1029
+ p_uninst.add_argument("repo", nargs="?", default=".", help="Target repository directory.")
1030
+ p_uninst.add_argument(
1031
+ "--remove-config",
1032
+ action="store_true",
1033
+ help="Also delete .stewardkit.toml from the repository root.",
1034
+ )
1035
+ p_uninst.add_argument("--dry-run", action="store_true", help="Preview without writing.")
1036
+ p_uninst.add_argument(
1037
+ "--json",
1038
+ action="store_true",
1039
+ help="Output uninstall-repo actions as JSON.",
1040
+ )
1041
+ p_uninst.set_defaults(func=_cmd_uninstall_repo)
1042
+
1043
+ # check-tests
1044
+ p_tests = sub.add_parser(
1045
+ "check-tests",
1046
+ help="Verify 1:1 parity between test files and the configured tests doc (default: docs/tests.md).",
1047
+ )
1048
+ p_tests.add_argument("repo", nargs="?", default=".", help="Target repository directory.")
1049
+ p_tests.add_argument("--tests-doc", help="Path to tests doc (default: config or docs/tests.md).")
1050
+ p_tests.add_argument(
1051
+ "--test-roots",
1052
+ nargs="+",
1053
+ help="Relative test root directories (default: config or tests).",
1054
+ )
1055
+ p_tests.add_argument(
1056
+ "--ignore-globs",
1057
+ nargs="+",
1058
+ help="Glob patterns excluded from test discovery (overrides config).",
1059
+ )
1060
+ p_tests.add_argument(
1061
+ "--no-doc-reader-check",
1062
+ action="store_true",
1063
+ help="Skip scanning Python tests for repo Markdown doc file reads.",
1064
+ )
1065
+ p_tests.add_argument(
1066
+ "--doc-readers-only",
1067
+ action="store_true",
1068
+ help="Run only the Python doc-reader check without requiring .stewardkit.toml or docs/tests.md.",
1069
+ )
1070
+ p_tests.add_argument(
1071
+ "--json",
1072
+ action="store_true",
1073
+ help="Output test parity results as JSON.",
1074
+ )
1075
+ p_tests.set_defaults(func=_cmd_check_tests)
1076
+
1077
+ # doctor
1078
+ p_doc = sub.add_parser(
1079
+ "doctor",
1080
+ help="Run environment, kit manifest, global install, repo sync, git, and test checks.",
1081
+ )
1082
+ p_doc.add_argument("repo", nargs="?", default=".", help="Target repository directory.")
1083
+ p_doc.add_argument("--kit-root", help="Optional explicit stewardkit root directory.")
1084
+ p_doc.add_argument("--home", help="Override user home directory.")
1085
+ p_doc.add_argument(
1086
+ "--min-free-disk-gb",
1087
+ "--min-free-gb",
1088
+ dest="min_free_disk_gb",
1089
+ type=float,
1090
+ default=None,
1091
+ help="Override configured hygiene.min_free_disk_gb threshold (0 disables).",
1092
+ )
1093
+ p_doc.add_argument(
1094
+ "--json",
1095
+ action="store_true",
1096
+ help="Output doctor diagnostics as JSON.",
1097
+ )
1098
+ p_doc.set_defaults(func=_cmd_doctor)
1099
+
1100
+ return parser
1101
+
1102
+
1103
+ def main(argv: Sequence[str] | None = None) -> int:
1104
+ parser = build_parser()
1105
+ args = parser.parse_args(argv)
1106
+ return int(args.func(args))
1107
+
1108
+
1109
+ if __name__ == "__main__":
1110
+ raise SystemExit(main())