-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
7249 lines (6628 loc) · 293 KB
/
Copy pathcli.py
File metadata and controls
7249 lines (6628 loc) · 293 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# GitHub Repo Auditor — CLI entry point
#
# Orchestrates the full audit pipeline:
# 1. Fetch repo metadata from GitHub REST API (or GraphQL bulk fetch)
# 2. Shallow-clone each repo to a temp workspace
# 3. Run all 12 analyzers (completeness, interest, security, cicd, …)
# 4. Score and tier each repo via the configured scoring profile
# 5. Write JSON / Markdown / Excel / HTML reports to the output directory
#
# Three run modes:
# full — re-analyze every repo for the given username
# targeted — re-analyze specific repos (--repos) and merge into latest report
# incremental — re-analyze only repos with new pushes since last run
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import warnings
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path
from time import perf_counter
from src.analyzers import run_all_analyzers
from src.baseline_context import (
build_baseline_context_from_args,
build_watch_state,
compare_baseline_context,
extract_baseline_context,
format_mismatch_value,
normalize_scoring_profile,
)
from src.cache import ResponseCache
from src.cli_mode_validation import validate_cli_mode_args
from src.cli_output import create_progress, print_info, print_status, print_warning
from src.cloner import clone_workspace
from src.github_client import GitHubClient
from src.models import AnalyzerResult, AuditReport, RepoAudit, RepoMetadata
from src.portfolio_truth_types import TRUTH_LATEST_FILENAME, truth_latest_path
from src.recurring_review import FULL_REFRESH_DAYS
from src.report_enrichment import build_run_change_counts, build_run_change_summary
from src.reporter import (
write_json_report,
write_markdown_report,
write_pcc_export,
write_raw_metadata,
)
from src.scorer import score_repo
from src.terminology import ACTION_SYNC_CANONICAL_LABELS
# Emitted at most once per process when legacy flat invocation is used.
_LEGACY_WARNING_EVENTS: set[str] = set()
DEFAULT_ANALYSIS_WORKERS = 1
MAX_ANALYSIS_WORKERS = 8
DEFAULT_PORTFOLIO_WORKSPACE = Path.home() / "Projects"
CLI_MODE_GUIDE = """GitHub portfolio operating system with four product modes:
First Run setup, baseline creation, first workbook, first control-center read
Weekly Review normal workbook-first operator loop
Deep Dive repo-level drilldown and investigation
Action Sync campaign, writeback, GitHub Projects, and Notion mirroring
Recommended defaults:
- Start with --doctor before the first real run
- Prefer --excel-mode standard for the stable workbook path
- Use --control-center for read-only daily triage
- Treat campaigns, writeback, catalog overrides, scorecards overrides, and GitHub Projects as advanced workflows"""
CLI_MODE_EXAMPLES = """Subcommands: run, triage, report, serve
Run `audit run --help`, `audit triage --help`, or `audit report --help` for flags.
Subcommand form (preferred):
audit run <github-username> --html
audit run <github-username> --repos <repo-name>
audit triage <github-username> --control-center
audit triage <github-username> --approval-center
audit report <github-username> --portfolio-truth
audit report <github-username> --campaign security-review --writeback-target github
audit serve [--port 8080]
Legacy flat form (deprecated, still supported):
audit <github-username> --doctor
audit <github-username> --html
audit <github-username> --control-center
audit <github-username> --campaign security-review --writeback-target all --github-projects"""
def _date_str(dt: datetime) -> str:
return dt.strftime("%Y-%m-%d")
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def _gh_auth_token() -> str | None:
"""Fall back to `gh auth token` if GITHUB_TOKEN env var is unset."""
try:
result = subprocess.run(
["gh", "auth", "token"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
# Missing or slow gh CLI auth falls back to unauthenticated/public mode.
pass
return None
# ── Subcommand builders ───────────────────────────────────────────────
#
# Each builder defines the PRIMARY (help-visible) flags for its subcommand.
# The legacy flat parser at the top level accepts ALL flags so that existing
# invocations (`audit username --flag`) continue to work unchanged.
#
# Global flags shared across all subcommands: --token, --output-dir, --config, --verbose
def _add_global_flags(parser: argparse.ArgumentParser) -> None:
"""Add flags that appear on every subcommand."""
parser.add_argument(
"username",
nargs="?",
default=None,
help="GitHub username to audit",
)
parser.add_argument(
"--token",
default=os.environ.get("GITHUB_TOKEN") or _gh_auth_token(),
help="GitHub personal access token (default: $GITHUB_TOKEN or `gh auth token`)",
)
parser.add_argument(
"--output-dir",
default="output",
help="Directory for output files (default: output/)",
)
parser.add_argument(
"--config",
default=None,
help="Path to audit-config.yaml (default: ./audit-config.yaml if exists)",
)
parser.add_argument(
"--verbose",
action="store_true",
help="Print detailed output",
)
def _build_run_subparser(subparsers: argparse._SubParsersAction) -> None: # type: ignore[type-arg]
"""Subcommand: `audit run` — produce a fresh audit."""
p = subparsers.add_parser(
"run",
help="Run a fresh audit against a GitHub user's repos",
description="Fetch, clone, analyze, and score all repos for the given username.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
_add_global_flags(p)
p.add_argument(
"--repos",
nargs="+",
default=None,
metavar="REPO",
help="Audit only these specific repos (targeted mode)",
)
p.add_argument("--skip-forks", action="store_true", help="Exclude forked repos")
p.add_argument("--skip-archived", action="store_true", help="Exclude archived repos")
p.add_argument("--skip-clone", action="store_true", help="Skip clone step (metadata only)")
p.add_argument(
"--incremental", action="store_true", help="Re-audit only repos changed since last run"
)
p.add_argument("--graphql", action="store_true", help="Use GraphQL API for faster bulk fetch")
p.add_argument("--badges", action="store_true", help="Generate Shields.io badge files")
p.add_argument("--html", action="store_true", help="Generate interactive HTML dashboard")
p.add_argument("--pdf", action="store_true", help="Generate PDF audit report")
p.add_argument("--narrative", action="store_true", help="Generate AI portfolio narrative")
p.add_argument(
"--briefing", action="store_true", help="Generate structured weekly operator briefing"
)
p.add_argument(
"--fetch-mode",
choices=["sync", "async"],
default="sync",
help="Per-repo enrichment fetch strategy (default: sync)",
)
p.add_argument(
"--analysis-workers", type=int, default=None, help="Number of repo-analysis workers"
)
p.add_argument("--no-cache", action="store_true", help="Bypass API response cache")
p.add_argument(
"--scoring-profile",
type=str,
default=None,
metavar="NAME",
help="Custom scoring profile from config/scoring-profiles/NAME.json",
)
p.add_argument(
"--watch", action="store_true", help="Re-run audit on interval (see --watch-interval)"
)
p.add_argument("--resume", action="store_true", help="Resume a partial audit run")
p.add_argument(
"--vuln-check", action="store_true", help="Query OSV.dev for known vulnerabilities"
)
p.add_argument(
"--reindex", action="store_true", help="Rebuild portfolio semantic index after audit"
)
p.add_argument(
"--embedder",
choices=["voyage", "local"],
default="voyage",
help="Embedder backend for --reindex (default: voyage)",
)
def _build_triage_subparser(subparsers: argparse._SubParsersAction) -> None: # type: ignore[type-arg]
"""Subcommand: `audit triage` — review existing run + approval workflows."""
p = subparsers.add_parser(
"triage",
help="Review operator state and manage approval workflows",
description="Inspect control-center, approval queues, acknowledgments, and semantic search.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
_add_global_flags(p)
p.add_argument("--control-center", action="store_true", help="Show latest operator state")
p.add_argument(
"--approval-center", action="store_true", help="Show latest approval workflow state"
)
p.add_argument(
"--triage-view",
choices=["all", "urgent", "ready", "blocked", "deferred"],
default="all",
help="Filter control-center output (default: all)",
)
p.add_argument(
"--approval-view",
choices=["all", "ready", "approved", "needs-reapproval", "blocked", "applied"],
default="all",
help="Filter approval-center output (default: all)",
)
p.add_argument(
"--auto-apply-approved",
action="store_true",
help="Apply approved campaign packets for repos passing the automation trust bar",
)
p.add_argument("--dry-run", action="store_true", help="Preview without making changes")
p.add_argument(
"--approve-governance", action="store_true", help="Capture a governance approval"
)
p.add_argument("--approve-packet", action="store_true", help="Capture a campaign approval")
p.add_argument(
"--review-governance", action="store_true", help="Capture a governance follow-up review"
)
p.add_argument(
"--review-packet", action="store_true", help="Capture a campaign follow-up review"
)
p.add_argument("--reset-prefs", action="store_true", help="Clear operator suppression hints")
p.add_argument(
"--acknowledge-target", type=str, default=None, help="Repo to acknowledge in review queue"
)
p.add_argument("--acknowledge-kind", type=str, default=None, help="Change type to acknowledge")
p.add_argument(
"--semantic-search",
default=None,
metavar="QUERY",
help="Semantic search against portfolio index",
)
p.add_argument("--ask", default=None, metavar="QUERY", help="Alias for --semantic-search")
# ── Initiative tracker (7A.3) ─────────────────────────────────────────
p.add_argument(
"--set-initiative",
default=None,
metavar="REPO",
dest="set_initiative",
help="Set or update a tier-upgrade initiative for REPO",
)
p.add_argument(
"--target-tier",
type=int,
choices=[2, 3, 4],
default=None,
dest="target_tier",
help="Target maturity tier (2=Silver, 3=Gold, 4=Platinum); required with --set-initiative",
)
p.add_argument(
"--deadline",
default=None,
metavar="YYYY-MM-DD",
help="Deadline for the initiative (YYYY-MM-DD); required with --set-initiative",
)
p.add_argument(
"--initiatives",
action="store_true",
help="List all initiatives with current status",
)
p.add_argument(
"--close-initiative",
default=None,
metavar="REPO",
dest="close_initiative",
help="Close the open initiative for REPO (marks as met)",
)
# ── LLM-suggested initiatives (8.4) ───────────────────────────────────
p.add_argument(
"--suggest-initiatives",
nargs="?",
const=0,
type=int,
default=None,
metavar="TARGET_TIER",
help="LLM-rank repos closest to qualifying for TARGET_TIER (default: next tier from current)",
)
p.add_argument(
"--llm-budget",
type=float,
default=None,
metavar="USD",
help="Override default LLM cost ceiling (default $0.10 for --suggest-initiatives)",
)
# ── Accept suggestion (9.1) ───────────────────────────────────────────
p.add_argument(
"--accept-suggestion",
type=str,
default=None,
metavar="REPO",
dest="accept_suggestion",
help="Convert a suggestion into an initiative (creates an initiatives.json entry)",
)
# ── Dismiss suggestion (11.4) ─────────────────────────────────────────
p.add_argument(
"--dismiss-suggestion",
type=str,
default=None,
metavar="REPO",
help="Suppress repo from future LLM-suggested initiatives",
)
p.add_argument(
"--reason",
type=str,
default="",
help="Reason for dismissal (used with --dismiss-suggestion)",
)
p.add_argument(
"--undo-dismiss",
type=str,
default=None,
metavar="REPO",
help="Restore a dismissed repo to the suggestion pool",
)
p.add_argument(
"--list-dismissed",
action="store_true",
help="List currently dismissed suggestion repos",
)
# ── Auto-expire + audit trail (12.1) ─────────────────────────────────────
p.add_argument(
"--dismiss-expires-days",
type=int,
default=None,
metavar="N",
help="Auto-expire dismissal after N days (default: permanent)",
)
p.add_argument(
"--expire-dismissals",
action="store_true",
help="Run cleanup: remove dismissals whose expiry date has passed",
)
p.add_argument(
"--dismissal-history",
action="store_true",
help="Show audit trail of dismissal events",
)
def _add_automation_proposal_flags(parser: argparse.ArgumentParser) -> None:
"""Arc D phase-3b bounded-automation proposal triage flags.
Added to both the ``report`` subparser and the legacy parser so the queue
can be driven from either invocation form, mirroring the context-recovery
flags. Execution is dry-run unless ``--apply`` is also given.
"""
parser.add_argument(
"--propose-automation",
action="store_true",
help="Generate/refresh bounded-automation proposals for eligible repos",
)
parser.add_argument(
"--list-proposals",
action="store_true",
help="List the durable bounded-automation proposal queue",
)
parser.add_argument(
"--approve-proposal",
type=str,
default=None,
metavar="ID",
help="Approve a pending bounded-automation proposal by id",
)
parser.add_argument(
"--reject-proposal",
type=str,
default=None,
metavar="ID",
help="Reject a pending bounded-automation proposal by id",
)
parser.add_argument(
"--execute-proposals",
action="store_true",
help="Execute approved bounded-automation proposals (dry-run unless --apply)",
)
parser.add_argument(
"--apply",
action="store_true",
help="With --execute-proposals: actually apply (open PRs / write catalog seeds)",
)
def _build_report_subparser(subparsers: argparse._SubParsersAction) -> None: # type: ignore[type-arg]
"""Subcommand: `audit report` — generate exports, packets, and writebacks."""
p = subparsers.add_parser(
"report",
help="Generate exports, campaign packets, and writeback actions",
description="Portfolio truth, Excel workbooks, campaigns, writebacks, and context recovery.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
_add_global_flags(p)
p.add_argument(
"--portfolio-truth", action="store_true", help="Generate canonical portfolio truth snapshot"
)
p.add_argument(
"--portfolio-context-recovery",
action="store_true",
help="Build active/recent weak-context recovery plan",
)
p.add_argument(
"--apply-context-recovery",
action="store_true",
help="Apply eligible context recovery updates",
)
p.add_argument(
"--tier-recalibration-report",
action="store_true",
help="Generate tier distribution report and flag bunching",
)
p.add_argument(
"--context-triage",
action="store_true",
help="Run context quality triage across the portfolio",
)
_add_automation_proposal_flags(p)
p.add_argument(
"--excel-mode",
choices=["template", "standard"],
default="standard",
help="Workbook style: standard (default) or template-backed",
)
p.add_argument(
"--diff",
type=Path,
default=None,
metavar="PREVIOUS_REPORT",
help="Compare against a previous report",
)
p.add_argument("--summary", action="store_true", help="Print a Rich diff summary to stderr")
p.add_argument("--scorecard", action="store_true", help="Apply internal scorecard programs")
p.add_argument(
"--campaign",
choices=[
"security-review",
"promotion-push",
"archive-sweep",
"showcase-publish",
"maintenance-cleanup",
],
default=None,
help="Build a managed campaign view",
)
p.add_argument(
"--writeback-target",
choices=["github", "notion", "all"],
default=None,
help="External system to receive writeback actions",
)
p.add_argument(
"--writeback-apply", action="store_true", help="Execute live writeback (not preview)"
)
p.add_argument(
"--campaign-from-ledger",
action="store_true",
help="When paired with --writeback-apply, execute approved campaign-plan packets from the ledger",
)
p.add_argument(
"--github-projects",
action="store_true",
help="Mirror campaign actions into GitHub Projects v2",
)
p.add_argument(
"--campaign-sync-mode",
choices=["reconcile", "append-only", "close-missing"],
default="reconcile",
help="Campaign record reconciliation strategy (default: reconcile)",
)
p.add_argument(
"--max-actions",
type=int,
default=20,
help="Max managed actions per campaign run (default: 20)",
)
p.add_argument(
"--apply-metadata",
action="store_true",
help="Apply description/topics from improvements file",
)
p.add_argument(
"--apply-readmes", action="store_true", help="Push README updates via Contents API"
)
p.add_argument(
"--improvements-file", type=Path, default=None, help="Path to improvements JSON file"
)
p.add_argument(
"--generate-manifest",
action="store_true",
help="Generate improvement manifest from latest report",
)
p.add_argument(
"--create-issues",
action="store_true",
help="Create GitHub issues for high-priority action items",
)
p.add_argument("--upload-badges", action="store_true", help="Upload badge JSON to GitHub Gist")
p.add_argument("--notion-sync", action="store_true", help="Push audit events to Notion API")
p.add_argument("--notion-registry", action="store_true", help="Use Notion as registry source")
p.add_argument(
"--portfolio-profile",
type=str,
default="default",
metavar="NAME",
help="Ranking overlay profile for analyst-facing outputs (default: default)",
)
p.add_argument(
"--collection",
type=str,
default=None,
metavar="NAME",
help="Filter outputs to named collection",
)
# ── Draft README authoring (Arc G S5.1-5.3) ──────────────────────
p.add_argument(
"--draft-readmes",
action="store_true",
help="Draft README packets for qualifying repos via LLM",
)
p.add_argument(
"--draft-readmes-all",
action="store_true",
help="Apply to every qualifying repo (stale/missing/short)",
)
p.add_argument(
"--draft-readmes-repo",
action="append",
default=None,
dest="draft_readmes_repos",
metavar="REPO",
help="Explicit per-repo opt-in (repeatable)",
)
# ── Campaign planner (Arc G S6.1-6.2) ────────────────────────────
p.add_argument(
"--plan-campaign",
default=None,
metavar="GOAL",
dest="plan_campaign",
help="Generate a goal-driven campaign plan via LLM (e.g. 'archive dead repos')",
)
p.add_argument(
"--max-repos",
type=int,
default=50,
dest="max_repos",
help="Max repos to consider when planning a campaign (default: 50)",
)
# ── Tier-gap export (Arc G S12.4) ─────────────────────────────────
p.add_argument(
"--tier-gaps",
action="store_true",
help="Dump per-repo TierGap data (current tier + missing requirements + source) for external tooling",
)
p.add_argument(
"--tier-gaps-target",
type=int,
choices=[2, 3, 4],
default=None,
metavar="TIER",
help="Override target tier for gap calculation (default: current+1 per repo). Valid: 2-4.",
)
p.add_argument(
"--format",
choices=["json", "markdown"],
default="json",
help="Output format for --tier-gaps (default: json)",
)
def _build_serve_subparser(subparsers: argparse._SubParsersAction) -> None: # type: ignore[type-arg]
"""Subcommand: `audit serve` — start the local web UI."""
p = subparsers.add_parser(
"serve",
help="Start local web UI (FastAPI + HTMX) for portfolio artefacts",
description="Serve portfolio artefacts via a local FastAPI + HTMX web UI. Requires [serve] extra.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
p.add_argument("--port", type=int, default=8080, help="Port to listen on (default: 8080)")
p.add_argument("--host", default="127.0.0.1", help="Host to bind (default: 127.0.0.1)")
p.add_argument(
"--token",
default=os.environ.get("GITHUB_TOKEN") or _gh_auth_token(),
help="GitHub personal access token",
)
p.add_argument(
"--output-dir", default="output", help="Directory for output files (default: output/)"
)
p.add_argument("--config", default=None, help="Path to audit-config.yaml")
p.add_argument("--verbose", action="store_true", help="Print detailed output")
# ── Argument parser ──────────────────────────────────────────────────
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="github-repo-auditor",
description=CLI_MODE_GUIDE,
epilog=CLI_MODE_EXAMPLES,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"username",
nargs="?",
default=None,
help="GitHub username to audit (omit when using --serve)",
)
parser.add_argument(
"--token",
default=os.environ.get("GITHUB_TOKEN") or _gh_auth_token(),
help="GitHub personal access token (default: $GITHUB_TOKEN or `gh auth token`)",
)
parser.add_argument(
"--output-dir",
default="output",
help="Directory for output files (default: output/)",
)
parser.add_argument(
"--portfolio-truth",
action="store_true",
help="Generate the canonical portfolio truth snapshot and compatibility portfolio artifacts",
)
parser.add_argument(
"--portfolio-truth-include-release-count",
action="store_true",
help=(
"Overlay derived.release_count on each project from the latest "
"output/audit-report-<username>-*.json warehouse file (requires a prior audit run)"
),
)
parser.add_argument(
"--portfolio-truth-include-security",
action="store_true",
help=(
"Overlay the security.* GHAS alert counts on each project from the latest "
"output/ghas-alerts-<username>-*.json file, feeding the active-high-severity-alerts "
"risk factor (requires a prior `audit report --ghas-alerts` run)"
),
)
parser.add_argument(
"--portfolio-context-recovery",
action="store_true",
help="Build the active/recent weak-context recovery plan and optionally apply the safe context upgrades",
)
parser.add_argument(
"--apply-context-recovery",
action="store_true",
help="Apply eligible context recovery updates after building the recovery plan",
)
parser.add_argument(
"--tier-recalibration-report",
action="store_true",
help="Generate tier distribution report and flag bunching",
)
parser.add_argument(
"--context-triage",
action="store_true",
help="Run context quality triage across the portfolio",
)
parser.add_argument(
"--context-recovery-limit",
type=int,
default=None,
help="Optional cap on how many eligible recovery targets to apply in one run",
)
parser.add_argument(
"--allow-dirty-worktree",
action="store_true",
help="Allow context recovery to apply to repos with uncommitted changes",
)
_add_automation_proposal_flags(parser)
parser.add_argument(
"--workspace-root",
type=Path,
default=DEFAULT_PORTFOLIO_WORKSPACE,
help="Workspace root to scan for portfolio truth generation (default: ~/Projects)",
)
parser.add_argument(
"--registry-output",
type=Path,
default=None,
help="Where to publish the generated project-registry.md compatibility artifact",
)
parser.add_argument(
"--portfolio-report-output",
type=Path,
default=None,
help="Where to publish the generated PORTFOLIO-AUDIT-REPORT.md compatibility artifact",
)
parser.add_argument(
"--catalog",
type=Path,
default=None,
help="Path to portfolio-catalog.yaml for local repo ownership and lifecycle contracts",
)
parser.add_argument(
"--skip-forks",
action="store_true",
help="Exclude forked repos from the audit",
)
parser.add_argument(
"--skip-archived",
action="store_true",
help="Exclude archived repos from the audit",
)
parser.add_argument(
"--skip-clone",
action="store_true",
help="Skip the clone step (metadata only)",
)
parser.add_argument(
"--registry",
type=Path,
default=None,
help="Path to project-registry.md for reconciliation",
)
parser.add_argument(
"--sync-registry",
action="store_true",
help="Auto-add untracked GitHub repos to the registry (requires --registry)",
)
parser.add_argument(
"--no-cache",
action="store_true",
help="Bypass API response cache",
)
parser.add_argument(
"--no-analyzer-cache",
action="store_true",
help="Disable per-(repo, sha, analyzer) result cache for this run (reads and writes). "
"Useful for reconcile gates that need fresh analyzer output.",
)
parser.add_argument(
"--reconcile-cache",
action="store_true",
help="After audit, re-run analyzers without cache and diff against cached results. "
"Exits non-zero on divergence. Intended for CI release gates.",
)
parser.add_argument(
"--repos",
nargs="+",
default=None,
metavar="REPO",
help="Audit only these specific repos (by name or URL). Merges into the most recent full report.",
)
parser.add_argument(
"--incremental",
action="store_true",
help="Only re-audit repos that changed since last run (compares pushed_at timestamps)",
)
parser.add_argument(
"--verbose",
action="store_true",
help="Print detailed output",
)
parser.add_argument(
"--graphql",
action="store_true",
help="Use GraphQL API for faster bulk metadata fetch",
)
parser.add_argument(
"--diff",
type=Path,
default=None,
metavar="PREVIOUS_REPORT",
help="Compare against a previous audit-report JSON to show changes",
)
parser.add_argument(
"--badges",
action="store_true",
help="Generate Shields.io badge JSON files and badges.md",
)
parser.add_argument(
"--upload-badges",
action="store_true",
help="Upload badge JSON to GitHub Gist for endpoint badges (implies --badges)",
)
parser.add_argument(
"--notion",
action="store_true",
help="Generate Notion audit event JSON (dry-run, no API calls)",
)
parser.add_argument(
"--notion-sync",
action="store_true",
help="Push audit events to Notion API (implies --notion)",
)
parser.add_argument(
"--portfolio-readme",
action="store_true",
help="Generate PORTFOLIO.md from audit data",
)
parser.add_argument(
"--readme-suggestions",
action="store_true",
help="Generate per-repo README improvement suggestions",
)
parser.add_argument(
"--notion-registry",
action="store_true",
help="Use Notion Local Portfolio Projects as registry source (requires NOTION_TOKEN)",
)
parser.add_argument(
"--html",
action="store_true",
help="Generate interactive HTML dashboard",
)
parser.add_argument(
"--pdf",
action="store_true",
help="Generate PDF audit report",
)
parser.add_argument(
"--excel-mode",
choices=["template", "standard"],
default="standard",
help="Generate the stable standard workbook (default) or the template-backed presentation workbook",
)
parser.add_argument(
"--scoring-profile",
type=str,
default=None,
metavar="NAME",
help="Use a custom scoring profile from config/scoring-profiles/NAME.json",
)
parser.add_argument(
"--scorecards",
type=Path,
default=None,
metavar="PATH",
help="Use a custom scorecards config file (default: config/scorecards.yaml)",
)
parser.add_argument(
"--portfolio-profile",
type=str,
default="default",
metavar="NAME",
help="Apply a ranking overlay profile for analyst-facing outputs (default: default)",
)
parser.add_argument(
"--collection",
type=str,
default=None,
metavar="NAME",
help="Filter analyst-facing outputs to a named collection (does not affect audited repos)",
)
parser.add_argument(
"--review-pack",
action="store_true",
help="Generate a concise analyst review pack from the current run and compare context",
)
parser.add_argument(
"--scorecard",
action="store_true",
help="Apply internal scorecard programs from config/scorecards.yaml",
)
parser.add_argument(
"--ossf-scorecard",
action="store_true",
dest="ossf_scorecard",
help=(
"Fetch pre-computed OSSF Scorecard scores for public repos from "
"api.securityscorecards.dev and write output/ossf-scorecard-<user>-<date>.json"
),
)
parser.add_argument(
"--sbom-source",
choices=["lockfile", "github"],
default="lockfile",
dest="sbom_source",
help=(
"Dependency count source. 'lockfile' (default) uses local manifest parsing. "
"'github' fetches the SPDX SBOM from GitHub's dependency graph API, "
"which catches transitive deps and works without a clone."
),
)
parser.add_argument(
"--security-offline",
action="store_true",
help="Use local security analysis only and skip GitHub-native or external security enrichment",
)
parser.add_argument(
"--analysis-workers",
type=int,
default=None,
help=(
"Number of repo-analysis workers. Defaults to 1 for reliable, visible full "
"audits. Set GITHUB_REPO_AUDITOR_ANALYSIS_WORKERS or pass this flag to opt "
"into parallel analysis."
),
)
parser.add_argument(
"--fetch-mode",
choices=["sync", "async"],
default="sync",
help=(
"Per-repo enrichment fetch strategy. 'sync' (default) uses the existing "
"sequential requests path. 'async' enables the httpx-based parallel fetcher "
"which pre-fetches all enrichment endpoints concurrently before analysis."
),
)
parser.add_argument(
"--fetch-workers",
type=int,
default=10,
help=(
"Max concurrent in-flight HTTP requests for the async enrichment fetcher "
"(only used when --fetch-mode async is set). Default: 10."
),
)
parser.add_argument(
"--campaign",
choices=[
"security-review",
"promotion-push",
"archive-sweep",
"showcase-publish",
"maintenance-cleanup",
],
default=None,
help="Build a managed campaign view from the current report facts",
)
parser.add_argument(
"--writeback-target",
choices=["github", "notion", "all"],
default=None,
help="Select which external system should receive writeback actions",
)
parser.add_argument(
"--writeback-apply",
action="store_true",
help="Execute live writeback instead of preview-only planning",
)
parser.add_argument(
"--campaign-from-ledger",
action="store_true",
help="When paired with --writeback-apply, execute approved campaign-plan packets from the ledger",
)
parser.add_argument(
"--github-projects",
action="store_true",
help="Mirror managed GitHub campaign actions into a configured GitHub Projects v2 board",
)
parser.add_argument(
"--github-projects-config",
type=Path,
default=None,
help="Path to github-projects.yaml for GitHub Projects v2 mirroring",
)
parser.add_argument(
"--campaign-sync-mode",
choices=["reconcile", "append-only", "close-missing"],
default="reconcile",
help="How managed campaign records should reconcile against prior state (default: reconcile)",
)
parser.add_argument(
"--max-actions",
type=int,
default=20,
help="Maximum managed actions to include in a campaign run (default: 20)",
)
parser.add_argument(
"--governance-view",