git-contribution-analyzer 0.8.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.
Files changed (187) hide show
  1. git_contribution_analyzer/__init__.py +3 -0
  2. git_contribution_analyzer/adapters/__init__.py +1 -0
  3. git_contribution_analyzer/adapters/git/__init__.py +1 -0
  4. git_contribution_analyzer/adapters/git/local_identity.py +51 -0
  5. git_contribution_analyzer/adapters/git/native_git.py +353 -0
  6. git_contribution_analyzer/adapters/git/pydriller_history.py +57 -0
  7. git_contribution_analyzer/adapters/git/repository_discovery.py +75 -0
  8. git_contribution_analyzer/adapters/gui/__init__.py +1 -0
  9. git_contribution_analyzer/adapters/gui/app.py +63 -0
  10. git_contribution_analyzer/adapters/gui/controller.py +1084 -0
  11. git_contribution_analyzer/adapters/gui/models/__init__.py +3 -0
  12. git_contribution_analyzer/adapters/gui/models/base_table.py +108 -0
  13. git_contribution_analyzer/adapters/gui/settings.py +53 -0
  14. git_contribution_analyzer/adapters/gui/task_runner.py +196 -0
  15. git_contribution_analyzer/adapters/llm/__init__.py +1 -0
  16. git_contribution_analyzer/adapters/llm/anthropic.py +52 -0
  17. git_contribution_analyzer/adapters/llm/base.py +142 -0
  18. git_contribution_analyzer/adapters/llm/cache.py +148 -0
  19. git_contribution_analyzer/adapters/llm/claude_cli.py +52 -0
  20. git_contribution_analyzer/adapters/llm/codex_cli.py +52 -0
  21. git_contribution_analyzer/adapters/llm/command_base.py +153 -0
  22. git_contribution_analyzer/adapters/llm/mock.py +82 -0
  23. git_contribution_analyzer/adapters/llm/ollama.py +53 -0
  24. git_contribution_analyzer/adapters/llm/openai_compatible.py +61 -0
  25. git_contribution_analyzer/adapters/llm/registry.py +117 -0
  26. git_contribution_analyzer/adapters/mcp/__init__.py +13 -0
  27. git_contribution_analyzer/adapters/mcp/installer.py +175 -0
  28. git_contribution_analyzer/adapters/mcp/prompts_resources.py +218 -0
  29. git_contribution_analyzer/adapters/mcp/protocol.py +361 -0
  30. git_contribution_analyzer/adapters/mcp/server.py +52 -0
  31. git_contribution_analyzer/adapters/mcp/tools.py +621 -0
  32. git_contribution_analyzer/adapters/outcomes/__init__.py +1 -0
  33. git_contribution_analyzer/adapters/outcomes/yaml_loader.py +55 -0
  34. git_contribution_analyzer/adapters/outcomes/yaml_store.py +104 -0
  35. git_contribution_analyzer/adapters/reporting/__init__.py +1 -0
  36. git_contribution_analyzer/adapters/reporting/brag_markdown.py +115 -0
  37. git_contribution_analyzer/adapters/reporting/html_report.py +1413 -0
  38. git_contribution_analyzer/adapters/reporting/markdown.py +217 -0
  39. git_contribution_analyzer/adapters/reporting/portfolio_markdown.py +167 -0
  40. git_contribution_analyzer/adapters/reporting/recap_markdown.py +212 -0
  41. git_contribution_analyzer/adapters/reporting/resume_markdown.py +37 -0
  42. git_contribution_analyzer/adapters/reporting/work_assessment_csv.py +117 -0
  43. git_contribution_analyzer/adapters/reporting/work_assessment_markdown.py +90 -0
  44. git_contribution_analyzer/adapters/reporting/work_assessment_series_markdown.py +31 -0
  45. git_contribution_analyzer/adapters/storage/__init__.py +1 -0
  46. git_contribution_analyzer/adapters/storage/sqlite/__init__.py +1 -0
  47. git_contribution_analyzer/adapters/storage/sqlite/analysis.py +708 -0
  48. git_contribution_analyzer/adapters/storage/sqlite/database.py +98 -0
  49. git_contribution_analyzer/adapters/storage/sqlite/git_index.py +482 -0
  50. git_contribution_analyzer/adapters/storage/sqlite/identity_merge.py +373 -0
  51. git_contribution_analyzer/adapters/storage/sqlite/llm_audit.py +109 -0
  52. git_contribution_analyzer/adapters/storage/sqlite/migrations/env.py +34 -0
  53. git_contribution_analyzer/adapters/storage/sqlite/migrations/script.py.mako +22 -0
  54. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0001_initial.py +51 -0
  55. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0002_git_index.py +146 -0
  56. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0003_analysis.py +79 -0
  57. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0004_llm_audit.py +69 -0
  58. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0005_run_types.py +42 -0
  59. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0006_identity_merges.py +83 -0
  60. git_contribution_analyzer/adapters/storage/sqlite/migrations/versions/0007_structural_baselines.py +173 -0
  61. git_contribution_analyzer/adapters/storage/sqlite/models.py +354 -0
  62. git_contribution_analyzer/adapters/storage/sqlite/structural_baseline.py +841 -0
  63. git_contribution_analyzer/adapters/workspace/__init__.py +1 -0
  64. git_contribution_analyzer/adapters/workspace/config.py +135 -0
  65. git_contribution_analyzer/adapters/workspace/git_exclude.py +32 -0
  66. git_contribution_analyzer/adapters/workspace/layout.py +40 -0
  67. git_contribution_analyzer/adapters/workspace/locks.py +27 -0
  68. git_contribution_analyzer/adapters/workspace/portfolio_workspace.py +380 -0
  69. git_contribution_analyzer/adapters/workspace/ranking_config.py +17 -0
  70. git_contribution_analyzer/application/__init__.py +1 -0
  71. git_contribution_analyzer/application/dto/__init__.py +19 -0
  72. git_contribution_analyzer/application/dto/gui.py +86 -0
  73. git_contribution_analyzer/application/dto/results.py +21 -0
  74. git_contribution_analyzer/application/facades/__init__.py +3 -0
  75. git_contribution_analyzer/application/facades/gui.py +568 -0
  76. git_contribution_analyzer/application/ports/__init__.py +22 -0
  77. git_contribution_analyzer/application/ports/cancellation.py +50 -0
  78. git_contribution_analyzer/application/ports/git_history.py +22 -0
  79. git_contribution_analyzer/application/ports/llm.py +44 -0
  80. git_contribution_analyzer/application/ports/portfolio_store.py +34 -0
  81. git_contribution_analyzer/application/ports/progress.py +43 -0
  82. git_contribution_analyzer/application/ports/structural_baseline.py +93 -0
  83. git_contribution_analyzer/application/services/__init__.py +1 -0
  84. git_contribution_analyzer/application/services/assessment_explanation.py +127 -0
  85. git_contribution_analyzer/application/services/default_person.py +61 -0
  86. git_contribution_analyzer/application/services/evidence_snapshot.py +64 -0
  87. git_contribution_analyzer/application/services/person_selection.py +88 -0
  88. git_contribution_analyzer/application/services/resume_generation.py +318 -0
  89. git_contribution_analyzer/application/services/semantic_enhancement.py +157 -0
  90. git_contribution_analyzer/application/services/time_boundaries.py +49 -0
  91. git_contribution_analyzer/application/use_cases/__init__.py +1 -0
  92. git_contribution_analyzer/application/use_cases/analyze_contributions.py +276 -0
  93. git_contribution_analyzer/application/use_cases/analyze_project.py +295 -0
  94. git_contribution_analyzer/application/use_cases/assess_portfolio.py +327 -0
  95. git_contribution_analyzer/application/use_cases/assess_work.py +602 -0
  96. git_contribution_analyzer/application/use_cases/assess_work_series.py +212 -0
  97. git_contribution_analyzer/application/use_cases/compare_assessment_runs.py +121 -0
  98. git_contribution_analyzer/application/use_cases/export_report.py +49 -0
  99. git_contribution_analyzer/application/use_cases/generate_brag.py +308 -0
  100. git_contribution_analyzer/application/use_cases/generate_portfolio_recap.py +244 -0
  101. git_contribution_analyzer/application/use_cases/generate_portfolio_resume.py +152 -0
  102. git_contribution_analyzer/application/use_cases/generate_recap.py +316 -0
  103. git_contribution_analyzer/application/use_cases/generate_report.py +32 -0
  104. git_contribution_analyzer/application/use_cases/generate_resume.py +209 -0
  105. git_contribution_analyzer/application/use_cases/get_portfolio_status.py +83 -0
  106. git_contribution_analyzer/application/use_cases/get_run.py +16 -0
  107. git_contribution_analyzer/application/use_cases/get_status.py +69 -0
  108. git_contribution_analyzer/application/use_cases/index_repository.py +267 -0
  109. git_contribution_analyzer/application/use_cases/init_portfolio.py +89 -0
  110. git_contribution_analyzer/application/use_cases/init_project.py +71 -0
  111. git_contribution_analyzer/application/use_cases/list_identities.py +16 -0
  112. git_contribution_analyzer/application/use_cases/list_providers.py +29 -0
  113. git_contribution_analyzer/application/use_cases/list_runs.py +17 -0
  114. git_contribution_analyzer/application/use_cases/manage_identity_merges.py +48 -0
  115. git_contribution_analyzer/application/use_cases/manage_outcomes.py +189 -0
  116. git_contribution_analyzer/application/use_cases/manage_structural_baselines.py +262 -0
  117. git_contribution_analyzer/application/use_cases/map_identity.py +28 -0
  118. git_contribution_analyzer/application/use_cases/recover_runs.py +22 -0
  119. git_contribution_analyzer/application/use_cases/run_doctor.py +81 -0
  120. git_contribution_analyzer/application/use_cases/sync_portfolio.py +232 -0
  121. git_contribution_analyzer/application/use_cases/test_provider.py +22 -0
  122. git_contribution_analyzer/application/use_cases/uninit_project.py +23 -0
  123. git_contribution_analyzer/application/use_cases/verify_portfolio.py +165 -0
  124. git_contribution_analyzer/cli/__init__.py +1 -0
  125. git_contribution_analyzer/cli/app.py +1430 -0
  126. git_contribution_analyzer/cli/exit_codes.py +13 -0
  127. git_contribution_analyzer/cli/output.py +26 -0
  128. git_contribution_analyzer/cli/portfolio_commands.py +629 -0
  129. git_contribution_analyzer/domain/__init__.py +1 -0
  130. git_contribution_analyzer/domain/errors.py +55 -0
  131. git_contribution_analyzer/domain/models/__init__.py +3 -0
  132. git_contribution_analyzer/domain/models/analysis.py +29 -0
  133. git_contribution_analyzer/domain/models/assessment.py +12 -0
  134. git_contribution_analyzer/domain/models/brag.py +148 -0
  135. git_contribution_analyzer/domain/models/contribution.py +55 -0
  136. git_contribution_analyzer/domain/models/git_history.py +69 -0
  137. git_contribution_analyzer/domain/models/person_selection.py +46 -0
  138. git_contribution_analyzer/domain/models/portfolio.py +498 -0
  139. git_contribution_analyzer/domain/models/ranking.py +48 -0
  140. git_contribution_analyzer/domain/models/recap.py +235 -0
  141. git_contribution_analyzer/domain/models/repository.py +10 -0
  142. git_contribution_analyzer/domain/models/resume.py +59 -0
  143. git_contribution_analyzer/domain/models/run.py +10 -0
  144. git_contribution_analyzer/domain/models/semantic.py +34 -0
  145. git_contribution_analyzer/domain/models/snapshot.py +208 -0
  146. git_contribution_analyzer/domain/models/structural_baseline.py +120 -0
  147. git_contribution_analyzer/domain/models/work_assessment.py +81 -0
  148. git_contribution_analyzer/domain/services/assessment_periods.py +182 -0
  149. git_contribution_analyzer/domain/services/brag_rules.py +250 -0
  150. git_contribution_analyzer/domain/services/capability_rules.py +91 -0
  151. git_contribution_analyzer/domain/services/contribution_clustering.py +98 -0
  152. git_contribution_analyzer/domain/services/contribution_rules.py +79 -0
  153. git_contribution_analyzer/domain/services/difficulty_rules.py +191 -0
  154. git_contribution_analyzer/domain/services/dimensional_summary.py +117 -0
  155. git_contribution_analyzer/domain/services/portfolio_aggregation.py +250 -0
  156. git_contribution_analyzer/domain/services/portfolio_resume_rules.py +265 -0
  157. git_contribution_analyzer/domain/services/portfolio_verifier.py +238 -0
  158. git_contribution_analyzer/domain/services/ranking_rules.py +226 -0
  159. git_contribution_analyzer/domain/services/recap_rules.py +268 -0
  160. git_contribution_analyzer/domain/services/resume_claim_rules.py +70 -0
  161. git_contribution_analyzer/domain/services/structural_baseline.py +317 -0
  162. git_contribution_analyzer/domain/services/structural_signals.py +151 -0
  163. git_contribution_analyzer/domain/services/workload_rules.py +185 -0
  164. git_contribution_analyzer/gui/__init__.py +1 -0
  165. git_contribution_analyzer/gui/qml/Main.qml +1141 -0
  166. git_contribution_analyzer/gui/qml/__init__.py +1 -0
  167. git_contribution_analyzer/prompts/__init__.py +1 -0
  168. git_contribution_analyzer/prompts/assessment/__init__.py +1 -0
  169. git_contribution_analyzer/prompts/assessment/v1/__init__.py +1 -0
  170. git_contribution_analyzer/prompts/assessment/v1/explanation.txt +4 -0
  171. git_contribution_analyzer/prompts/resume/__init__.py +1 -0
  172. git_contribution_analyzer/prompts/resume/v1/__init__.py +1 -0
  173. git_contribution_analyzer/prompts/resume/v1/style-concise.txt +1 -0
  174. git_contribution_analyzer/prompts/resume/v1/style-star.txt +1 -0
  175. git_contribution_analyzer/prompts/resume/v1/style-xyz.txt +1 -0
  176. git_contribution_analyzer/prompts/resume/v1/system.txt +3 -0
  177. git_contribution_analyzer/prompts/v1/__init__.py +1 -0
  178. git_contribution_analyzer/prompts/v1/capability_explanation.txt +2 -0
  179. git_contribution_analyzer/prompts/v1/contribution_summary.txt +2 -0
  180. git_contribution_analyzer/prompts/v1/overall_summary.txt +2 -0
  181. git_contribution_analyzer/prompts/v1/resume_bullet.txt +2 -0
  182. git_contribution_analyzer-0.8.0.dist-info/METADATA +667 -0
  183. git_contribution_analyzer-0.8.0.dist-info/RECORD +187 -0
  184. git_contribution_analyzer-0.8.0.dist-info/WHEEL +4 -0
  185. git_contribution_analyzer-0.8.0.dist-info/entry_points.txt +3 -0
  186. git_contribution_analyzer-0.8.0.dist-info/licenses/LICENSE +201 -0
  187. git_contribution_analyzer-0.8.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,1430 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import webbrowser
