xithead 1.4.0 → 1.5.1

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 (86) hide show
  1. package/README.md +108 -72
  2. package/app/api/config/route.ts +22 -0
  3. package/app/api/export/route.ts +83 -0
  4. package/app/api/models/route.ts +12 -0
  5. package/app/api/stats/route.ts +46 -0
  6. package/app/dashboard/page.tsx +445 -0
  7. package/app/globals.css +35 -0
  8. package/app/installation/page.tsx +293 -0
  9. package/app/layout.tsx +35 -0
  10. package/app/master-design-system.css +2076 -0
  11. package/app/master-design-system.source.css +8 -0
  12. package/app/page.tsx +187 -0
  13. package/app/rechtliches/agb/page.tsx +165 -0
  14. package/app/rechtliches/datenschutz/page.tsx +128 -0
  15. package/app/rechtliches/impressum/page.tsx +122 -0
  16. package/app/rechtliches/widerruf/page.tsx +185 -0
  17. package/bin/xithead.js +264 -0
  18. package/components/layout/AppShell.tsx +25 -0
  19. package/components/layout/Footer.tsx +120 -0
  20. package/components/layout/Header.tsx +145 -0
  21. package/components/marketing/LegalHighlights.tsx +45 -0
  22. package/components/marketing/LegalPageShell.tsx +49 -0
  23. package/components/marketing/LegalPanel.tsx +41 -0
  24. package/components/marketing/index.ts +3 -0
  25. package/design-system/README.md +80 -0
  26. package/design-system/base.css +127 -0
  27. package/design-system/components.css +1943 -0
  28. package/design-system/fonts.css +17 -0
  29. package/design-system/tailwind-preset.js +95 -0
  30. package/design-system/tokens.css +48 -0
  31. package/design-system/utilities.css +53 -0
  32. package/lib/config/index.ts +12 -0
  33. package/lib/hooks/index.ts +4 -0
  34. package/lib/hooks/use-mounted.ts +13 -0
  35. package/lib/hooks/use-session.ts +34 -0
  36. package/lib/hooks/use-settings.ts +49 -0
  37. package/lib/utils/index.ts +1 -0
  38. package/lib/utils/settings.ts +162 -0
  39. package/lib/utils/utils.ts +6 -0
  40. package/middleware.ts +26 -0
  41. package/next-env.d.ts +7 -0
  42. package/next.config.ts +12 -0
  43. package/package.json +77 -36
  44. package/postcss.config.mjs +7 -0
  45. package/public/apple-touch-icon.png +0 -0
  46. package/public/logo-transparent.png +0 -0
  47. package/public/xithead.ps1 +937 -0
  48. package/scripts/README.md +77 -0
  49. package/scripts/audit_wheel_glibc_symbols.py +217 -0
  50. package/scripts/build-master-design-system.cjs +33 -0
  51. package/scripts/build_rust_extension.sh +58 -0
  52. package/scripts/changelog-gen.py +203 -0
  53. package/scripts/eval_output_shaper.py +235 -0
  54. package/scripts/export_kompress_v2_onnx.py +267 -0
  55. package/scripts/fixtures/anthropic_replay_body.json +133 -0
  56. package/scripts/fixtures/codex_response_create_frame.json +52 -0
  57. package/scripts/install-git-hooks.sh +104 -0
  58. package/scripts/install.ps1 +1809 -0
  59. package/scripts/install.sh +1673 -0
  60. package/scripts/pr-governance.py +297 -0
  61. package/scripts/record_fixtures.py +59 -0
  62. package/scripts/refresh_model_limits.sh +48 -0
  63. package/scripts/replay_codex_ws_load.py +445 -0
  64. package/scripts/repro_codex_replay.py +699 -0
  65. package/scripts/smoke_issue_327.py +233 -0
  66. package/scripts/sync-plugin-versions.py +116 -0
  67. package/scripts/tests/test_changelog_gen.py +302 -0
  68. package/scripts/tests/test_pr_governance.py +163 -0
  69. package/scripts/tests/test_pr_health_labels.py +94 -0
  70. package/scripts/tests/test_pr_health_workflow.py +14 -0
  71. package/scripts/tests/test_sync_plugin_versions.py +131 -0
  72. package/scripts/tests/test_version_sync.py +291 -0
  73. package/scripts/validate-workflows.sh +39 -0
  74. package/scripts/verify-versions.py +106 -0
  75. package/scripts/version-sync.py +207 -0
  76. package/tailwind.config.js +31 -0
  77. package/tailwind.master.config.cjs +47 -0
  78. package/tsconfig.json +84 -0
  79. package/types/api.ts +12 -0
  80. package/types/config.ts +9 -0
  81. package/types/index.ts +2 -0
  82. package/npm/bin/xithead.js +0 -366
  83. package/npm/index.d.ts +0 -57
  84. package/npm/index.js +0 -139
  85. package/npm/package.json +0 -54
  86. package/npm/postinstall.js +0 -43
