@danmoisan/drm-copilot-mcp 0.0.5 → 1.0.0

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 (96) hide show
  1. package/out/mcp-server.js +10268 -380
  2. package/package.json +2 -2
  3. package/resources/claude-customizations/.claude/agents/orchestrator.md +6 -2
  4. package/resources/claude-customizations/.claude/agents/pr-author.md +78 -0
  5. package/resources/claude-customizations/.claude/agents/task-researcher.md +10 -6
  6. package/resources/claude-customizations/.claude/hooks/enforce-checkpoint-monotonic.ps1 +68 -10
  7. package/resources/claude-customizations/.claude/hooks/enforce-completion-consistency.ps1 +148 -11
  8. package/resources/claude-customizations/.claude/hooks/enforce-completion-helpers.ps1 +163 -0
  9. package/resources/claude-customizations/.claude/hooks/enforce-evidence-locations.ps1 +40 -14
  10. package/resources/claude-customizations/.claude/hooks/enforce-orchestration-preimplementation-gate.ps1 +198 -0
  11. package/resources/claude-customizations/.claude/hooks/enforce-pr-author-skill.ps1 +153 -10
  12. package/resources/claude-customizations/.claude/hooks/validate-orchestrator-output.ps1 +68 -1
  13. package/resources/claude-customizations/.claude/hooks/validate-pr-author-output.ps1 +136 -0
  14. package/resources/claude-customizations/.claude/hooks/validate-task-researcher-output.ps1 +22 -6
  15. package/resources/claude-customizations/.claude/settings.json +22 -0
  16. package/resources/claude-customizations/.claude/skills/evidence-and-timestamp-conventions/SKILL.md +0 -1
  17. package/resources/claude-customizations/.claude/skills/orchestrate/SKILL.md +76 -2
  18. package/resources/claude-customizations/.claude/skills/research-issue/SKILL.md +5 -3
  19. package/resources/claude-customizations/.claude-variants/csharp-legacy/agents/csharp-typed-engineer.md +69 -0
  20. package/resources/claude-customizations/.claude-variants/csharp-legacy/rules/csharp.md +96 -0
  21. package/resources/claude-customizations/.claude-variants/csharp-legacy/skills/csharp-qa-gate/SKILL.md +77 -0
  22. package/resources/claude-customizations/.claude-variants/csharp-legacy/skills/invoke-csharp-engineer/SKILL.md +64 -0
  23. package/resources/claude-customizations/pack-manifests/core.json +65 -0
  24. package/resources/claude-customizations/pack-manifests/csharp-legacy.json +11 -0
  25. package/resources/claude-customizations/pack-manifests/csharp-modern.json +12 -0
  26. package/resources/claude-customizations/pack-manifests/powershell.json +14 -0
  27. package/resources/claude-customizations/pack-manifests/python.json +14 -0
  28. package/resources/claude-customizations/pack-manifests/typescript.json +9 -0
  29. package/resources/codex-and-agents-customizations/.agents/skills/feature-promotion-lifecycle/SKILL.md +30 -13
  30. package/resources/codex-and-agents-customizations/.agents/skills/orchestrate/SKILL.md +113 -10
  31. package/resources/codex-and-agents-customizations/.agents/skills/orchestrator-workflow/SKILL.md +33 -8
  32. package/resources/codex-and-agents-customizations/.agents/skills/repo-automation-adapter/SKILL.md +12 -7
  33. package/resources/codex-and-agents-customizations/.codex/config.toml +65 -6
  34. package/resources/codex-and-agents-customizations/.codex/hooks/enforce-checkpoint-monotonic.ps1 +303 -0
  35. package/resources/codex-and-agents-customizations/.codex/hooks/enforce-completion-consistency.ps1 +300 -0
  36. package/resources/codex-and-agents-customizations/.codex/hooks/enforce-orchestration-preimplementation-gate.ps1 +148 -0
  37. package/resources/codex-and-agents-customizations/.codex/hooks/enforce-pr-author-skill.ps1 +336 -0
  38. package/resources/codex-and-agents-customizations/.codex/hooks/enforce-promotion-mcp-only.ps1 +83 -17
  39. package/resources/config/orchestration-routing.json +5 -13
  40. package/resources/customizations/.github/agents/pr-author.agent.md +25 -0
  41. package/resources/customizations/.github/agents/task-researcher.agent.md +4 -4
  42. package/resources/customizations/.github/prompts/fillout-prd-feature.prompt.md +1 -1
  43. package/resources/customizations/.github/prompts/research-issue.prompt.md +4 -3
  44. package/resources/codex-and-agents-customizations/.codex/scripts/post-codex-worktree-session.ps1 +0 -5
  45. package/resources/scripts/dev_tools/__init__.py +0 -0
  46. package/resources/scripts/dev_tools/_orchestrator_state_human_interaction.py +0 -127
  47. package/resources/scripts/dev_tools/_orchestrator_state_routing.py +0 -216
  48. package/resources/scripts/dev_tools/agentic_sync.py +0 -819
  49. package/resources/scripts/dev_tools/codex_native_converter/__init__.py +0 -11
  50. package/resources/scripts/dev_tools/codex_native_converter/__main__.py +0 -6
  51. package/resources/scripts/dev_tools/codex_native_converter/cli.py +0 -11
  52. package/resources/scripts/dev_tools/new_active_feature_folder.py +0 -79
  53. package/resources/scripts/dev_tools/new_active_feature_folder_docs.py +0 -268
  54. package/resources/scripts/dev_tools/new_active_feature_folder_flow.py +0 -366
  55. package/resources/scripts/dev_tools/new_active_feature_folder_io.py +0 -306
  56. package/resources/scripts/dev_tools/new_active_feature_folder_markdown.py +0 -252
  57. package/resources/scripts/dev_tools/new_active_feature_folder_models.py +0 -136
  58. package/resources/scripts/dev_tools/new_potential_bug_entry.py +0 -465
  59. package/resources/scripts/dev_tools/potential_to_issue.py +0 -421
  60. package/resources/scripts/dev_tools/potential_to_issue_content.py +0 -212
  61. package/resources/scripts/dev_tools/pr_context/__init__.py +0 -0
  62. package/resources/scripts/dev_tools/pr_context/collector.py +0 -619
  63. package/resources/scripts/dev_tools/pr_context/feature_docs.py +0 -349
  64. package/resources/scripts/dev_tools/pr_context/git.py +0 -153
  65. package/resources/scripts/dev_tools/pr_context/github.py +0 -549
  66. package/resources/scripts/dev_tools/pr_context/models.py +0 -198
  67. package/resources/scripts/dev_tools/pr_context/render.py +0 -342
  68. package/resources/scripts/dev_tools/pr_context/render_feature_excerpts.py +0 -256
  69. package/resources/scripts/dev_tools/pr_context/render_pr_helpers.py +0 -291
  70. package/resources/scripts/dev_tools/pr_context/summary_helpers.py +0 -386
  71. package/resources/scripts/dev_tools/pr_context/verification_evidence.py +0 -171
  72. package/resources/scripts/dev_tools/prompt_mode_contract.py +0 -152
  73. package/resources/scripts/dev_tools/push_down_claude_customizations.py +0 -374
  74. package/resources/scripts/dev_tools/push_down_codex_and_agents_customizations.py +0 -139
  75. package/resources/scripts/dev_tools/push_down_copilot_customizations.py +0 -504
  76. package/resources/scripts/dev_tools/push_down_copilot_customizations_filesystem.py +0 -217
  77. package/resources/scripts/dev_tools/push_down_copilot_customizations_rewrites.py +0 -293
  78. package/resources/scripts/dev_tools/resolve_file_prompt.py +0 -457
  79. package/resources/scripts/dev_tools/resolve_hard_lock_prompt.py +0 -444
  80. package/resources/scripts/dev_tools/validate_orchestration_artifacts.py +0 -246
  81. package/resources/scripts/dev_tools/validate_orchestration_review_artifacts.py +0 -107
  82. package/resources/scripts/dev_tools/validate_orchestrator_state.py +0 -428
  83. package/resources/scripts/dev_tools/validate_policy_audit_artifact.py +0 -448
  84. package/resources/templates/codex_native_converter.py +0 -35
  85. package/resources/templates/collect_commit_context.py +0 -212
  86. package/resources/templates/collect_pr_context.py +0 -74
  87. package/resources/templates/hello_python.py +0 -11
  88. package/resources/templates/new_active_feature_folder.py +0 -67
  89. package/resources/templates/new_potential_bug_entry.py +0 -54
  90. package/resources/templates/potential_to_issue.py +0 -55
  91. package/resources/templates/push_down_claude_customizations.py +0 -409
  92. package/resources/templates/push_down_codex_and_agents_customizations.py +0 -95
  93. package/resources/templates/push_down_copilot_customizations.py +0 -124
  94. package/resources/templates/resolve_atomic_plan_prompt.py +0 -75
  95. package/resources/templates/resolve_hard_lock_prompt.py +0 -65
  96. package/resources/templates/validate_orchestration_artifacts.py +0 -55
