intentumdiff-python 0.0.1__py3-none-win_arm64.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 (165) hide show
  1. intentumdiff/__init__.py +134 -0
  2. intentumdiff/_differ_gate.py +210 -0
  3. intentumdiff/_differ_presentation.py +786 -0
  4. intentumdiff/_differ_runtime.py +320 -0
  5. intentumdiff/analysis/__init__.py +1 -0
  6. intentumdiff/analysis/compile_commands.py +151 -0
  7. intentumdiff/analysis/cross_file.py +71 -0
  8. intentumdiff/analysis/diagnostics.py +309 -0
  9. intentumdiff/analysis/guardrail_reports.py +254 -0
  10. intentumdiff/analysis/guardrails.py +318 -0
  11. intentumdiff/analysis/invariances.py +1207 -0
  12. intentumdiff/analysis/keyed_profiles.py +25 -0
  13. intentumdiff/analysis/resource_profiles.py +14 -0
  14. intentumdiff/analysis/schema_resolver.py +816 -0
  15. intentumdiff/analysis/text_review.py +46 -0
  16. intentumdiff/analysis/user_schemas.py +430 -0
  17. intentumdiff/assets.py +45 -0
  18. intentumdiff/cache/__init__.py +37 -0
  19. intentumdiff/cache/duckdb_store.py +98 -0
  20. intentumdiff/cache/sqlite_store.py +149 -0
  21. intentumdiff/cache/store.py +190 -0
  22. intentumdiff/cli/__init__.py +199 -0
  23. intentumdiff/cli/_commands.py +2141 -0
  24. intentumdiff/cli/_parser.py +1061 -0
  25. intentumdiff/cli/_shared.py +644 -0
  26. intentumdiff/content_type.py +59 -0
  27. intentumdiff/core/__init__.py +1 -0
  28. intentumdiff/core/commit_differ.py +599 -0
  29. intentumdiff/core/config.py +51 -0
  30. intentumdiff/core/cst_serializer.py +101 -0
  31. intentumdiff/core/diffignore.py +87 -0
  32. intentumdiff/core/index.py +189 -0
  33. intentumdiff/core/indexer.py +792 -0
  34. intentumdiff/core/models.py +837 -0
  35. intentumdiff/differ.py +2195 -0
  36. intentumdiff/github_app.py +287 -0
  37. intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
  38. intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
  39. intentumdiff/intentumdiff_rust_core/intentumdiff_rust_core.dll +0 -0
  40. intentumdiff/invariances/__init__.py +2 -0
  41. intentumdiff/invariances/rules.schema.json +283 -0
  42. intentumdiff/invariances/rules.yaml +349 -0
  43. intentumdiff/live_server.py +1314 -0
  44. intentumdiff/lsp/__init__.py +67 -0
  45. intentumdiff/lsp/client.py +544 -0
  46. intentumdiff/lsp/config.py +96 -0
  47. intentumdiff/lsp/enricher.py +227 -0
  48. intentumdiff/lsp/exceptions.py +27 -0
  49. intentumdiff/lsp/launcher.py +273 -0
  50. intentumdiff/lsp/servers.py +356 -0
  51. intentumdiff/lsp_server/__init__.py +14 -0
  52. intentumdiff/lsp_server/_codelens.py +67 -0
  53. intentumdiff/lsp_server/_diagnostics.py +62 -0
  54. intentumdiff/lsp_server/_handlers.py +175 -0
  55. intentumdiff/lsp_server/server.py +205 -0
  56. intentumdiff/plugins/__init__.py +1 -0
  57. intentumdiff/plugins/adapter.py +397 -0
  58. intentumdiff/plugins/builtins.py +323 -0
  59. intentumdiff/plugins/exceptions.py +93 -0
  60. intentumdiff/plugins/hub.py +1155 -0
  61. intentumdiff/plugins/language_metadata.py +250 -0
  62. intentumdiff/plugins/loader.py +1252 -0
  63. intentumdiff/plugins/registry.py +1079 -0
  64. intentumdiff/plugins/registry.schema.json +99 -0
  65. intentumdiff/plugins/registry_schema.py +280 -0
  66. intentumdiff/plugins/wit/plugin.wit +351 -0
  67. intentumdiff/rust_core.py +2370 -0
  68. intentumdiff/serve/__init__.py +19 -0
  69. intentumdiff/serve/_app.py +485 -0
  70. intentumdiff/serve/_static/index.html +326 -0
  71. intentumdiff/serve/_static/playground.js +567 -0
  72. intentumdiff/sources/__init__.py +1 -0
  73. intentumdiff/sources/base.py +28 -0
  74. intentumdiff/sources/file_source.py +48 -0
  75. intentumdiff/sources/git_source.py +375 -0
  76. intentumdiff/sources/live_buffer_source.py +113 -0
  77. intentumdiff/sources/patch_source.py +126 -0
  78. intentumdiff/sources/string_source.py +44 -0
  79. intentumdiff/testing.py +165 -0
  80. intentumdiff/vcs/__init__.py +37 -0
  81. intentumdiff/vcs/_safe_path.py +50 -0
  82. intentumdiff/vcs/base.py +136 -0
  83. intentumdiff/vcs/git_backend.py +97 -0
  84. intentumdiff/vcs/git_cli.py +100 -0
  85. intentumdiff/vcs/hg_backend.py +94 -0
  86. intentumdiff/vcs/perforce_backend.py +109 -0
  87. intentumdiff/vcs/svn_backend.py +105 -0
  88. intentumdiff/wasm/.gitkeep +2 -0
  89. intentumdiff/wasm/abap_parser.wasm +0 -0
  90. intentumdiff/wasm/adf_parser.wasm +0 -0
  91. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  92. intentumdiff/wasm/asm_parser.wasm +0 -0
  93. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  94. intentumdiff/wasm/astro_parser.wasm +0 -0
  95. intentumdiff/wasm/bash_parser.wasm +0 -0
  96. intentumdiff/wasm/clojure_parser.wasm +0 -0
  97. intentumdiff/wasm/cmake_parser.wasm +0 -0
  98. intentumdiff/wasm/cpp_parser.wasm +0 -0
  99. intentumdiff/wasm/csharp_parser.wasm +0 -0
  100. intentumdiff/wasm/css_parser.wasm +0 -0
  101. intentumdiff/wasm/dart_parser.wasm +0 -0
  102. intentumdiff/wasm/databricks_parser.wasm +0 -0
  103. intentumdiff/wasm/dax_parser.wasm +0 -0
  104. intentumdiff/wasm/delphi_parser.wasm +0 -0
  105. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  106. intentumdiff/wasm/elixir_parser.wasm +0 -0
  107. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  108. intentumdiff/wasm/generic_parser.wasm +0 -0
  109. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  110. intentumdiff/wasm/go_parser.wasm +0 -0
  111. intentumdiff/wasm/gomod_parser.wasm +0 -0
  112. intentumdiff/wasm/graphql_parser.wasm +0 -0
  113. intentumdiff/wasm/groovy_parser.wasm +0 -0
  114. intentumdiff/wasm/haskell_parser.wasm +0 -0
  115. intentumdiff/wasm/html_parser.wasm +0 -0
  116. intentumdiff/wasm/ini_parser.wasm +0 -0
  117. intentumdiff/wasm/java_parser.wasm +0 -0
  118. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  119. intentumdiff/wasm/json_parser.wasm +0 -0
  120. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  121. intentumdiff/wasm/latex_parser.wasm +0 -0
  122. intentumdiff/wasm/lua_parser.wasm +0 -0
  123. intentumdiff/wasm/make_parser.wasm +0 -0
  124. intentumdiff/wasm/markdown_parser.wasm +0 -0
  125. intentumdiff/wasm/mdx_parser.wasm +0 -0
  126. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  127. intentumdiff/wasm/odin_parser.wasm +0 -0
  128. intentumdiff/wasm/parser_manifest.json +590 -0
  129. intentumdiff/wasm/perl_parser.wasm +0 -0
  130. intentumdiff/wasm/php_parser.wasm +0 -0
  131. intentumdiff/wasm/plsql_parser.wasm +0 -0
  132. intentumdiff/wasm/po_parser.wasm +0 -0
  133. intentumdiff/wasm/postscript_parser.wasm +0 -0
  134. intentumdiff/wasm/powershell_parser.wasm +0 -0
  135. intentumdiff/wasm/proto_parser.wasm +0 -0
  136. intentumdiff/wasm/puppet_parser.wasm +0 -0
  137. intentumdiff/wasm/python_parser.wasm +0 -0
  138. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  139. intentumdiff/wasm/r_parser.wasm +0 -0
  140. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  141. intentumdiff/wasm/ruby_parser.wasm +0 -0
  142. intentumdiff/wasm/rust_parser.wasm +0 -0
  143. intentumdiff/wasm/sas_parser.wasm +0 -0
  144. intentumdiff/wasm/scala_parser.wasm +0 -0
  145. intentumdiff/wasm/scss_parser.wasm +0 -0
  146. intentumdiff/wasm/sql_parser.wasm +0 -0
  147. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  148. intentumdiff/wasm/svelte_parser.wasm +0 -0
  149. intentumdiff/wasm/swift_parser.wasm +0 -0
  150. intentumdiff/wasm/terraform_parser.wasm +0 -0
  151. intentumdiff/wasm/toml_parser.wasm +0 -0
  152. intentumdiff/wasm/tsql_parser.wasm +0 -0
  153. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  154. intentumdiff/wasm/vue_parser.wasm +0 -0
  155. intentumdiff/wasm/wat_parser.wasm +0 -0
  156. intentumdiff/wasm/xml_parser.wasm +0 -0
  157. intentumdiff/wasm/yaml_parser.wasm +0 -0
  158. intentumdiff/wasm/zig_parser.wasm +0 -0
  159. intentumdiff/watcher.py +259 -0
  160. intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
  161. intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
  162. intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
  163. intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
  164. intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
  165. intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