6
+ from datetime import date
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from git_contribution_analyzer import __version__
13
+ from git_contribution_analyzer.adapters.git.repository_discovery import discover_repository
14
+ from git_contribution_analyzer.adapters.llm.registry import (
15
+ build_provider,
16
+ )
17
+ from git_contribution_analyzer.adapters.mcp.installer import (
18
+ SUPPORTED_AGENT_TARGETS,
19
+ install_agent_mcp_config,
20
+ )
21
+ from git_contribution_analyzer.adapters.mcp.server import run_stdio_server
22
+ from git_contribution_analyzer.adapters.outcomes.yaml_loader import load_verified_outcomes
23
+ from git_contribution_analyzer.adapters.outcomes.yaml_store import (
24
+ default_outcomes_path,
25
+ load_outcomes_if_exists,
26
+ )
27
+ from git_contribution_analyzer.adapters.reporting.brag_markdown import render_brag_markdown
28
+ from git_contribution_analyzer.adapters.reporting.html_report import render_html_report
29
+ from git_contribution_analyzer.adapters.reporting.recap_markdown import render_recap_markdown
30
+ from git_contribution_analyzer.adapters.workspace.config import load_config
31
+ from git_contribution_analyzer.adapters.workspace.layout import WorkspaceLayout
32
+ from git_contribution_analyzer.adapters.workspace.ranking_config import load_ranking_config
33
+ from git_contribution_analyzer.application.dto.results import CommandEnvelope
34
+ from git_contribution_analyzer.application.services.time_boundaries import (
35
+ parse_boundaries,
36
+ parse_boundary,
37
+ uses_system_timezone,
38
+ )
39
+ from git_contribution_analyzer.application.use_cases.analyze_contributions import (
40
+ analyze_contributions,
41
+ )
42
+ from git_contribution_analyzer.application.use_cases.analyze_project import analyze_project
43
+ from git_contribution_analyzer.application.use_cases.assess_work import assess_work
44
+ from git_contribution_analyzer.application.use_cases.assess_work_series import assess_work_series
45
+ from git_contribution_analyzer.application.use_cases.compare_assessment_runs import (
46
+ compare_assessment_runs,
47
+ )
48
+ from git_contribution_analyzer.application.use_cases.export_report import export_report
49
+ from git_contribution_analyzer.application.use_cases.generate_brag import generate_brag
50
+ from git_contribution_analyzer.application.use_cases.generate_recap import generate_recap
51
+ from git_contribution_analyzer.application.use_cases.generate_report import generate_report
52
+ from git_contribution_analyzer.application.use_cases.generate_resume import generate_resume
53
+ from git_contribution_analyzer.application.use_cases.get_run import get_run
54
+ from git_contribution_analyzer.application.use_cases.get_status import get_status
55
+ from git_contribution_analyzer.application.use_cases.index_repository import index_repository
56
+ from git_contribution_analyzer.application.use_cases.init_project import init_project
57
+ from git_contribution_analyzer.application.use_cases.list_identities import list_identities
58
+ from git_contribution_analyzer.application.use_cases.list_providers import (
59
+ list_providers as list_provider_status,
60
+ )
61
+ from git_contribution_analyzer.application.use_cases.list_runs import list_runs
62
+ from git_contribution_analyzer.application.use_cases.manage_identity_merges import (
63
+ list_identity_merges,
64
+ merge_identities,
65
+ preview_identity_merge,
66
+ unmerge_identities,
67
+ )
68
+ from git_contribution_analyzer.application.use_cases.manage_outcomes import (
69
+ add_outcome,
70
+ list_outcomes,
71
+ remove_outcome,
72
+ )
73
+ from git_contribution_analyzer.application.use_cases.manage_structural_baselines import (
74
+ default_structural_cutoff,
75
+ get_structural_status,
76
+ prune_structural_baselines,
77
+ rebuild_structural_baseline,
78
+ show_structural_baseline,
79
+ )
80
+ from git_contribution_analyzer.application.use_cases.map_identity import map_identity
81
+ from git_contribution_analyzer.application.use_cases.run_doctor import run_doctor
82
+ from git_contribution_analyzer.application.use_cases.test_provider import test_provider
83
+ from git_contribution_analyzer.application.use_cases.uninit_project import uninit_project
84
+ from git_contribution_analyzer.cli.exit_codes import ExitCode
85
+ from git_contribution_analyzer.cli.output import emit_human, emit_json
86
+ from git_contribution_analyzer.cli.portfolio_commands import portfolio_app
87
+ from git_contribution_analyzer.domain.errors import (
88
+ ConfigurationError,
89
+ IdentityResolutionError,
90
+ LlmProviderError,
91
+ NotARepositoryError,
92
+ ReportError,
93
+ WorkspaceError,
94
+ )
95
+ from git_contribution_analyzer.domain.models.analysis import AnalysisFilters
96
+ from git_contribution_analyzer.domain.models.structural_baseline import StructuralTimeStrategy
97
+ from git_contribution_analyzer.domain.services.ranking_rules import SUPPORTED_DIMENSIONS
98
+
99
+ app = typer.Typer(
100
+ name="gca",
101
+ help="Git contribution analysis with deterministic evidence and pluggable LLM providers.",
102
+ no_args_is_help=True,
103
+ pretty_exceptions_enable=False,
104
+ )
105
+ identities_app = typer.Typer(help="Inspect and confirm Git author identities.")
106
+ runs_app = typer.Typer(help="Inspect persisted deterministic analysis runs.")
107
+ providers_app = typer.Typer(help="Inspect and test pluggable LLM providers.")
108
+ structural_app = typer.Typer(help="Build and inspect historical structural baselines.")
109
+ outcome_app = typer.Typer(
110
+ help="Manage verified business and engineering outcomes (Brag Document ledger).",
111
+ no_args_is_help=True,
112
+ )
113
+ app.add_typer(identities_app, name="identities")
114
+ app.add_typer(runs_app, name="runs")
115
+ app.add_typer(providers_app, name="providers")
116
+ app.add_typer(structural_app, name="structural")
117
+ app.add_typer(outcome_app, name="outcome")
118
+ app.add_typer(portfolio_app, name="portfolio")
119
+ BOUNDARY_HELP = "Inclusive ISO date/time; values without an offset use the system time zone."
120
+
121
+
122
+ def _version_callback(value: bool) -> None:
123
+ if value:
124
+ typer.echo(__version__)
125
+ raise typer.Exit(code=ExitCode.SUCCESS)
126
+
127
+
128
+ @app.callback()
129
+ def root(
130
+ version: Annotated[
131
+ bool | None,
132
+ typer.Option("--version", callback=_version_callback, is_eager=True, help="Show version."),
133
+ ] = None,
134
+ ) -> None:
135
+ """Git contribution analysis CLI."""
136
+
137
+
138
+ def _exit_for_error(error: Exception) -> None:
139
+ if isinstance(error, NotARepositoryError):
140
+ emit_human(f"Error: {error}")
141
+ raise typer.Exit(code=ExitCode.NOT_A_REPOSITORY) from error
142
+ if isinstance(error, (WorkspaceError, ConfigurationError)):
143
+ emit_human(f"Error: {error}")
144
+ raise typer.Exit(code=ExitCode.WORKSPACE_ERROR) from error
145
+ if isinstance(error, IdentityResolutionError):
146
+ emit_human(f"Error: {error}")
147
+ raise typer.Exit(code=ExitCode.IDENTITY_AMBIGUOUS) from error
148
+ if isinstance(error, ReportError):
149
+ emit_human(f"Error: {error}")
150
+ raise typer.Exit(code=ExitCode.REPORT_ERROR) from error
151
+ if isinstance(error, LlmProviderError):
152
+ emit_human(f"Error: {error}")
153
+ raise typer.Exit(code=ExitCode.PROVIDER_ERROR) from error
154
+ raise error
155
+
156
+
157
+ @app.command("init")
158
+ def init_command(
159
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
160
+ ) -> None:
161
+ """Initialize a repository-local GCA workspace."""
162
+ try:
163
+ layout = init_project(path)
164
+ except Exception as exc:
165
+ _exit_for_error(exc)
166
+ return
167
+ emit_human(f"Initialized GCA workspace: {layout.root}")
168
+
169
+
170
+ @app.command("status")
171
+ def status_command(
172
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
173
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
174
+ ) -> None:
175
+ """Show repository and workspace status."""
176
+ try:
177
+ data = get_status(path)
178
+ except Exception as exc:
179
+ _exit_for_error(exc)
180
+ return
181
+ if json_output:
182
+ emit_json(CommandEnvelope(schemaVersion="2.0", command="status", data=data))
183
+ return
184
+ emit_human(f"Repository: {data['repository']}")
185
+ emit_human(f"Workspace initialized: {str(data['workspaceInitialized']).lower()}")
186
+ emit_human(f"Database healthy: {str(data['databaseHealthy']).lower()}")
187
+ emit_human(f"Index status: {data['indexStatus']}")
188
+
189
+
190
+ def _run_index_command(path: Path, *, full_rebuild: bool, json_output: bool) -> None:
191
+ try:
192
+ data = index_repository(path, full_rebuild=full_rebuild)
193
+ except Exception as exc:
194
+ _exit_for_error(exc)
195
+ return
196
+ command_name = "index" if full_rebuild else "sync"
197
+ if json_output:
198
+ emit_json(CommandEnvelope(command=command_name, data=data))
199
+ return
200
+ emit_human(
201
+ f"Indexed commits: {data['indexedCommits']} "
202
+ f"(new: {data['newCommits']}, identities: {data['identities']})"
203
+ )
204
+
205
+
206
+ @app.command("index")
207
+ def index_command(
208
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
209
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
210
+ ) -> None:
211
+ """Rebuild the Git history index from configured refs."""
212
+ _run_index_command(path, full_rebuild=True, json_output=json_output)
213
+
214
+
215
+ @app.command("sync")
216
+ def sync_command(
217
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
218
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
219
+ ) -> None:
220
+ """Incrementally synchronize new commits and changed refs."""
221
+ _run_index_command(path, full_rebuild=False, json_output=json_output)
222
+
223
+
224
+ @app.command("analyze")
225
+ def analyze_command(
226
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
227
+ person: Annotated[str, typer.Option("--person", help="Confirmed person name or email.")] = "",
228
+ all_people: Annotated[
229
+ bool,
230
+ typer.Option(
231
+ "--all",
232
+ help="Analyze every Git person, including unconfirmed identities.",
233
+ ),
234
+ ] = False,
235
+ since: Annotated[str | None, typer.Option("--since", help=BOUNDARY_HELP)] = None,
236
+ until: Annotated[str | None, typer.Option("--until", help=BOUNDARY_HELP)] = None,
237
+ branch: Annotated[str | None, typer.Option("--branch", help="Reachable branch ref.")] = None,
238
+ release: Annotated[str | None, typer.Option("--release", help="Release tag.")] = None,
239
+ scope: Annotated[str | None, typer.Option("--scope", help="Repository path prefix.")] = None,
240
+ delivery: Annotated[
241
+ str | None,
242
+ typer.Option(
243
+ "--delivery",
244
+ help="AUTHORED_ONLY, LANDED, RELEASED, REVERTED, or DELIVERED.",
245
+ ),
246
+ ] = None,
247
+ no_llm: Annotated[
248
+ bool, typer.Option("--no-llm", help="Disable semantic LLM analysis.")
249
+ ] = False,
250
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
251
+ ) -> None:
252
+ """Analyze deterministic Git contribution evidence for one or all people."""
253
+ if person and all_people:
254
+ raise typer.BadParameter("--person and --all are mutually exclusive")
255
+ if not person and not all_people:
256
+ raise typer.BadParameter("Either --person or --all is required")
257
+ if all_people and not no_llm:
258
+ raise typer.BadParameter("--all currently requires --no-llm")
259
+ try:
260
+ repository = discover_repository(path)
261
+ config = load_config(WorkspaceLayout.for_repository(repository.root).config)
262
+ parsed_since, parsed_until = _parse_boundaries(since, until)
263
+ filters = AnalysisFilters(
264
+ since=parsed_since,
265
+ until=parsed_until,
266
+ branch=branch,
267
+ release=release,
268
+ scope=scope,
269
+ delivery=delivery,
270
+ system_timezone=_uses_system_timezone(since, until),
271
+ )
272
+ if all_people:
273
+ report = analyze_project(path, filters=filters)
274
+ else:
275
+ provider = None
276
+ if config.llm.enabled and not no_llm:
277
+ provider = build_provider(config.llm)
278
+ report = analyze_contributions(
279
+ path,
280
+ person_selector=person,
281
+ filters=filters,
282
+ llm_provider=provider,
283
+ allow_llm_fallback=config.llm.allow_fallback_to_rules,
284
+ )
285
+ except Exception as exc:
286
+ _exit_for_error(exc)
287
+ return
288
+ if json_output:
289
+ emit_json(CommandEnvelope(command="analyze", data=report, warnings=report["warnings"]))
290
+ return
291
+ if report["reportType"] == "PROJECT":
292
+ emit_human(
293
+ f"Project analysis run {report['run']['id']}: "
294
+ f"{report['summary']['people']} people, "
295
+ f"{report['summary']['commits']} commits"
296
+ )
297
+ else:
298
+ emit_human(
299
+ f"Analysis run {report['run']['id']}: "
300
+ f"{report['summary']['commits']} commits, "
301
+ f"{len(report['contributionItems'])} contribution items"
302
+ )
303
+
304
+
305
+ @app.command("assess")
306
+ def assess_command(
307
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
308
+ person: Annotated[
309
+ list[str] | None,
310
+ typer.Option("--person", help="Confirmed person ID, name, or email. Repeatable."),
311
+ ] = None,
312
+ all_people: Annotated[
313
+ bool, typer.Option("--all", help="Assess every Git person independently.")
314
+ ] = False,
315
+ exclude_person: Annotated[
316
+ list[str] | None,
317
+ typer.Option(
318
+ "--exclude-person",
319
+ help="Exclude a person ID, name, or email from --all. Repeatable.",
320
+ ),
321
+ ] = None,
322
+ rank_by: Annotated[
323
+ list[str] | None,
324
+ typer.Option(
325
+ "--rank-by",
326
+ help="Rank by workload, difficulty, or delivery. Repeatable.",
327
+ ),
328
+ ] = None,
329
+ ranking_config: Annotated[
330
+ Path | None,
331
+ typer.Option(
332
+ "--ranking-config",
333
+ exists=True,
334
+ file_okay=True,
335
+ dir_okay=False,
336
+ help="YAML weights for an optional composite score.",
337
+ ),
338
+ ] = None,
339
+ since: Annotated[str | None, typer.Option("--since", help=BOUNDARY_HELP)] = None,
340
+ until: Annotated[str | None, typer.Option("--until", help=BOUNDARY_HELP)] = None,
341
+ branch: Annotated[str | None, typer.Option("--branch", help="Reachable branch ref.")] = None,
342
+ release: Annotated[str | None, typer.Option("--release", help="Release tag.")] = None,
343
+ scope: Annotated[str | None, typer.Option("--scope", help="Repository path prefix.")] = None,
344
+ delivery: Annotated[
345
+ str | None, typer.Option("--delivery", help="Delivery status filter.")
346
+ ] = None,
347
+ time_basis: Annotated[
348
+ str,
349
+ typer.Option(
350
+ "--time-basis",
351
+ help="Assessment time: authored, committed, merged, landed, or released.",
352
+ ),
353
+ ] = "authored",
354
+ period: Annotated[
355
+ str | None,
356
+ typer.Option("--period", help="Split into calendar week, month, or quarter."),
357
+ ] = None,
358
+ no_llm: Annotated[
359
+ bool, typer.Option("--no-llm", help="Disable optional explanations.")
360
+ ] = False,
361
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
362
+ ) -> None:
363
+ """Assess completed workload and deterministic engineering difficulty."""
364
+ person_selectors = tuple(person or ())
365
+ exclude_selectors = tuple(exclude_person or ())
366
+ ranking_dimensions = tuple(value.casefold() for value in (rank_by or ()))
367
+ if person_selectors and all_people:
368
+ raise typer.BadParameter("--person and --all are mutually exclusive")
369
+ if not person_selectors and not all_people:
370
+ raise typer.BadParameter("Either --person or --all is required")
371
+ if exclude_selectors and not all_people:
372
+ raise typer.BadParameter("--exclude-person requires --all")
373
+ if len(ranking_dimensions) != len(set(ranking_dimensions)):
374
+ raise typer.BadParameter("--rank-by dimensions must not be repeated")
375
+ unsupported_dimensions = set(ranking_dimensions) - set(SUPPORTED_DIMENSIONS)
376
+ if unsupported_dimensions:
377
+ raise typer.BadParameter(
378
+ "Unsupported --rank-by dimension: " + ", ".join(sorted(unsupported_dimensions))
379
+ )
380
+ normalized_time_basis = time_basis.upper()
381
+ if normalized_time_basis not in {"AUTHORED", "COMMITTED", "MERGED", "LANDED", "RELEASED"}:
382
+ raise typer.BadParameter("Unsupported --time-basis")
383
+ normalized_period = period.casefold() if period else None
384
+ if normalized_period not in {None, "week", "month", "quarter"}:
385
+ raise typer.BadParameter("Unsupported --period")
386
+ if normalized_period is not None and (since is None or until is None):
387
+ raise typer.BadParameter("--period requires both --since and --until")
388
+ try:
389
+ repository = discover_repository(path)
390
+ config = load_config(WorkspaceLayout.for_repository(repository.root).config)
391
+ active_ranking_config = (
392
+ load_ranking_config(ranking_config) if ranking_config is not None else None
393
+ )
394
+ provider = build_provider(config.llm) if config.llm.enabled and not no_llm else None
395
+ parsed_since, parsed_until = _parse_boundaries(since, until)
396
+ filters = AnalysisFilters(
397
+ since=parsed_since,
398
+ until=parsed_until,
399
+ branch=branch,
400
+ release=release,
401
+ scope=scope,
402
+ delivery=delivery,
403
+ time_basis=normalized_time_basis,
404
+ system_timezone=_uses_system_timezone(since, until),
405
+ )
406
+ if normalized_period is not None:
407
+ report = assess_work_series(
408
+ path,
409
+ period=normalized_period,
410
+ person_selectors=person_selectors,
411
+ all_people=all_people,
412
+ exclude_selectors=exclude_selectors,
413
+ rank_by=ranking_dimensions,
414
+ ranking_config=active_ranking_config,
415
+ filters=filters,
416
+ llm_provider=provider,
417
+ allow_llm_fallback=config.llm.allow_fallback_to_rules,
418
+ )
419
+ else:
420
+ report = assess_work(
421
+ path,
422
+ person_selectors=person_selectors,
423
+ all_people=all_people,
424
+ exclude_selectors=exclude_selectors,
425
+ rank_by=ranking_dimensions,
426
+ ranking_config=active_ranking_config,
427
+ filters=filters,
428
+ llm_provider=provider,
429
+ allow_llm_fallback=config.llm.allow_fallback_to_rules,
430
+ )
431
+ except Exception as exc:
432
+ _exit_for_error(exc)
433
+ return
434
+ if json_output:
435
+ emit_json(CommandEnvelope(command="assess", data=report, warnings=report["warnings"]))
436
+ return
437
+ if report["reportType"] == "WORK_ASSESSMENT_SERIES":
438
+ emit_human(f"Assessment series {report['run']['id']}: {len(report['periods'])} periods")
439
+ return
440
+ workload = report["workloadSummary"]
441
+ emit_human(
442
+ f"Assessment run {report['run']['id']}: {workload['completedItems']} completed, "
443
+ f"{workload['pendingItems']} pending items"
444
+ )
445
+
446
+
447
+ @app.command("resume")
448
+ def resume_command(
449
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
450
+ person: Annotated[str, typer.Option("--person", help="Confirmed person name or email.")] = "",
451
+ since: Annotated[str | None, typer.Option("--since", help=BOUNDARY_HELP)] = None,
452
+ until: Annotated[str | None, typer.Option("--until", help=BOUNDARY_HELP)] = None,
453
+ branch: Annotated[str | None, typer.Option("--branch", help="Reachable branch ref.")] = None,
454
+ release: Annotated[str | None, typer.Option("--release", help="Release tag.")] = None,
455
+ scope: Annotated[str | None, typer.Option("--scope", help="Repository path prefix.")] = None,
456
+ target_role: Annotated[str, typer.Option("--target-role", help="Target role context.")] = "",
457
+ language: Annotated[str, typer.Option("--language", help="zh-CN or en-US.")] = "zh-CN",
458
+ style: Annotated[str, typer.Option("--style", help="concise, star, or xyz.")] = "concise",
459
+ max_bullets: Annotated[int, typer.Option("--max-bullets", min=1, max=20)] = 6,
460
+ include_pending: Annotated[
461
+ bool, typer.Option("--include-pending", help="Include clearly marked pending work.")
462
+ ] = False,
463
+ verified_outcomes: Annotated[
464
+ Path | None,
465
+ typer.Option("--verified-outcomes", exists=True, dir_okay=False),
466
+ ] = None,
467
+ no_default_outcomes: Annotated[
468
+ bool,
469
+ typer.Option(
470
+ "--no-default-outcomes",
471
+ help="Skip auto-loading .gca/outcomes.yml when --verified-outcomes is omitted.",
472
+ ),
473
+ ] = False,
474
+ no_llm: Annotated[bool, typer.Option("--no-llm", help="Use conservative templates.")] = False,
475
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
476
+ ) -> None:
477
+ """Generate evidence-backed resume candidates for one confirmed person."""
478
+ if not person:
479
+ raise typer.BadParameter("--person is required")
480
+ try:
481
+ repository = discover_repository(path)
482
+ config = load_config(WorkspaceLayout.for_repository(repository.root).config)
483
+ provider = build_provider(config.llm) if config.llm.enabled and not no_llm else None
484
+ if verified_outcomes is not None:
485
+ outcomes = load_verified_outcomes(verified_outcomes)
486
+ elif not no_default_outcomes:
487
+ outcomes = load_outcomes_if_exists(default_outcomes_path(repository.root))
488
+ else:
489
+ outcomes = ()
490
+ parsed_since, parsed_until = _parse_boundaries(since, until)
491
+ report = generate_resume(
492
+ path,
493
+ person_selector=person,
494
+ filters=AnalysisFilters(
495
+ since=parsed_since,
496
+ until=parsed_until,
497
+ branch=branch,
498
+ release=release,
499
+ scope=scope,
500
+ system_timezone=_uses_system_timezone(since, until),
501
+ ),
502
+ target_role=target_role,
503
+ language=language,
504
+ style=style,
505
+ max_bullets=max_bullets,
506
+ include_pending=include_pending,
507
+ outcomes=outcomes,
508
+ llm_provider=provider,
509
+ allow_llm_fallback=config.llm.allow_fallback_to_rules,
510
+ )
511
+ except Exception as exc:
512
+ _exit_for_error(exc)
513
+ return
514
+ if json_output:
515
+ emit_json(CommandEnvelope(command="resume", data=report, warnings=report["warnings"]))
516
+ return
517
+ emit_human(f"Resume run {report['run']['id']}: {len(report['experienceBullets'])} candidates")
518
+
519
+
520
+ def _uses_system_timezone(*values: str | None) -> bool:
521
+ return uses_system_timezone(*values)
522
+
523
+
524
+ def _parse_boundaries(since: str | None, until: str | None): # type: ignore[no-untyped-def]
525
+ try:
526
+ return parse_boundaries(since, until)
527
+ except ValueError as exc:
528
+ message = str(exc)
529
+ if message.startswith("since"):
530
+ message = "--since must be earlier than or equal to --until"
531
+ raise typer.BadParameter(message) from exc
532
+
533
+
534
+ @identities_app.command("list")
535
+ def identities_list_command(
536
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
537
+ unresolved: Annotated[
538
+ bool, typer.Option("--unresolved", help="Show only unresolved persons.")
539
+ ] = False,
540
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
541
+ ) -> None:
542
+ """List normalized persons and their Git aliases."""
543
+ try:
544
+ data = list_identities(path, unresolved_only=unresolved)
545
+ except Exception as exc:
546
+ _exit_for_error(exc)
547
+ return
548
+ if json_output:
549
+ emit_json(CommandEnvelope(command="identities.list", data=data))
550
+ return
551
+ for person in data["persons"]:
552
+ if not person["active"]:
553
+ marker = f"merged -> {person['mergedIntoPersonId']}"
554
+ else:
555
+ marker = "confirmed" if person["confirmed"] else "unresolved"
556
+ emit_human(f"{person['name']} <{person['email']}> [{marker}]")
557
+ for alias in person["aliases"]:
558
+ emit_human(f" - {alias['name']} <{alias['email']}> ({alias['source']})")
559
+
560
+
561
+ @identities_app.command("map")
562
+ def identities_map_command(
563
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
564
+ name: Annotated[str, typer.Option("--name", help="Existing Git author name.")] = "",
565
+ email: Annotated[str, typer.Option("--email", help="Existing Git author email.")] = "",
566
+ person_name: Annotated[str, typer.Option("--person-name", help="Canonical person name.")] = "",
567
+ person_email: Annotated[
568
+ str, typer.Option("--person-email", help="Canonical person email.")
569
+ ] = "",
570
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
571
+ ) -> None:
572
+ """Confirm an alias mapping to a canonical person."""
573
+ if not all((name, email, person_name, person_email)):
574
+ raise typer.BadParameter("All identity mapping options are required")
575
+ try:
576
+ data = map_identity(
577
+ path,
578
+ name=name,
579
+ email=email,
580
+ person_name=person_name,
581
+ person_email=person_email,
582
+ )
583
+ except Exception as exc:
584
+ _exit_for_error(exc)
585
+ return
586
+ if json_output:
587
+ emit_json(CommandEnvelope(command="identities.map", data=data))
588
+ return
589
+ person = data["person"]
590
+ emit_human(f"Mapped to {person['name']} <{person['email']}>")
591
+
592
+
593
+ @identities_app.command("merge")
594
+ def identities_merge_command(
595
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
596
+ source: Annotated[
597
+ list[str] | None,
598
+ typer.Option("--source", help="Source person selector. Repeatable."),
599
+ ] = None,
600
+ target: Annotated[str, typer.Option("--target", help="Target person selector.")] = "",
601
+ dry_run: Annotated[
602
+ bool, typer.Option("--dry-run", help="Preview without changing identities.")
603
+ ] = False,
604
+ yes: Annotated[bool, typer.Option("--yes", help="Confirm the merge operation.")] = False,
605
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
606
+ ) -> None:
607
+ """Preview or execute a reversible identity merge."""
608
+ sources = tuple(source or ())
609
+ if not sources or not target:
610
+ raise typer.BadParameter("--source and --target are required")
611
+ if dry_run == yes:
612
+ raise typer.BadParameter("Choose exactly one of --dry-run or --yes")
613
+ try:
614
+ data = (
615
+ preview_identity_merge(path, sources, target)
616
+ if dry_run
617
+ else merge_identities(path, sources, target)
618
+ )
619
+ except Exception as exc:
620
+ _exit_for_error(exc)
621
+ return
622
+ if json_output:
623
+ emit_json(CommandEnvelope(command="identities.merge", data=data))
624
+ return
625
+ action = "preview" if dry_run else f"merge {data['mergeId']}"
626
+ emit_human(
627
+ f"Identity {action}: {len(data['sources'])} source person(s) -> {data['target']['name']}"
628
+ )
629
+
630
+
631
+ @identities_app.command("merges")
632
+ def identities_merges_command(
633
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
634
+ status: Annotated[str, typer.Option("--status", help="ACTIVE, REVERTED, or ALL.")] = "ALL",
635
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
636
+ ) -> None:
637
+ """List reversible identity merge events."""
638
+ normalized_status = status.upper()
639
+ if normalized_status not in {"ACTIVE", "REVERTED", "ALL"}:
640
+ raise typer.BadParameter("--status must be ACTIVE, REVERTED, or ALL")
641
+ try:
642
+ data = list_identity_merges(path, normalized_status)
643
+ except Exception as exc:
644
+ _exit_for_error(exc)
645
+ return
646
+ if json_output:
647
+ emit_json(CommandEnvelope(command="identities.merges", data=data))
648
+ return
649
+ for event in data["merges"]:
650
+ emit_human(f"{event['mergeId']} [{event['status']}] -> {event['targetPersonId']}")
651
+
652
+
653
+ @identities_app.command("unmerge")
654
+ def identities_unmerge_command(
655
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
656
+ merge_id: Annotated[str, typer.Option("--merge-id", help="Merge event ID.")] = "",
657
+ yes: Annotated[bool, typer.Option("--yes", help="Confirm the unmerge operation.")] = False,
658
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
659
+ ) -> None:
660
+ """Reverse an active identity merge event."""
661
+ if not merge_id or not yes:
662
+ raise typer.BadParameter("--merge-id and --yes are required")
663
+ try:
664
+ data = unmerge_identities(path, merge_id)
665
+ except Exception as exc:
666
+ _exit_for_error(exc)
667
+ return
668
+ if json_output:
669
+ emit_json(CommandEnvelope(command="identities.unmerge", data=data))
670
+ return
671
+ emit_human(f"Identity merge {merge_id} reverted")
672
+
673
+
674
+ @runs_app.command("list")
675
+ def runs_list_command(
676
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
677
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
678
+ ) -> None:
679
+ """List persisted analysis runs."""
680
+ try:
681
+ data = list_runs(path)
682
+ except Exception as exc:
683
+ _exit_for_error(exc)
684
+ return
685
+ if json_output:
686
+ emit_json(CommandEnvelope(command="runs.list", data=data))
687
+ return
688
+ for run in data["runs"]:
689
+ emit_human(f"{run['id']} [{run['runType']}/{run['status']}] {run['startedAt']}")
690
+
691
+
692
+ @runs_app.command("compare")
693
+ def runs_compare_command(
694
+ base_run_id: Annotated[str, typer.Argument(help="Baseline work assessment run ID.")],
695
+ target_run_id: Annotated[str, typer.Argument(help="Target work assessment run ID.")],
696
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
697
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
698
+ ) -> None:
699
+ """Compare two persisted work assessment runs."""
700
+ try:
701
+ data = compare_assessment_runs(path, base_run_id, target_run_id)
702
+ except Exception as exc:
703
+ _exit_for_error(exc)
704
+ return
705
+ if json_output:
706
+ emit_json(CommandEnvelope(command="runs.compare", data=data, warnings=data["warnings"]))
707
+ return
708
+ changes = data["changes"]
709
+ emit_human(
710
+ f"Assessment comparison {base_run_id} -> {target_run_id}: "
711
+ f"completed items {changes['completedItems']['absolute']:+d}"
712
+ )
713
+
714
+
715
+ @runs_app.command("show")
716
+ def runs_show_command(
717
+ run_id: Annotated[str, typer.Argument(help="Analysis run ID or 'latest'.")],
718
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
719
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
720
+ ) -> None:
721
+ """Show a persisted completed analysis run."""
722
+ try:
723
+ data = get_run(path, run_id)
724
+ except Exception as exc:
725
+ _exit_for_error(exc)
726
+ return
727
+ if json_output:
728
+ emit_json(CommandEnvelope(command="runs.show", data=data))
729
+ return
730
+ emit_human(f"Run: {data['run']['id']} [{data['run']['status']}]")
731
+ report_type = data.get("reportType")
732
+ if report_type in ("PERSON", "PROJECT"):
733
+ emit_human(f"Commits: {data['summary']['commits']}")
734
+ elif report_type == "WORK_ASSESSMENT":
735
+ emit_human(f"Completed items: {data['workloadSummary']['completedItems']}")
736
+ elif report_type == "WORK_ASSESSMENT_SERIES":
737
+ emit_human(f"Assessment periods: {len(data['periods'])}")
738
+ elif report_type == "RESUME":
739
+ emit_human(f"Resume candidates: {len(data['experienceBullets'])}")
740
+
741
+
742
+ @providers_app.command("list")
743
+ def providers_list_command(
744
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
745
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
746
+ ) -> None:
747
+ """List built-in providers and the repository's selected provider."""
748
+ try:
749
+ data = list_provider_status(path)
750
+ except Exception as exc:
751
+ _exit_for_error(exc)
752
+ return
753
+ if json_output:
754
+ emit_json(CommandEnvelope(command="providers.list", data=data))
755
+ return
756
+ for provider in data["providers"]:
757
+ marker = "selected" if provider["selected"] else "available"
758
+ locality = "local" if provider["localExecution"] else "remote"
759
+ emit_human(f"{provider['id']} [{marker}, {locality}]")
760
+
761
+
762
+ @providers_app.command("test")
763
+ def providers_test_command(
764
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
765
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
766
+ ) -> None:
767
+ """Test the selected provider's configuration and health endpoint."""
768
+ try:
769
+ data = test_provider(path)
770
+ except Exception as exc:
771
+ _exit_for_error(exc)
772
+ return
773
+ healthy = bool(data["healthy"])
774
+ if json_output:
775
+ emit_json(CommandEnvelope(command="providers.test", data=data, success=healthy))
776
+ else:
777
+ emit_human(f"Provider {data['provider']}: {'healthy' if healthy else 'unhealthy'}")
778
+ if not healthy:
779
+ raise typer.Exit(code=ExitCode.PROVIDER_ERROR)
780
+
781
+
782
+ @app.command("report")
783
+ def report_command(
784
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
785
+ run_id: Annotated[str, typer.Option("--run", help="Analysis run ID or 'latest'.")] = "latest",
786
+ report_format: Annotated[
787
+ str, typer.Option("--format", help="Report format: markdown, json, csv, or html.")
788
+ ] = "markdown",
789
+ output: Annotated[
790
+ Path | None, typer.Option("--output", help="Write report to this file.")
791
+ ] = None,
792
+ include_email: Annotated[
793
+ bool, typer.Option("--include-email", help="Include email in CSV output.")
794
+ ] = False,
795
+ ) -> None:
796
+ """Rebuild a Markdown, JSON, or CSV report from a persisted analysis run."""
797
+ try:
798
+ if output is not None:
799
+ exported = export_report(
800
+ path,
801
+ run_id,
802
+ report_format,
803
+ output,
804
+ include_email=include_email,
805
+ overwrite=True,
806
+ )
807
+ emit_human(f"Report written: {exported}")
808
+ return
809
+ rendered = generate_report(path, run_id, report_format, include_email=include_email)
810
+ except Exception as exc:
811
+ _exit_for_error(exc)
812
+ return
813
+ typer.echo(rendered, nl=False)
814
+
815
+
816
+ @app.command("doctor")
817
+ def doctor_command(
818
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
819
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
820
+ ) -> None:
821
+ """Diagnose Git, workspace, database, and lock health."""
822
+ try:
823
+ data = run_doctor(path)
824
+ except Exception as exc:
825
+ _exit_for_error(exc)
826
+ return
827
+ if json_output:
828
+ emit_json(CommandEnvelope(command="doctor", data=data, success=bool(data["healthy"])))
829
+ if not data["healthy"]:
830
+ raise typer.Exit(code=ExitCode.WORKSPACE_ERROR)
831
+ return
832
+ for check in data["checks"]:
833
+ marker = "OK" if check["healthy"] else "FAIL"
834
+ emit_human(f"[{marker}] {check['name']}: {check['detail']}")
835
+ if not data["healthy"]:
836
+ raise typer.Exit(code=ExitCode.WORKSPACE_ERROR)
837
+
838
+
839
+ @structural_app.command("status")
840
+ def structural_status_command(
841
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
842
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
843
+ ) -> None:
844
+ """Show historical structural cache status."""
845
+ try:
846
+ data = get_structural_status(path)
847
+ except Exception as exc:
848
+ _exit_for_error(exc)
849
+ return
850
+ if json_output:
851
+ emit_json(CommandEnvelope(command="structural status", data=data))
852
+ return
853
+ emit_human(
854
+ f"Structural baselines: {data['baselineCount']} "
855
+ f"(processed commits: {data['processedCommits']})"
856
+ )
857
+
858
+
859
+ @structural_app.command("rebuild")
860
+ def structural_rebuild_command(
861
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
862
+ cutoff: Annotated[
863
+ str | None,
864
+ typer.Option("--cutoff", help="Exclusive ISO date/time baseline boundary."),
865
+ ] = None,
866
+ branch: Annotated[str | None, typer.Option("--branch", help="Target branch ref.")] = None,
867
+ scope: Annotated[str | None, typer.Option("--scope", help="Repository path prefix.")] = None,
868
+ time_strategy: Annotated[
869
+ str | None,
870
+ typer.Option(
871
+ "--time-strategy",
872
+ help="Override config: lifetime, rolling-window, or dual-window.",
873
+ ),
874
+ ] = None,
875
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
876
+ ) -> None:
877
+ """Rebuild and persist an immutable structural baseline."""
878
+ try:
879
+ parsed_cutoff = (
880
+ parse_boundary(cutoff, end_of_day=False) if cutoff else default_structural_cutoff()
881
+ )
882
+ if parsed_cutoff is None:
883
+ raise ValueError("cutoff is required")
884
+ strategy = (
885
+ StructuralTimeStrategy(time_strategy.replace("-", "_").upper())
886
+ if time_strategy is not None
887
+ else None
888
+ )
889
+ data = rebuild_structural_baseline(
890
+ path,
891
+ cutoff=parsed_cutoff,
892
+ branch=branch,
893
+ scope=scope,
894
+ time_strategy=strategy,
895
+ )
896
+ except Exception as exc:
897
+ _exit_for_error(exc)
898
+ return
899
+ if json_output:
900
+ emit_json(CommandEnvelope(command="structural rebuild", data=data))
901
+ return
902
+ emit_human(
903
+ f"Structural baseline {data['baselineId']}: "
904
+ f"{data['summary']['eligibleCommits']} commits, "
905
+ f"{data['summary']['rawEdges']} raw edges"
906
+ )
907
+
908
+
909
+ @structural_app.command("show")
910
+ def structural_show_command(
911
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
912
+ baseline_id: Annotated[
913
+ str,
914
+ typer.Option("--baseline", help="Structural baseline ID."),
915
+ ] = "",
916
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
917
+ ) -> None:
918
+ """Show one persisted structural baseline."""
919
+ try:
920
+ if not baseline_id:
921
+ raise ValueError("--baseline is required")
922
+ data = show_structural_baseline(path, baseline_id)
923
+ except Exception as exc:
924
+ _exit_for_error(exc)
925
+ return
926
+ if json_output:
927
+ emit_json(CommandEnvelope(command="structural show", data=data))
928
+ return
929
+ emit_human(json.dumps(data, ensure_ascii=False, indent=2))
930
+
931
+
932
+ @structural_app.command("prune")
933
+ def structural_prune_command(
934
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
935
+ keep: Annotated[int, typer.Option("--keep", min=0, help="Newest baselines to keep.")] = 8,
936
+ yes: Annotated[bool, typer.Option("--yes", help="Confirm cache deletion.")] = False,
937
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
938
+ ) -> None:
939
+ """Delete old rebuildable structural baseline caches."""
940
+ if not yes:
941
+ emit_human("Error: structural prune requires --yes")
942
+ raise typer.Exit(code=ExitCode.INVALID_USAGE)
943
+ try:
944
+ data = prune_structural_baselines(path, keep=keep)
945
+ except Exception as exc:
946
+ _exit_for_error(exc)
947
+ return
948
+ if json_output:
949
+ emit_json(CommandEnvelope(command="structural prune", data=data))
950
+ return
951
+ emit_human(
952
+ f"Deleted structural baselines: {data['deletedBaselines']} "
953
+ f"(remaining: {data['remainingBaselines']})"
954
+ )
955
+
956
+
957
+ def _slug_filename(label: str) -> str:
958
+ cleaned = re.sub(r"[^A-Za-z0-9._-]+", "-", label.strip()).strip("-")
959
+ return cleaned or "report"
960
+
961
+
962
+ @app.command("recap")
963
+ def recap_command(
964
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
965
+ person: Annotated[
966
+ str | None,
967
+ typer.Option(
968
+ "--person",
969
+ help="Person selector (ID, email, or name). Defaults to local git user.email.",
970
+ ),
971
+ ] = None,
972
+ me: Annotated[
973
+ bool,
974
+ typer.Option(
975
+ "--me",
976
+ help="Explicitly resolve identity from local git config user.email/user.name.",
977
+ ),
978
+ ] = False,
979
+ window: Annotated[
980
+ str | None,
981
+ typer.Option(
982
+ "--window",
983
+ help="Shorthand window: today|yesterday|1d|day|7d|14d|30d|week|month|quarter.",
984
+ ),
985
+ ] = None,
986
+ since: Annotated[str | None, typer.Option("--since", help=BOUNDARY_HELP)] = None,
987
+ until: Annotated[str | None, typer.Option("--until", help=BOUNDARY_HELP)] = None,
988
+ branch: Annotated[str | None, typer.Option("--branch", help="Optional branch filter.")] = None,
989
+ auto_sync: Annotated[
990
+ bool,
991
+ typer.Option(
992
+ "--auto-sync/--no-auto-sync",
993
+ help="Automatically initialize or incrementally sync the local .gca index.",
994
+ ),
995
+ ] = True,
996
+ language: Annotated[
997
+ str,
998
+ typer.Option("--language", help="Markdown/HTML language: zh-CN|en-US."),
999
+ ] = "zh-CN",
1000
+ report_format: Annotated[
1001
+ str | None,
1002
+ typer.Option("--format", help="Output format: markdown|json|html."),
1003
+ ] = None,
1004
+ output: Annotated[
1005
+ Path | None,
1006
+ typer.Option("--output", help="Optional path to write rendered recap."),
1007
+ ] = None,
1008
+ open_browser: Annotated[
1009
+ bool,
1010
+ typer.Option(
1011
+ "--open",
1012
+ help="Render self-contained HTML and open it in the default browser.",
1013
+ ),
1014
+ ] = False,
1015
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
1016
+ ) -> None:
1017
+ """Generate a deterministic daily/weekly/monthly/quarterly recap for one repository."""
1018
+ try:
1019
+ if me and person:
1020
+ raise ConfigurationError("Pass either --person or --me, not both")
1021
+ fmt = (report_format or ("html" if open_browser else "markdown")).lower()
1022
+ if fmt not in {"json", "markdown", "html"}:
1023
+ raise ConfigurationError(f"Unsupported format: {report_format}")
1024
+ if open_browser and fmt != "html":
1025
+ raise ConfigurationError("--open is only supported with --format html")
1026
+ since_dt, until_dt = parse_boundaries(since, until)
1027
+ data = generate_recap(
1028
+ path,
1029
+ person_selector=None if me else person,
1030
+ window=window,
1031
+ since=since_dt,
1032
+ until=until_dt,
1033
+ branch=branch,
1034
+ auto_sync=auto_sync,
1035
+ )
1036
+ if fmt == "json":
1037
+ rendered = json.dumps(data["report"], ensure_ascii=False, indent=2) + "\n"
1038
+ elif fmt == "markdown":
1039
+ rendered = render_recap_markdown(data["report"], language=language)
1040
+ else:
1041
+ rendered = render_html_report(data["report"], language=language)
1042
+
1043
+ resolved_output = output
1044
+ if open_browser and resolved_output is None:
1045
+ repository = discover_repository(path)
1046
+ layout = WorkspaceLayout.for_repository(repository.root)
1047
+ layout.reports.mkdir(parents=True, exist_ok=True)
1048
+ label_slug = _slug_filename(str(data["report"]["window"]["label"]))
1049
+ resolved_output = layout.reports / f"recap-{label_slug}.html"
1050
+
1051
+ if resolved_output is not None:
1052
+ resolved_output.parent.mkdir(parents=True, exist_ok=True)
1053
+ resolved_output.write_text(rendered, encoding="utf-8", newline="\n")
1054
+ if open_browser and resolved_output is not None:
1055
+ webbrowser.open(resolved_output.resolve().as_uri())
1056
+ except Exception as exc:
1057
+ _exit_for_error(exc)
1058
+ return
1059
+
1060
+ if json_output:
1061
+ emit_json(CommandEnvelope(command="recap", data=data))
1062
+ return
1063
+ if resolved_output is not None:
1064
+ totals = data["report"]["totals"]
1065
+ emit_human(
1066
+ f"Recap ({data['report']['window']['label']}) written to {resolved_output}: "
1067
+ f"{totals['commits']} commits, {totals['completedItems']} completed, "
1068
+ f"{totals['pendingItems']} pending."
1069
+ )
1070
+ return
1071
+ typer.echo(rendered, nl=False)
1072
+
1073
+
1074
+ @app.command("serve")
1075
+ def serve_command(
1076
+ mcp: Annotated[
1077
+ bool,
1078
+ typer.Option("--mcp", help="Run the read-only stdio MCP JSON-RPC 2.0 server."),
1079
+ ] = False,
1080
+ workspace: Annotated[
1081
+ list[Path] | None,
1082
+ typer.Option(
1083
+ "--workspace",
1084
+ help="Repeatable allowed workspace root directory for read-only MCP access.",
1085
+ ),
1086
+ ] = None,
1087
+ ) -> None:
1088
+ """Start the local read-only MCP stdio server for AI coding agents."""
1089
+ try:
1090
+ if not mcp:
1091
+ raise ConfigurationError("Pass --mcp to start the read-only MCP stdio server")
1092
+ roots = tuple(workspace) if workspace else (Path.cwd(),)
1093
+ resolved_roots: list[Path] = []
1094
+ for root in roots:
1095
+ resolved = root.expanduser().resolve()
1096
+ if not resolved.is_dir():
1097
+ raise ConfigurationError(f"Workspace root does not exist: {root}")
1098
+ resolved_roots.append(resolved)
1099
+ except Exception as exc:
1100
+ _exit_for_error(exc)
1101
+ return
1102
+ exit_code = run_stdio_server(tuple(resolved_roots))
1103
+ if exit_code != 0:
1104
+ raise typer.Exit(code=exit_code)
1105
+
1106
+
1107
+ @app.command("install-agent")
1108
+ def install_agent_command(
1109
+ target: Annotated[
1110
+ str | None,
1111
+ typer.Option(
1112
+ "--target",
1113
+ help=f"Target AI agent client: {'|'.join(SUPPORTED_AGENT_TARGETS)}.",
1114
+ ),
1115
+ ] = None,
1116
+ workspace: Annotated[
1117
+ list[Path] | None,
1118
+ typer.Option(
1119
+ "--workspace",
1120
+ help="Repeatable workspace directory to authorize for GCA MCP access.",
1121
+ ),
1122
+ ] = None,
1123
+ command: Annotated[
1124
+ str,
1125
+ typer.Option("--command", help="Executable name or path used to launch GCA."),
1126
+ ] = "gca",
1127
+ config_path: Annotated[
1128
+ Path | None,
1129
+ typer.Option("--config-path", help="Optional custom MCP config file path."),
1130
+ ] = None,
1131
+ apply: Annotated[
1132
+ bool,
1133
+ typer.Option(
1134
+ "--apply",
1135
+ help="Write and merge into the target config file (with automatic backup).",
1136
+ ),
1137
+ ] = False,
1138
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
1139
+ ) -> None:
1140
+ """Preview (dry-run by default) or apply GCA MCP config for AI coding agents."""
1141
+ try:
1142
+ if not target:
1143
+ raise ConfigurationError("--target is required")
1144
+ roots = tuple(workspace) if workspace else (Path.cwd(),)
1145
+ result = install_agent_mcp_config(
1146
+ target=target,
1147
+ workspaces=roots,
1148
+ command=command,
1149
+ config_path=config_path,
1150
+ apply=apply,
1151
+ )
1152
+ except Exception as exc:
1153
+ _exit_for_error(exc)
1154
+ return
1155
+
1156
+ if json_output:
1157
+ emit_json(CommandEnvelope(command="install-agent", data=result.to_dict()))
1158
+ return
1159
+ if result.applied:
1160
+ backup_note = f" (backup: {result.backup_path})" if result.backup_path else ""
1161
+ emit_human(
1162
+ f"Applied GCA MCP config for '{result.target}' to {result.config_path}{backup_note}."
1163
+ )
1164
+ return
1165
+ emit_human(
1166
+ f"# Dry-run preview for '{result.target}' ({result.config_path})\n"
1167
+ f"# Re-run with --apply to write this configuration.\n\n"
1168
+ f"{result.snippet}"
1169
+ )
1170
+
1171
+
1172
+ @outcome_app.command("list")
1173
+ def outcome_list_command(
1174
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
1175
+ file: Annotated[
1176
+ Path | None,
1177
+ typer.Option("--file", help="Optional custom outcomes YAML file path."),
1178
+ ] = None,
1179
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
1180
+ ) -> None:
1181
+ """List verified outcomes stored in the local repository or portfolio ledger."""
1182
+ try:
1183
+ data = list_outcomes(path, outcomes_file=file)
1184
+ except Exception as exc:
1185
+ _exit_for_error(exc)
1186
+ return
1187
+ if json_output:
1188
+ emit_json(CommandEnvelope(command="outcome list", data=data))
1189
+ return
1190
+ if not data["outcomes"]:
1191
+ emit_human(f"No verified outcomes recorded ({data['file']}).")
1192
+ return
1193
+ for item in data["outcomes"]:
1194
+ evs = f" [{', '.join(item['evidenceIds'])}]" if item["evidenceIds"] else ""
1195
+ emit_human(
1196
+ f"{item['id']} ({item['verifiedAt']}, {item['verifiedBy']}): {item['text']}{evs}"
1197
+ )
1198
+
1199
+
1200
+ @outcome_app.command("add")
1201
+ def outcome_add_command(
1202
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
1203
+ text: Annotated[str, typer.Option("--text", help="Verified outcome description.")] = "",
1204
+ source: Annotated[str, typer.Option("--source", help="Supporting document/link/report.")] = "",
1205
+ verified_by: Annotated[
1206
+ str,
1207
+ typer.Option("--verified-by", help="Reviewer/system who verified the metric."),
1208
+ ] = "",
1209
+ verified_at: Annotated[
1210
+ str | None,
1211
+ typer.Option("--verified-at", help="ISO date YYYY-MM-DD (defaults to today)."),
1212
+ ] = None,
1213
+ kind: Annotated[
1214
+ str,
1215
+ typer.Option("--kind", help="Outcome kind (default: OUTCOME)."),
1216
+ ] = "OUTCOME",
1217
+ outcome_id: Annotated[
1218
+ str | None,
1219
+ typer.Option("--id", help="Optional explicit ID (defaults to next OUT-xxx)."),
1220
+ ] = None,
1221
+ evidence: Annotated[
1222
+ list[str] | None,
1223
+ typer.Option("--evidence", help="Repeatable EV-xxx or <repoKey>:EV-xxx ID to link."),
1224
+ ] = None,
1225
+ tag: Annotated[
1226
+ list[str] | None,
1227
+ typer.Option("--tag", help="Repeatable category tag (e.g. performance, reliability)."),
1228
+ ] = None,
1229
+ verify_evidence: Annotated[
1230
+ bool,
1231
+ typer.Option(
1232
+ "--verify-evidence/--no-verify-evidence",
1233
+ help="Verify linked evidence IDs exist in persisted GCA runs.",
1234
+ ),
1235
+ ] = True,
1236
+ file: Annotated[
1237
+ Path | None,
1238
+ typer.Option("--file", help="Optional custom outcomes YAML file path."),
1239
+ ] = None,
1240
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
1241
+ ) -> None:
1242
+ """Record a verified business or engineering outcome linked to GCA evidence."""
1243
+ try:
1244
+ parsed_date = date.fromisoformat(verified_at) if verified_at else None
1245
+ data = add_outcome(
1246
+ path,
1247
+ text=text,
1248
+ source=source,
1249
+ verified_by=verified_by,
1250
+ verified_at=parsed_date,
1251
+ kind=kind,
1252
+ outcome_id=outcome_id,
1253
+ evidence_ids=tuple(evidence or ()),
1254
+ tags=tuple(tag or ()),
1255
+ verify_evidence=verify_evidence,
1256
+ outcomes_file=file,
1257
+ )
1258
+ except Exception as exc:
1259
+ _exit_for_error(exc)
1260
+ return
1261
+ if json_output:
1262
+ emit_json(CommandEnvelope(command="outcome add", data=data))
1263
+ return
1264
+ added = data["outcome"]
1265
+ emit_human(
1266
+ f"Saved outcome {added['id']} to {data['file']} (total: {data['totalOutcomes']})."
1267
+ )
1268
+
1269
+
1270
+ @outcome_app.command("remove")
1271
+ def outcome_remove_command(
1272
+ outcome_id: Annotated[str, typer.Argument(help="Outcome ID to remove (e.g. OUT-001).")],
1273
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
1274
+ file: Annotated[
1275
+ Path | None,
1276
+ typer.Option("--file", help="Optional custom outcomes YAML file path."),
1277
+ ] = None,
1278
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
1279
+ ) -> None:
1280
+ """Remove a verified outcome by ID from the local ledger."""
1281
+ try:
1282
+ data = remove_outcome(path, outcome_id=outcome_id, outcomes_file=file)
1283
+ except Exception as exc:
1284
+ _exit_for_error(exc)
1285
+ return
1286
+ if json_output:
1287
+ emit_json(CommandEnvelope(command="outcome remove", data=data))
1288
+ return
1289
+ emit_human(
1290
+ f"Removed outcome {data['removedId']} from {data['file']} "
1291
+ f"(remaining: {data['remainingOutcomes']})."
1292
+ )
1293
+
1294
+
1295
+ @app.command("brag")
1296
+ def brag_command(
1297
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
1298
+ person: Annotated[
1299
+ str | None,
1300
+ typer.Option(
1301
+ "--person",
1302
+ help="Person selector (defaults to local git user.email).",
1303
+ ),
1304
+ ] = None,
1305
+ me: Annotated[
1306
+ bool,
1307
+ typer.Option("--me", help="Explicitly resolve identity from local git config."),
1308
+ ] = False,
1309
+ year: Annotated[int | None, typer.Option("--year", help="Calendar year (e.g. 2026).")] = None,
1310
+ quarter: Annotated[
1311
+ str | None,
1312
+ typer.Option("--quarter", help="Calendar quarter (e.g. 2026-Q3)."),
1313
+ ] = None,
1314
+ since: Annotated[str | None, typer.Option("--since", help=BOUNDARY_HELP)] = None,
1315
+ until: Annotated[str | None, typer.Option("--until", help=BOUNDARY_HELP)] = None,
1316
+ branch: Annotated[str | None, typer.Option("--branch", help="Optional branch filter.")] = None,
1317
+ outcomes_file: Annotated[
1318
+ Path | None,
1319
+ typer.Option(
1320
+ "--outcomes",
1321
+ help="Optional outcomes YAML file (defaults to .gca/outcomes.yml).",
1322
+ ),
1323
+ ] = None,
1324
+ auto_sync: Annotated[
1325
+ bool,
1326
+ typer.Option(
1327
+ "--auto-sync/--no-auto-sync",
1328
+ help="Automatically initialize or incrementally sync the local .gca index.",
1329
+ ),
1330
+ ] = True,
1331
+ language: Annotated[
1332
+ str,
1333
+ typer.Option("--language", help="Output language: zh-CN|en-US."),
1334
+ ] = "zh-CN",
1335
+ report_format: Annotated[
1336
+ str | None,
1337
+ typer.Option("--format", help="Output format: markdown|json|html."),
1338
+ ] = None,
1339
+ output: Annotated[
1340
+ Path | None,
1341
+ typer.Option("--output", help="Optional path to write rendered brag document."),
1342
+ ] = None,
1343
+ open_browser: Annotated[
1344
+ bool,
1345
+ typer.Option("--open", help="Render self-contained HTML and open it in the browser."),
1346
+ ] = False,
1347
+ json_output: Annotated[bool, typer.Option("--json", help="Output versioned JSON.")] = False,
1348
+ ) -> None:
1349
+ """Generate an evidence-backed annual/quarterly Brag Document for one repository."""
1350
+ try:
1351
+ if me and person:
1352
+ raise ConfigurationError("Pass either --person or --me, not both")
1353
+ fmt = (report_format or ("html" if open_browser else "markdown")).lower()
1354
+ if fmt not in {"json", "markdown", "html"}:
1355
+ raise ConfigurationError(f"Unsupported format: {report_format}")
1356
+ if open_browser and fmt != "html":
1357
+ raise ConfigurationError("--open is only supported with --format html")
1358
+ since_dt, until_dt = parse_boundaries(since, until)
1359
+ data = generate_brag(
1360
+ path,
1361
+ person_selector=None if me else person,
1362
+ year=year,
1363
+ quarter=quarter,
1364
+ since=since_dt,
1365
+ until=until_dt,
1366
+ branch=branch,
1367
+ outcomes_file=outcomes_file,
1368
+ auto_sync=auto_sync,
1369
+ )
1370
+ if fmt == "json":
1371
+ rendered = json.dumps(data["report"], ensure_ascii=False, indent=2) + "\n"
1372
+ elif fmt == "markdown":
1373
+ rendered = render_brag_markdown(data["report"], language=language)
1374
+ else:
1375
+ rendered = render_html_report(data["report"], language=language)
1376
+
1377
+ resolved_output = output
1378
+ if open_browser and resolved_output is None:
1379
+ repository = discover_repository(path)
1380
+ layout = WorkspaceLayout.for_repository(repository.root)
1381
+ layout.reports.mkdir(parents=True, exist_ok=True)
1382
+ label_slug = _slug_filename(str(data["report"]["period"]["label"]))
1383
+ resolved_output = layout.reports / f"brag-{label_slug}.html"
1384
+
1385
+ if resolved_output is not None:
1386
+ resolved_output.parent.mkdir(parents=True, exist_ok=True)
1387
+ resolved_output.write_text(rendered, encoding="utf-8", newline="\n")
1388
+ if open_browser and resolved_output is not None:
1389
+ webbrowser.open(resolved_output.resolve().as_uri())
1390
+ except Exception as exc:
1391
+ _exit_for_error(exc)
1392
+ return
1393
+
1394
+ if json_output:
1395
+ emit_json(CommandEnvelope(command="brag", data=data))
1396
+ return
1397
+ if resolved_output is not None:
1398
+ summary = data["report"]["summary"]
1399
+ emit_human(
1400
+ f"Brag document ({data['report']['period']['label']}) written to {resolved_output}: "
1401
+ f"{summary['completedItems']} completed items, {summary['verifiedOutcomes']} outcomes."
1402
+ )
1403
+ return
1404
+ typer.echo(rendered, nl=False)
1405
+
1406
+
1407
+ @app.command("uninit")
1408
+ def uninit_command(
1409
+ path: Annotated[Path, typer.Argument(exists=True, file_okay=False)] = Path("."),
1410
+ yes: Annotated[
1411
+ bool, typer.Option("--yes", help="Delete without interactive confirmation.")
1412
+ ] = False,
1413
+ ) -> None:
1414
+ """Remove the repository-local GCA workspace."""
1415
+ if not yes and not typer.confirm("Remove the .gca workspace?"):
1416
+ raise typer.Abort()
1417
+ try:
1418
+ removed = uninit_project(path)
1419
+ except Exception as exc:
1420
+ _exit_for_error(exc)
1421
+ return
1422
+ emit_human("Removed GCA workspace." if removed else "GCA workspace was not initialized.")
1423
+
1424
+
1425
+ def main() -> None:
1426
+ app()
1427
+
1428
+
1429
+ if __name__ == "__main__":
1430
+ main()