@@ -0,0 +1,233 @@
1
+ """Issue #327 — live API smoke test.
2
+
3
+ Drives a 10-turn multi-turn conversation against `api.anthropic.com` directly
4
+ (NO proxy in the loop) and against the local Xtream Head proxy, and asserts:
5
+
6
+ 1. Both shapes of `tool_result` content (string and list-of-blocks) are
7
+ accepted by the upstream API for both streaming and non-streaming.
8
+ 2. When proxied through Headroom in token mode, at least one post-warmup
9
+ turn has `transforms_applied != []` AND `cache_read_input_tokens > 0`
10
+ on turns 2+ (proves prefix cache is intact AND compression resumed).
11
+ 3. No cache busts (bust_count stays at 0 across the session).
12
+
13
+ GUARDS
14
+
15
+ * Skipped unless `RUN_LIVE_API=1` to keep CI hermetic.
16
+ * Requires `ANTHROPIC_API_KEY` in env (read from `.env` if not exported).
17
+ * Costs a few cents per run (small messages × 10 turns × 2 modes).
18
+
19
+ USAGE
20
+
21
+ RUN_LIVE_API=1 .venv/bin/python scripts/smoke_issue_327.py
22
+
23
+ # With local proxy running on :8787:
24
+ RUN_LIVE_API=1 HEADROOM_PROXY_URL=http://localhost:8787 \
25
+ .venv/bin/python scripts/smoke_issue_327.py
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import os
32
+ import sys
33
+ from pathlib import Path
34
+
35
+ if os.environ.get("RUN_LIVE_API") != "1":
36
+ print("Set RUN_LIVE_API=1 to run this smoke test.")
37
+ sys.exit(0)
38
+
39
+ # Hydrate .env if needed
40
+ _env = Path(__file__).resolve().parent.parent / ".env"
41
+ if _env.exists():
42
+ for line in _env.read_text().splitlines():
43
+ line = line.strip()
44
+ if not line or line.startswith("#") or "=" not in line:
45
+ continue
46
+ k, _, v = line.partition("=")
47
+ os.environ.setdefault(k, v.strip().strip('"').strip("'"))
48
+
49
+ KEY = os.environ.get("ANTHROPIC_API_KEY")
50
+ if not KEY:
51
+ print("ANTHROPIC_API_KEY not set — cannot run live smoke")
52
+ sys.exit(1)
53
+
54
+ import anthropic # noqa: E402
55
+
56
+ PROXY_URL = os.environ.get("HEADROOM_PROXY_URL") # optional
57
+ TOOLS = [
58
+ {
59
+ "name": "get_lines",
60
+ "description": "Return N lines of synthetic test output for compression testing",
61
+ "input_schema": {
62
+ "type": "object",
63
+ "properties": {"n": {"type": "integer"}},
64
+ "required": ["n"],
65
+ },
66
+ }
67
+ ]
68
+ LARGE_OUTPUT = "\n".join(
69
+ f"line {i:04d}: synthetic content for compression smoke test" for i in range(120)
70
+ )
71
+
72
+
73
+ def _make_string_tool_result(tool_use_id: str) -> dict:
74
+ return {"type": "tool_result", "tool_use_id": tool_use_id, "content": LARGE_OUTPUT}
75
+
76
+
77
+ def _make_list_tool_result(tool_use_id: str) -> dict:
78
+ return {
79
+ "type": "tool_result",
80
+ "tool_use_id": tool_use_id,
81
+ "content": [{"type": "text", "text": LARGE_OUTPUT}],
82
+ }
83
+
84
+
85
+ def _drive_conversation(client: anthropic.Anthropic, *, shape: str, stream: bool) -> dict:
86
+ """Drive a 10-turn conversation, return aggregate stats."""
87
+ print(f"\n=== shape={shape} stream={stream} ===")
88
+ messages: list = []
89
+ cache_reads: list[int] = []
90
+ cache_writes: list[int] = []
91
+ turn_results: list[dict] = []
92
+
93
+ for turn in range(10):
94
+ if turn == 0:
95
+ messages.append({"role": "user", "content": "Use get_lines with n=120"})
96
+ else:
97
+ messages.append({"role": "user", "content": f"continue {turn}, run get_lines again"})
98
+
99
+ try:
100
+ kwargs = {
101
+ "model": "claude-haiku-4-5-20251001",
102
+ "max_tokens": 128,
103
+ "tools": TOOLS,
104
+ "messages": messages,
105
+ }
106
+ if stream:
107
+ with client.messages.stream(**kwargs) as s:
108
+ for _ in s:
109
+ pass
110
+ final = s.get_final_message()
111
+ else:
112
+ final = client.messages.create(**kwargs)
113
+
114
+ usage = getattr(final, "usage", None)
115
+ cache_read = getattr(usage, "cache_read_input_tokens", 0) or 0
116
+ cache_write = getattr(usage, "cache_creation_input_tokens", 0) or 0
117
+ cache_reads.append(cache_read)
118
+ cache_writes.append(cache_write)
119
+
120
+ # Append the assistant turn
121
+ messages.append({"role": "assistant", "content": final.content})
122
+
123
+ # If model called the tool, send back a tool_result in the chosen shape
124
+ tool_use_block = None
125
+ for blk in final.content:
126
+ if getattr(blk, "type", None) == "tool_use":
127
+ tool_use_block = blk
128
+ break
129
+ if tool_use_block is not None:
130
+ tool_use_id = tool_use_block.id
131
+ if shape == "string":
132
+ tr = _make_string_tool_result(tool_use_id)
133
+ else:
134
+ tr = _make_list_tool_result(tool_use_id)
135
+ messages.append({"role": "user", "content": [tr]})
136
+
137
+ turn_results.append(
138
+ {
139
+ "turn": turn,
140
+ "stop_reason": final.stop_reason,
141
+ "cache_read_input_tokens": cache_read,
142
+ "cache_creation_input_tokens": cache_write,
143
+ }
144
+ )
145
+ print(
146
+ f" turn {turn}: stop={final.stop_reason} "
147
+ f"cache_read={cache_read} cache_write={cache_write}"
148
+ )
149
+ except anthropic.APIError as e:
150
+ print(f" turn {turn} FAIL: {type(e).__name__}: {e}")
151
+ return {"ok": False, "error": str(e), "turn_results": turn_results}
152
+
153
+ return {
154
+ "ok": True,
155
+ "turn_results": turn_results,
156
+ "cache_reads": cache_reads,
157
+ "cache_writes": cache_writes,
158
+ }
159
+
160
+
161
+ def main() -> int:
162
+ base_url_kwarg = {}
163
+ if PROXY_URL:
164
+ base_url_kwarg["base_url"] = PROXY_URL
165
+ print(f"Routing through proxy: {PROXY_URL}")
166
+ else:
167
+ print("Direct to api.anthropic.com (no proxy)")
168
+
169
+ client = anthropic.Anthropic(api_key=KEY, **base_url_kwarg)
170
+
171
+ overall_ok = True
172
+ matrix = [
173
+ ("string", False),
174
+ ("string", True),
175
+ ("list_of_blocks", False),
176
+ ("list_of_blocks", True),
177
+ ]
178
+
179
+ summary: dict = {}
180
+ for shape, stream in matrix:
181
+ r = _drive_conversation(client, shape=shape, stream=stream)
182
+ summary[(shape, stream)] = r
183
+ if not r["ok"]:
184
+ overall_ok = False
185
+ continue
186
+
187
+ # Assert: at least one turn after turn 0 reports cache_read > 0 (prefix
188
+ # cache is being used).
189
+ post_turn0_cache_reads = [t["cache_read_input_tokens"] for t in r["turn_results"][1:]]
190
+ if not any(c > 0 for c in post_turn0_cache_reads):
191
+ print(
192
+ f" WARN: shape={shape} stream={stream} — no post-warmup turn had "
193
+ f"cache_read > 0. cache_reads={post_turn0_cache_reads}"
194
+ )
195
+
196
+ print("\n=== SUMMARY ===")
197
+ for k, v in summary.items():
198
+ print(f" {k}: ok={v['ok']}")
199
+
200
+ print("\n--- Per-turn cache_read tokens ---")
201
+ for k, v in summary.items():
202
+ if v["ok"]:
203
+ print(f" {k}: {v['cache_reads']}")
204
+
205
+ print(f"\noverall_ok={overall_ok}")
206
+ if PROXY_URL:
207
+ try:
208
+ import httpx
209
+
210
+ stats = httpx.get(f"{PROXY_URL}/stats", timeout=5).json()
211
+ print("\n=== Proxy /stats key fields ===")
212
+ print(
213
+ json.dumps(
214
+ {
215
+ "summary": stats.get("summary"),
216
+ "compressions_by_strategy": stats.get("compressions_by_strategy"),
217
+ "tokens_saved_by_strategy": stats.get("tokens_saved_by_strategy"),
218
+ "compression_cache": stats.get("compression_cache"),
219
+ "prefix_cache_busts": (
220
+ stats.get("prefix_cache", {}).get("totals", {}).get("bust_count")
221
+ ),
222
+ },
223
+ indent=2,
224
+ )
225
+ )
226
+ except Exception as e: # pragma: no cover
227
+ print(f" proxy stats fetch failed: {e}")
228
+
229
+ return 0 if overall_ok else 1
230
+
231
+
232
+ if __name__ == "__main__":
233
+ sys.exit(main())
@@ -0,0 +1,116 @@
1
+ """Sync plugin manifest versions to the repo's computed release semver.
2
+
3
+ Branch-aware: by default this script is a NO-OP on feature branches.
4
+ Pre-this-fix it ran on every commit and bumped the manifests to the
5
+ PREDICTED next release version, which polluted every PR with version-
6
+ bump noise (the prediction advanced as commits landed; each PR ended
7
+ up carrying the bump as collateral).
8
+
9
+ Sync now only runs when EITHER:
10
+ * We're on the ``main`` branch, OR
11
+ * ``HEADROOM_SYNC_VERSIONS=1`` is set explicitly (release workflow)
12
+
13
+ Result: feature-branch PRs no longer carry manifest bumps; the
14
+ release workflow still gets a canonical sync at publish time.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import subprocess
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ ROOT = Path(__file__).resolve().parent.parent
25
+ if str(ROOT) not in sys.path:
26
+ sys.path.insert(0, str(ROOT))
27
+
28
+ try:
29
+ from headroom.release_version import ( # noqa: E402
30
+ compute_release_version,
31
+ determine_bump_level,
32
+ find_latest_release_tag,
33
+ get_canonical_version,
34
+ list_release_commits,
35
+ list_release_tags,
36
+ )
37
+ except ImportError:
38
+ print("skip: headroom deps not installed (run from a dev venv to enable)")
39
+ sys.exit(0)
40
+
41
+
42
+ def compute_repo_semver(root: Path) -> str:
43
+ """Return the npm-style semver for the repo's next release."""
44
+ tags = list_release_tags(root)
45
+ previous_tag = find_latest_release_tag(tags) or ""
46
+ level = determine_bump_level(list_release_commits(root, previous_tag))
47
+ info = compute_release_version(
48
+ canonical_version=get_canonical_version(root),
49
+ level=level,
50
+ tags=tags,
51
+ )
52
+ return info.npm_version
53
+
54
+
55
+ def _current_branch(root: Path) -> str | None:
56
+ """Return the current git branch name, or None if git isn't usable."""
57
+ try:
58
+ result = subprocess.run(
59
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
60
+ cwd=root,
61
+ capture_output=True,
62
+ text=True,
63
+ check=False,
64
+ )
65
+ except (FileNotFoundError, OSError):
66
+ return None
67
+ if result.returncode != 0:
68
+ return None
69
+ return result.stdout.strip() or None
70
+
71
+
72
+ def _should_sync(root: Path) -> bool:
73
+ """Decide whether to actually run the sync.
74
+
75
+ Release workflow opts in via ``HEADROOM_SYNC_VERSIONS=1``; otherwise
76
+ we only sync on ``main`` (where the next-release prediction
77
+ legitimately lives). On feature branches we no-op — the prediction
78
+ would just create PR-level noise.
79
+ """
80
+ if os.environ.get("HEADROOM_SYNC_VERSIONS") == "1":
81
+ return True
82
+ branch = _current_branch(root)
83
+ if branch is None:
84
+ # Git unavailable or detached HEAD — safest default is no-op.
85
+ return False
86
+ return branch == "main"
87
+
88
+
89
+ def main() -> None:
90
+ root = ROOT
91
+ if not _should_sync(root):
92
+ # Quiet no-op on feature branches. Print a single line so
93
+ # pre-commit users see the reason if they look.
94
+ branch = _current_branch(root) or "<unknown>"
95
+ print(
96
+ f"sync-plugin-versions: skipping on branch '{branch}' (set HEADROOM_SYNC_VERSIONS=1 to force)"
97
+ )
98
+ return
99
+ version = compute_repo_semver(root)
100
+ subprocess.run(
101
+ [
102
+ sys.executable,
103
+ str(root / "scripts" / "version-sync.py"),
104
+ "--root",
105
+ str(root),
106
+ "--version",
107
+ version,
108
+ "--plugin-manifests-only",
109
+ ],
110
+ cwd=root,
111
+ check=True,
112
+ )
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
@@ -0,0 +1,302 @@
1
+ """Tests for changelog-gen.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ ROOT = Path(__file__).resolve().parent.parent.parent
11
+
12
+ # Load changelog_gen module from scripts directory (filename has hyphen)
13
+ _spec = importlib.util.spec_from_file_location(
14
+ "changelog_gen", ROOT / "scripts" / "changelog-gen.py"
15
+ )
16
+ if _spec is None:
17
+ raise ImportError("Could not load changelog_gen module")
18
+ _changelog_gen = importlib.util.module_from_spec(_spec)
19
+ if _spec.loader is None:
20
+ raise ImportError("Could not load changelog_gen module")
21
+ _spec.loader.exec_module(_changelog_gen)
22
+
23
+ COMMIT_PATTERN = _changelog_gen.COMMIT_PATTERN
24
+ BREAKING_CHANGE_PATTERN = _changelog_gen.BREAKING_CHANGE_PATTERN
25
+ FIELD_SEP = _changelog_gen.FIELD_SEP
26
+ RECORD_SEP = _changelog_gen.RECORD_SEP
27
+ ParsedCommit = _changelog_gen.ParsedCommit
28
+ generate_changelog = _changelog_gen.generate_changelog
29
+ iter_commit_entries = _changelog_gen.iter_commit_entries
30
+ parse_commits = _changelog_gen.parse_commits
31
+
32
+
33
+ def make_log_entry(subject: str, commit_hash: str, body: str = "") -> str:
34
+ return f"{subject}{FIELD_SEP}{body}{FIELD_SEP}{commit_hash}{RECORD_SEP}"
35
+
36
+
37
+ class TestParseCommits:
38
+ """Tests for parse_commits function."""
39
+
40
+ def test_parses_feat_commit(self) -> None:
41
+ log_output = make_log_entry("feat(core): add feature", "abc1234")
42
+ commits = parse_commits(log_output)
43
+ assert len(commits) == 1
44
+ assert commits[0].type == "feat"
45
+ assert commits[0].scope == "core"
46
+ assert commits[0].message == "add feature"
47
+ assert commits[0].hash == "abc1234"
48
+ assert commits[0].breaking is False
49
+
50
+ def test_parses_fix_commit(self) -> None:
51
+ log_output = make_log_entry("fix(ui): fix bug", "def5678")
52
+ commits = parse_commits(log_output)
53
+ assert len(commits) == 1
54
+ assert commits[0].type == "fix"
55
+ assert commits[0].scope == "ui"
56
+ assert commits[0].message == "fix bug"
57
+ assert commits[0].hash == "def5678"
58
+
59
+ def test_parses_ci_commit(self) -> None:
60
+ log_output = make_log_entry("ci: update github actions", "xyz789")
61
+ commits = parse_commits(log_output)
62
+ assert len(commits) == 1
63
+ assert commits[0].type == "ci"
64
+ assert commits[0].scope is None
65
+ assert commits[0].message == "update github actions"
66
+ assert commits[0].hash == "xyz789"
67
+
68
+ def test_parses_chore_commit(self) -> None:
69
+ log_output = make_log_entry("chore: cleanup", "xyz999")
70
+ commits = parse_commits(log_output)
71
+ assert len(commits) == 1
72
+ assert commits[0].type == "chore"
73
+ assert commits[0].scope is None
74
+
75
+ def test_parses_perf_commit(self) -> None:
76
+ log_output = make_log_entry("perf(dashboard): improve performance", "abc111")
77
+ commits = parse_commits(log_output)
78
+ assert len(commits) == 1
79
+ assert commits[0].type == "perf"
80
+ assert commits[0].scope == "dashboard"
81
+
82
+ def test_parses_refactor_commit(self) -> None:
83
+ log_output = make_log_entry("refactor(api): refactor endpoint", "abc222")
84
+ commits = parse_commits(log_output)
85
+ assert len(commits) == 1
86
+ assert commits[0].type == "refactor"
87
+ assert commits[0].scope == "api"
88
+
89
+ def test_parses_docs_commit(self) -> None:
90
+ log_output = make_log_entry("docs: update readme", "abc333")
91
+ commits = parse_commits(log_output)
92
+ assert len(commits) == 1
93
+ assert commits[0].type == "docs"
94
+
95
+ def test_parses_style_commit(self) -> None:
96
+ log_output = make_log_entry("style: format code", "abc444")
97
+ commits = parse_commits(log_output)
98
+ assert len(commits) == 1
99
+ assert commits[0].type == "style"
100
+
101
+ def test_parses_test_commit(self) -> None:
102
+ log_output = make_log_entry("test: add tests for feature", "abc555")
103
+ commits = parse_commits(log_output)
104
+ assert len(commits) == 1
105
+ assert commits[0].type == "test"
106
+
107
+ def test_detects_breaking_change_in_body(self) -> None:
108
+ log_output = make_log_entry(
109
+ "feat(core): add feature",
110
+ "abc666",
111
+ "BREAKING CHANGE: api changed",
112
+ )
113
+ commits = parse_commits(log_output)
114
+ assert len(commits) == 1
115
+ assert commits[0].breaking is True
116
+
117
+ def test_detects_breaking_change_exclamation(self) -> None:
118
+ log_output = make_log_entry("feat(core)!: api changed", "abc777")
119
+ commits = parse_commits(log_output)
120
+ assert len(commits) == 1
121
+ assert commits[0].breaking is True
122
+
123
+ def test_no_scope_no_problem(self) -> None:
124
+ log_output = make_log_entry("feat: simple feature", "abc888")
125
+ commits = parse_commits(log_output)
126
+ assert len(commits) == 1
127
+ assert commits[0].scope is None
128
+ assert commits[0].message == "simple feature"
129
+
130
+ def test_uses_pr_title_from_merge_commit_body(self) -> None:
131
+ log_output = make_log_entry(
132
+ "Merge pull request #173 from JerrettDavis/fix/pipeline-permissions-and-docs",
133
+ "73f6673",
134
+ "fix: repair release and docs pipelines",
135
+ )
136
+ commits = parse_commits(log_output)
137
+ assert len(commits) == 1
138
+ assert commits[0].type == "fix"
139
+ assert commits[0].message == "repair release and docs pipelines"
140
+
141
+ def test_falls_back_to_other_changes_for_non_conventional_merge(self) -> None:
142
+ log_output = make_log_entry(
143
+ "Merge pull request #186 from skorokithakis/patch-1",
144
+ "1e80ee3",
145
+ "Add support for custom Anthropic API URL",
146
+ )
147
+ commits = parse_commits(log_output)
148
+ assert len(commits) == 1
149
+ assert commits[0].type == "other"
150
+ assert commits[0].message == "Add support for custom Anthropic API URL"
151
+
152
+ def test_iter_commit_entries_parses_real_git_log_delimiters(self) -> None:
153
+ log_output = make_log_entry(
154
+ "fix: patch release flow", "abc1234", "BREAKING CHANGE: no"
155
+ ) + make_log_entry("docs: update readme", "def5678")
156
+ assert iter_commit_entries(log_output) == [
157
+ ("fix: patch release flow", "BREAKING CHANGE: no", "abc1234"),
158
+ ("docs: update readme", "", "def5678"),
159
+ ]
160
+
161
+ def test_iter_commit_entries_keeps_field_separator_inside_body(self) -> None:
162
+ body = f"line one{FIELD_SEP}line two"
163
+ log_output = make_log_entry("fix: patch release flow", "abc1234", body)
164
+ assert iter_commit_entries(log_output) == [
165
+ ("fix: patch release flow", body, "abc1234"),
166
+ ]
167
+
168
+
169
+ class TestGenerateChangelog:
170
+ """Tests for generate_changelog function."""
171
+
172
+ def test_generates_version_header(self) -> None:
173
+ commits = [
174
+ ParsedCommit(type="feat", scope=None, breaking=False, message="test", hash="abc123")
175
+ ]
176
+ result = generate_changelog("0.6.0", commits)
177
+ assert "## [0.6.0]" in result
178
+
179
+ def test_includes_date(self) -> None:
180
+ commits = []
181
+ result = generate_changelog("0.6.0", commits)
182
+ import re
183
+
184
+ date_match = re.search(r"\d{4}-\d{2}-\d{2}", result)
185
+ assert date_match is not None
186
+
187
+ def test_groups_by_type(self) -> None:
188
+ commits = [
189
+ ParsedCommit(
190
+ type="feat", scope=None, breaking=False, message="add feature", hash="abc123"
191
+ ),
192
+ ParsedCommit(type="fix", scope=None, breaking=False, message="fix bug", hash="def456"),
193
+ ]
194
+ result = generate_changelog("0.6.0", commits)
195
+ assert "### Features" in result
196
+ assert "### Bug Fixes" in result
197
+ assert "- add feature (abc123)" in result
198
+ assert "- fix bug (def456)" in result
199
+
200
+ def test_includes_scope_in_bullet(self) -> None:
201
+ commits = [
202
+ ParsedCommit(
203
+ type="feat", scope="core", breaking=False, message="add feature", hash="abc123"
204
+ )
205
+ ]
206
+ result = generate_changelog("0.6.0", commits)
207
+ assert "- **core**: add feature (abc123)" in result
208
+
209
+ def test_breaking_change_section_when_present(self) -> None:
210
+ commits = [
211
+ ParsedCommit(
212
+ type="feat", scope="core", breaking=True, message="api changed", hash="abc123"
213
+ )
214
+ ]
215
+ result = generate_changelog("0.6.0", commits)
216
+ assert "### Breaking Changes" in result
217
+ assert "**core**" in result
218
+
219
+ def test_no_breaking_change_section_when_none(self) -> None:
220
+ commits = [
221
+ ParsedCommit(
222
+ type="feat", scope=None, breaking=False, message="add feature", hash="abc123"
223
+ )
224
+ ]
225
+ result = generate_changelog("0.6.0", commits)
226
+ assert "Breaking Changes" not in result
227
+
228
+ def test_includes_other_changes_section(self) -> None:
229
+ commits = [
230
+ ParsedCommit(
231
+ type="other",
232
+ scope=None,
233
+ breaking=False,
234
+ message="Add support for custom Anthropic API URL",
235
+ hash="abc123",
236
+ )
237
+ ]
238
+ result = generate_changelog("0.6.0", commits)
239
+ assert "### Other Changes" in result
240
+ assert "- Add support for custom Anthropic API URL (abc123)" in result
241
+
242
+
243
+ class TestIntegrationWithMock:
244
+ """Integration tests with mocked subprocess.run."""
245
+
246
+ def test_full_flow_with_mocked_git(self) -> None:
247
+ log_output = (
248
+ make_log_entry("feat(core): add new feature", "abc1234")
249
+ + make_log_entry("fix(ui): fix bug", "def5678")
250
+ + make_log_entry("ci: update github actions", "xyz789")
251
+ + make_log_entry(
252
+ "feat(outer): breaking change", "bbb111", "BREAKING CHANGE: this is breaking"
253
+ )
254
+ + make_log_entry("chore: cleanup", "yyy999")
255
+ )
256
+ commits = parse_commits(log_output)
257
+
258
+ assert len(commits) == 5
259
+ assert any(c.type == "feat" and c.scope == "core" for c in commits)
260
+ assert any(c.type == "fix" and c.scope == "ui" for c in commits)
261
+ assert any(c.type == "ci" for c in commits)
262
+ assert any(c.type == "feat" and c.breaking for c in commits)
263
+ assert any(c.type == "chore" for c in commits)
264
+
265
+ changelog = generate_changelog("0.7.0", commits)
266
+ assert "## [0.7.0]" in changelog
267
+ assert "### Features" in changelog
268
+ assert "### Bug Fixes" in changelog
269
+ assert "### CI/CD" in changelog
270
+ assert "### Breaking Changes" in changelog
271
+
272
+
273
+ class TestCommitPattern:
274
+ """Tests for the commit regex pattern."""
275
+
276
+ def test_feat_with_scope(self) -> None:
277
+ match = COMMIT_PATTERN.match("feat(core): add feature")
278
+ assert match is not None
279
+ assert match.group(1) == "feat"
280
+ assert match.group(2) == "(core)"
281
+ assert match.group(4) == "add feature"
282
+
283
+ def test_fix_without_scope(self) -> None:
284
+ match = COMMIT_PATTERN.match("fix: fix bug")
285
+ assert match is not None
286
+ assert match.group(1) == "fix"
287
+ assert match.group(2) is None
288
+ assert match.group(4) == "fix bug"
289
+
290
+ def test_with_exclamation(self) -> None:
291
+ match = COMMIT_PATTERN.match("feat(core)!: api changed")
292
+ assert match is not None
293
+ assert match.group(3) == "!"
294
+
295
+ def test_without_exclamation(self) -> None:
296
+ match = COMMIT_PATTERN.match("feat(core): add feature")
297
+ assert match is not None
298
+ assert match.group(3) is None
299
+
300
+
301
+ if __name__ == "__main__":
302
+ pytest.main([__file__, "-v"])