@@ -0,0 +1,2141 @@
1
+ """
2
+ intentumdiff.cli
3
+ ~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Command-line interface for IntentumDiff.
6
+
7
+ Usage
8
+ -----
9
+ intentumdiff git <repo> <file> [--old REF] [--new REF] [--format FORMAT] [--output FILE]
10
+ intentumdiff file <old-file> <new-file> [--format FORMAT] [--output FILE]
11
+ intentumdiff patch [PATCH_FILE] [--base BASE_FILE]
12
+ intentumdiff string <old> <new> [--lang LANG]
13
+ intentumdiff plugins List installed parser and renderer plugins
14
+
15
+ Formats: terminal (default), terminal-color, json, patch, html, llm
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import shlex
23
+ import sys
24
+ import time
25
+ from contextlib import suppress
26
+ from pathlib import Path
27
+ from typing import TYPE_CHECKING, Any
28
+
29
+ try: # rich-click is a runtime dependency, but this fallback keeps source-tree tests robust.
30
+ import rich_click as click
31
+ _CLICK_RUNTIME_AVAILABLE = True
32
+ except ModuleNotFoundError: # pragma: no cover - exercised only in minimal dev envs.
33
+ _CLICK_RUNTIME_AVAILABLE = False
34
+ click = None # type: ignore[assignment]
35
+
36
+ from rich.panel import Panel
37
+ from rich.table import Table
38
+
39
+ from intentumdiff import (
40
+ FileSource,
41
+ GitSource,
42
+ PatchSource,
43
+ SemanticDiff,
44
+ SemanticDiffer,
45
+ WorkingTreeSource,
46
+ )
47
+ from intentumdiff.analysis.guardrail_reports import (
48
+ render_guardrail_annotations,
49
+ render_guardrail_json,
50
+ render_guardrail_sarif,
51
+ render_guardrail_terminal,
52
+ )
53
+ from intentumdiff.cli._shared import ( # noqa: F401
54
+ _asset_options_from_args,
55
+ _console,
56
+ _differ,
57
+ _emit_asset_payload,
58
+ _emit_guardrail_reports,
59
+ _err,
60
+ _exit_if_guardrail_result_fails,
61
+ _guardrail_result,
62
+ _json_default,
63
+ _load_cli_config,
64
+ _parse_fuel,
65
+ _record_diagnostics_db,
66
+ _render,
67
+ _render_with_profile,
68
+ _resolve_repo_root,
69
+ _warn_if_unlimited_fuel,
70
+ _write_output,
71
+ )
72
+
73
+
74
+ def _cmd_assets_diff(args: argparse.Namespace) -> None:
75
+ from intentumdiff.assets import diff_image_assets
76
+
77
+ result = diff_image_assets(
78
+ before_path=args.before,
79
+ after_path=args.after,
80
+ out_dir=args.out,
81
+ options=_asset_options_from_args(args),
82
+ )
83
+ _emit_asset_payload(result, json_output=args.json)
84
+
85
+
86
+ def _cmd_assets_git(args: argparse.Namespace) -> None:
87
+ from intentumdiff.assets import diff_git_assets
88
+
89
+ repo_path = args.repo
90
+ new_ref: str = args.head
91
+ if getattr(args, "staged", False):
92
+ new_ref = ":staged"
93
+ elif getattr(args, "unpushed", False):
94
+ new_ref = ":unpushed"
95
+ old_ref: str = args.base
96
+ if old_ref is None:
97
+ old_ref = "HEAD" if not new_ref or new_ref in {":staged", ":unpushed"} else "HEAD~1"
98
+
99
+ payload = diff_git_assets(
100
+ repo_path=repo_path,
101
+ base=old_ref,
102
+ head=new_ref,
103
+ out_dir=args.out,
104
+ options=_asset_options_from_args(args),
105
+ )
106
+ _emit_asset_payload(payload, json_output=args.json)
107
+
108
+
109
+ def _cmd_git(args: argparse.Namespace) -> None:
110
+ from intentumdiff.sources.git_source import _REF_STAGED, _REF_UNPUSHED
111
+ from intentumdiff.vcs.git_cli import NotAGitRepositoryError
112
+
113
+ repo_path = args.repo # '.' when not supplied
114
+
115
+ # Resolve the effective new_ref from mutually-exclusive scope flags.
116
+ new_ref: str = args.new # may be "", ":staged", ":unpushed", or an explicit ref
117
+ if getattr(args, "staged", False):
118
+ new_ref = _REF_STAGED
119
+ elif getattr(args, "unpushed", False):
120
+ new_ref = _REF_UNPUSHED
121
+
122
+ # Resolve the effective new_ref from mutually-exclusive scope flags.
123
+ new_ref: str = args.new # may be "", ":staged", ":unpushed", or an explicit ref
124
+ if getattr(args, "staged", False):
125
+ new_ref = _REF_STAGED
126
+ elif getattr(args, "unpushed", False):
127
+ new_ref = _REF_UNPUSHED
128
+
129
+ # Smart --old default: HEAD for working-tree / scoped modes; HEAD~1 when an
130
+ # explicit commit ref is given for --new so that `intentumdiff git --new HEAD`
131
+ # means "show the last commit" rather than HEAD vs HEAD = no diff.
132
+ _is_working_tree_mode = not new_ref or new_ref in (_REF_STAGED, _REF_UNPUSHED)
133
+ old_ref: str = args.old if args.old is not None else (
134
+ "HEAD" if _is_working_tree_mode else "HEAD~1"
135
+ )
136
+
137
+ try:
138
+ if args.file:
139
+ # Single-file mode — pick the appropriate Source based on scope.
140
+ if not new_ref:
141
+ source: object = WorkingTreeSource(
142
+ repo_path=repo_path,
143
+ file_path=args.file,
144
+ ref=old_ref,
145
+ )
146
+ elif new_ref == _REF_STAGED:
147
+ # Staged single-file: use WorkingTreeSource pointing at the index.
148
+ # WorkingTreeSource reads the committed version for old_content and
149
+ # the on-disk file for new_content — for staged-only accuracy the
150
+ # user should rely on commit-wide mode or pass an explicit --new ref.
151
+ source = WorkingTreeSource(
152
+ repo_path=repo_path,
153
+ file_path=args.file,
154
+ ref=old_ref,
155
+ )
156
+ else:
157
+ source = GitSource(
158
+ repo_path=repo_path,
159
+ file_path=args.file,
160
+ old_ref=old_ref,
161
+ new_ref=new_ref,
162
+ )
163
+ differ = _differ(
164
+ args.fuel,
165
+ args.resolve_references,
166
+ diagnostics=getattr(args, "diagnostics", False),
167
+ profile_phases=getattr(args, "profile_phases", False),
168
+ guardrails_strict=getattr(args, "guardrails_strict", False),
169
+ config_start_path=repo_path,
170
+ guardrails_policy=getattr(args, "guardrails_policy", None),
171
+ )
172
+ diff = differ.diff(source)
173
+ _render_with_profile(diff, args, fuel=differ._config.plugin_fuel)
174
+ result = _emit_guardrail_reports(diff, args)
175
+ _record_diagnostics_db(diff, args)
176
+ _exit_if_guardrail_result_fails(result)
177
+ else:
178
+ # Commit-wide mode — diff every changed file
179
+ differ = _differ(
180
+ args.fuel,
181
+ args.resolve_references,
182
+ parallel=args.parallel,
183
+ diagnostics=getattr(args, "diagnostics", False),
184
+ profile_phases=getattr(args, "profile_phases", False),
185
+ guardrails_strict=getattr(args, "guardrails_strict", False),
186
+ config_start_path=repo_path,
187
+ guardrails_policy=getattr(args, "guardrails_policy", None),
188
+ )
189
+ diffs = differ.diff_commit(
190
+ repo_path=repo_path,
191
+ old_ref=old_ref,
192
+ new_ref=new_ref,
193
+ )
194
+ if not diffs:
195
+ _console.print("[green]No parseable changes found.[/green]")
196
+ return
197
+ for diff in diffs:
198
+ if args.format == "terminal" and not args.output:
199
+ label = diff.staging_status or ""
200
+ rule_title = diff.new_filename or diff.old_filename
201
+ if label:
202
+ rule_title = f"{rule_title} [{label}]"
203
+ _console.rule(rule_title)
204
+ _render_with_profile(diff, args, fuel=differ._config.plugin_fuel)
205
+ result = _emit_guardrail_reports(diffs, args)
206
+ _record_diagnostics_db(diffs, args)
207
+ _exit_if_guardrail_result_fails(result)
208
+ except NotAGitRepositoryError:
209
+ # Distinguish a missing path (often a mistyped ref) from a real directory
210
+ # that isn't a git repo — preserving the two GitPython-era messages + hint.
211
+ if repo_path != "." and not Path(repo_path).exists():
212
+ _err.print(f"[red]Repository path not found:[/red] {repo_path}")
213
+ # When the repo path looks like a git ref name (e.g. "main", "HEAD",
214
+ # "new") the user probably typed '-- ref' instead of '--new ref'.
215
+ if not Path(repo_path).is_absolute():
216
+ import re as _re
217
+ if _re.fullmatch(r"[A-Za-z0-9_/.\-]+", repo_path):
218
+ _err.print(
219
+ f"[yellow]Hint: '{repo_path}' looks like a git ref. "
220
+ f"Did you mean [bold]--new {repo_path}[/bold]?[/yellow]"
221
+ )
222
+ else:
223
+ _err.print(
224
+ f"[red]Not a git repository:[/red] {repo_path!r} "
225
+ "(pass a REPO path or run from inside a git repository)"
226
+ )
227
+ sys.exit(1)
228
+ except ValueError as exc:
229
+ # e.g. no tracking branch for --unpushed
230
+ _err.print(f"[red]Error:[/red] {exc}")
231
+ sys.exit(1)
232
+
233
+
234
+ def _cmd_file(args: argparse.Namespace) -> None:
235
+ source = FileSource(old_path=args.old_file, new_path=args.new_file)
236
+ differ = _differ(
237
+ args.fuel,
238
+ args.resolve_references,
239
+ diagnostics=getattr(args, "diagnostics", False),
240
+ profile_phases=getattr(args, "profile_phases", False),
241
+ guardrails_strict=getattr(args, "guardrails_strict", False),
242
+ config_start_path=args.new_file,
243
+ guardrails_policy=getattr(args, "guardrails_policy", None),
244
+ )
245
+ if args.stream:
246
+ for change in differ.diff_stream(source):
247
+ ct_str = (
248
+ change.change_type.value
249
+ if hasattr(change.change_type, "value")
250
+ else str(change.change_type)
251
+ )
252
+ line = f"{ct_str:16} {change.description}"
253
+ if change.text_diff:
254
+ line += f" [{change.text_diff}]"
255
+ _console.print(line)
256
+ else:
257
+ diff = differ.diff(source)
258
+ _render_with_profile(diff, args, fuel=differ._config.plugin_fuel)
259
+ result = _emit_guardrail_reports(diff, args)
260
+ _record_diagnostics_db(diff, args)
261
+ _exit_if_guardrail_result_fails(result)
262
+
263
+
264
+ def _cmd_patch(args: argparse.Namespace) -> None:
265
+ if args.patch_file and args.patch_file != "-":
266
+ patch_text = Path(args.patch_file).read_text(encoding="utf-8")
267
+ else:
268
+ patch_text = sys.stdin.read()
269
+
270
+ base_text = ""
271
+ if args.base:
272
+ base_text = Path(args.base).read_text(encoding="utf-8")
273
+
274
+ source = PatchSource(
275
+ patch_text=patch_text,
276
+ original_content=base_text if args.base else None,
277
+ )
278
+ differ = _differ(
279
+ args.fuel,
280
+ args.resolve_references,
281
+ diagnostics=getattr(args, "diagnostics", False),
282
+ profile_phases=getattr(args, "profile_phases", False),
283
+ guardrails_strict=getattr(args, "guardrails_strict", False),
284
+ config_start_path=args.base,
285
+ guardrails_policy=getattr(args, "guardrails_policy", None),
286
+ )
287
+ diff = differ.diff(source)
288
+ _render_with_profile(diff, args, fuel=differ._config.plugin_fuel)
289
+ result = _emit_guardrail_reports(diff, args)
290
+ _record_diagnostics_db(diff, args)
291
+ _exit_if_guardrail_result_fails(result)
292
+
293
+
294
+ def _cmd_string(args: argparse.Namespace) -> None:
295
+ differ = _differ(
296
+ args.fuel,
297
+ args.resolve_references,
298
+ diagnostics=getattr(args, "diagnostics", False),
299
+ profile_phases=getattr(args, "profile_phases", False),
300
+ guardrails_strict=getattr(args, "guardrails_strict", False),
301
+ guardrails_policy=getattr(args, "guardrails_policy", None),
302
+ )
303
+ diff = differ.diff_strings(
304
+ old=args.old,
305
+ new=args.new,
306
+ filename=f"<string>.{args.lang}" if args.lang else "<string>",
307
+ language_hint=args.lang,
308
+ )
309
+ _render_with_profile(diff, args, fuel=differ._config.plugin_fuel)
310
+ result = _emit_guardrail_reports(diff, args)
311
+ _record_diagnostics_db(diff, args)
312
+ _exit_if_guardrail_result_fails(result)
313
+
314
+
315
+ def _cmd_github_pr(args: argparse.Namespace) -> None:
316
+ from intentumdiff.github_app import parse_pull_request_url
317
+
318
+ ref = parse_pull_request_url(args.url)
319
+ payload = {
320
+ "kind": "github_pr",
321
+ "owner": ref.owner,
322
+ "repo": ref.repo,
323
+ "number": ref.number,
324
+ "review_command": (
325
+ f"intentumdiff-github-app review-pr --owner {shlex.quote(ref.owner)} "
326
+ f"--repo {shlex.quote(ref.repo)} --number {ref.number}"
327
+ ),
328
+ }
329
+ print(json.dumps(payload, indent=2, sort_keys=True))
330
+
331
+
332
+ def _cmd_gist_diff(args: argparse.Namespace) -> None:
333
+ from intentumdiff.github_app import parse_gist_url
334
+
335
+ ref = parse_gist_url(args.url)
336
+ payload = {
337
+ "kind": "gist_diff",
338
+ "gist_id": ref.gist_id,
339
+ "revision": ref.revision,
340
+ "review_command": f"intentumdiff gist-diff {shlex.quote(args.url)} --format html",
341
+ }
342
+ print(json.dumps(payload, indent=2, sort_keys=True))
343
+
344
+
345
+ def _diagnostics_store(args: argparse.Namespace) -> Any:
346
+ from intentumdiff.cache.duckdb_store import DuckDBAnalyticsStore
347
+
348
+ return DuckDBAnalyticsStore(args.db)
349
+
350
+
351
+ def _emit_rows(rows: list[dict[str, Any]], args: argparse.Namespace) -> None:
352
+ if getattr(args, "format", "terminal") == "json":
353
+ _write_output(
354
+ json.dumps(rows, indent=2, sort_keys=True, default=_json_default),
355
+ getattr(args, "output", None),
356
+ )
357
+ return
358
+ if not rows:
359
+ _console.print("[yellow]No diagnostics rows found.[/yellow]")
360
+ return
361
+ columns = list(rows[0])
362
+ widths = {
363
+ column: min(
364
+ max(len(column), *(len(str(row.get(column, ""))) for row in rows)),
365
+ 42,
366
+ )
367
+ for column in columns
368
+ }
369
+ _console.print(" ".join(column.ljust(widths[column]) for column in columns))
370
+ _console.print(" ".join("-" * widths[column] for column in columns))
371
+ for row in rows:
372
+ _console.print(
373
+ " ".join(
374
+ str(row.get(column, ""))[:widths[column]].ljust(widths[column])
375
+ for column in columns
376
+ )
377
+ )
378
+
379
+
380
+ def _cmd_diagnostics_summary(args: argparse.Namespace) -> None:
381
+ with _diagnostics_store(args) as store:
382
+ payload = {
383
+ "recent_runs": store.recent_diagnostic_runs(limit=args.limit),
384
+ "fuel_by_language": store.fuel_by_language(limit=args.limit),
385
+ }
386
+ if args.format == "json":
387
+ _write_output(
388
+ json.dumps(payload, indent=2, sort_keys=True, default=_json_default),
389
+ args.output,
390
+ )
391
+ return
392
+ _console.print("[bold cyan]Recent diagnostics runs[/bold cyan]")
393
+ _emit_rows(payload["recent_runs"], args)
394
+ _console.print()
395
+ _console.print("[bold cyan]Fuel by language[/bold cyan]")
396
+ _emit_rows(payload["fuel_by_language"], args)
397
+
398
+
399
+ def _cmd_diagnostics_hotspots(args: argparse.Namespace) -> None:
400
+ with _diagnostics_store(args) as store:
401
+ rows = store.top_fuel_hotspots(limit=args.limit)
402
+ _emit_rows(rows, args)
403
+
404
+
405
+ def _cmd_diagnostics_query(args: argparse.Namespace) -> None:
406
+ with _diagnostics_store(args) as store:
407
+ rows = store.query_readonly(args.sql)
408
+ _emit_rows(rows, args)
409
+
410
+
411
+ def _cmd_guardrails_check(args: argparse.Namespace) -> None:
412
+ from intentumdiff.vcs.git_cli import NotAGitRepositoryError
413
+
414
+ try:
415
+ differ = _differ(
416
+ args.fuel,
417
+ guardrails_strict=args.strict,
418
+ config_start_path=args.repo,
419
+ guardrails_policy=args.guardrails_policy,
420
+ )
421
+ diffs = differ.diff_commit(
422
+ repo_path=args.repo,
423
+ old_ref=args.old,
424
+ new_ref=args.new,
425
+ )
426
+ result = _guardrail_result(diffs, strict=args.strict)
427
+
428
+ if args.annotations == "github":
429
+ annotations = render_guardrail_annotations(result)
430
+ if annotations:
431
+ print(annotations)
432
+
433
+ if args.format == "json":
434
+ rendered = render_guardrail_json(result)
435
+ elif args.format == "sarif":
436
+ rendered = render_guardrail_sarif(result)
437
+ else:
438
+ rendered = render_guardrail_terminal(result)
439
+ _write_output(rendered, args.output)
440
+ _exit_if_guardrail_result_fails(result)
441
+ except NotAGitRepositoryError:
442
+ _err.print(f"[red]Not a git repository:[/red] {args.repo!r}")
443
+ sys.exit(1)
444
+ except ValueError as exc:
445
+ _err.print(f"[red]Error:[/red] {exc}")
446
+ sys.exit(1)
447
+
448
+
449
+ def _cmd_plugins_list(_args: argparse.Namespace) -> None:
450
+
451
+ from intentumdiff.plugins.registry import PluginRegistry
452
+
453
+ registry = PluginRegistry()
454
+
455
+ # Resolve the core package provenance string once for built-in rows
456
+ import importlib.metadata as _meta
457
+ for _dist_name in ("intentumdiff",):
458
+ try:
459
+ _core_dist = _meta.distribution(_dist_name)
460
+ _core_prov = (
461
+ f"{_core_dist.metadata.get('Name')} "
462
+ f"{_core_dist.metadata.get('Version')}"
463
+ )
464
+ break
465
+ except _meta.PackageNotFoundError:
466
+ continue
467
+ else:
468
+ _core_prov = "IntentumDiff"
469
+
470
+ # ── Parser plugins ────────────────────────────────────────────────────
471
+ parsers = sorted(registry.parsers, key=lambda p: (-p.priority, p.grammar_id))
472
+
473
+ parser_table = Table(title="Parser plugins", show_header=True, header_style="bold")
474
+ parser_table.add_column("Grammar ID", style="cyan")
475
+ parser_table.add_column("Languages", style="green")
476
+ parser_table.add_column("Mode", style="dim")
477
+ parser_table.add_column("Priority", justify="right", style="dim")
478
+ parser_table.add_column("Package", style="dim")
479
+
480
+ for p in parsers:
481
+ parser_table.add_row(
482
+ p.grammar_id,
483
+ ", ".join(p.language_ids),
484
+ p.parser_mode,
485
+ str(p.priority),
486
+ p.provenance or _core_prov,
487
+ )
488
+
489
+ if not parsers:
490
+ parser_table.add_row("[dim](none)[/dim]", "", "", "", "")
491
+
492
+ _console.print(parser_table)
493
+ _console.print()
494
+
495
+ # ── Renderer plugins ──────────────────────────────────────────────────
496
+ renderers = sorted(registry.renderers, key=lambda r: (-r.priority, r.format_name))
497
+
498
+ renderer_table = Table(title="Renderer plugins", show_header=True, header_style="bold")
499
+ renderer_table.add_column("Format", style="cyan")
500
+ renderer_table.add_column("Priority", justify="right", style="dim")
501
+ renderer_table.add_column("Package", style="dim")
502
+
503
+ wasm_formats = {r.format_name for r in renderers}
504
+ for r in renderers:
505
+ renderer_table.add_row(r.format_name, str(r.priority), r.provenance or _core_prov)
506
+
507
+ # Show built-in formats (implemented in Python, not Wasm) if not already listed
508
+ for builtin_fmt in ("terminal", "json"):
509
+ if builtin_fmt not in wasm_formats:
510
+ renderer_table.add_row(builtin_fmt, "[dim]built-in[/dim]", _core_prov)
511
+
512
+ _console.print(renderer_table)
513
+
514
+
515
+ def _cmd_plugins_add(args: argparse.Namespace) -> None:
516
+ import os as _os
517
+
518
+ from intentumdiff.plugins.hub import (
519
+ PluginSpec,
520
+ RegistryEntry,
521
+ compute_wasm_checksums,
522
+ fetch_official_registry,
523
+ load_plugins_file,
524
+ pip_install,
525
+ pip_uninstall,
526
+ pre_install_security_check,
527
+ save_plugins_file,
528
+ security_check_plugin,
529
+ )
530
+
531
+ source: str = getattr(args, "source", "git")
532
+ skip_verify: bool = getattr(args, "skip_verify", False)
533
+
534
+ # Gate --skip-verify: require --yes or env var to avoid silent bypasses.
535
+ if skip_verify:
536
+ yes: bool = getattr(args, "yes", False)
537
+ if not yes and not _os.environ.get("INTENTUMDIFF_ALLOW_SKIP_VERIFY"):
538
+ _err.print(
539
+ "[bold red]--skip-verify requires --yes or "
540
+ "INTENTUMDIFF_ALLOW_SKIP_VERIFY=1 to prevent accidental use.[/bold red]"
541
+ )
542
+ sys.exit(1)
543
+ _err.print(
544
+ "[yellow]Warning: security verification skipped (--skip-verify).[/yellow]"
545
+ )
546
+
547
+ # ── 1. Consult the official registry for official plugins ─────────────────
548
+ registry_entry: RegistryEntry | None = None
549
+ if not args.repo and not skip_verify:
550
+ try:
551
+ registry = fetch_official_registry(
552
+ strict=getattr(args, "strict_registry", False),
553
+ )
554
+ short = (
555
+ args.plugin_name[len("intentumdiff-"):]
556
+ if args.plugin_name.startswith("intentumdiff-")
557
+ else args.plugin_name
558
+ )
559
+ registry_entry = registry.get(short)
560
+ if registry_entry is not None:
561
+ # #94: refuse an ABI-incompatible plugin at RESOLVE time, before any install.
562
+ abi_error = registry_entry.abi_incompatibility()
563
+ if abi_error is not None:
564
+ _err.print(f"[bold red]ABI incompatibility:[/bold red] {abi_error}")
565
+ _err.print("[red]Installation aborted — nothing was installed.[/red]")
566
+ sys.exit(1)
567
+ # #95: warn (non-blocking) for a community-tier / unverified plugin.
568
+ trust_warning = registry_entry.trust_warning()
569
+ if trust_warning is not None:
570
+ _err.print(f"[yellow]Trust warning:[/yellow] {trust_warning}")
571
+ _console.print(
572
+ f"[dim]Found '{short}' in official registry "
573
+ f"({registry_entry.source} {registry_entry.ref}, "
574
+ f"{registry_entry.effective_trust_tier()} tier)[/dim]"
575
+ )
576
+ except RuntimeError as exc:
577
+ _err.print(
578
+ f"[yellow]Warning: could not fetch official registry: {exc}\n"
579
+ "Proceeding without registry verification.[/yellow]"
580
+ )
581
+
582
+ # ── 2. Build the PluginSpec (registry overrides CLI defaults if available) ─
583
+ if registry_entry is not None and args.ref == "main" and not args.repo:
584
+ # Use registry-pinned values when the user didn't explicitly override
585
+ spec = registry_entry.to_spec()
586
+ else:
587
+ spec = PluginSpec(
588
+ name=args.plugin_name,
589
+ source=source,
590
+ ref=args.ref,
591
+ repo=args.repo,
592
+ )
593
+
594
+ _console.print(
595
+ f"Installing [cyan]{spec.package_name}[/cyan] "
596
+ f"[dim]({spec.source}: {spec.install_target})[/dim]"
597
+ )
598
+
599
+ # ── 3. Pre-install wasm verification (before any Python code runs) ────────
600
+ if not skip_verify:
601
+ pre_errors, pre_warnings = pre_install_security_check(
602
+ spec.install_target, spec,
603
+ allow_source=getattr(args, "allow_source_plugin", False),
604
+ )
605
+ for w in pre_warnings:
606
+ _err.print(f"[yellow]Pre-install warning:[/yellow] {w}")
607
+ if pre_errors:
608
+ _err.print("[bold red]Pre-install security check FAILED:[/bold red]")
609
+ for e in pre_errors:
610
+ _err.print(f" [red]{e}[/red]")
611
+ _err.print("[red]Installation aborted — nothing was installed.[/red]")
612
+ sys.exit(1)
613
+
614
+ # ── 4. Install ────────────────────────────────────────────────────────────
615
+ rc = pip_install(spec.install_target, spec)
616
+ if rc != 0:
617
+ _err.print(f"[red]pip install failed (exit code {rc})[/red]")
618
+ sys.exit(rc)
619
+
620
+ # ── 5. Post-install: compute checksums and run security checks ────────────
621
+ if not skip_verify:
622
+ # If we have no registry-supplied checksums, compute them now (TOFU)
623
+ if not spec.wasm_checksums:
624
+ spec.wasm_checksums = compute_wasm_checksums(spec.package_name)
625
+ if spec.wasm_checksums:
626
+ _console.print(
627
+ "[dim]Recorded wasm checksums (trust-on-first-use):[/dim]"
628
+ )
629
+ for fname, digest in spec.wasm_checksums.items():
630
+ _console.print(f" [dim]{fname}: {digest[:16]}…[/dim]")
631
+ else:
632
+ _err.print(
633
+ "[yellow]Warning: no .wasm files found — checksums not recorded.[/yellow]"
634
+ )
635
+
636
+ errors, warnings = security_check_plugin(spec)
637
+ for w in warnings:
638
+ _err.print(f"[yellow]Security warning:[/yellow] {w}")
639
+ if errors:
640
+ _err.print("[bold red]Security check FAILED — quarantining plugin:[/bold red]")
641
+ for e in errors:
642
+ _err.print(f" [red]{e}[/red]")
643
+ _err.print(
644
+ f"[red]Uninstalling '{spec.package_name}' to prevent loading "
645
+ "a potentially tampered binary.[/red]"
646
+ )
647
+ pip_uninstall(spec.package_name)
648
+ sys.exit(1)
649
+
650
+ # ── 6. Save to manifest ───────────────────────────────────────────────────
651
+ if args.save:
652
+ yaml_path = Path(args.file)
653
+ existing: list = []
654
+ if yaml_path.exists():
655
+ with suppress(Exception):
656
+ existing = load_plugins_file(yaml_path)
657
+ # Replace if already present, otherwise append
658
+ existing = [
659
+ s for s in existing
660
+ if s.name != spec.name and s.name != spec.package_name
661
+ ]
662
+ existing.append(spec)
663
+ save_plugins_file(yaml_path, existing)
664
+ _console.print(f"[green]Saved to {yaml_path}[/green]")
665
+
666
+ _console.print(f"[green]Plugin '{spec.package_name}' installed.[/green]")
667
+
668
+
669
+ def _cmd_plugins_install(args: argparse.Namespace) -> None:
670
+ import os as _os
671
+
672
+ from intentumdiff.plugins.hub import (
673
+ load_plugins_file,
674
+ pip_install,
675
+ pip_uninstall,
676
+ pre_install_security_check,
677
+ security_check_plugin,
678
+ )
679
+
680
+ skip_verify: bool = getattr(args, "skip_verify", False)
681
+
682
+ # Gate --skip-verify.
683
+ if skip_verify:
684
+ yes: bool = getattr(args, "yes", False)
685
+ if not yes and not _os.environ.get("INTENTUMDIFF_ALLOW_SKIP_VERIFY"):
686
+ _err.print(
687
+ "[bold red]--skip-verify requires --yes or "
688
+ "INTENTUMDIFF_ALLOW_SKIP_VERIFY=1 to prevent accidental use.[/bold red]"
689
+ )
690
+ sys.exit(1)
691
+ _err.print(
692
+ "[yellow]Warning: security verification skipped (--skip-verify).[/yellow]"
693
+ )
694
+
695
+ yaml_path = Path(args.file)
696
+ if not yaml_path.exists():
697
+ _err.print(f"[red]Plugins file not found:[/red] {yaml_path}")
698
+ _err.print(
699
+ "Create one with [bold]intentumdiff plugins add <name>[/bold] "
700
+ "([bold]intentumdiff plugins add <name>[/bold] remains an alias) "
701
+ "or write it manually."
702
+ )
703
+ sys.exit(1)
704
+
705
+ specs = load_plugins_file(yaml_path)
706
+ if not specs:
707
+ _console.print(f"[yellow]No plugins defined in[/yellow] {yaml_path}")
708
+ return
709
+
710
+ _console.print(f"Installing {len(specs)} plugin(s) from [dim]{yaml_path}[/dim] ...")
711
+ failed: list[str] = []
712
+ security_failed: list[str] = []
713
+
714
+ for spec in specs:
715
+ _console.print(
716
+ f" [cyan]{spec.package_name}[/cyan] "
717
+ f"[dim]({spec.source}: {spec.install_target})[/dim]"
718
+ )
719
+
720
+ # Pre-install wasm verification.
721
+ if not skip_verify:
722
+ pre_errors, pre_warnings = pre_install_security_check(
723
+ spec.install_target, spec,
724
+ allow_source=getattr(args, "allow_source_plugin", False),
725
+ )
726
+ for w in pre_warnings:
727
+ _err.print(f" [yellow]Pre-install warning:[/yellow] {w}")
728
+ if pre_errors:
729
+ _err.print(
730
+ f" [bold red]Pre-install security check FAILED for "
731
+ f"'{spec.package_name}':[/bold red]"
732
+ )
733
+ for e in pre_errors:
734
+ _err.print(f" [red]{e}[/red]")
735
+ security_failed.append(spec.name)
736
+ continue
737
+
738
+ rc = pip_install(spec.install_target, spec, upgrade=args.upgrade)
739
+ if rc != 0:
740
+ _err.print(f" [red]FAILED[/red] (exit code {rc})")
741
+ failed.append(spec.name)
742
+ continue
743
+
744
+ if not skip_verify:
745
+ errors, warnings = security_check_plugin(spec)
746
+ for w in warnings:
747
+ _err.print(f" [yellow]Security warning:[/yellow] {w}")
748
+ if errors:
749
+ _err.print(
750
+ f" [bold red]Post-install security check FAILED for "
751
+ f"'{spec.package_name}' — quarantining:[/bold red]"
752
+ )
753
+ for e in errors:
754
+ _err.print(f" [red]{e}[/red]")
755
+ _err.print(
756
+ f" [red]Uninstalling '{spec.package_name}'.[/red]"
757
+ )
758
+ pip_uninstall(spec.package_name)
759
+ security_failed.append(spec.name)
760
+
761
+ if failed:
762
+ _err.print(f"[red]{len(failed)} plugin(s) failed to install: {', '.join(failed)}[/red]")
763
+ if security_failed:
764
+ _err.print(
765
+ f"[bold red]{len(security_failed)} plugin(s) failed security checks: "
766
+ f"{', '.join(security_failed)}[/bold red]\n"
767
+ "These plugins were refused or quarantined."
768
+ )
769
+ if failed or security_failed:
770
+ sys.exit(1)
771
+ _console.print(f"[green]All {len(specs)} plugin(s) installed and verified.[/green]")
772
+
773
+
774
+ def _cmd_security_check(args: argparse.Namespace) -> None:
775
+ """Sync OSV advisory check: fetch if stale or --refresh, display results."""
776
+ import time as _time_sc
777
+
778
+ from intentumdiff.plugins.loader import (
779
+ _OSV_FETCH_INTERVAL,
780
+ _PACKAGES_TO_AUDIT,
781
+ _load_osv_cache,
782
+ _osv_cache_path,
783
+ _osv_stamp_path,
784
+ _read_stamp,
785
+ refresh_osv_cache,
786
+ )
787
+
788
+ force_refresh: bool = getattr(args, "refresh", False)
789
+ stamp_age = _time_sc.time() - _read_stamp()
790
+ cache = _load_osv_cache()
791
+ needs_fetch = force_refresh or stamp_age >= _OSV_FETCH_INTERVAL or cache is None
792
+
793
+ if needs_fetch:
794
+ if force_refresh:
795
+ _console.print("[dim]Forcing OSV cache refresh (--refresh)...[/dim]")
796
+ else:
797
+ _console.print("[dim]OSV cache is stale or absent — fetching...[/dim]")
798
+ try:
799
+ vulns = refresh_osv_cache()
800
+ except Exception as exc:
801
+ _err.print(
802
+ f"[bold red]Failed to fetch OSV advisory database:[/bold red] {exc}\n\n"
803
+ "The advisory cache has been marked as failed.\n"
804
+ "Plugin loading will be blocked until you run\n"
805
+ " [bold]intentumdiff security-check --refresh[/bold]\n"
806
+ "successfully, or set [bold]INTENTUMDIFF_ALLOW_VULNERABLE_WASMTIME=1[/bold] "
807
+ "to bypass (not recommended)."
808
+ )
809
+ sys.exit(1)
810
+ _console.print("[green]OSV advisory database refreshed.[/green]")
811
+ else:
812
+ last = _time_sc.strftime(
813
+ "%Y-%m-%d %H:%M:%S",
814
+ _time_sc.localtime(_time_sc.time() - stamp_age),
815
+ )
816
+ _console.print(f"[dim]Using cached OSV data (last fetched: {last})[/dim]")
817
+ vulns = cache # type: ignore[assignment]
818
+
819
+ _console.print(
820
+ f"[dim]Checked {len(_PACKAGES_TO_AUDIT)} package(s) "
821
+ "against the OSV advisory database.[/dim]"
822
+ )
823
+ _console.print(
824
+ f"[dim]Cache: {_osv_cache_path()}[/dim]\n"
825
+ f"[dim]Stamp: {_osv_stamp_path()}[/dim]"
826
+ )
827
+
828
+ if not vulns:
829
+ _console.print("\n[bold green]No known vulnerabilities found.[/bold green]")
830
+ sys.exit(0)
831
+
832
+ table = Table(
833
+ title=f"[bold red]OSV Advisories — {len(vulns)} finding(s)[/bold red]",
834
+ show_header=True,
835
+ header_style="bold",
836
+ )
837
+ table.add_column("Package", style="cyan")
838
+ table.add_column("Version")
839
+ table.add_column("Advisory ID", style="red")
840
+ table.add_column("Aliases", style="dim")
841
+ table.add_column("Summary")
842
+
843
+ for v in vulns:
844
+ table.add_row(
845
+ v.get("package", ""),
846
+ v.get("version", ""),
847
+ v.get("id", ""),
848
+ ", ".join(v.get("aliases", [])),
849
+ v.get("summary", ""),
850
+ )
851
+
852
+ _console.print(table)
853
+ _console.print(
854
+ "\n[bold red]Action required:[/bold red] upgrade the affected packages.\n"
855
+ "Until resolved, plugin loading is blocked. To bypass (not recommended),\n"
856
+ "set [bold]INTENTUMDIFF_ALLOW_VULNERABLE_WASMTIME=1[/bold]."
857
+ )
858
+ sys.exit(1)
859
+
860
+
861
+ def _cmd_plugins_remove(args: argparse.Namespace) -> None:
862
+ from intentumdiff.plugins.hub import (
863
+ PluginSpec,
864
+ load_plugins_file,
865
+ pip_uninstall,
866
+ save_plugins_file,
867
+ )
868
+
869
+ name = args.plugin_name
870
+ spec = PluginSpec(name=name)
871
+ _console.print(f"Uninstalling [cyan]{spec.package_name}[/cyan] ...")
872
+ rc = pip_uninstall(spec.package_name)
873
+ if rc != 0:
874
+ _err.print(f"[red]pip uninstall failed (exit code {rc})[/red]")
875
+ sys.exit(rc)
876
+
877
+ if args.save:
878
+ yaml_path = Path(args.file)
879
+ if yaml_path.exists():
880
+ try:
881
+ specs = load_plugins_file(yaml_path)
882
+ specs = [
883
+ s for s in specs
884
+ if s.name != name and s.name != spec.package_name
885
+ ]
886
+ save_plugins_file(yaml_path, specs)
887
+ _console.print(f"[green]Removed from {yaml_path}[/green]")
888
+ except Exception as exc:
889
+ _err.print(f"[yellow]Warning: could not update {yaml_path}: {exc}[/yellow]")
890
+
891
+ _console.print(f"[green]Plugin '{spec.package_name}' uninstalled.[/green]")
892
+
893
+
894
+ # ---------------------------------------------------------------------------
895
+ # ---------------------------------------------------------------------------
896
+ # index command
897
+ # ---------------------------------------------------------------------------
898
+
899
+
900
+ def _cmd_index(args: argparse.Namespace) -> None:
901
+ """Walk a git repository and pre-warm the parse/symbol-index cache."""
902
+ import asyncio
903
+
904
+ asyncio.run(_cmd_index_async(args))
905
+
906
+
907
+ async def _cmd_index_async(args: argparse.Namespace) -> None:
908
+ """Entry point for the index command — creates differ/indexer, dispatches."""
909
+ from intentumdiff.core.indexer import Indexer
910
+ from intentumdiff.plugins.exceptions import PluginNotFoundError
911
+
912
+ cache_path = Path(args.cache_path)
913
+ fuel: int | None = getattr(args, "fuel", None)
914
+ cfg = _load_cli_config(fuel=fuel, config_start_path=getattr(args, "repo", "."))
915
+ cfg.cache_path = cache_path
916
+ differ = SemanticDiffer(cfg)
917
+ indexer = Indexer(differ)
918
+
919
+ try:
920
+ if getattr(args, "lsp", False):
921
+ await _two_pass_index(args, differ, indexer)
922
+ else:
923
+ result = await _index_with_progress(
924
+ indexer,
925
+ repo_path=getattr(args, "repo", "."),
926
+ ref=args.ref,
927
+ force=args.force,
928
+ lsp_clients={},
929
+ )
930
+ _print_index_result(result)
931
+ except PluginNotFoundError as exc:
932
+ _err.print(f"[red]No parser found:[/red] {exc}")
933
+ sys.exit(1)
934
+ except Exception as exc:
935
+ _err.print(f"[red]Indexing failed:[/red] {exc}")
936
+ sys.exit(1)
937
+ finally:
938
+ if differ._cache is not None:
939
+ differ._cache.close()
940
+
941
+
942
+ async def _two_pass_index(
943
+ args: argparse.Namespace,
944
+ differ: Any,
945
+ indexer: Any,
946
+ ) -> None:
947
+ """Two-pass LSP-enriched index.
948
+
949
+ Pass 1: plain index to detect which languages are present.
950
+ Pass 2: re-index with LSP clients attached for type enrichment.
951
+
952
+ Server config is read from ``lsp_servers.json`` in the repo root
953
+ (user-defined entries override the built-in defaults).
954
+ """
955
+ import asyncio
956
+
957
+ from intentumdiff.lsp.client import AsyncLspClient
958
+ from intentumdiff.lsp.config import LspServerConfig
959
+ from intentumdiff.lsp.launcher import LspServerProcess
960
+ from intentumdiff.lsp.servers import KNOWN_SERVER_SPECS, load_lsp_servers_json
961
+
962
+ repo_path: str = getattr(args, "repo", ".")
963
+ ref: str = args.ref
964
+
965
+ # ── Load user-defined server config ──────────────────────────────────────
966
+ trust_repo_lsp_config: bool = getattr(args, "trust_repo_lsp_config", False)
967
+ lsp_json = Path(repo_path) / "lsp_servers.json"
968
+ user_entries: dict = {}
969
+ if lsp_json.exists():
970
+ if not trust_repo_lsp_config:
971
+ _err.print(
972
+ f"[yellow]Warning: {lsp_json.name} found in repository root but "
973
+ "--trust-repo-lsp-config was not passed. "
974
+ "Repo-local LSP server commands are ignored to prevent command "
975
+ "injection via untrusted repository content. "
976
+ "Re-run with --trust-repo-lsp-config if you own this repo.[/yellow]"
977
+ )
978
+ else:
979
+ try:
980
+ user_entries = load_lsp_servers_json(lsp_json)
981
+ _console.print(
982
+ f"[dim]Loaded {len(user_entries)} LSP server(s) "
983
+ f"from {lsp_json.name}[/dim]"
984
+ )
985
+ except Exception as exc:
986
+ _err.print(
987
+ f"[yellow]Warning: cannot load {lsp_json.name}: {exc}[/yellow]"
988
+ )
989
+
990
+ # ── Pass 1: detect languages (fast extension/heuristic scan, no Wasm parse) ──
991
+ from rich.progress import (
992
+ BarColumn,
993
+ MofNCompleteColumn,
994
+ Progress,
995
+ SpinnerColumn,
996
+ TextColumn,
997
+ TimeElapsedColumn,
998
+ )
999
+ from rich.table import Column
1000
+
1001
+ _console.print("[bold]Pass 1[/bold] — scanning languages…")
1002
+ with Progress(
1003
+ SpinnerColumn(),
1004
+ TextColumn(
1005
+ "[bold blue]{task.description}", table_column=Column(no_wrap=True)
1006
+ ),
1007
+ BarColumn(),
1008
+ MofNCompleteColumn(),
1009
+ TimeElapsedColumn(),
1010
+ expand=False,
1011
+ console=_console,
1012
+ transient=True,
1013
+ ) as _detect_progress:
1014
+ _detect_task = _detect_progress.add_task(
1015
+ "Scanning files", total=None
1016
+ )
1017
+
1018
+ def _on_detect_progress(done: int, total: int) -> None:
1019
+ _detect_progress.update(_detect_task, completed=done, total=total)
1020
+
1021
+ detected, _file_count = await asyncio.to_thread(
1022
+ indexer.detect_languages, repo_path, ref,
1023
+ on_progress=_on_detect_progress,
1024
+ )
1025
+
1026
+ launchable = {
1027
+ lang for lang in detected
1028
+ if lang in user_entries or lang in KNOWN_SERVER_SPECS
1029
+ }
1030
+
1031
+ if not launchable:
1032
+ langs_str = ", ".join(sorted(detected)) or "none"
1033
+ _console.print(
1034
+ f"[dim]No LSP servers configured for detected languages "
1035
+ f"({langs_str}). Running plain index.[/dim]"
1036
+ )
1037
+ result = await _index_with_progress(
1038
+ indexer,
1039
+ repo_path=repo_path,
1040
+ ref=ref,
1041
+ force=args.force,
1042
+ lsp_clients={},
1043
+ initial_total=_file_count,
1044
+ )
1045
+ _print_index_result(result)
1046
+ return
1047
+
1048
+ _console.print(
1049
+ f"[bold]Pass 1 complete[/bold] — "
1050
+ f"LSP available for: [cyan]{', '.join(sorted(launchable))}[/cyan]"
1051
+ )
1052
+
1053
+ # ── Start servers + connect clients ───────────────────────────────────────
1054
+ # Resolve the workspace root URI once — LSP servers need this to find
1055
+ # project files (Cargo.toml, pyproject.toml, tsconfig.json, etc.).
1056
+ root_uri = Path(repo_path).resolve().as_uri()
1057
+
1058
+ launchers: dict[str, LspServerProcess] = {}
1059
+ clients: dict[str, AsyncLspClient] = {}
1060
+
1061
+ # Separate languages into "already running" vs "needs auto-start".
1062
+ manual: list[str] = []
1063
+ to_start: list[str] = []
1064
+ for lang in sorted(launchable):
1065
+ entry = user_entries.get(lang)
1066
+ if entry is not None and entry.is_manual_connect:
1067
+ manual.append(lang)
1068
+ else:
1069
+ to_start.append(lang)
1070
+
1071
+ # For auto-start languages, ask the user once before spawning anything.
1072
+ if to_start:
1073
+ _console.print()
1074
+ _console.print(
1075
+ "[bold]The following LSP servers will be started automatically "
1076
+ "and terminated when indexing completes:[/bold]"
1077
+ )
1078
+ for lang in to_start:
1079
+ entry = user_entries.get(lang)
1080
+ spec = entry.to_spec() if entry is not None else KNOWN_SERVER_SPECS.get(lang)
1081
+ cmd_str = " ".join(spec.command) if spec else lang
1082
+ _console.print(f" [cyan]{lang}[/cyan] -> {cmd_str}")
1083
+
1084
+ _console.print()
1085
+ try:
1086
+ raw = await asyncio.get_event_loop().run_in_executor(
1087
+ None,
1088
+ lambda: _console.input(
1089
+ "[bold]Start these servers?[/bold] [Y/n]: "
1090
+ ).strip().lower(),
1091
+ )
1092
+ except (EOFError, KeyboardInterrupt):
1093
+ raw = "n"
1094
+
1095
+ if raw not in ("", "y", "yes"):
1096
+ _console.print(
1097
+ "[dim]Skipping auto-start. Servers that are already "
1098
+ "running will still be used.[/dim]"
1099
+ )
1100
+ to_start = []
1101
+ _console.print()
1102
+
1103
+ # Connect to already-running (manual) servers first.
1104
+ for lang in manual:
1105
+ entry = user_entries[lang]
1106
+ try:
1107
+ cfg_lsp = LspServerConfig.tcp(entry.host, port=entry.port)
1108
+ client = AsyncLspClient(cfg_lsp, root_uri=root_uri)
1109
+ await client.start()
1110
+ clients[lang] = client
1111
+ _console.print(
1112
+ f" [green]✓[/green] {lang} (tcp, already running @ {cfg_lsp})"
1113
+ )
1114
+ except (Exception, asyncio.CancelledError) as exc:
1115
+ _err.print(f" [yellow]⚠[/yellow] {lang}: {exc} — skipped")
1116
+ _hint = entry.install_hint
1117
+ if _hint:
1118
+ _err.print(f" [dim]Install: {_hint}[/dim]")
1119
+
1120
+ # Spawn approved auto-start servers.
1121
+ for lang in to_start:
1122
+ entry = user_entries.get(lang)
1123
+ try:
1124
+ spec = entry.to_spec() if entry is not None else None
1125
+ launcher = LspServerProcess(lang, spec=spec)
1126
+ cfg_lsp = await launcher.start()
1127
+ client = AsyncLspClient(cfg_lsp, root_uri=root_uri)
1128
+ await client.start()
1129
+ launchers[lang] = launcher
1130
+ clients[lang] = client
1131
+ _console.print(
1132
+ f" [green]✓[/green] {lang} ({cfg_lsp.transport}, auto-started)"
1133
+ )
1134
+ except (Exception, asyncio.CancelledError) as exc:
1135
+ _err.print(f" [yellow]⚠[/yellow] {lang}: {exc} — skipped")
1136
+ _hint = (
1137
+ entry.install_hint
1138
+ if entry is not None
1139
+ else (KNOWN_SERVER_SPECS[lang].install_hint if lang in KNOWN_SERVER_SPECS else "")
1140
+ )
1141
+ if _hint:
1142
+ _err.print(f" [dim]Install: {_hint}[/dim]")
1143
+ if lang in launchers:
1144
+ with suppress(Exception):
1145
+ await launchers.pop(lang).stop()
1146
+
1147
+ if not clients:
1148
+ _console.print(
1149
+ "[dim]No LSP servers connected; running plain index.[/dim]"
1150
+ )
1151
+ result = await _index_with_progress(
1152
+ indexer,
1153
+ repo_path=repo_path,
1154
+ ref=ref,
1155
+ force=args.force,
1156
+ lsp_clients={},
1157
+ initial_total=_file_count,
1158
+ )
1159
+ _print_index_result(result)
1160
+ return
1161
+
1162
+ # ── Pass 2: enrich with LSP ───────────────────────────────────────────────
1163
+ n = len(clients)
1164
+ _console.print(
1165
+ f"[bold]Pass 2[/bold] — enriching with LSP "
1166
+ f"({n} server{'s' if n != 1 else ''})…"
1167
+ )
1168
+ try:
1169
+ result = await _index_with_progress(
1170
+ indexer,
1171
+ repo_path=repo_path,
1172
+ ref=ref,
1173
+ force=args.force,
1174
+ lsp_clients=clients,
1175
+ initial_total=_file_count,
1176
+ )
1177
+ _print_index_result(result)
1178
+ finally:
1179
+ for c in clients.values():
1180
+ with suppress(Exception):
1181
+ await c.shutdown()
1182
+ for lp in launchers.values():
1183
+ with suppress(Exception):
1184
+ await lp.stop()
1185
+
1186
+
1187
+ async def _index_with_progress(
1188
+ indexer: Any,
1189
+ *,
1190
+ repo_path: str,
1191
+ ref: str,
1192
+ force: bool,
1193
+ lsp_clients: dict[str, Any],
1194
+ initial_total: int | None = None,
1195
+ ) -> Any:
1196
+ """Run the indexer with a Rich progress bar and return the result."""
1197
+ from rich.progress import (
1198
+ BarColumn,
1199
+ MofNCompleteColumn,
1200
+ Progress,
1201
+ SpinnerColumn,
1202
+ TextColumn,
1203
+ TimeElapsedColumn,
1204
+ )
1205
+ from rich.table import Column
1206
+
1207
+ from intentumdiff.core.indexer import IndexProgress
1208
+
1209
+ with Progress(
1210
+ SpinnerColumn(),
1211
+ TextColumn(
1212
+ "[bold blue]{task.description}", table_column=Column(no_wrap=True)
1213
+ ),
1214
+ BarColumn(),
1215
+ MofNCompleteColumn(),
1216
+ TimeElapsedColumn(),
1217
+ TextColumn(
1218
+ "[dim]{task.fields[current_file]}[/dim]",
1219
+ table_column=Column(no_wrap=True),
1220
+ ),
1221
+ expand=False,
1222
+ console=_console,
1223
+ transient=False,
1224
+ ) as progress:
1225
+ lsp_tag = " [dim][LSP][/dim]" if lsp_clients else ""
1226
+ task = progress.add_task(
1227
+ f"Indexing [cyan]{ref}[/cyan]{lsp_tag}",
1228
+ total=initial_total,
1229
+ current_file="collecting files…",
1230
+ )
1231
+
1232
+ def _on_progress(p: IndexProgress) -> None:
1233
+ progress.update(
1234
+ task,
1235
+ total=p.total,
1236
+ completed=p.done,
1237
+ current_file=p.current_file if p.current_file else "",
1238
+ )
1239
+
1240
+ if lsp_clients:
1241
+ return await indexer.index_repo_lsp(
1242
+ repo_path,
1243
+ ref=ref,
1244
+ lsp_clients=lsp_clients,
1245
+ on_progress=_on_progress,
1246
+ force=force,
1247
+ )
1248
+ else:
1249
+ return indexer.index_repo(
1250
+ repo_path, ref=ref, on_progress=_on_progress, force=force
1251
+ )
1252
+
1253
+
1254
+ def _print_index_result(result: Any) -> None:
1255
+ """Print a human-readable summary of an :class:`IndexResult`."""
1256
+ if result.from_cache:
1257
+ _console.print("[green]Symbol index loaded from cache[/green]")
1258
+ return
1259
+
1260
+ type_enriched = getattr(result, "type_enriched_count", 0)
1261
+ files_ignored = getattr(result, "files_ignored", 0)
1262
+ _console.print()
1263
+ _console.print(
1264
+ f"[green]Indexed[/green] [bold]{result.files_indexed}[/bold] file(s) "
1265
+ f"[dim]{result.files_skipped} skipped"
1266
+ + (f" {files_ignored} ignored" if files_ignored else "")
1267
+ + f" {len(result.errors)} error(s)"
1268
+ + (f" {type_enriched} type-enriched" if type_enriched else "")
1269
+ + "[/dim]"
1270
+ )
1271
+
1272
+ if result.errors:
1273
+ _console.print()
1274
+ _console.print("[yellow]Parse errors:[/yellow]")
1275
+ for filename, msg in result.errors[:10]:
1276
+ _console.print(f" [red]{filename}[/red]: {msg}")
1277
+ if len(result.errors) > 10:
1278
+ _console.print(f" [dim]…and {len(result.errors) - 10} more[/dim]")
1279
+
1280
+ if result.skipped_files:
1281
+ from collections import Counter
1282
+ from pathlib import Path as _Path
1283
+
1284
+ ext_counts: Counter[str] = Counter(
1285
+ _Path(f).suffix or "(no extension)" for f in result.skipped_files
1286
+ )
1287
+ _console.print()
1288
+ _console.print(
1289
+ f"[dim]Skipped {result.files_skipped} file(s) with no registered parser "
1290
+ f"({', '.join(f'{c}×{e}' for e, c in ext_counts.most_common())})[/dim]"
1291
+ )
1292
+
1293
+ ignored_files = getattr(result, "ignored_files", [])
1294
+ if ignored_files:
1295
+ _console.print()
1296
+ _console.print(
1297
+ f"[dim]Ignored {len(ignored_files)} file(s) via .diffignore[/dim]"
1298
+ )
1299
+
1300
+
1301
+
1302
+
1303
+
1304
+
1305
+ # ---------------------------------------------------------------------------
1306
+ # cache command
1307
+ # ---------------------------------------------------------------------------
1308
+
1309
+
1310
+ def _cmd_cache_stats(args: argparse.Namespace) -> None:
1311
+ """Show cache statistics including hit/miss metrics."""
1312
+ import time
1313
+
1314
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1315
+
1316
+ cache_path = Path(args.cache_path) / "cache.db"
1317
+ if not cache_path.exists():
1318
+ _console.print(f"[yellow]No cache found at[/yellow] {cache_path}")
1319
+ return
1320
+
1321
+ store = SqliteCacheStore(cache_path)
1322
+ data = store.stats()
1323
+ met = store.metrics()
1324
+ store.close()
1325
+
1326
+ table = Table(title=f"Cache: {cache_path}", show_header=True, header_style="bold")
1327
+ table.add_column("Table", style="cyan")
1328
+ table.add_column("Entries", justify="right")
1329
+ table.add_column("Size (MB)", justify="right")
1330
+ table.add_column("Oldest entry")
1331
+ table.add_column("Newest entry")
1332
+ table.add_column("TTL (days)", justify="right")
1333
+ table.add_column("Hits", justify="right", style="green")
1334
+ table.add_column("Misses", justify="right", style="red")
1335
+ table.add_column("Hit rate", justify="right")
1336
+
1337
+ total_size = 0
1338
+ total_hits = 0
1339
+ total_misses = 0
1340
+
1341
+ for tbl_name, s in data.items():
1342
+ m = met.get(tbl_name, {})
1343
+ size_mb = f"{s['size_bytes'] / 1024 / 1024:.2f}"
1344
+ oldest = (
1345
+ time.strftime("%Y-%m-%d", time.localtime(s["oldest"]))
1346
+ if s["oldest"] is not None else "—"
1347
+ )
1348
+ newest = (
1349
+ time.strftime("%Y-%m-%d", time.localtime(s["newest"]))
1350
+ if s.get("newest") is not None else "—"
1351
+ )
1352
+ hits = m.get("hits", 0)
1353
+ misses = m.get("misses", 0)
1354
+ hit_rate = f"{m.get('hit_rate_pct', 0.0):.1f}%" if (hits + misses) else "—"
1355
+ table.add_row(
1356
+ tbl_name, str(s["count"]), size_mb, oldest, newest,
1357
+ str(s.get("ttl_days", "?")),
1358
+ str(hits), str(misses), hit_rate,
1359
+ )
1360
+ total_size += s["size_bytes"]
1361
+ total_hits += hits
1362
+ total_misses += misses
1363
+
1364
+ total_requests = total_hits + total_misses
1365
+ combined_rate = f"{total_hits / total_requests * 100:.1f}%" if total_requests else "—"
1366
+ table.add_section()
1367
+ table.add_row(
1368
+ "[bold]TOTAL[/bold]",
1369
+ "",
1370
+ f"{total_size / 1024 / 1024:.2f}",
1371
+ "", "", "",
1372
+ f"[bold]{total_hits}[/bold]",
1373
+ f"[bold]{total_misses}[/bold]",
1374
+ f"[bold]{combined_rate}[/bold]",
1375
+ )
1376
+
1377
+ _console.print(table)
1378
+
1379
+
1380
+ def _cmd_cache_list(args: argparse.Namespace) -> None:
1381
+ """List cache entries with optional filters."""
1382
+
1383
+
1384
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1385
+
1386
+ cache_path = Path(args.cache_path) / "cache.db"
1387
+ if not cache_path.exists():
1388
+ _console.print(f"[yellow]No cache found at[/yellow] {cache_path}")
1389
+ return
1390
+
1391
+ store = SqliteCacheStore(cache_path)
1392
+
1393
+ tables_to_list = (
1394
+ [_TABLE_ALIAS[args.table]]
1395
+ if args.table
1396
+ else ["parse_cache", "diff_cache", "symbol_index_cache", "hover_map_cache"]
1397
+ )
1398
+
1399
+ since = _parse_date_arg(getattr(args, "since", None))
1400
+ before = _parse_date_arg(getattr(args, "before", None))
1401
+
1402
+ for tbl in tables_to_list:
1403
+ rows = store.list_entries(
1404
+ tbl,
1405
+ language=getattr(args, "language", None),
1406
+ file_glob=getattr(args, "file", None),
1407
+ since=since,
1408
+ before=before,
1409
+ min_size=getattr(args, "min_size", None),
1410
+ max_size=getattr(args, "max_size", None),
1411
+ limit=args.limit,
1412
+ )
1413
+ if not rows:
1414
+ _console.print(f"[dim]No entries in {tbl}[/dim]")
1415
+ continue
1416
+
1417
+ verbose: bool = getattr(args, "verbose", False)
1418
+ title = f"{tbl} ({len(rows)} shown)"
1419
+ table = Table(title=title, show_header=True, header_style="bold")
1420
+ table.add_column("Key", style="cyan")
1421
+ if verbose:
1422
+ table.add_column("Full key", style="dim")
1423
+ if tbl == "diff_cache":
1424
+ table.add_column("Language")
1425
+ table.add_column("old → new filename")
1426
+ elif tbl == "parse_cache":
1427
+ table.add_column("Grammar ID")
1428
+ elif tbl == "symbol_index_cache":
1429
+ table.add_column("Files")
1430
+ table.add_column("Size (KB)", justify="right")
1431
+ table.add_column("Age")
1432
+ table.add_column("TTL left")
1433
+
1434
+ for r in rows:
1435
+ key_prefix = r["key"][:12]
1436
+ age = _human_duration(r["age_seconds"])
1437
+ ttl_left = (
1438
+ _human_duration(max(r["expires_in_seconds"], 0))
1439
+ if r["expires_in_seconds"] > 0
1440
+ else "[red]expired[/red]"
1441
+ )
1442
+ size_kb = f"{r['size_bytes'] / 1024:.1f}"
1443
+
1444
+ row_cells = [key_prefix]
1445
+ if verbose:
1446
+ row_cells.append(r["key"])
1447
+ if tbl == "diff_cache":
1448
+ row_cells.append(r.get("language", ""))
1449
+ old_f = r.get("old_filename", "")
1450
+ new_f = r.get("new_filename", "")
1451
+ row_cells.append(f"{old_f} → {new_f}" if old_f != new_f else old_f)
1452
+ elif tbl == "parse_cache":
1453
+ row_cells.append(r.get("grammar_id", ""))
1454
+ elif tbl == "symbol_index_cache":
1455
+ row_cells.append(str(r.get("file_count", "")))
1456
+ row_cells += [size_kb, age, ttl_left]
1457
+ table.add_row(*row_cells)
1458
+
1459
+ _console.print(table)
1460
+
1461
+ store.close()
1462
+
1463
+
1464
+ def _cmd_cache_inspect(args: argparse.Namespace) -> None:
1465
+ """Show detailed metadata and a payload summary for a single cache entry."""
1466
+ import json
1467
+ import time
1468
+
1469
+ from rich.table import Table
1470
+
1471
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1472
+
1473
+ cache_path = Path(args.cache_path) / "cache.db"
1474
+ if not cache_path.exists():
1475
+ _console.print(f"[yellow]No cache found at[/yellow] {cache_path}")
1476
+ return
1477
+
1478
+ store = SqliteCacheStore(cache_path)
1479
+ key_prefix = args.key
1480
+
1481
+ # Resolve key — try exact match first, then prefix across all (or specified) tables
1482
+ tables_to_search = (
1483
+ [_TABLE_ALIAS[args.table]]
1484
+ if getattr(args, "table", None)
1485
+ else ["parse_cache", "diff_cache", "symbol_index_cache", "hover_map_cache"]
1486
+ )
1487
+
1488
+ found_table: str | None = None
1489
+ full_key: str | None = None
1490
+ for tbl in tables_to_search:
1491
+ rows = store.list_entries(tbl, limit=1000)
1492
+ matches = [r for r in rows if r["key"].startswith(key_prefix)]
1493
+ if len(matches) == 1:
1494
+ found_table = tbl
1495
+ full_key = matches[0]["key"]
1496
+ break
1497
+ if len(matches) > 1:
1498
+ _err.print(
1499
+ f"[red]Ambiguous key prefix[/red] {key_prefix!r} matches "
1500
+ f"{len(matches)} entries in {tbl}. Use a longer prefix."
1501
+ )
1502
+ store.close()
1503
+ sys.exit(1)
1504
+
1505
+ if full_key is None or found_table is None:
1506
+ _err.print(f"[red]Key not found:[/red] {key_prefix!r}")
1507
+ store.close()
1508
+ sys.exit(1)
1509
+
1510
+ meta = store.get_entry_metadata(full_key, found_table)
1511
+ payload_str = store.get_entry_payload(full_key, found_table)
1512
+ store.close()
1513
+
1514
+ # Metadata panel
1515
+ created = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(meta["created_at"]))
1516
+ ttl_left = (
1517
+ _human_duration(max(meta["expires_in_seconds"], 0))
1518
+ if meta["expires_in_seconds"] > 0
1519
+ else "[red]expired[/red]"
1520
+ )
1521
+ decompressed_size = len(payload_str.encode()) if payload_str else 0
1522
+
1523
+ meta_table = Table(show_header=False, box=None, padding=(0, 1))
1524
+ meta_table.add_column("Field", style="bold cyan")
1525
+ meta_table.add_column("Value")
1526
+ meta_table.add_row("Table", found_table)
1527
+ meta_table.add_row("Key", full_key)
1528
+ meta_table.add_row("Compressed size", f"{meta['size_bytes'] / 1024:.2f} KB")
1529
+ meta_table.add_row("Decompressed size", f"{decompressed_size / 1024:.2f} KB")
1530
+ meta_table.add_row("Created at", created)
1531
+ meta_table.add_row("Age", _human_duration(meta["age_seconds"]))
1532
+ meta_table.add_row("TTL remaining", ttl_left)
1533
+ if "grammar_id" in meta:
1534
+ meta_table.add_row("Grammar ID", meta["grammar_id"])
1535
+ if "language" in meta:
1536
+ meta_table.add_row("Language", meta["language"])
1537
+ if "old_filename" in meta:
1538
+ meta_table.add_row("Old filename", meta["old_filename"])
1539
+ if "new_filename" in meta:
1540
+ meta_table.add_row("New filename", meta["new_filename"])
1541
+ if "file_count" in meta:
1542
+ meta_table.add_row("File count", str(meta["file_count"]))
1543
+
1544
+ _console.print(Panel(meta_table, title="[bold]Cache Entry[/bold]", expand=False))
1545
+
1546
+ if not payload_str:
1547
+ _console.print("[dim]No payload.[/dim]")
1548
+ return
1549
+
1550
+ payload = json.loads(payload_str)
1551
+
1552
+ # Per-table payload summary
1553
+ _console.print()
1554
+ if found_table == "diff_cache":
1555
+ changes = payload.get("changes", [])
1556
+ _console.print(
1557
+ f"[bold]SemanticDiff[/bold] language=[cyan]{payload.get('language', '?')}[/cyan]"
1558
+ f" changes=[yellow]{len(changes)}[/yellow]"
1559
+ f" semantic=[green]{payload.get('has_semantic_changes', '?')}[/green]"
1560
+ f" style_only=[dim]{payload.get('is_style_only', '?')}[/dim]"
1561
+ )
1562
+ for ch in changes[:3]:
1563
+ _console.print(
1564
+ f" • [yellow]{ch.get('change_type', '?')}[/yellow]"
1565
+ f" {ch.get('description', '')}"
1566
+ )
1567
+ if len(changes) > 3:
1568
+ _console.print(f" [dim]… and {len(changes) - 3} more changes[/dim]")
1569
+
1570
+ elif found_table == "parse_cache":
1571
+ _console.print(
1572
+ f"[bold]SemanticNode[/bold] type=[cyan]{payload.get('node_type', '?')}[/cyan]"
1573
+ f" label=[yellow]{payload.get('label', '?')}[/yellow]"
1574
+ f" children=[green]{len(payload.get('children', []))}[/green]"
1575
+ )
1576
+
1577
+ elif found_table == "symbol_index_cache":
1578
+ symbols: dict = payload.get("symbols", {})
1579
+ _console.print(f"[bold]SymbolIndex[/bold] symbols=[yellow]{len(symbols)}[/yellow]")
1580
+ for name in list(symbols.keys())[:10]:
1581
+ _console.print(f" • {name}")
1582
+ if len(symbols) > 10:
1583
+ _console.print(f" [dim]… and {len(symbols) - 10} more[/dim]")
1584
+
1585
+ elif found_table == "hover_map_cache":
1586
+ items = list(payload.items()) if isinstance(payload, dict) else []
1587
+ _console.print(f"[bold]HoverMap[/bold] entries=[yellow]{len(items)}[/yellow]")
1588
+ for node_id, type_str in items[:10]:
1589
+ _console.print(f" • [cyan]{node_id}[/cyan] → {type_str}")
1590
+ if len(items) > 10:
1591
+ _console.print(f" [dim]… and {len(items) - 10} more[/dim]")
1592
+
1593
+
1594
+ def _cmd_watch(args: argparse.Namespace) -> None:
1595
+ """Watch files/directories and show a semantic diff whenever a file is saved."""
1596
+ from intentumdiff.watcher import FileWatcher
1597
+
1598
+ fuel: int | None = getattr(args, "fuel", None)
1599
+ paths: list[str] = args.paths or ["."]
1600
+ repo_root = _resolve_repo_root(paths[0])
1601
+ ref: str = args.ref
1602
+ cfg = _load_cli_config(fuel=fuel, config_start_path=repo_root)
1603
+ differ = SemanticDiffer(cfg)
1604
+
1605
+ # ── LiveServer stdin mode (no file watcher) ───────────────────────────
1606
+ if getattr(args, "live_stdin", False):
1607
+ from intentumdiff.live_server import LiveServer
1608
+
1609
+ live_server = LiveServer(
1610
+ differ,
1611
+ repo_path=repo_root,
1612
+ ref=ref,
1613
+ debounce=getattr(args, "live_debounce", 0.15),
1614
+ stream_analysis=getattr(args, "live_stream", False),
1615
+ )
1616
+ _err.print(
1617
+ "[bold green]LiveServer[/bold green] ready — reading requests from stdin"
1618
+ )
1619
+ try:
1620
+ live_server.start_stdin()
1621
+ except KeyboardInterrupt:
1622
+ _err.print("\n[dim]Stopped.[/dim]")
1623
+ finally:
1624
+ live_server.stop()
1625
+ if differ._cache is not None:
1626
+ differ._cache.close()
1627
+ return
1628
+
1629
+ fmt: str = args.format
1630
+ output: str | None = getattr(args, "output", None)
1631
+
1632
+ def _render_fn(diff: SemanticDiff) -> None:
1633
+ _render(diff, fmt, output, fuel=cfg.plugin_fuel)
1634
+
1635
+ debounce: float = args.debounce
1636
+
1637
+ watcher = FileWatcher(
1638
+ paths,
1639
+ differ,
1640
+ render_fn=_render_fn,
1641
+ ref=ref,
1642
+ debounce=debounce,
1643
+ )
1644
+
1645
+ # ── Optional LiveServer socket ────────────────────────────────────────
1646
+ live_server: Any | None = None
1647
+ if getattr(args, "live", False):
1648
+ from intentumdiff.live_server import LiveServer
1649
+
1650
+ live_server = LiveServer(
1651
+ differ,
1652
+ repo_path=repo_root,
1653
+ ref=ref,
1654
+ debounce=getattr(args, "live_debounce", 0.15),
1655
+ console=_console,
1656
+ stream_analysis=getattr(args, "live_stream", False),
1657
+ )
1658
+ socket_path: str | None = getattr(args, "live_socket", None)
1659
+ addr = live_server.start_socket(socket_path)
1660
+ _console.print(f"[bold green]LiveServer[/bold green] listening on [cyan]{addr}[/cyan]")
1661
+
1662
+ _console.print(
1663
+ f"[bold green]Watching[/bold green] {len(paths)} path(s) against "
1664
+ f"[cyan]{ref}[/cyan] — [dim]Ctrl+C to stop[/dim]"
1665
+ )
1666
+ try:
1667
+ watcher.start()
1668
+ watcher.wait()
1669
+ except KeyboardInterrupt:
1670
+ watcher.stop()
1671
+ if live_server is not None:
1672
+ live_server.stop()
1673
+ _console.print("\n[dim]Stopped.[/dim]")
1674
+ finally:
1675
+ if live_server is not None:
1676
+ live_server.stop()
1677
+ if differ._cache is not None:
1678
+ differ._cache.close()
1679
+
1680
+
1681
+ def _cmd_live_server(args: argparse.Namespace) -> None:
1682
+ """Start the editor-facing LiveServer protocol endpoint."""
1683
+ from intentumdiff.live_server import LiveServer, _write_line
1684
+
1685
+ fuel: int | None = getattr(args, "fuel", None)
1686
+ repo_root = _resolve_repo_root(getattr(args, "repo", "."))
1687
+ cfg = _load_cli_config(fuel=fuel, config_start_path=repo_root)
1688
+ stream = bool(getattr(args, "stream", False))
1689
+ cfg.stream_analysis = stream
1690
+ differ = SemanticDiffer(cfg)
1691
+
1692
+ live_server = LiveServer(
1693
+ differ,
1694
+ repo_path=repo_root,
1695
+ ref=getattr(args, "ref", "HEAD"),
1696
+ debounce=getattr(args, "debounce", 0.15),
1697
+ stream_analysis=stream,
1698
+ )
1699
+
1700
+ try:
1701
+ socket_path: str | None = getattr(args, "socket", None)
1702
+ if socket_path is None:
1703
+ live_server.start_stdin()
1704
+ return
1705
+
1706
+ addr = live_server.start_socket(socket_path or None)
1707
+ _write_line(
1708
+ sys.stdout,
1709
+ live_server.ready_message(transport="socket", address=addr),
1710
+ )
1711
+ while True:
1712
+ time.sleep(3600)
1713
+ except KeyboardInterrupt:
1714
+ pass
1715
+ finally:
1716
+ live_server.stop()
1717
+ if differ._cache is not None:
1718
+ differ._cache.close()
1719
+
1720
+
1721
+ def _cmd_lsp_server(args: argparse.Namespace) -> None:
1722
+ """Start the IntentumDiff LSP server (stdio or TCP)."""
1723
+ try:
1724
+ from intentumdiff.lsp_server import create_server
1725
+ except ImportError:
1726
+ _err.print(
1727
+ "[red]Error:[/red] pygls is required for 'lsp-server'. "
1728
+ "Install with: [bold]pip install 'intentumdiff[lsp-server]'[/bold]"
1729
+ )
1730
+ sys.exit(1)
1731
+
1732
+ fuel: int | None = getattr(args, "fuel", None)
1733
+ cfg = _load_cli_config(fuel=fuel)
1734
+
1735
+ cache_path: str | None = getattr(args, "cache_path", None)
1736
+ if cache_path is not None:
1737
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1738
+
1739
+ store = SqliteCacheStore(Path(cache_path) / "cache.db")
1740
+ cfg = cfg.model_copy(update={"cache": store})
1741
+
1742
+ server = create_server(
1743
+ config=cfg,
1744
+ ref=args.ref,
1745
+ debounce=args.debounce,
1746
+ )
1747
+
1748
+ tcp_port: int | None = getattr(args, "tcp", None)
1749
+ if tcp_port is not None:
1750
+ _err.print(
1751
+ f"[bold green]IntentumDiff LSP[/bold green] listening on "
1752
+ f"[cyan]127.0.0.1:{tcp_port}[/cyan]"
1753
+ )
1754
+ server.start_tcp("127.0.0.1", tcp_port)
1755
+ else:
1756
+ # stdio is the default transport.
1757
+ server.start_io()
1758
+
1759
+
1760
+ def _cmd_serve(args: argparse.Namespace) -> None:
1761
+ """Start the IntentumDiff HTTP playground server."""
1762
+ try:
1763
+ import uvicorn # noqa: F401
1764
+
1765
+ from intentumdiff.serve import create_app
1766
+ except ImportError:
1767
+ _err.print(
1768
+ "[red]Error:[/red] fastapi and uvicorn are required for 'serve'. "
1769
+ "Install with: [bold]pip install 'intentumdiff[serve]'[/bold]"
1770
+ )
1771
+ sys.exit(1)
1772
+
1773
+ fuel: int | None = getattr(args, "fuel", None)
1774
+ cfg = _load_cli_config(fuel=fuel)
1775
+
1776
+ cache_path: str | None = getattr(args, "cache_path", None)
1777
+ if cache_path is not None:
1778
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1779
+
1780
+ store = SqliteCacheStore(Path(cache_path) / "cache.db")
1781
+ cfg = cfg.model_copy(update={"cache": store})
1782
+
1783
+ host: str = args.host
1784
+ port: int = args.port
1785
+
1786
+ # Guard against accidentally exposing the playground to the network.
1787
+ _loopback = {"127.0.0.1", "::1", "localhost"}
1788
+ if host not in _loopback and not getattr(args, "allow_remote", False):
1789
+ _err.print(
1790
+ f"[bold red]Error:[/bold red] binding to '{host}' would expose the "
1791
+ "playground on the network. "
1792
+ "Pass --allow-remote if this is intentional."
1793
+ )
1794
+ sys.exit(1)
1795
+
1796
+ cors_origins: list[str] | None = getattr(args, "cors_origins", None)
1797
+ app = create_app(config=cfg, cors_origins=cors_origins)
1798
+
1799
+ # Try the requested port; fall back to a free OS-assigned port if taken.
1800
+ import socket
1801
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as _s:
1802
+ _s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1803
+ try:
1804
+ _s.bind((host, port))
1805
+ _s.close()
1806
+ except OSError:
1807
+ _s.bind((host, 0))
1808
+ port = _s.getsockname()[1]
1809
+ _console.print(
1810
+ f"[yellow]Warning:[/yellow] requested port was unavailable; "
1811
+ f"binding to free port [cyan]{port}[/cyan] instead."
1812
+ )
1813
+
1814
+ _console.print(
1815
+ f"[bold green]IntentumDiff serve[/bold green] listening on "
1816
+ f"[cyan]http://{host}:{port}[/cyan] "
1817
+ f"([dim]Ctrl+C to stop[/dim])"
1818
+ )
1819
+ uvicorn.run(app, host=host, port=port, log_level="warning")
1820
+
1821
+
1822
+ def _cmd_cache_export(args: argparse.Namespace) -> None:
1823
+ """Export cache entries as NDJSON (one JSON object per line)."""
1824
+ import json
1825
+
1826
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1827
+
1828
+ cache_path = Path(args.cache_path) / "cache.db"
1829
+ if not cache_path.exists():
1830
+ _console.print(f"[yellow]No cache found at[/yellow] {cache_path}")
1831
+ return
1832
+
1833
+ tables_to_export = (
1834
+ [_TABLE_ALIAS[args.table]]
1835
+ if args.table and args.table != "all"
1836
+ else ["parse_cache", "diff_cache", "symbol_index_cache", "hover_map_cache"]
1837
+ )
1838
+
1839
+ store = SqliteCacheStore(cache_path)
1840
+ output_path = getattr(args, "output", None)
1841
+ fh = open(output_path, "w", encoding="utf-8") if output_path else sys.stdout # noqa: SIM115
1842
+ try:
1843
+ count = 0
1844
+ for tbl in tables_to_export:
1845
+ for entry in store.export_entries(tbl):
1846
+ fh.write(json.dumps(entry, default=str) + "\n")
1847
+ count += 1
1848
+ finally:
1849
+ if output_path:
1850
+ fh.close()
1851
+ store.close()
1852
+
1853
+ if output_path:
1854
+ _console.print(f"[green]Exported {count} entries to[/green] {output_path}")
1855
+
1856
+
1857
+ # ---------------------------------------------------------------------------
1858
+ # Date/duration helpers (used by cache list/inspect)
1859
+ # ---------------------------------------------------------------------------
1860
+
1861
+ def _parse_date_arg(value: str | None) -> int | None:
1862
+ """Parse a YYYY-MM-DD string to a Unix epoch int, or return None."""
1863
+ if value is None:
1864
+ return None
1865
+ import time # noqa: PLC0415
1866
+ try:
1867
+ return int(time.mktime(time.strptime(value, "%Y-%m-%d")))
1868
+ except ValueError:
1869
+ _err.print(f"[red]Invalid date format[/red]: {value!r} (expected YYYY-MM-DD)")
1870
+ sys.exit(1)
1871
+
1872
+
1873
+ _TABLE_ALIAS: dict[str | None, str | None] = {
1874
+ "parse": "parse_cache",
1875
+ "diff": "diff_cache",
1876
+ "index": "symbol_index_cache",
1877
+ "hover": "hover_map_cache",
1878
+ None: None,
1879
+ }
1880
+
1881
+
1882
+ def _human_duration(seconds: int) -> str:
1883
+ """Return a human-readable duration string from a seconds count."""
1884
+ if seconds < 60:
1885
+ return f"{seconds}s"
1886
+ if seconds < 3600:
1887
+ return f"{seconds // 60}m"
1888
+ if seconds < 86_400:
1889
+ return f"{seconds // 3600}h"
1890
+ return f"{seconds // 86_400}d"
1891
+
1892
+
1893
+ def _cmd_cache_clear(args: argparse.Namespace) -> None:
1894
+ """Clear cache entries selectively."""
1895
+ from intentumdiff.cache.sqlite_store import SqliteCacheStore
1896
+
1897
+ cache_path = Path(args.cache_path) / "cache.db"
1898
+ if not cache_path.exists():
1899
+ _console.print(f"[yellow]No cache found at[/yellow] {cache_path}")
1900
+ return
1901
+
1902
+ clear_all: bool = getattr(args, "all", False)
1903
+ clear_parse: bool = getattr(args, "parse", False) or clear_all
1904
+ clear_diff: bool = getattr(args, "diff", False) or clear_all
1905
+ clear_index: bool = getattr(args, "index", False) or clear_all
1906
+
1907
+ if not any([clear_parse, clear_diff, clear_index]):
1908
+ _err.print(
1909
+ "[yellow]Specify at least one of --parse, --diff, --index, or --all[/yellow]"
1910
+ )
1911
+ sys.exit(1)
1912
+
1913
+ store = SqliteCacheStore(cache_path)
1914
+ store.clear(parse=clear_parse, diff=clear_diff, index=clear_index)
1915
+ store.close()
1916
+
1917
+ cleared = ", ".join(
1918
+ t
1919
+ for t, flag in [
1920
+ ("parse_cache", clear_parse),
1921
+ ("diff_cache", clear_diff),
1922
+ ("symbol_index_cache", clear_index),
1923
+ ]
1924
+ if flag
1925
+ )
1926
+ _console.print(f"[green]Cleared:[/green] {cleared}")
1927
+
1928
+
1929
+ # ---------------------------------------------------------------------------
1930
+ # Parser construction
1931
+ # ---------------------------------------------------------------------------
1932
+
1933
+
1934
+ def _add_output_args(p: argparse.ArgumentParser) -> None:
1935
+ p.add_argument(
1936
+ "--format", "-f",
1937
+ choices=["terminal", "json", "patch", "html", "llm"],
1938
+ default="terminal",
1939
+ metavar="FORMAT",
1940
+ help="Output format: terminal (default), json, patch, html, llm",
1941
+ )
1942
+ p.add_argument(
1943
+ "--output", "-o",
1944
+ metavar="FILE",
1945
+ default=None,
1946
+ help="Write output to FILE instead of stdout",
1947
+ )
1948
+
1949
+
1950
+ def _parse_megapixels(value: str) -> int:
1951
+ try:
1952
+ megapixels = float(value)
1953
+ except ValueError:
1954
+ raise argparse.ArgumentTypeError(
1955
+ f"invalid megapixel value {value!r}: use a positive number"
1956
+ ) from None
1957
+ if megapixels <= 0:
1958
+ raise argparse.ArgumentTypeError("max decoded megapixels must be positive")
1959
+ return max(1, int(megapixels * 1_000_000))
1960
+
1961
+
1962
+ def _add_asset_diff_args(p: argparse.ArgumentParser) -> None:
1963
+ p.add_argument(
1964
+ "--out",
1965
+ default=".intentumdiff/assets",
1966
+ metavar="DIR",
1967
+ help="Directory for generated asset-diff artifacts.",
1968
+ )
1969
+ p.add_argument(
1970
+ "--json",
1971
+ action="store_true",
1972
+ default=False,
1973
+ help="Emit machine-readable JSON.",
1974
+ )
1975
+ p.add_argument(
1976
+ "--dimension-policy",
1977
+ choices=("strict", "resize", "pad"),
1978
+ default="strict",
1979
+ help="How to compare images with different dimensions.",
1980
+ )
1981
+ p.add_argument(
1982
+ "--pixel-threshold",
1983
+ type=int,
1984
+ default=16,
1985
+ metavar="N",
1986
+ help="Per-pixel channel threshold before a pixel counts as changed.",
1987
+ )
1988
+ p.add_argument(
1989
+ "--region-min-area",
1990
+ type=int,
1991
+ default=4,
1992
+ metavar="PX",
1993
+ help="Minimum connected changed-pixel region to keep.",
1994
+ )
1995
+ p.add_argument(
1996
+ "--alpha-handling",
1997
+ choices=("include", "ignore"),
1998
+ default="include",
1999
+ help="Whether alpha channel differences affect perceptual metrics.",
2000
+ )
2001
+ p.add_argument(
2002
+ "--max-decoded-megapixels",
2003
+ dest="max_decoded_pixels",
2004
+ type=_parse_megapixels,
2005
+ default=40_000_000,
2006
+ metavar="MP",
2007
+ help="Maximum decoded image size per asset, in megapixels (default: 40).",
2008
+ )
2009
+
2010
+
2011
+
2012
+ if TYPE_CHECKING:
2013
+ from intentumdiff.lsp.config import LspServerConfig as LspServerConfig # noqa: F811
2014
+
2015
+
2016
+ def _add_fuel_arg(p: argparse.ArgumentParser) -> None:
2017
+ p.add_argument(
2018
+ "--fuel",
2019
+ type=_parse_fuel,
2020
+ default=None,
2021
+ metavar="N",
2022
+ help=(
2023
+ "Wasm fuel budget (minimum) per plugin call. "
2024
+ "By default the budget scales automatically with file size. "
2025
+ "Use -1, 'inf', or 'infinite' to remove the cap entirely (use with care)."
2026
+ ),
2027
+ )
2028
+
2029
+
2030
+ def _add_resolve_references_arg(p: argparse.ArgumentParser) -> None:
2031
+ p.add_argument(
2032
+ "--resolve-references",
2033
+ dest="resolve_references",
2034
+ action="store_true",
2035
+ default=False,
2036
+ help=(
2037
+ "Attach a resolved SymbolDefinition to each ReferenceUsage returned "
2038
+ "by SemanticIndex.find_references() when exactly one matching "
2039
+ "definition exists in the index."
2040
+ ),
2041
+ )
2042
+
2043
+
2044
+ def _add_diagnostics_arg(p: argparse.ArgumentParser) -> None:
2045
+ p.add_argument(
2046
+ "--diagnostics",
2047
+ action="store_true",
2048
+ default=False,
2049
+ help=(
2050
+ "Include an opt-in semantic diagnostics trace in JSON output. "
2051
+ "Terminal rendering is unchanged."
2052
+ ),
2053
+ )
2054
+
2055
+
2056
+ def _add_diagnostics_db_arg(p: argparse.ArgumentParser) -> None:
2057
+ p.add_argument(
2058
+ "--diagnostics-db",
2059
+ metavar="FILE",
2060
+ default=None,
2061
+ help=(
2062
+ "Append normalized fuel diagnostics to a local DuckDB database. "
2063
+ "Use intentumdiff diagnostics summary/query to inspect it."
2064
+ ),
2065
+ )
2066
+
2067
+
2068
+ def _add_profile_phases_arg(p: argparse.ArgumentParser) -> None:
2069
+ p.add_argument(
2070
+ "--profile-phases",
2071
+ action="store_true",
2072
+ default=False,
2073
+ help=(
2074
+ "Emit compact phase timing JSON to stderr and attach timing metadata "
2075
+ "to diff results. Also enabled by INTENTUMDIFF_PROFILE_PHASES=1."
2076
+ ),
2077
+ )
2078
+
2079
+
2080
+ def _add_guardrail_args(p: argparse.ArgumentParser) -> None:
2081
+ p.add_argument(
2082
+ "--guardrails-strict",
2083
+ action="store_true",
2084
+ default=False,
2085
+ help=(
2086
+ "Exit non-zero when an immutable protected config guardrail "
2087
+ "violation is detected."
2088
+ ),
2089
+ )
2090
+ p.add_argument(
2091
+ "--guardrails-policy",
2092
+ metavar="PATH",
2093
+ default=None,
2094
+ help=(
2095
+ "Use a specific intentumdiff.yaml policy file for protected config "
2096
+ "guardrail rules."
2097
+ ),
2098
+ )
2099
+ p.add_argument(
2100
+ "--guardrails-annotations",
2101
+ choices=("github", "none"),
2102
+ default="none",
2103
+ help="Emit guardrail-only GitHub Actions annotations.",
2104
+ )
2105
+ p.add_argument(
2106
+ "--guardrails-sarif",
2107
+ metavar="FILE",
2108
+ default=None,
2109
+ help="Write guardrail-only SARIF 2.1.0 output to FILE.",
2110
+ )
2111
+ p.add_argument(
2112
+ "--guardrails-json",
2113
+ metavar="FILE",
2114
+ default=None,
2115
+ help="Write guardrail-only JSON output to FILE.",
2116
+ )
2117
+
2118
+
2119
+ class _GitPositionalsAction(argparse.Action):
2120
+ """Distribute optional [REPO] FILE positionals for the git sub-command.
2121
+
2122
+ With one positional: ``git FILE`` → repo=".", file=FILE
2123
+ With two positionals: ``git REPO FILE`` → repo=REPO, file=FILE
2124
+ With zero positionals: → repo=".", file=None (commit-wide)
2125
+ """
2126
+
2127
+ def __call__(
2128
+ self,
2129
+ parser: argparse.ArgumentParser,
2130
+ namespace: argparse.Namespace,
2131
+ values: list[str],
2132
+ option_string: str | None = None,
2133
+ ) -> None:
2134
+ if len(values) >= 2:
2135
+ namespace.repo = values[0]
2136
+ namespace.file = values[1]
2137
+ elif len(values) == 1:
2138
+ namespace.file = values[0]
2139
+ # else: keep set_defaults (repo=".", file=None)
2140
+
2141
+