ai-push-hooks 0.3.0 → 0.3.2

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 (40) hide show
  1. package/CHANGELOG.md +78 -2
  2. package/README.md +80 -993
  3. package/SECURITY.md +21 -16
  4. package/ai-push-hooks.toml +1 -1
  5. package/bin/ai-push-hooks.js +6 -6
  6. package/docs/configuration.md +263 -0
  7. package/package.json +4 -3
  8. package/pyproject.toml +12 -3
  9. package/src/ai_push_hooks/artifacts.py +19 -19
  10. package/src/ai_push_hooks/cli.py +24 -8
  11. package/src/ai_push_hooks/config.py +239 -54
  12. package/src/ai_push_hooks/engine.py +94 -43
  13. package/src/ai_push_hooks/executors/apply.py +124 -46
  14. package/src/ai_push_hooks/executors/ask.py +30 -536
  15. package/src/ai_push_hooks/executors/exec.py +73 -818
  16. package/src/ai_push_hooks/executors/runner_workflow.py +42 -20
  17. package/src/ai_push_hooks/executors/runners/claude.py +18 -6
  18. package/src/ai_push_hooks/executors/runners/codex.py +9 -3
  19. package/src/ai_push_hooks/executors/runners/command.py +25 -9
  20. package/src/ai_push_hooks/executors/runners/contracts.py +52 -25
  21. package/src/ai_push_hooks/executors/runners/opencode.py +109 -27
  22. package/src/ai_push_hooks/executors/runners/opencode_support.py +286 -0
  23. package/src/ai_push_hooks/executors/runners/process.py +97 -17
  24. package/src/ai_push_hooks/executors/runners/registry.py +31 -9
  25. package/src/ai_push_hooks/executors/step_commands.py +65 -20
  26. package/src/ai_push_hooks/git_utils.py +899 -0
  27. package/src/ai_push_hooks/hook.py +49 -13
  28. package/src/ai_push_hooks/install.py +40 -18
  29. package/src/ai_push_hooks/modules/beads.py +19 -8
  30. package/src/ai_push_hooks/modules/docs.py +146 -96
  31. package/src/ai_push_hooks/modules/pr.py +19 -8
  32. package/src/ai_push_hooks/paths.py +6 -2
  33. package/src/ai_push_hooks/plugin_loader.py +182 -105
  34. package/src/ai_push_hooks/plugins.py +3 -1
  35. package/src/ai_push_hooks/prompts_builtin.py +1 -1
  36. package/src/ai_push_hooks/types.py +48 -27
  37. package/vendor/README.md +15 -0
  38. package/vendor/requirements.txt +1 -0
  39. package/vendor/tomli-2.4.0-py3-none-any.whl +0 -0
  40. package/run.sh +0 -29