@@ -1,448 +0,0 @@
1
- """Validate policy-audit orchestration review artifacts.
2
-
3
- Purpose:
4
- Hold the policy-audit specific parsing helpers and substantive validation
5
- checks so the review-artifact validator stays cohesive and below the
6
- repository file-size limit.
7
-
8
- Usage:
9
- Import ``validate_policy_audit_text`` from this module when a caller needs
10
- only policy-audit validation, or through
11
- ``scripts.dev_tools.validate_orchestration_artifacts`` for the stable CLI
12
- entrypoint contract.
13
-
14
- Flow:
15
- 1. Parse the coverage table, checklist lines, and per-language comparison
16
- bullets from the policy-audit document.
17
- 2. Reject placeholder, malformed, or non-numeric coverage evidence when the
18
- repository policy requires explicit percentages.
19
- 3. Return a list of contract violations for the caller to surface.
20
-
21
- Invariants / Constraints:
22
- - Placeholder markers are treated as failures.
23
- - Coverage rows must retain numeric evidence unless the field is marked N/A.
24
- - The public validator functions return lists of error strings and do not
25
- print or mutate files.
26
-
27
- Side Effects:
28
- None.
29
- """
30
-
31
- from __future__ import annotations
32
-
33
- import re
34
-
35
- COVERAGE_PERCENT_RE = re.compile(r"\b\d+(?:\.\d+)?%")
36
- POLICY_AUDIT_REQUIRED_HEADINGS = (
37
- "## Executive Summary",
38
- "## 1. General Unit Test Policy Compliance",
39
- "## 2. General Code Change Policy Compliance",
40
- "## 3. Language-Specific Code Change Policy Compliance",
41
- "## 4. Language-Specific Unit Test Policy Compliance",
42
- "## 5. Test Coverage Detail",
43
- "## 6. Test Execution Metrics",
44
- "## 7. Code Quality Checks",
45
- "## 8. Gaps and Exceptions",
46
- "## 9. Summary of Changes",
47
- "## 10. Compliance Verdict",
48
- "## Appendix A: Test Inventory",
49
- "## Appendix B: Toolchain Commands Reference",
50
- )
51
- POLICY_AUDIT_REQUIRED_CHECKLIST_LABELS = (
52
- "TypeScript baseline coverage artifact:",
53
- "TypeScript post-change coverage artifact:",
54
- "PowerShell baseline coverage artifact:",
55
- "PowerShell post-change coverage artifact:",
56
- "Per-language comparison summary:",
57
- )
58
- POLICY_AUDIT_COMPARISON_HEADING = "### 1.2.1 Per-Language Coverage Comparison"
59
- PLACEHOLDER_MARKERS = (
60
- "[n]",
61
- "[path",
62
- "[artifact",
63
- "[section reference",
64
- "[language]",
65
- "tbd",
66
- "unverified",
67
- "missing",
68
- )
69
-
70
-
71
- def _has_numeric_coverage(value: str) -> bool:
72
- """Return True when a coverage field contains a numeric percentage.
73
-
74
- Purpose:
75
- Identify whether a coverage field satisfies the policy requirement for
76
- explicit numeric evidence.
77
-
78
- Args:
79
- value (str): Raw coverage field text extracted from an audit artifact.
80
-
81
- Returns:
82
- bool: True when the value contains at least one percentage token.
83
-
84
- Raises:
85
- None.
86
-
87
- Side Effects:
88
- None.
89
- """
90
-
91
- return COVERAGE_PERCENT_RE.search(value) is not None
92
-
93
-
94
- def _is_na_value(value: str) -> bool:
95
- """Return True when an audit field explicitly records not-applicable.
96
-
97
- Purpose:
98
- Allow the validator to distinguish missing numeric evidence from fields
99
- that are intentionally marked not applicable.
100
-
101
- Args:
102
- value (str): Raw field text to inspect.
103
-
104
- Returns:
105
- bool: True when the value begins with an N/A marker.
106
-
107
- Raises:
108
- None.
109
-
110
- Side Effects:
111
- None.
112
- """
113
-
114
- return value.strip().lower().startswith("n/a")
115
-
116
-
117
- def _has_placeholder_marker(value: str) -> bool:
118
- """Return True when a field still contains template placeholder text.
119
-
120
- Purpose:
121
- Fail closed when a review artifact still includes unfinished template or
122
- draft markers.
123
-
124
- Args:
125
- value (str): Raw field text to inspect.
126
-
127
- Returns:
128
- bool: True when the field includes a known placeholder marker.
129
-
130
- Raises:
131
- None.
132
-
133
- Side Effects:
134
- None.
135
- """
136
-
137
- lowered = value.lower()
138
- return any(marker in lowered for marker in PLACEHOLDER_MARKERS)
139
-
140
-
141
- def _extract_policy_audit_coverage_rows(text: str) -> list[dict[str, str]]:
142
- """Parse the policy-audit coverage table into named row dictionaries.
143
-
144
- Purpose:
145
- Normalize coverage table rows so later validation checks can reason
146
- about baseline, post-change, and new-code evidence by language.
147
-
148
- Args:
149
- text (str): Full policy-audit artifact text.
150
-
151
- Returns:
152
- list[dict[str, str]]: Parsed coverage rows keyed by canonical column
153
- names.
154
-
155
- Raises:
156
- None.
157
-
158
- Side Effects:
159
- None.
160
- """
161
-
162
- rows: list[dict[str, str]] = []
163
-
164
- # Interpret only the seven-column coverage table rows and ignore headers or
165
- # separator rows.
166
- for line in text.splitlines():
167
- if not line.startswith("|"):
168
- continue
169
- cells = [cell.strip() for cell in line.split("|")[1:-1]]
170
- if len(cells) != 7:
171
- continue
172
- language = cells[0]
173
- if language in {"Language", "----------"} or not language:
174
- continue
175
- if set(language) == {"-"}:
176
- continue
177
- rows.append(
178
- {
179
- "Language": language,
180
- "Files Changed": cells[1],
181
- "Tests": cells[2],
182
- "Test Result": cells[3],
183
- "Baseline Coverage": cells[4],
184
- "Post-Change Coverage": cells[5],
185
- "New Code Coverage": cells[6],
186
- }
187
- )
188
-
189
- return rows
190
-
191
-
192
- def _find_policy_audit_checklist_line(text: str, label: str) -> str | None:
193
- """Return the checklist line containing a required label.
194
-
195
- Purpose:
196
- Locate required evidence checklist entries without assuming a fixed line
197
- number or surrounding context.
198
-
199
- Args:
200
- text (str): Full policy-audit artifact text.
201
- label (str): Required checklist label to locate.
202
-
203
- Returns:
204
- str | None: The matching checklist line, if present.
205
-
206
- Raises:
207
- None.
208
-
209
- Side Effects:
210
- None.
211
- """
212
-
213
- # Search only checklist bullets because the same label text may appear in
214
- # narrative prose elsewhere in the document.
215
- for line in text.splitlines():
216
- stripped = line.strip()
217
- if stripped.startswith("- ") and label in stripped:
218
- return stripped
219
- return None
220
-
221
-
222
- def _extract_policy_audit_comparison_lines(text: str) -> dict[str, str]:
223
- """Return per-language comparison lines keyed by normalized language name.
224
-
225
- Purpose:
226
- Capture the explicit comparison bullets under the per-language coverage
227
- section so downstream checks can verify each language summary is present.
228
-
229
- Args:
230
- text (str): Full policy-audit artifact text.
231
-
232
- Returns:
233
- dict[str, str]: Mapping of lowercase language name to the matching
234
- comparison bullet.
235
-
236
- Raises:
237
- None.
238
-
239
- Side Effects:
240
- None.
241
- """
242
-
243
- in_section = False
244
- comparison_lines: dict[str, str] = {}
245
-
246
- # Limit parsing to the per-language coverage section so unrelated bullets do
247
- # not satisfy the evidence checks accidentally.
248
- for line in text.splitlines():
249
- stripped = line.strip()
250
- if stripped == POLICY_AUDIT_COMPARISON_HEADING:
251
- in_section = True
252
- continue
253
- if in_section and stripped.startswith("### "):
254
- break
255
- if not in_section or not stripped.startswith("- "):
256
- continue
257
- language, separator, _ = stripped[2:].partition(":")
258
- if not separator:
259
- continue
260
- comparison_lines[language.strip().lower()] = stripped
261
-
262
- return comparison_lines
263
-
264
-
265
- def _comparison_line_has_labelled_percentage(line: str, label: str) -> bool:
266
- """Return True when the comparison line includes a labelled percentage.
267
-
268
- Purpose:
269
- Verify that each comparison bullet records numeric evidence after the
270
- expected label, rather than narrative text alone.
271
-
272
- Args:
273
- line (str): Comparison bullet text.
274
- label (str): Required label to anchor the percentage search.
275
-
276
- Returns:
277
- bool: True when the labelled numeric evidence is present.
278
-
279
- Raises:
280
- None.
281
-
282
- Side Effects:
283
- None.
284
- """
285
-
286
- pattern = re.compile(rf"{re.escape(label)}.*?\d+(?:\.\d+)?%")
287
- return pattern.search(line) is not None
288
-
289
-
290
- def validate_policy_audit_substantive_requirements(text: str) -> list[str]:
291
- """Validate policy-audit evidence requirements beyond headings.
292
-
293
- Purpose:
294
- Enforce the numeric coverage and evidence checklist requirements that
295
- turn the review template into an auditable artifact.
296
-
297
- Args:
298
- text (str): Full policy-audit artifact text.
299
-
300
- Returns:
301
- list[str]: Validation errors describing each missing or malformed
302
- evidence element.
303
-
304
- Raises:
305
- None.
306
-
307
- Side Effects:
308
- None.
309
- """
310
-
311
- errors: list[str] = []
312
-
313
- # Require every checklist line to exist and remain free of unresolved
314
- # placeholders before the audit can report a passing verdict.
315
- for label in POLICY_AUDIT_REQUIRED_CHECKLIST_LABELS:
316
- line = _find_policy_audit_checklist_line(text, label)
317
- if line is None:
318
- errors.append(f"Policy audit missing required checklist line: {label}")
319
- continue
320
- if _has_placeholder_marker(line):
321
- errors.append(
322
- f"Policy audit checklist line still contains placeholder text: {label}"
323
- )
324
-
325
- coverage_rows = _extract_policy_audit_coverage_rows(text)
326
- if not coverage_rows:
327
- errors.append("Policy audit missing coverage metrics table rows.")
328
-
329
- if POLICY_AUDIT_COMPARISON_HEADING not in text:
330
- errors.append(
331
- "Policy audit missing required heading: "
332
- f"{POLICY_AUDIT_COMPARISON_HEADING}"
333
- )
334
-
335
- comparison_lines = _extract_policy_audit_comparison_lines(text)
336
-
337
- # Validate each language row against the comparison summary so baseline,
338
- # post-change, and changed-code evidence remain synchronized.
339
- for row in coverage_rows:
340
- language = row["Language"]
341
- baseline = row["Baseline Coverage"]
342
- post_change = row["Post-Change Coverage"]
343
- new_code = row["New Code Coverage"]
344
- requires_coverage_comparison = any(
345
- not _is_na_value(value) for value in (baseline, post_change, new_code)
346
- )
347
-
348
- if not _is_na_value(baseline) and not _has_numeric_coverage(baseline):
349
- errors.append(
350
- f"Policy audit missing numeric baseline coverage for {language}."
351
- )
352
- if not _is_na_value(post_change) and not _has_numeric_coverage(post_change):
353
- errors.append(
354
- f"Policy audit missing numeric post-change coverage for {language}."
355
- )
356
- if not _is_na_value(new_code) and not _has_numeric_coverage(new_code):
357
- errors.append(
358
- "Policy audit missing numeric new/changed-code coverage for "
359
- f"{language}."
360
- )
361
-
362
- if not requires_coverage_comparison:
363
- continue
364
-
365
- comparison_line = comparison_lines.get(language.lower())
366
- if comparison_line is None:
367
- errors.append(
368
- f"Policy audit missing per-language comparison line for {language}."
369
- )
370
- continue
371
-
372
- if not _comparison_line_has_labelled_percentage(comparison_line, "Baseline:"):
373
- errors.append(
374
- f"Policy audit comparison line missing numeric baseline for {language}."
375
- )
376
- if not _comparison_line_has_labelled_percentage(
377
- comparison_line, "Post-change:"
378
- ):
379
- errors.append(
380
- "Policy audit comparison line missing numeric post-change "
381
- f"coverage for {language}."
382
- )
383
- if "Change:" not in comparison_line:
384
- errors.append(
385
- "Policy audit comparison line missing explicit change text for "
386
- f"{language}."
387
- )
388
- if (
389
- re.search(
390
- r"Disposition:\s*(PASS|FAIL|N/A|INCOMPLETE|BLOCKED)",
391
- comparison_line,
392
- )
393
- is None
394
- ):
395
- errors.append(
396
- f"Policy audit comparison line missing disposition for {language}."
397
- )
398
- if not _is_na_value(new_code) and not _comparison_line_has_labelled_percentage(
399
- comparison_line, "New/changed-code coverage:"
400
- ):
401
- errors.append(
402
- "Policy audit comparison line missing numeric new/changed-code "
403
- f"coverage for {language}."
404
- )
405
- if "Evidence:" not in comparison_line:
406
- errors.append(
407
- "Policy audit comparison line missing evidence reference for "
408
- f"{language}."
409
- )
410
- elif _has_placeholder_marker(comparison_line):
411
- errors.append(
412
- "Policy audit comparison line still contains placeholder text for "
413
- f"{language}."
414
- )
415
-
416
- return errors
417
-
418
-
419
- def validate_policy_audit_text(text: str) -> list[str]:
420
- """Validate template-derived policy-audit structure.
421
-
422
- Purpose:
423
- Enforce the required policy-audit headings and substantive evidence
424
- checks for repository review artifacts.
425
-
426
- Args:
427
- text (str): Full policy-audit artifact text.
428
-
429
- Returns:
430
- list[str]: Validation errors for missing headings or evidence.
431
-
432
- Raises:
433
- None.
434
-
435
- Side Effects:
436
- None.
437
- """
438
-
439
- errors: list[str] = []
440
- if "Template Usage Instructions" in text:
441
- errors.append("Policy audit still contains the template instruction block.")
442
- if "[Component Name]" in text:
443
- errors.append("Policy audit still contains placeholder component text.")
444
- for heading in POLICY_AUDIT_REQUIRED_HEADINGS:
445
- if heading not in text:
446
- errors.append(f"Policy audit missing required heading: {heading}")
447
- errors.extend(validate_policy_audit_substantive_requirements(text))
448
- return errors
@@ -1,35 +0,0 @@
1
- """Compatibility wrapper for the bundled Codex-native converter.
2
-
3
- Purpose:
4
- Preserve an extension-side Python entry point that delegates converter
5
- execution to the bundled ``dev_tools`` package published with the extension
6
- resources.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import importlib
12
- import sys
13
- from pathlib import Path
14
-
15
-
16
- def _ensure_bundled_scripts_import_path() -> None:
17
- """Prepend bundled `resources/scripts` directory to ``sys.path``."""
18
-
19
- scripts_dir = Path(__file__).resolve().parent.parent / "scripts"
20
- scripts_dir_str = str(scripts_dir)
21
- if scripts_dir_str not in sys.path:
22
- sys.path.insert(0, scripts_dir_str)
23
-
24
-
25
- def main() -> int:
26
- """Execute the bundled Codex-native converter in-process."""
27
-
28
- _ensure_bundled_scripts_import_path()
29
- module = importlib.import_module("dev_tools.codex_native_converter.cli")
30
- module.main()
31
- return 0
32
-
33
-
34
- if __name__ == "__main__":
35
- raise SystemExit(main())
@@ -1,212 +0,0 @@
1
- """Collect Git commit context for commit message generation.
2
-
3
- This script gathers staged changes and repository state information
4
- to provide context for generating conventional commit messages.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import argparse
10
- import shutil
11
- import subprocess
12
- import sys
13
- from pathlib import Path
14
-
15
-
16
- def run_git(args: list[str], allow_error: bool = False) -> str:
17
- """Run a git command and return stdout.
18
-
19
- Args:
20
- args: Git subcommand and arguments (e.g., ["status", "-sb"])
21
- allow_error: If True, return empty output on error instead of raising
22
-
23
- Returns:
24
- Git command stdout as string, stripped of whitespace
25
-
26
- Raises:
27
- FileNotFoundError: If git executable not found on PATH
28
- subprocess.CalledProcessError: If git command fails and allow_error is False
29
- """
30
- # Validate git executable exists
31
- git_exe = shutil.which("git")
32
- if not git_exe:
33
- raise FileNotFoundError("git executable not found on PATH")
34
-
35
- try:
36
- result = subprocess.run( # noqa: S603 - static analysis can't verify runtime validation
37
- [git_exe, *args],
38
- capture_output=True,
39
- text=True,
40
- encoding="utf-8",
41
- errors="replace",
42
- check=not allow_error,
43
- )
44
- stdout = result.stdout or ""
45
- return stdout.strip()
46
- except subprocess.CalledProcessError as e:
47
- if allow_error:
48
- stdout = e.stdout or ""
49
- return stdout.strip()
50
- raise
51
-
52
-
53
- def collect_commit_context(output_path: Path) -> None:
54
- """Collect commit context and write to output file."""
55
- sections: list[str] = []
56
-
57
- sections.append("Please generate a commit message based on the following content:")
58
- sections.append("\n")
59
-
60
- # Repository remotes
61
- sections.append("===== Repository remotes =====")
62
- sections.append("")
63
- remotes = run_git(["remote", "-v"])
64
- sections.append(remotes)
65
- sections.append("")
66
-
67
- # Current branch
68
- sections.append("===== Current branch =====")
69
- sections.append("")
70
- branch = run_git(["rev-parse", "--abbrev-ref", "HEAD"])
71
- sections.append(branch)
72
- sections.append("")
73
-
74
- # Upstream
75
- sections.append("===== Upstream =====")
76
- sections.append("")
77
- upstream = run_git(
78
- ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], allow_error=True
79
- )
80
- sections.append(upstream if upstream else "(no upstream)")
81
- sections.append("")
82
-
83
- # Status (short)
84
- sections.append("===== Status (short) =====")
85
- sections.append("")
86
- status = run_git(["status", "-sb"])
87
- sections.append(status)
88
- sections.append("")
89
-
90
- # Staged files (name-status)
91
- sections.append("===== Staged files (name-status) =====")
92
- sections.append("")
93
- staged = run_git(["diff", "--cached", "--name-status"], allow_error=True)
94
- sections.append(staged if staged else "(no staged changes)")
95
- sections.append("")
96
-
97
- # Staged diff
98
- sections.append("===== Staged diff =====")
99
- sections.append("")
100
- staged_diff = run_git(["diff", "--cached"], allow_error=True)
101
- sections.append(staged_diff if staged_diff else "(no staged changes)")
102
- sections.append("")
103
-
104
- # Unstaged files (name-status)
105
- sections.append("===== Unstaged files (name-status) =====")
106
- sections.append("")
107
- unstaged = run_git(["diff", "--name-status"], allow_error=True)
108
- sections.append(unstaged if unstaged else "(no unstaged changes)")
109
- sections.append("")
110
-
111
- # Unstaged diff
112
- sections.append("===== Unstaged diff =====")
113
- sections.append("")
114
- unstaged_diff = run_git(["diff"], allow_error=True)
115
- sections.append(unstaged_diff if unstaged_diff else "(no unstaged changes)")
116
- sections.append("")
117
-
118
- # Untracked files
119
- sections.append("===== Untracked files =====")
120
- sections.append("")
121
- untracked = run_git(
122
- ["ls-files", "--others", "--exclude-standard"], allow_error=True
123
- )
124
- sections.append(untracked if untracked else "(no untracked files)")
125
- sections.append("")
126
-
127
- # Diff stat (combined)
128
- sections.append("===== Diff stat (staged + unstaged) =====")
129
- sections.append("")
130
- diff_stat = run_git(["diff", "HEAD", "--stat"], allow_error=True)
131
- sections.append(diff_stat if diff_stat else "(no changes)")
132
- sections.append("")
133
-
134
- # Changed Python files
135
- sections.append("===== Changed Python files =====")
136
- sections.append("")
137
- all_changed = run_git(["diff", "HEAD", "--name-only"], allow_error=True)
138
- py_files = (
139
- [f for f in all_changed.split("\n") if f.endswith(".py")] if all_changed else []
140
- )
141
- sections.append("\n".join(py_files) if py_files else "(no Python files changed)")
142
- sections.append("")
143
-
144
- # Last commit (header only)
145
- sections.append("===== Last commit (header only) =====")
146
- sections.append("")
147
- last_commit = run_git(
148
- ["log", "-1", "--format=%H%n%aN <%aE>%n%aD%n%cN <%cE>%n%cD%n%s%n%b"],
149
- allow_error=True,
150
- )
151
- if last_commit:
152
- lines = last_commit.split("\n")
153
- sections.append(f"commit {lines[0]}")
154
- if len(lines) > 1:
155
- sections.append(f"Author: {lines[1]}")
156
- if len(lines) > 2:
157
- sections.append(f"AuthorDate: {lines[2]}")
158
- if len(lines) > 3:
159
- sections.append(f"Commit: {lines[3]}")
160
- if len(lines) > 4:
161
- sections.append(f"CommitDate: {lines[4]}")
162
- if len(lines) > 5:
163
- sections.append("")
164
- sections.append(f" {lines[5]}")
165
- for line in lines[6:]:
166
- if line.strip():
167
- sections.append(f" {line}")
168
- else:
169
- sections.append("(no previous commits)")
170
- sections.append("")
171
-
172
- # Change intent (editable section)
173
- sections.append("===== Change intent (edit below) =====")
174
- sections.append("- What/why summary:")
175
- sections.append("- Breaking changes:")
176
- sections.append("- Affected modules:")
177
- sections.append("- Issue/PR refs:")
178
- sections.append("")
179
-
180
- # Write to output file
181
- output_path.parent.mkdir(parents=True, exist_ok=True)
182
- output_path.write_text("\n".join(sections), encoding="utf-8")
183
- print(f"Commit context written to: {output_path}")
184
-
185
-
186
- def main(argv: list[str] | None = None) -> int:
187
- """Main entry point."""
188
- parser = argparse.ArgumentParser(
189
- description="Collect Git commit context for commit message generation"
190
- )
191
- parser.add_argument(
192
- "--output",
193
- "-o",
194
- type=Path,
195
- default=Path("artifacts/commit_context.txt"),
196
- help="Output file path (default: artifacts/commit_context.txt)",
197
- )
198
- args = parser.parse_args(argv)
199
-
200
- try:
201
- collect_commit_context(args.output)
202
- return 0
203
- except subprocess.CalledProcessError as e:
204
- print(f"Git command failed: {e}", file=sys.stderr)
205
- return 1
206
- except Exception as e:
207
- print(f"Error: {e}", file=sys.stderr)
208
- return 1
209
-
210
-
211
- if __name__ == "__main__":
212
- sys.exit(main())