@@ -0,0 +1,899 @@
1
+ from __future__ import annotations
2
+
3
+ import codecs
4
+ import fnmatch
5
+ import json
6
+ import os
7
+ import pathlib
8
+ import re
9
+ import shlex
10
+ import stat
11
+ import subprocess
12
+ from urllib.parse import urlsplit
13
+
14
+ from .executors.runners.contracts import (
15
+ RunnerError,
16
+ RunnerExecutableNotFoundError,
17
+ RunnerSignalError,
18
+ RunnerTimeoutError,
19
+ bounded_redacted_diagnostics,
20
+ )
21
+ from .executors.runners.process import (
22
+ DEFAULT_MAX_OUTPUT_BYTES,
23
+ ProcessResult,
24
+ run_process,
25
+ )
26
+ from .paths import (
27
+ ensure_private_directory,
28
+ path_has_symlink,
29
+ path_is_link_or_reparse,
30
+ relative_path_parts,
31
+ resolve_contained_path,
32
+ write_text_no_follow,
33
+ )
34
+ from .types import (
35
+ FEATURE_BRANCH_PREFIXES,
36
+ ZERO_OID_LENGTHS,
37
+ HookError,
38
+ PushRefUpdate,
39
+ PushRevisionRange,
40
+ )
41
+
42
+ GIT_ERROR_BYTES = 64 * 1024
43
+ DIFF_TRUNCATION_MARKER = "\n[diff truncated]\n"
44
+ COMMAND_DEFAULT_TIMEOUT_SECONDS = 120
45
+ GITHUB_REPOSITORY_COMPONENT = re.compile(r"[A-Za-z0-9_.-]+\Z")
46
+
47
+
48
+ def env_bool(name: str) -> bool | None:
49
+ value = os.getenv(name)
50
+ if value is None:
51
+ return None
52
+ value = value.strip().lower()
53
+ if value in {"1", "true", "yes", "y", "on"}:
54
+ return True
55
+ if value in {"0", "false", "no", "n", "off"}:
56
+ return False
57
+ return None
58
+
59
+
60
+ def run_command(
61
+ args: list[str],
62
+ cwd: pathlib.Path,
63
+ input_text: str | None = None,
64
+ timeout: float | None = None,
65
+ check: bool = False,
66
+ env: dict[str, str | None] | None = None,
67
+ inherit_env: bool = True,
68
+ max_output_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
69
+ ) -> subprocess.CompletedProcess[str]:
70
+ """Run an argv command with bounded capture and fail-closed cleanup.
71
+
72
+ ``timeout=None`` is retained for compatibility with existing internal
73
+ callers, but now means the finite command budget rather than no timeout.
74
+ Output remains text decoded with surrogateescape and non-zero results are
75
+ returned unless ``check`` is true. Capture overflow always fails closed.
76
+ """
77
+
78
+ merged_env = os.environ.copy() if inherit_env else {}
79
+ if env is not None:
80
+ for key, value in env.items():
81
+ if value is None:
82
+ merged_env.pop(key, None)
83
+ else:
84
+ merged_env[key] = value
85
+
86
+ effective_timeout = COMMAND_DEFAULT_TIMEOUT_SECONDS if timeout is None else timeout
87
+ result = _run_bounded_text_command(
88
+ args,
89
+ cwd,
90
+ input_text=input_text,
91
+ timeout_seconds=effective_timeout,
92
+ check=check,
93
+ env=merged_env,
94
+ max_bytes=max_output_bytes,
95
+ )
96
+ return subprocess.CompletedProcess(
97
+ list(args), result.returncode, result.stdout, result.stderr
98
+ )
99
+
100
+
101
+ def _run_bounded_text_command(
102
+ args: list[str],
103
+ cwd: pathlib.Path,
104
+ max_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
105
+ *,
106
+ input_text: str | None = None,
107
+ timeout_seconds: float = COMMAND_DEFAULT_TIMEOUT_SECONDS,
108
+ check: bool = False,
109
+ env: dict[str, str] | None = None,
110
+ max_stderr_bytes: int | None = None,
111
+ ) -> ProcessResult:
112
+ """Run a bounded text command and normalize process failures.
113
+
114
+ Most Git commands must not silently consume a partial result. Diff
115
+ collection has separate handling because it deliberately preserves a
116
+ partial result and adds its own marker.
117
+ """
118
+
119
+ try:
120
+ process_kwargs: dict[str, object] = {
121
+ "cwd": cwd,
122
+ "input_text": input_text,
123
+ "timeout_seconds": timeout_seconds,
124
+ "env": env,
125
+ "max_output_bytes": max_bytes,
126
+ }
127
+ if max_stderr_bytes is not None:
128
+ process_kwargs["max_stderr_bytes"] = max_stderr_bytes
129
+ result = run_process(args, **process_kwargs)
130
+ except RunnerExecutableNotFoundError as exc:
131
+ raise HookError("Command executable was not found") from exc
132
+ except RunnerSignalError as exc:
133
+ process_result = _process_result_from_error(exc)
134
+ if not check and process_result is not None:
135
+ return process_result
136
+ details = _command_diagnostics(
137
+ args,
138
+ process_result.stdout if process_result else "",
139
+ process_result.stderr if process_result else "",
140
+ input_text=input_text,
141
+ env=env,
142
+ )
143
+ suffix = f": {details}" if details else ""
144
+ raise HookError(f"Command terminated by signal{suffix}") from exc
145
+ except RunnerTimeoutError as exc:
146
+ process_result = _process_result_from_error(exc)
147
+ details = _command_diagnostics(
148
+ args,
149
+ process_result.stdout if process_result else "",
150
+ process_result.stderr if process_result else "",
151
+ input_text=input_text,
152
+ env=env,
153
+ )
154
+ suffix = f": {details}" if details else ""
155
+ raise HookError(f"Command timed out{suffix}") from exc
156
+ except RunnerError as exc:
157
+ raise HookError(str(exc)) from exc
158
+
159
+ if result.stdout_truncated or result.stderr_truncated:
160
+ details = _command_diagnostics(
161
+ args,
162
+ result.stdout,
163
+ result.stderr,
164
+ input_text=input_text,
165
+ env=env,
166
+ )
167
+ details = details or "capture limit exceeded"
168
+ raise HookError(f"Command output exceeded capture limit: {details}")
169
+ if check and result.returncode != 0:
170
+ details = _command_diagnostics(
171
+ args,
172
+ result.stdout,
173
+ result.stderr,
174
+ input_text=input_text,
175
+ env=env,
176
+ )
177
+ details = details or f"exit code {result.returncode}"
178
+ raise HookError(f"Command failed: {details}")
179
+ return result
180
+
181
+
182
+ def _process_result_from_error(error: BaseException) -> ProcessResult | None:
183
+ result = getattr(error, "_process_result", None)
184
+ return result if isinstance(result, ProcessResult) else None
185
+
186
+
187
+ def _command_diagnostics(
188
+ args: list[str],
189
+ stdout: str,
190
+ stderr: str,
191
+ *,
192
+ input_text: str | None = None,
193
+ env: dict[str, str] | None = None,
194
+ ) -> str:
195
+ """Build a short diagnostic without echoing argv, prompts, or secrets."""
196
+
197
+ secret_values = [*args]
198
+ if input_text:
199
+ secret_values.append(input_text)
200
+ if env is not None:
201
+ secret_markers = (
202
+ "API_KEY",
203
+ "TOKEN",
204
+ "SECRET",
205
+ "PASSWORD",
206
+ "AUTH",
207
+ "CREDENTIAL",
208
+ )
209
+ secret_values.extend(
210
+ value
211
+ for name, value in env.items()
212
+ if any(marker in name.upper() for marker in secret_markers)
213
+ )
214
+ return bounded_redacted_diagnostics(stdout, stderr, secrets=secret_values)
215
+
216
+
217
+ def git(cwd: pathlib.Path, args: list[str], check: bool = True) -> str:
218
+ completed = run_command(["git", *args], cwd=cwd, check=check)
219
+ return completed.stdout.strip()
220
+
221
+
222
+ def resolve_repo_root(cwd: pathlib.Path) -> pathlib.Path:
223
+ return pathlib.Path(git(cwd, ["rev-parse", "--show-toplevel"])).resolve()
224
+
225
+
226
+ def resolve_git_dir(repo_root: pathlib.Path) -> pathlib.Path:
227
+ raw = git(repo_root, ["rev-parse", "--git-dir"])
228
+ path = pathlib.Path(raw)
229
+ if path.is_absolute():
230
+ return path
231
+ return (repo_root / path).resolve()
232
+
233
+
234
+ def resolve_git_common_dir(repo_root: pathlib.Path) -> pathlib.Path:
235
+ raw = git(repo_root, ["rev-parse", "--git-common-dir"])
236
+ path = pathlib.Path(raw)
237
+ if path.is_absolute():
238
+ return path.resolve()
239
+ return (repo_root / path).resolve()
240
+
241
+
242
+ def resolve_storage_path(
243
+ repo_root: pathlib.Path, git_dir: pathlib.Path, raw: str
244
+ ) -> pathlib.Path:
245
+ parts = relative_path_parts(raw, "Configured storage path")
246
+ posix_raw = raw.replace("\\", "/")
247
+ if parts[0] == ".git":
248
+ if len(parts) == 1:
249
+ return pathlib.Path(git_dir).resolve(strict=False)
250
+ lexical_path = pathlib.Path(git_dir).joinpath(*parts[1:])
251
+ if path_has_symlink(pathlib.Path(git_dir), lexical_path):
252
+ raise HookError(
253
+ f"Configured Git storage path must not traverse a symlink: {raw}"
254
+ )
255
+ return resolve_contained_path(
256
+ git_dir,
257
+ "/".join(parts[1:]),
258
+ "Configured Git storage path",
259
+ )
260
+ lexical_path = repo_root.joinpath(*parts)
261
+ if path_has_symlink(repo_root, lexical_path):
262
+ raise HookError(
263
+ f"Configured repository storage path must not traverse a symlink: {raw}"
264
+ )
265
+ return resolve_contained_path(
266
+ repo_root, posix_raw, "Configured repository storage path"
267
+ )
268
+
269
+
270
+ def ensure_dir(path: pathlib.Path) -> pathlib.Path | None:
271
+ try:
272
+ return ensure_private_directory(path)
273
+ except Exception: # noqa: BLE001
274
+ return None
275
+
276
+
277
+ def current_branch(repo_root: pathlib.Path) -> str:
278
+ return git(repo_root, ["rev-parse", "--abbrev-ref", "HEAD"], check=False).strip()
279
+
280
+
281
+ def is_feature_branch(branch_name: str) -> bool:
282
+ return bool(branch_name) and branch_name.startswith(FEATURE_BRANCH_PREFIXES)
283
+
284
+
285
+ def should_skip_for_sync_branch(
286
+ repo_root: pathlib.Path,
287
+ pushed_branches: list[str] | None = None,
288
+ push_updates: list[PushRefUpdate] | None = None,
289
+ ) -> tuple[bool, str]:
290
+ sync_branch = os.getenv("BEADS_SYNC_BRANCH", "beads-sync")
291
+ if pushed_branches is None:
292
+ pushed_branches = [current_branch(repo_root)]
293
+ if push_updates is not None:
294
+ only_sync_branch_updates = bool(push_updates) and all(
295
+ update.ref_kind == "branch"
296
+ and update.operation != "delete"
297
+ and update.branch_name == sync_branch
298
+ for update in push_updates
299
+ )
300
+ if push_updates and not only_sync_branch_updates:
301
+ return False, ""
302
+ else:
303
+ only_sync_branch_updates = bool(pushed_branches) and all(
304
+ branch_name == sync_branch for branch_name in pushed_branches
305
+ )
306
+ if "/.beads-sync-worktrees/" in repo_root.as_posix():
307
+ return True, "worktree is inside .beads-sync-worktrees"
308
+ if only_sync_branch_updates:
309
+ return True, f"all pushed branches are {sync_branch}"
310
+ return False, ""
311
+
312
+
313
+ def path_matches(path: str, pattern: str) -> bool:
314
+ path_parts = tuple(path.split("/"))
315
+ if (
316
+ not path_parts
317
+ or path.startswith("/")
318
+ or any(part in {"", ".", ".."} for part in path_parts)
319
+ ):
320
+ return False
321
+ try:
322
+ pattern_parts = relative_path_parts(pattern, "Glob pattern")
323
+ except HookError:
324
+ return False
325
+
326
+ memo: dict[tuple[int, int], bool] = {}
327
+
328
+ def matches(path_index: int, pattern_index: int) -> bool:
329
+ key = (path_index, pattern_index)
330
+ if key in memo:
331
+ return memo[key]
332
+ if pattern_index == len(pattern_parts):
333
+ result = path_index == len(path_parts)
334
+ elif pattern_parts[pattern_index] == "**":
335
+ result = matches(path_index, pattern_index + 1) or (
336
+ path_index < len(path_parts) and matches(path_index + 1, pattern_index)
337
+ )
338
+ else:
339
+ result = (
340
+ path_index < len(path_parts)
341
+ and fnmatch.fnmatchcase(
342
+ path_parts[path_index], pattern_parts[pattern_index]
343
+ )
344
+ and matches(path_index + 1, pattern_index + 1)
345
+ )
346
+ memo[key] = result
347
+ return result
348
+
349
+ return matches(0, 0)
350
+
351
+
352
+ def list_repo_changes(repo_root: pathlib.Path) -> set[str]:
353
+ changes: set[str] = set()
354
+ output = run_command(
355
+ ["git", "status", "--porcelain=v1", "-z", "--untracked-files=all"],
356
+ cwd=repo_root,
357
+ ).stdout
358
+ records = output.split("\x00")
359
+ index = 0
360
+ while index < len(records):
361
+ record = records[index]
362
+ index += 1
363
+ if not record:
364
+ continue
365
+ if len(record) < 4 or record[2] != " ":
366
+ raise HookError("Malformed output from `git status --porcelain=v1 -z`")
367
+ status = record[:2]
368
+ changes.add(record[3:])
369
+ if "R" in status or "C" in status:
370
+ if index >= len(records) or not records[index]:
371
+ raise HookError(
372
+ "Malformed rename output from `git status --porcelain=v1 -z`"
373
+ )
374
+ changes.add(records[index])
375
+ index += 1
376
+ return changes
377
+
378
+
379
+ def parse_push_updates(stdin_lines: list[str]) -> list[PushRefUpdate]:
380
+ updates: list[PushRefUpdate] = []
381
+ oid_pattern = re.compile(r"[0-9a-fA-F]+\Z")
382
+ for line_number, line in enumerate(stdin_lines, start=1):
383
+ if not line.strip():
384
+ continue
385
+ parts = line.split()
386
+ if len(parts) != 4:
387
+ raise HookError(
388
+ f"Malformed pre-push input on line {line_number}: expected four fields"
389
+ )
390
+ local_ref, local_sha, remote_ref, remote_sha = parts
391
+ if (
392
+ len(local_sha) not in ZERO_OID_LENGTHS
393
+ or len(remote_sha) != len(local_sha)
394
+ or oid_pattern.fullmatch(local_sha) is None
395
+ or oid_pattern.fullmatch(remote_sha) is None
396
+ ):
397
+ raise HookError(
398
+ f"Malformed pre-push input on line {line_number}: expected full SHA-1 or SHA-256 object IDs"
399
+ )
400
+ updates.append(
401
+ PushRefUpdate(
402
+ local_ref=local_ref,
403
+ local_sha=local_sha.lower(),
404
+ remote_ref=remote_ref,
405
+ remote_sha=remote_sha.lower(),
406
+ )
407
+ )
408
+ return updates
409
+
410
+
411
+ def _resolve_commit(repo_root: pathlib.Path, oid: str) -> str:
412
+ return git(
413
+ repo_root,
414
+ ["rev-parse", "--verify", "--quiet", f"{oid}^{{commit}}"],
415
+ check=False,
416
+ )
417
+
418
+
419
+ def _configured_base_commit(
420
+ repo_root: pathlib.Path, remote_name: str, base_branch: str
421
+ ) -> str:
422
+ base_branch = base_branch.strip() or "main"
423
+ candidates: list[str] = []
424
+ if base_branch.startswith("refs/"):
425
+ candidates.append(base_branch)
426
+ else:
427
+ configured_remotes = set(git(repo_root, ["remote"], check=False).splitlines())
428
+ if remote_name in configured_remotes:
429
+ candidates.append(f"refs/remotes/{remote_name}/{base_branch}")
430
+ candidates.append(f"refs/heads/{base_branch}")
431
+ for candidate in candidates:
432
+ commit = _resolve_commit(repo_root, candidate)
433
+ if commit:
434
+ return commit
435
+ return ""
436
+
437
+
438
+ def _empty_tree_oid(repo_root: pathlib.Path) -> str:
439
+ completed = run_command(
440
+ ["git", "hash-object", "-t", "tree", "--stdin"],
441
+ cwd=repo_root,
442
+ input_text="",
443
+ check=True,
444
+ )
445
+ return (completed.stdout or "").strip()
446
+
447
+
448
+ def _fallback_range(
449
+ repo_root: pathlib.Path,
450
+ remote_name: str,
451
+ base_branch: str,
452
+ local_commit: str,
453
+ *,
454
+ reason: str,
455
+ pushed_ref: str,
456
+ ) -> tuple[str, str]:
457
+ configured_base = base_branch.strip() or "main"
458
+ configured_base_ref = ""
459
+ if configured_base.startswith("refs/heads/"):
460
+ configured_base_ref = configured_base
461
+ elif configured_base.startswith("refs/remotes/"):
462
+ remote_base = configured_base.removeprefix("refs/remotes/").split("/", 1)
463
+ if len(remote_base) == 2 and all(remote_base):
464
+ configured_base_ref = f"refs/heads/{remote_base[1]}"
465
+ elif not configured_base.startswith("refs/"):
466
+ configured_base_ref = f"refs/heads/{configured_base}"
467
+
468
+ # A zero advertised OID means the remote target is absent; a local or stale
469
+ # tracking base cannot describe this first publication.
470
+ if pushed_ref == configured_base_ref:
471
+ return f"{_empty_tree_oid(repo_root)}..{local_commit}", f"{reason}:empty-tree"
472
+
473
+ base_commit = _configured_base_commit(repo_root, remote_name, base_branch)
474
+ if base_commit:
475
+ merge_base = git(
476
+ repo_root, ["merge-base", local_commit, base_commit], check=False
477
+ )
478
+ if merge_base:
479
+ return f"{merge_base}..{local_commit}", f"{reason}:configured-base"
480
+ return f"{_empty_tree_oid(repo_root)}..{local_commit}", f"{reason}:empty-tree"
481
+
482
+
483
+ def collect_revision_ranges(
484
+ repo_root: pathlib.Path,
485
+ remote_name: str,
486
+ updates: list[PushRefUpdate],
487
+ base_branch: str = "main",
488
+ ) -> list[PushRevisionRange]:
489
+ ranges: list[PushRevisionRange] = []
490
+ for update in updates:
491
+ if update.operation == "delete":
492
+ continue
493
+ local_commit = _resolve_commit(repo_root, update.local_sha)
494
+ if not local_commit:
495
+ # Tags may legally point to non-commit objects. They still remain in
496
+ # push_updates, but there is no commit/tree diff to collect for them.
497
+ continue
498
+ if update.operation == "update":
499
+ remote_commit = _resolve_commit(repo_root, update.remote_sha)
500
+ if remote_commit:
501
+ expression = f"{remote_commit}..{local_commit}"
502
+ strategy = "remote-object"
503
+ else:
504
+ raise HookError(
505
+ "Advertised remote commit is unavailable locally; refusing to "
506
+ f"approximate push range for {update.remote_ref}: {update.remote_sha}"
507
+ )
508
+ else:
509
+ expression, strategy = _fallback_range(
510
+ repo_root,
511
+ remote_name,
512
+ base_branch,
513
+ local_commit,
514
+ reason="new-ref",
515
+ pushed_ref=update.remote_ref,
516
+ )
517
+ ranges.append(
518
+ PushRevisionRange(update=update, expression=expression, strategy=strategy)
519
+ )
520
+ return ranges
521
+
522
+
523
+ def unique_range_expressions(ranges: list[PushRevisionRange]) -> list[str]:
524
+ return list(dict.fromkeys(item.expression for item in ranges))
525
+
526
+
527
+ def collect_ranges_from_stdin(
528
+ repo_root: pathlib.Path,
529
+ remote_name: str,
530
+ stdin_lines: list[str],
531
+ base_branch: str = "main",
532
+ ) -> list[str]:
533
+ updates = parse_push_updates(stdin_lines)
534
+ return unique_range_expressions(
535
+ collect_revision_ranges(repo_root, remote_name, updates, base_branch)
536
+ )
537
+
538
+
539
+ def collect_changed_files(repo_root: pathlib.Path, ranges: list[str]) -> list[str]:
540
+ files: set[str] = set()
541
+ for range_expr in ranges:
542
+ output = run_command(
543
+ [
544
+ "git",
545
+ "diff",
546
+ "--name-only",
547
+ "--diff-filter=ACMRD",
548
+ "-z",
549
+ range_expr,
550
+ ],
551
+ cwd=repo_root,
552
+ check=True,
553
+ ).stdout
554
+ for path in output.split("\x00"):
555
+ if path:
556
+ files.add(path)
557
+ return sorted(files)
558
+
559
+
560
+ def _collect_bounded_git_diff(
561
+ repo_root: pathlib.Path, args: list[str], max_bytes: int
562
+ ) -> tuple[bytes, bool]:
563
+ limit = max(0, max_bytes)
564
+ # Keep the diff's historical partial-capture behavior: a diff that reaches
565
+ # its caller-provided budget is returned with a marker rather than treated
566
+ # as a failed command. The generic process engine still owns timeout,
567
+ # bounded stream draining, and process-group cleanup. Keep stderr at its
568
+ # historical diagnostic bound even when the diff budget is much larger.
569
+ try:
570
+ result = run_process(
571
+ args,
572
+ cwd=repo_root,
573
+ timeout_seconds=COMMAND_DEFAULT_TIMEOUT_SECONDS,
574
+ max_output_bytes=limit,
575
+ max_stderr_bytes=GIT_ERROR_BYTES,
576
+ )
577
+ except (RunnerTimeoutError, RunnerSignalError) as exc:
578
+ process_result = _process_result_from_error(exc)
579
+ details = _command_diagnostics(
580
+ args,
581
+ process_result.stdout if process_result else "",
582
+ process_result.stderr if process_result else "",
583
+ )
584
+ reason = (
585
+ "timed out"
586
+ if isinstance(exc, RunnerTimeoutError)
587
+ else "terminated by signal"
588
+ )
589
+ suffix = f": {details}" if details else ""
590
+ raise HookError(f"Git diff command {reason}{suffix}") from exc
591
+ except RunnerError as exc:
592
+ raise HookError(str(exc)) from exc
593
+
594
+ output = result.stdout_bytes[:limit]
595
+ truncated = result.stdout_truncated
596
+ if result.returncode != 0 and not truncated:
597
+ details = _command_diagnostics(args, result.stdout, result.stderr)
598
+ details = details or f"exit code {result.returncode}"
599
+ raise HookError(f"Command failed: {details}")
600
+ return output, truncated
601
+
602
+
603
+ def _decode_diff_output(output: bytes, max_bytes: int, truncated: bool) -> str:
604
+ limit = max(0, max_bytes)
605
+ if limit == 0:
606
+ return ""
607
+
608
+ # Diff artifacts are written as strict UTF-8. Git normally emits UTF-8,
609
+ # but malformed bytes are represented explicitly as U+FFFD rather than
610
+ # leaking surrogateescape code points into the artifact writer. A decoder
611
+ # left non-final for a source-truncated stream drops only its incomplete
612
+ # pending character; a final decoder represents malformed EOF bytes.
613
+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
614
+ normalized = decoder.decode(output, final=not truncated)
615
+ normalized_bytes = normalized.encode("utf-8")
616
+ marker = DIFF_TRUNCATION_MARKER.encode("utf-8")
617
+ if not truncated and len(normalized_bytes) <= limit:
618
+ return normalized
619
+ if len(marker) >= limit:
620
+ return marker[:limit].decode("ascii")
621
+ payload_limit = limit - len(marker)
622
+ payload = normalized_bytes[:payload_limit].decode("utf-8", errors="ignore")
623
+ return payload + DIFF_TRUNCATION_MARKER
624
+
625
+
626
+ def collect_diff(repo_root: pathlib.Path, ranges: list[str], max_bytes: int) -> str:
627
+ output = bytearray()
628
+ limit = max(0, max_bytes)
629
+ truncated = False
630
+ for index, range_expr in enumerate(ranges):
631
+ prefix = ("\n" if index else "") + f"### RANGE {range_expr}\n"
632
+ prefix_bytes = prefix.encode("utf-8", errors="surrogateescape")
633
+ remaining = limit - len(output)
634
+ if len(prefix_bytes) > remaining:
635
+ output.extend(prefix_bytes[:remaining])
636
+ truncated = True
637
+ break
638
+ output.extend(prefix_bytes)
639
+
640
+ body, body_truncated = _collect_bounded_git_diff(
641
+ repo_root,
642
+ ["git", "diff", "--unified=3", range_expr],
643
+ limit - len(output),
644
+ )
645
+ if not body_truncated:
646
+ # `git()` historically stripped the captured diff before adding the
647
+ # section's trailing newline. Keep that output shape when the body
648
+ # fits, without ever collecting more than the remaining budget.
649
+ body = body.rstrip()
650
+ output.extend(body)
651
+ if body_truncated:
652
+ truncated = True
653
+ break
654
+
655
+ if len(output) >= limit:
656
+ truncated = True
657
+ break
658
+ output.extend(b"\n")
659
+ return _decode_diff_output(bytes(output), limit, truncated)
660
+
661
+
662
+ def collect_commit_messages_for_ranges(
663
+ repo_root: pathlib.Path, ranges: list[str]
664
+ ) -> list[dict[str, str]]:
665
+ commits: list[dict[str, str]] = []
666
+ seen_hashes: set[str] = set()
667
+ for range_expr in ranges:
668
+ completed = run_command(
669
+ ["git", "log", "--format=%H%x1f%s%x1f%b%x1e", range_expr],
670
+ cwd=repo_root,
671
+ check=True,
672
+ )
673
+ raw = completed.stdout or ""
674
+ for record in raw.split("\x1e"):
675
+ payload = record.rstrip("\r\n")
676
+ if not payload:
677
+ continue
678
+ parts = payload.split("\x1f", 2)
679
+ if len(parts) == 2:
680
+ commit_hash, subject = parts
681
+ body = ""
682
+ elif len(parts) == 3:
683
+ commit_hash, subject, body = parts
684
+ else:
685
+ continue
686
+ clean_hash = commit_hash.strip()
687
+ if not clean_hash or clean_hash in seen_hashes:
688
+ continue
689
+ seen_hashes.add(clean_hash)
690
+ commits.append(
691
+ {
692
+ "hash": clean_hash,
693
+ "subject": subject.strip(),
694
+ "body": body.strip(),
695
+ }
696
+ )
697
+ return commits
698
+
699
+
700
+ def write_text_file(
701
+ path: pathlib.Path,
702
+ content: str,
703
+ *,
704
+ root: pathlib.Path | None = None,
705
+ ) -> bool:
706
+ try:
707
+ if root is None:
708
+ path.parent.mkdir(parents=True, exist_ok=True)
709
+ else:
710
+ root = root.resolve(strict=True)
711
+ lexical_path = pathlib.Path(os.path.abspath(path))
712
+ relative_parent = lexical_path.parent.relative_to(root)
713
+ current = root
714
+ for part in relative_parent.parts:
715
+ current = current / part
716
+ if path_is_link_or_reparse(current):
717
+ raise HookError(
718
+ f"Output path traverses a symlink or reparse point: {path}"
719
+ )
720
+ if not current.exists():
721
+ current.mkdir()
722
+ if not current.is_dir():
723
+ raise HookError(f"Output path has a non-directory parent: {path}")
724
+ if path_has_symlink(root, lexical_path):
725
+ raise HookError(f"Output path traverses a symlink: {path}")
726
+ if lexical_path.exists() and not stat.S_ISREG(lexical_path.lstat().st_mode):
727
+ raise HookError(f"Output path is not a regular file: {path}")
728
+ write_text_no_follow(path, content)
729
+ return True
730
+ except Exception: # noqa: BLE001
731
+ return False
732
+
733
+
734
+ def parse_key_value_text(text: str) -> dict[str, str]:
735
+ payload: dict[str, str] = {}
736
+ for line in text.splitlines():
737
+ if "=" not in line:
738
+ continue
739
+ key, value = line.split("=", 1)
740
+ payload[key.strip()] = value.strip()
741
+ return payload
742
+
743
+
744
+ def _github_repository_from_url(remote_url: str) -> str:
745
+ value = remote_url.strip()
746
+ if not value or "\x00" in value or any(ord(character) < 32 for character in value):
747
+ return ""
748
+ scp_match = re.fullmatch(
749
+ r"(?:[^@/:\s]+@)?github\.com:([^/\s]+)/([^/\s]+)", value, re.IGNORECASE
750
+ )
751
+ if scp_match:
752
+ owner, repository = scp_match.groups()
753
+ else:
754
+ try:
755
+ parsed = urlsplit(value)
756
+ except ValueError:
757
+ return ""
758
+ if (
759
+ parsed.scheme.lower() not in {"git", "http", "https", "ssh"}
760
+ or (parsed.hostname or "").casefold() != "github.com"
761
+ or parsed.query
762
+ or parsed.fragment
763
+ or "%" in parsed.path
764
+ ):
765
+ return ""
766
+ parts = [part for part in parsed.path.split("/") if part]
767
+ if len(parts) != 2:
768
+ return ""
769
+ owner, repository = parts
770
+ if repository.endswith(".git"): # noqa: FURB188
771
+ repository = repository[:-4]
772
+ if (
773
+ not owner
774
+ or not repository
775
+ or owner in {".", ".."}
776
+ or repository in {".", ".."}
777
+ or GITHUB_REPOSITORY_COMPONENT.fullmatch(owner) is None
778
+ or GITHUB_REPOSITORY_COMPONENT.fullmatch(repository) is None
779
+ ):
780
+ return ""
781
+ return f"{owner}/{repository}"
782
+
783
+
784
+ def resolve_github_repository(
785
+ repo_root: pathlib.Path, remote_name: str, remote_url: str
786
+ ) -> str:
787
+ repository = _github_repository_from_url(remote_url)
788
+ if repository:
789
+ return repository
790
+ if remote_url.strip():
791
+ raise HookError(
792
+ "Cannot safely determine GitHub repository from push remote URL"
793
+ )
794
+ repository = _github_repository_from_url(remote_name)
795
+ if repository:
796
+ return repository
797
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]*", remote_name):
798
+ raise HookError("Cannot safely resolve push remote name")
799
+ configured_url = git(
800
+ repo_root, ["remote", "get-url", "--push", remote_name], check=False
801
+ )
802
+ repository = _github_repository_from_url(configured_url)
803
+ if not repository:
804
+ raise HookError(
805
+ "Cannot safely determine GitHub repository for the configured push remote"
806
+ )
807
+ return repository
808
+
809
+
810
+ def lookup_open_pr_url(
811
+ repo_root: pathlib.Path,
812
+ branch_name: str,
813
+ base_branch: str = "",
814
+ repository: str = "",
815
+ ) -> str:
816
+ if not repository:
817
+ raise HookError("GitHub repository scope is required for PR lookup")
818
+ args = [
819
+ "gh",
820
+ "pr",
821
+ "list",
822
+ "--repo",
823
+ repository,
824
+ "--head",
825
+ branch_name,
826
+ "--state",
827
+ "open",
828
+ "--limit",
829
+ "1",
830
+ "--json",
831
+ "url",
832
+ ]
833
+ if base_branch:
834
+ args.extend(["--base", base_branch])
835
+ completed = run_command(
836
+ args,
837
+ cwd=repo_root,
838
+ check=False,
839
+ )
840
+ if completed.returncode != 0:
841
+ details = _command_diagnostics(
842
+ args, completed.stdout or "", completed.stderr or ""
843
+ )
844
+ raise HookError(details or "`gh pr list` failed")
845
+ try:
846
+ payload = json.loads((completed.stdout or "").strip() or "[]")
847
+ except json.JSONDecodeError as exc:
848
+ raise HookError("Failed to parse `gh pr list` JSON output") from exc
849
+ if isinstance(payload, list) and payload and isinstance(payload[0], dict):
850
+ return str(payload[0].get("url", "")).strip()
851
+ return ""
852
+
853
+
854
+ def extract_pr_url(text: str) -> str:
855
+ match = re.search(r"https://github\.com/[^\s]+/pull/\d+", text)
856
+ return match.group(0).strip() if match else ""
857
+
858
+
859
+ def sanitize_pr_title(raw_title: str, branch_name: str) -> str:
860
+ title = re.sub(r"\s+", " ", raw_title).strip() or branch_name
861
+ return title[:240]
862
+
863
+
864
+ def initial_pr_defer_reason(branch_name: str, base_branch: str) -> str:
865
+ return (
866
+ f"PR creation deferred because `{branch_name}` does not exist on the remote before "
867
+ "this initial push. Complete the push, then create the PR with "
868
+ f"`gh pr create --head {shlex.quote(branch_name)} --base "
869
+ f"{shlex.quote(base_branch)}`, or push another commit with PR creation enabled."
870
+ )
871
+
872
+
873
+ def build_fallback_pr_body(
874
+ branch_name: str,
875
+ ranges: list[str],
876
+ changed_files: list[str],
877
+ commits: list[dict[str, str]],
878
+ ) -> str:
879
+ lines = [
880
+ "## Summary",
881
+ f"- Auto-created by `ai-push-hooks` for branch `{branch_name}`.",
882
+ ]
883
+ if ranges:
884
+ lines.append(f"- Push range: `{', '.join(ranges)}`.")
885
+ if commits:
886
+ lines.append("")
887
+ lines.append("## Commits")
888
+ for commit in commits[:8]:
889
+ subject = str(commit.get("subject", "")).strip()
890
+ if subject:
891
+ lines.append(f"- {subject}")
892
+ if changed_files:
893
+ lines.append("")
894
+ lines.append("## Changed Files")
895
+ for path in changed_files[:15]:
896
+ lines.append(f"- `{path}`")
897
+ if len(changed_files) > 15:
898
+ lines.append(f"- and {len(changed_files) - 15} more")
899
+ return "\n".join(lines).strip() + "\n"