lgit-cli 4.3.0__py3-none-any.whl → 5.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lgit/__init__.py +1 -1
- lgit/api.py +58 -10
- lgit/cache.py +64 -12
- lgit/changelog.py +161 -52
- lgit/cli.py +146 -16
- lgit/compose.py +4 -2
- lgit/config.py +9 -8
- lgit/diffing.py +68 -1
- lgit/git.py +13 -0
- lgit/map_reduce.py +10 -2
- lgit/markdown_output.py +5 -4
- lgit/pricing.py +197 -0
- lgit/resources/model_pricing.json +16 -0
- lgit/resources/prompts/changelog.md +10 -3
- lgit/resources/prompts/map.md +2 -1
- lgit/rewrite.py +2 -2
- lgit/templates.py +16 -46
- {lgit_cli-4.3.0.dist-info → lgit_cli-5.1.0.dist-info}/METADATA +1 -1
- {lgit_cli-4.3.0.dist-info → lgit_cli-5.1.0.dist-info}/RECORD +22 -20
- {lgit_cli-4.3.0.dist-info → lgit_cli-5.1.0.dist-info}/WHEEL +0 -0
- {lgit_cli-4.3.0.dist-info → lgit_cli-5.1.0.dist-info}/entry_points.txt +0 -0
- {lgit_cli-4.3.0.dist-info → lgit_cli-5.1.0.dist-info}/licenses/LICENSE +0 -0
lgit/__init__.py
CHANGED
lgit/api.py
CHANGED
|
@@ -18,7 +18,7 @@ import httpx
|
|
|
18
18
|
from jinja2 import Template
|
|
19
19
|
|
|
20
20
|
from . import cache as llm_cache
|
|
21
|
-
from . import profile
|
|
21
|
+
from . import pricing, profile
|
|
22
22
|
from .errors import ApiContextLengthExceeded, ApiError, LgitError
|
|
23
23
|
from .markdown_output import (
|
|
24
24
|
analysis_from_mapping,
|
|
@@ -83,6 +83,7 @@ class OneShotSpec:
|
|
|
83
83
|
progress_label: str | None = None
|
|
84
84
|
debug: OneShotDebug | Mapping[str, Any] | str | Path | None = None
|
|
85
85
|
cacheable: bool = True
|
|
86
|
+
reasoning_effort: str | None = None
|
|
86
87
|
|
|
87
88
|
|
|
88
89
|
@dataclass(frozen=True, slots=True)
|
|
@@ -269,19 +270,30 @@ async def generate_summary_from_analysis(
|
|
|
269
270
|
async def generate_analysis_with_map_reduce(
|
|
270
271
|
config: CommitConfig, stat: str, diff: str, scope_candidates: str = "", **kwargs: Any
|
|
271
272
|
) -> ConventionalAnalysis:
|
|
272
|
-
"""Generate analysis directly or through map-reduce for large diffs.
|
|
273
|
+
"""Generate analysis directly or through map-reduce for large diffs.
|
|
274
|
+
|
|
275
|
+
``on_observations`` (keyword) is forwarded to :func:`lgit.map_reduce.run_map_reduce`
|
|
276
|
+
and fires only when the map-reduce path is taken.
|
|
277
|
+
"""
|
|
273
278
|
|
|
274
279
|
from . import style
|
|
275
280
|
from .map_reduce import run_map_reduce, should_use_map_reduce
|
|
276
281
|
from .tokens import create_token_counter
|
|
277
282
|
|
|
278
283
|
counter = kwargs.pop("counter", None) or create_token_counter(config)
|
|
284
|
+
on_observations = kwargs.pop("on_observations", None)
|
|
279
285
|
if should_use_map_reduce(diff, config, counter):
|
|
280
286
|
count_sync = getattr(counter, "count_sync", None)
|
|
281
287
|
token_count = int(count_sync(diff)) if callable(count_sync) else max(1, len(diff) // 4)
|
|
282
288
|
style.print_info(f"Large diff detected ({token_count} tokens), using map-reduce...")
|
|
283
289
|
return await run_map_reduce(
|
|
284
|
-
config,
|
|
290
|
+
config,
|
|
291
|
+
stat,
|
|
292
|
+
diff,
|
|
293
|
+
scope_candidates,
|
|
294
|
+
model_name=kwargs.get("model_name"),
|
|
295
|
+
counter=counter,
|
|
296
|
+
on_observations=on_observations,
|
|
285
297
|
)
|
|
286
298
|
return await generate_conventional_analysis(config, stat, diff, scope_candidates, **kwargs)
|
|
287
299
|
|
|
@@ -426,11 +438,12 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
|
|
|
426
438
|
cache_entry = _build_cache_entry(config, spec)
|
|
427
439
|
if cache_entry is not None:
|
|
428
440
|
cache_obj, key = cache_entry
|
|
429
|
-
|
|
430
|
-
if
|
|
431
|
-
decoded = decode_cache_payload(spec.tool_name, spec.operation,
|
|
441
|
+
entry = cache_obj.get_entry(key)
|
|
442
|
+
if entry is not None:
|
|
443
|
+
decoded = decode_cache_payload(spec.tool_name, spec.operation, entry.response)
|
|
432
444
|
if decoded is not None:
|
|
433
445
|
output, text = decoded
|
|
446
|
+
pricing.record_saved(entry.cost_usd)
|
|
434
447
|
profile.print_llm_progress(lambda: f"cache hit {spec.operation} ({spec.model})")
|
|
435
448
|
return OneShotResponse(output=output, source=OneShotSource.CACHE, text_content=text)
|
|
436
449
|
|
|
@@ -441,7 +454,7 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
|
|
|
441
454
|
last_retry_from_error = False
|
|
442
455
|
for attempt in range(1, attempts + 1):
|
|
443
456
|
try:
|
|
444
|
-
request, response_text = await _send_oneshot(config, spec, mode)
|
|
457
|
+
request, response_text, cost = await _send_oneshot(config, spec, mode)
|
|
445
458
|
request_json = json.dumps(request, ensure_ascii=False, default=_json_default)
|
|
446
459
|
if not response_text.strip():
|
|
447
460
|
raise _RetryableResponse("empty response body")
|
|
@@ -449,7 +462,7 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
|
|
|
449
462
|
if cache_entry is not None:
|
|
450
463
|
payload = encode_cache_payload(response.source, response.output, response.text_content)
|
|
451
464
|
if payload is not None:
|
|
452
|
-
cache_entry[0].put(cache_entry[1], spec.model or "", spec.operation, request_json, payload)
|
|
465
|
+
cache_entry[0].put(cache_entry[1], spec.model or "", spec.operation, request_json, payload, cost)
|
|
453
466
|
return response
|
|
454
467
|
except ApiContextLengthExceeded:
|
|
455
468
|
raise
|
|
@@ -474,7 +487,9 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
|
|
|
474
487
|
raise LgitError(f"Max retries exceeded for {spec.operation}: {last_error}")
|
|
475
488
|
|
|
476
489
|
|
|
477
|
-
async def _send_oneshot(
|
|
490
|
+
async def _send_oneshot(
|
|
491
|
+
config: CommitConfig, spec: OneShotSpec, mode: ResolvedApiMode
|
|
492
|
+
) -> tuple[dict[str, Any], str, float | None]:
|
|
478
493
|
timeout = httpx.Timeout(float(config.request_timeout_secs), connect=float(config.connect_timeout_secs))
|
|
479
494
|
headers = {"content-type": "application/json"}
|
|
480
495
|
api_key = config.api_key
|
|
@@ -498,6 +513,7 @@ async def _send_oneshot(config: CommitConfig, spec: OneShotSpec, mode: ResolvedA
|
|
|
498
513
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
499
514
|
response = await client.post(url, headers=headers, json=request)
|
|
500
515
|
text = response.text
|
|
516
|
+
cost = _record_spend(spec, response, text)
|
|
501
517
|
profile.print_llm_progress(
|
|
502
518
|
lambda: (
|
|
503
519
|
f"response {spec.operation} status={response.status_code} elapsed={time.monotonic() - start:.2f}s size={len(text)}B"
|
|
@@ -512,7 +528,36 @@ async def _send_oneshot(config: CommitConfig, spec: OneShotSpec, mode: ResolvedA
|
|
|
512
528
|
raise _RetryableResponse(f"server error {response.status_code}: {text}")
|
|
513
529
|
if not response.is_success:
|
|
514
530
|
raise ApiError(status=response.status_code, body=text)
|
|
515
|
-
return request, text
|
|
531
|
+
return request, text, cost
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _record_spend(spec: OneShotSpec, response: httpx.Response, text: str) -> float | None:
|
|
535
|
+
"""Record token usage and cost for one real API response; returns the cost when known."""
|
|
536
|
+
reported = _header_cost(response.headers.get("x-litellm-response-cost"))
|
|
537
|
+
usage = None
|
|
538
|
+
try:
|
|
539
|
+
payload = json.loads(text)
|
|
540
|
+
except json.JSONDecodeError, ValueError:
|
|
541
|
+
payload = None
|
|
542
|
+
if isinstance(payload, Mapping):
|
|
543
|
+
usage = pricing.parse_usage(payload)
|
|
544
|
+
if usage is None and reported is None:
|
|
545
|
+
return None
|
|
546
|
+
usage = usage or pricing.TokenUsage()
|
|
547
|
+
cost = pricing.record_usage(spec.model or "", usage, reported)
|
|
548
|
+
sink = llm_cache.LlmCache.instance()
|
|
549
|
+
if sink is not None:
|
|
550
|
+
sink.record_usage(spec.model or "", spec.operation, usage, cost)
|
|
551
|
+
return cost
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _header_cost(raw: str | None) -> float | None:
|
|
555
|
+
if not raw:
|
|
556
|
+
return None
|
|
557
|
+
try:
|
|
558
|
+
return float(raw)
|
|
559
|
+
except ValueError:
|
|
560
|
+
return None
|
|
516
561
|
|
|
517
562
|
|
|
518
563
|
def _openai_request(config: CommitConfig, spec: OneShotSpec) -> dict[str, Any]:
|
|
@@ -521,6 +566,8 @@ def _openai_request(config: CommitConfig, spec: OneShotSpec) -> dict[str, Any]:
|
|
|
521
566
|
messages.append({"role": "system", "content": spec.system_prompt})
|
|
522
567
|
messages.append({"role": "user", "content": spec.user_prompt})
|
|
523
568
|
request: dict[str, Any] = {"model": spec.model, "messages": messages}
|
|
569
|
+
if spec.reasoning_effort:
|
|
570
|
+
request["reasoning_effort"] = spec.reasoning_effort
|
|
524
571
|
prompt_cache_key = _openai_prompt_cache_key(config, spec)
|
|
525
572
|
if prompt_cache_key:
|
|
526
573
|
request["prompt_cache_key"] = prompt_cache_key
|
|
@@ -700,6 +747,7 @@ def _build_cache_entry(config: CommitConfig, spec: OneShotSpec) -> tuple[Any, st
|
|
|
700
747
|
system_prompt=spec.system_prompt,
|
|
701
748
|
user_prompt=spec.user_prompt,
|
|
702
749
|
api_mode=mode,
|
|
750
|
+
reasoning_effort=spec.reasoning_effort,
|
|
703
751
|
)
|
|
704
752
|
)
|
|
705
753
|
return cache_obj, key
|
lgit/cache.py
CHANGED
|
@@ -15,6 +15,7 @@ from blake3 import blake3
|
|
|
15
15
|
|
|
16
16
|
if TYPE_CHECKING:
|
|
17
17
|
from .config import CommitConfig
|
|
18
|
+
from .pricing import TokenUsage
|
|
18
19
|
|
|
19
20
|
SCHEMA_VERSION = 3
|
|
20
21
|
PRUNE_DIVISOR = 64
|
|
@@ -28,6 +29,7 @@ class CachedLlmResponse:
|
|
|
28
29
|
request: str
|
|
29
30
|
response: str
|
|
30
31
|
created_at: int
|
|
32
|
+
cost_usd: float | None = None
|
|
31
33
|
|
|
32
34
|
|
|
33
35
|
@dataclass(frozen=True, slots=True)
|
|
@@ -51,6 +53,7 @@ class CacheMaterial:
|
|
|
51
53
|
system_prompt: str
|
|
52
54
|
user_prompt: str
|
|
53
55
|
api_mode: str
|
|
56
|
+
reasoning_effort: str | None = None
|
|
54
57
|
|
|
55
58
|
|
|
56
59
|
class LlmCache:
|
|
@@ -99,7 +102,7 @@ class LlmCache:
|
|
|
99
102
|
with self._lock:
|
|
100
103
|
row = self._conn.execute(
|
|
101
104
|
"""
|
|
102
|
-
SELECT request, response, created_at
|
|
105
|
+
SELECT request, response, created_at, cost_usd
|
|
103
106
|
FROM responses
|
|
104
107
|
WHERE key = ? AND schema_version = ?
|
|
105
108
|
""",
|
|
@@ -108,13 +111,14 @@ class LlmCache:
|
|
|
108
111
|
if row is None:
|
|
109
112
|
return None
|
|
110
113
|
request, response, created_at = str(row[0]), str(row[1]), int(row[2])
|
|
114
|
+
cost_usd = float(row[3]) if row[3] is not None else None
|
|
111
115
|
if self.ttl_secs > 0 and created_at < _now_unix() - self.ttl_secs:
|
|
112
116
|
self._conn.execute("DELETE FROM responses WHERE key = ?", (key,))
|
|
113
117
|
self._conn.commit()
|
|
114
118
|
return None
|
|
115
119
|
self._conn.execute("UPDATE responses SET accessed_at = ? WHERE key = ?", (_now_unix(), key))
|
|
116
120
|
self._conn.commit()
|
|
117
|
-
return CachedLlmResponse(request=request, response=response, created_at=created_at)
|
|
121
|
+
return CachedLlmResponse(request=request, response=response, created_at=created_at, cost_usd=cost_usd)
|
|
118
122
|
except Exception:
|
|
119
123
|
return None
|
|
120
124
|
|
|
@@ -124,8 +128,10 @@ class LlmCache:
|
|
|
124
128
|
entry = self.get_entry(key)
|
|
125
129
|
return entry.response if entry is not None else None
|
|
126
130
|
|
|
127
|
-
def put(
|
|
128
|
-
|
|
131
|
+
def put(
|
|
132
|
+
self, key: str, model: str, operation: str, request: str, response: str, cost_usd: float | None = None
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Insert or replace a successful response and its original cost, swallowing cache failures."""
|
|
129
135
|
|
|
130
136
|
try:
|
|
131
137
|
now = _now_unix()
|
|
@@ -133,10 +139,10 @@ class LlmCache:
|
|
|
133
139
|
self._conn.execute(
|
|
134
140
|
"""
|
|
135
141
|
INSERT OR REPLACE INTO responses
|
|
136
|
-
(key, schema_version, model, operation, request, response, created_at, accessed_at)
|
|
137
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
142
|
+
(key, schema_version, model, operation, request, response, cost_usd, created_at, accessed_at)
|
|
143
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
138
144
|
""",
|
|
139
|
-
(key, SCHEMA_VERSION, model, operation, request, response, now, now),
|
|
145
|
+
(key, SCHEMA_VERSION, model, operation, request, response, cost_usd, now, now),
|
|
140
146
|
)
|
|
141
147
|
if self.ttl_secs > 0 and now % PRUNE_DIVISOR == 0:
|
|
142
148
|
self._conn.execute("DELETE FROM responses WHERE created_at < ?", (now - self.ttl_secs,))
|
|
@@ -197,6 +203,33 @@ class LlmCache:
|
|
|
197
203
|
except Exception:
|
|
198
204
|
return []
|
|
199
205
|
|
|
206
|
+
def record_usage(self, model: str, operation: str, usage: TokenUsage, cost_usd: float | None) -> None:
|
|
207
|
+
"""Append one LLM response's token usage and estimated cost, swallowing failures."""
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
with self._lock:
|
|
211
|
+
self._conn.execute(
|
|
212
|
+
"""
|
|
213
|
+
INSERT INTO usage
|
|
214
|
+
(model, operation, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
|
|
215
|
+
cost_usd, created_at)
|
|
216
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
217
|
+
""",
|
|
218
|
+
(
|
|
219
|
+
model,
|
|
220
|
+
operation,
|
|
221
|
+
usage.input_tokens,
|
|
222
|
+
usage.output_tokens,
|
|
223
|
+
usage.cache_read_tokens,
|
|
224
|
+
usage.cache_write_tokens,
|
|
225
|
+
cost_usd,
|
|
226
|
+
_now_unix(),
|
|
227
|
+
),
|
|
228
|
+
)
|
|
229
|
+
self._conn.commit()
|
|
230
|
+
except Exception:
|
|
231
|
+
return
|
|
232
|
+
|
|
200
233
|
def close(self) -> None:
|
|
201
234
|
"""Close the underlying SQLite connection."""
|
|
202
235
|
|
|
@@ -214,6 +247,7 @@ class LlmCache:
|
|
|
214
247
|
operation TEXT NOT NULL,
|
|
215
248
|
request TEXT NOT NULL,
|
|
216
249
|
response TEXT NOT NULL,
|
|
250
|
+
cost_usd REAL,
|
|
217
251
|
created_at INTEGER NOT NULL,
|
|
218
252
|
accessed_at INTEGER NOT NULL
|
|
219
253
|
);
|
|
@@ -230,13 +264,29 @@ class LlmCache:
|
|
|
230
264
|
created_at INTEGER NOT NULL
|
|
231
265
|
);
|
|
232
266
|
CREATE INDEX IF NOT EXISTS idx_failures_created_at ON failures(created_at);
|
|
267
|
+
CREATE TABLE IF NOT EXISTS usage (
|
|
268
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
269
|
+
model TEXT NOT NULL,
|
|
270
|
+
operation TEXT NOT NULL,
|
|
271
|
+
input_tokens INTEGER NOT NULL,
|
|
272
|
+
output_tokens INTEGER NOT NULL,
|
|
273
|
+
cache_read_tokens INTEGER NOT NULL,
|
|
274
|
+
cache_write_tokens INTEGER NOT NULL,
|
|
275
|
+
cost_usd REAL,
|
|
276
|
+
created_at INTEGER NOT NULL
|
|
277
|
+
);
|
|
278
|
+
CREATE INDEX IF NOT EXISTS idx_usage_created_at ON usage(created_at);
|
|
233
279
|
"""
|
|
234
280
|
)
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
281
|
+
for migration in (
|
|
282
|
+
"ALTER TABLE responses ADD COLUMN request TEXT NOT NULL DEFAULT ''",
|
|
283
|
+
"ALTER TABLE responses ADD COLUMN cost_usd REAL",
|
|
284
|
+
):
|
|
285
|
+
try:
|
|
286
|
+
self._conn.execute(migration)
|
|
287
|
+
except sqlite3.OperationalError as error:
|
|
288
|
+
if "duplicate column name" not in str(error).lower():
|
|
289
|
+
raise
|
|
240
290
|
self._conn.commit()
|
|
241
291
|
|
|
242
292
|
|
|
@@ -251,6 +301,8 @@ def compute_key(material: CacheMaterial) -> str:
|
|
|
251
301
|
_write_field(hasher, "tool_name", material.tool_name)
|
|
252
302
|
_write_field(hasher, "system", material.system_prompt)
|
|
253
303
|
_write_field(hasher, "user", material.user_prompt)
|
|
304
|
+
if material.reasoning_effort:
|
|
305
|
+
_write_field(hasher, "reasoning_effort", material.reasoning_effort)
|
|
254
306
|
hasher.update(b"\n")
|
|
255
307
|
return hasher.hexdigest()
|
|
256
308
|
|
lgit/changelog.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
5
6
|
import json
|
|
6
7
|
import os
|
|
7
8
|
import re
|
|
@@ -11,7 +12,7 @@ from pathlib import Path
|
|
|
11
12
|
from typing import TYPE_CHECKING, Any
|
|
12
13
|
|
|
13
14
|
from . import style
|
|
14
|
-
from .diffing import smart_truncate_diff
|
|
15
|
+
from .diffing import scrub_diff_for_prompt, smart_truncate_diff
|
|
15
16
|
from .errors import GitError, ValidationFailure
|
|
16
17
|
from .git import run_git
|
|
17
18
|
from .markdown_output import parse_changelog_response
|
|
@@ -20,6 +21,7 @@ from .templates import render_changelog_prompt
|
|
|
20
21
|
|
|
21
22
|
if TYPE_CHECKING:
|
|
22
23
|
from .config import CommitConfig
|
|
24
|
+
from .map_reduce import FileObservation
|
|
23
25
|
|
|
24
26
|
_REVISE_BLOCK_RE = re.compile(r"<revise\b[^>]*>(.*?)(?:</revise>|$)", re.IGNORECASE | re.DOTALL)
|
|
25
27
|
_REVISION_LINE_RE = re.compile(r"^\s*(OLD|NEW)\s*:(.*)$", re.IGNORECASE)
|
|
@@ -53,26 +55,50 @@ class ChangelogBoundary:
|
|
|
53
55
|
stat: str = ""
|
|
54
56
|
|
|
55
57
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
@dataclass(frozen=True, slots=True)
|
|
59
|
+
class _BoundaryPrep:
|
|
60
|
+
"""One boundary's collected context, ready for concurrent entry generation."""
|
|
61
|
+
|
|
62
|
+
boundary: ChangelogBoundary
|
|
63
|
+
diff: str
|
|
64
|
+
stat: str
|
|
65
|
+
rel_path: str
|
|
66
|
+
is_tracked: bool
|
|
67
|
+
changelog_content: str
|
|
68
|
+
worktree_content: str
|
|
69
|
+
unreleased: UnreleasedSection
|
|
70
|
+
worktree_unreleased: UnreleasedSection | None
|
|
71
|
+
head_unreleased: UnreleasedSection | None
|
|
72
|
+
existing_entries: str | None
|
|
73
|
+
authored_entries: str | None
|
|
74
|
+
can_revise: bool
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(slots=True)
|
|
78
|
+
class PreparedChangelogFlow:
|
|
79
|
+
"""Boundary contexts collected from git, ready for generation and applying."""
|
|
80
|
+
|
|
81
|
+
repo_dir: Path
|
|
82
|
+
preps: list[_BoundaryPrep]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def prepare_changelog_flow(args: Any, config: CommitConfig) -> PreparedChangelogFlow:
|
|
86
|
+
"""Collect per-boundary context (diffs, stats, unreleased sections) for staged files."""
|
|
58
87
|
|
|
59
88
|
repo_dir = Path(getattr(args, "dir", "."))
|
|
89
|
+
prepared = PreparedChangelogFlow(repo_dir, [])
|
|
60
90
|
staged_files = _staged_files(repo_dir)
|
|
61
91
|
candidate_files = [path for path in staged_files if not path.lower().endswith("changelog.md")]
|
|
62
92
|
if not candidate_files:
|
|
63
|
-
return
|
|
93
|
+
return prepared
|
|
64
94
|
|
|
65
95
|
changelogs = _find_changelogs(repo_dir)
|
|
66
96
|
if not changelogs:
|
|
67
|
-
return
|
|
68
|
-
|
|
69
|
-
boundaries = detect_boundaries(candidate_files, changelogs, repo_dir)
|
|
70
|
-
updated: list[ChangelogBoundary] = []
|
|
71
|
-
untracked_to_stage: list[str] = []
|
|
97
|
+
return prepared
|
|
72
98
|
|
|
73
99
|
max_diff_length = config.max_diff_length
|
|
74
|
-
for boundary in
|
|
75
|
-
diff = _diff_for_files(boundary.files, repo_dir, max_diff_length)
|
|
100
|
+
for boundary in detect_boundaries(candidate_files, changelogs, repo_dir):
|
|
101
|
+
diff = scrub_diff_for_prompt(_diff_for_files(boundary.files, repo_dir, max_diff_length))
|
|
76
102
|
if not diff.strip():
|
|
77
103
|
continue
|
|
78
104
|
if len(diff) > max_diff_length:
|
|
@@ -106,23 +132,73 @@ async def run_changelog_flow(args: Any, config: CommitConfig) -> list[ChangelogB
|
|
|
106
132
|
authored_entries = _format_entry_map(_entries_added_since(head_unreleased, unreleased, worktree_unreleased))
|
|
107
133
|
|
|
108
134
|
can_revise = bool(config.changelog_revise) and head_unreleased is not None and bool(existing_entries)
|
|
135
|
+
prepared.preps.append(
|
|
136
|
+
_BoundaryPrep(
|
|
137
|
+
boundary,
|
|
138
|
+
diff,
|
|
139
|
+
stat,
|
|
140
|
+
rel_path,
|
|
141
|
+
is_tracked,
|
|
142
|
+
changelog_content,
|
|
143
|
+
worktree_content,
|
|
144
|
+
unreleased,
|
|
145
|
+
worktree_unreleased,
|
|
146
|
+
head_unreleased,
|
|
147
|
+
existing_entries,
|
|
148
|
+
authored_entries,
|
|
149
|
+
can_revise,
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
return prepared
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
async def generate_changelog_updates(
|
|
156
|
+
prepared: PreparedChangelogFlow,
|
|
157
|
+
config: CommitConfig,
|
|
158
|
+
observations: Sequence[FileObservation] | None = None,
|
|
159
|
+
) -> list[tuple[dict[ChangelogCategory, list[str]], list[ChangelogRevision]]]:
|
|
160
|
+
"""Run the changelog model concurrently for every prepared boundary.
|
|
161
|
+
|
|
162
|
+
When map-phase ``observations`` are given, boundaries covered by them are
|
|
163
|
+
prompted with per-file change summaries instead of their raw diff.
|
|
164
|
+
"""
|
|
109
165
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
166
|
+
return list(
|
|
167
|
+
await asyncio.gather(
|
|
168
|
+
*(
|
|
169
|
+
generate_changelog_entries(
|
|
170
|
+
prep.boundary.changelog_path,
|
|
171
|
+
_is_package_changelog(prep.boundary.changelog_path, prepared.repo_dir),
|
|
172
|
+
prep.stat,
|
|
173
|
+
prep.diff,
|
|
174
|
+
prep.existing_entries,
|
|
175
|
+
prep.authored_entries,
|
|
176
|
+
prep.can_revise,
|
|
177
|
+
config,
|
|
178
|
+
observations=_observations_markdown(observations, prep.boundary.files),
|
|
179
|
+
)
|
|
180
|
+
for prep in prepared.preps
|
|
181
|
+
)
|
|
119
182
|
)
|
|
120
|
-
|
|
121
|
-
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def apply_changelog_updates(
|
|
187
|
+
prepared: PreparedChangelogFlow,
|
|
188
|
+
generated: Sequence[tuple[dict[ChangelogCategory, list[str]], list[ChangelogRevision]]],
|
|
189
|
+
) -> list[ChangelogBoundary]:
|
|
190
|
+
"""Write generated entries into worktree changelogs and stage exact blobs."""
|
|
191
|
+
|
|
192
|
+
repo_dir = prepared.repo_dir
|
|
193
|
+
updated: list[ChangelogBoundary] = []
|
|
194
|
+
untracked_to_stage: list[str] = []
|
|
195
|
+
for prep, (entries, revisions) in zip(prepared.preps, generated, strict=True):
|
|
196
|
+
staged_entries = prep.unreleased.entries
|
|
197
|
+
worktree_entries = prep.worktree_unreleased.entries if prep.worktree_unreleased is not None else None
|
|
122
198
|
applied: list[ChangelogRevision] = []
|
|
123
|
-
if can_revise:
|
|
124
|
-
assert head_unreleased is not None
|
|
125
|
-
revisable = {entry.casefold() for values in head_unreleased.entries.values() for entry in values}
|
|
199
|
+
if prep.can_revise:
|
|
200
|
+
assert prep.head_unreleased is not None
|
|
201
|
+
revisable = {entry.casefold() for values in prep.head_unreleased.entries.values() for entry in values}
|
|
126
202
|
staged_entries, applied = apply_revisions(staged_entries, revisions, revisable)
|
|
127
203
|
if worktree_entries is not None:
|
|
128
204
|
worktree_entries, _ = apply_revisions(worktree_entries, revisions, revisable)
|
|
@@ -131,33 +207,59 @@ async def run_changelog_flow(args: Any, config: CommitConfig) -> list[ChangelogB
|
|
|
131
207
|
continue
|
|
132
208
|
|
|
133
209
|
updated_staged = write_entries(
|
|
134
|
-
changelog_content,
|
|
135
|
-
replace(unreleased, entries=staged_entries),
|
|
210
|
+
prep.changelog_content,
|
|
211
|
+
replace(prep.unreleased, entries=staged_entries),
|
|
136
212
|
entries,
|
|
137
213
|
)
|
|
138
214
|
updated_worktree = (
|
|
139
215
|
write_entries(
|
|
140
|
-
worktree_content,
|
|
141
|
-
replace(worktree_unreleased, entries=worktree_entries),
|
|
216
|
+
prep.worktree_content,
|
|
217
|
+
replace(prep.worktree_unreleased, entries=worktree_entries),
|
|
142
218
|
entries,
|
|
143
219
|
)
|
|
144
|
-
if worktree_unreleased is not None and worktree_entries is not None
|
|
220
|
+
if prep.worktree_unreleased is not None and worktree_entries is not None
|
|
145
221
|
else updated_staged
|
|
146
222
|
)
|
|
147
|
-
boundary.changelog_path.write_text(updated_worktree, encoding="utf-8")
|
|
223
|
+
prep.boundary.changelog_path.write_text(updated_worktree, encoding="utf-8")
|
|
148
224
|
|
|
149
|
-
if is_tracked:
|
|
150
|
-
stage_changelog_blob(rel_path, updated_staged, repo_dir)
|
|
225
|
+
if prep.is_tracked:
|
|
226
|
+
stage_changelog_blob(prep.rel_path, updated_staged, repo_dir)
|
|
151
227
|
else:
|
|
152
|
-
untracked_to_stage.append(rel_path)
|
|
228
|
+
untracked_to_stage.append(prep.rel_path)
|
|
153
229
|
_report_applied_revisions(applied)
|
|
154
|
-
updated.append(ChangelogBoundary(boundary.changelog_path, boundary.files, diff, stat))
|
|
230
|
+
updated.append(ChangelogBoundary(prep.boundary.changelog_path, prep.boundary.files, prep.diff, prep.stat))
|
|
155
231
|
|
|
156
232
|
if untracked_to_stage:
|
|
157
233
|
run_git(["add", "--", *untracked_to_stage], cwd=repo_dir)
|
|
158
234
|
return updated
|
|
159
235
|
|
|
160
236
|
|
|
237
|
+
async def run_changelog_flow(
|
|
238
|
+
args: Any,
|
|
239
|
+
config: CommitConfig,
|
|
240
|
+
observations: Sequence[FileObservation] | None = None,
|
|
241
|
+
) -> list[ChangelogBoundary]:
|
|
242
|
+
"""Generate and stage changelog entries for currently staged files."""
|
|
243
|
+
|
|
244
|
+
prepared = prepare_changelog_flow(args, config)
|
|
245
|
+
generated = await generate_changelog_updates(prepared, config, observations)
|
|
246
|
+
return apply_changelog_updates(prepared, generated)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _observations_markdown(observations: Sequence[FileObservation] | None, files: Collection[str]) -> str | None:
|
|
250
|
+
"""Render map-phase observations for ``files`` as per-file markdown, or None when uncovered."""
|
|
251
|
+
|
|
252
|
+
if observations is None:
|
|
253
|
+
return None
|
|
254
|
+
wanted = set(files)
|
|
255
|
+
sections = [
|
|
256
|
+
"# {}\n{}".format(item.file, "\n".join(f"- {text}" for text in item.observations))
|
|
257
|
+
for item in observations
|
|
258
|
+
if item.file in wanted and item.observations
|
|
259
|
+
]
|
|
260
|
+
return "\n\n".join(sections) if sections else None
|
|
261
|
+
|
|
262
|
+
|
|
161
263
|
@dataclass(slots=True)
|
|
162
264
|
class _ComposeBoundaryState:
|
|
163
265
|
rel_path: str
|
|
@@ -296,11 +398,9 @@ class ChangelogWeaver:
|
|
|
296
398
|
repo_dir,
|
|
297
399
|
)
|
|
298
400
|
states = {state.changelog_path: state for state in self.boundaries}
|
|
299
|
-
group_diff = (
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
else diff
|
|
303
|
-
)
|
|
401
|
+
group_diff = scrub_diff_for_prompt(diff)
|
|
402
|
+
if len(group_diff) > self.config.max_diff_length:
|
|
403
|
+
group_diff = smart_truncate_diff(group_diff, self.config.max_diff_length, self.config)
|
|
304
404
|
for boundary in matched:
|
|
305
405
|
state = states[boundary.changelog_path]
|
|
306
406
|
try:
|
|
@@ -560,8 +660,13 @@ async def generate_changelog_entries(
|
|
|
560
660
|
authored_entries: str | None,
|
|
561
661
|
can_revise: bool,
|
|
562
662
|
config: CommitConfig,
|
|
663
|
+
observations: str | None = None,
|
|
563
664
|
) -> tuple[dict[ChangelogCategory, list[str]], list[ChangelogRevision]]:
|
|
564
|
-
"""Ask the configured model for Keep a Changelog entries and revision operations.
|
|
665
|
+
"""Ask the configured model for Keep a Changelog entries and revision operations.
|
|
666
|
+
|
|
667
|
+
``observations`` (per-file change-summary markdown) replaces the raw diff
|
|
668
|
+
in the prompt when provided.
|
|
669
|
+
"""
|
|
565
670
|
|
|
566
671
|
prompt = render_changelog_prompt(
|
|
567
672
|
os.fspath(changelog_path),
|
|
@@ -571,6 +676,7 @@ async def generate_changelog_entries(
|
|
|
571
676
|
existing_entries=existing_entries,
|
|
572
677
|
authored_entries=authored_entries,
|
|
573
678
|
can_revise=can_revise,
|
|
679
|
+
observations=observations,
|
|
574
680
|
)
|
|
575
681
|
from .api import OneShotSpec, run_oneshot
|
|
576
682
|
|
|
@@ -585,6 +691,7 @@ async def generate_changelog_entries(
|
|
|
585
691
|
tool_name="create_changelog_entries",
|
|
586
692
|
progress_label="changelog",
|
|
587
693
|
cacheable=True,
|
|
694
|
+
reasoning_effort=config.changelog_reasoning_effort,
|
|
588
695
|
),
|
|
589
696
|
)
|
|
590
697
|
output = response.output if hasattr(response, "output") else response
|
|
@@ -631,19 +738,17 @@ def _staged_files(dir: Path) -> list[str]:
|
|
|
631
738
|
|
|
632
739
|
|
|
633
740
|
def _find_changelogs(dir: Path) -> list[Path]:
|
|
741
|
+
"""Locate tracked plus untracked-but-not-ignored CHANGELOG.md files via git.
|
|
742
|
+
|
|
743
|
+
Avoids walking the worktree (node_modules and friends); gitignored
|
|
744
|
+
changelogs are never changelog boundaries.
|
|
745
|
+
"""
|
|
746
|
+
patterns = ["CHANGELOG.md", "**/CHANGELOG.md"]
|
|
747
|
+
tracked = run_git(["ls-files", "--", *patterns], cwd=dir).stdout
|
|
748
|
+
untracked = run_git(["ls-files", "--others", "--exclude-standard", "--", *patterns], cwd=dir).stdout
|
|
634
749
|
paths = {
|
|
635
|
-
dir /
|
|
636
|
-
for path in run_git(["ls-files", "--", "CHANGELOG.md", "**/CHANGELOG.md"], cwd=dir).stdout.splitlines()
|
|
637
|
-
if Path(path).name == "CHANGELOG.md"
|
|
750
|
+
dir / line for line in (*tracked.splitlines(), *untracked.splitlines()) if Path(line).name == "CHANGELOG.md"
|
|
638
751
|
}
|
|
639
|
-
for path in dir.rglob("CHANGELOG.md"):
|
|
640
|
-
if ".git" in path.parts:
|
|
641
|
-
continue
|
|
642
|
-
try:
|
|
643
|
-
exact_path = next(child for child in path.parent.iterdir() if child.name == "CHANGELOG.md")
|
|
644
|
-
except OSError, StopIteration:
|
|
645
|
-
continue
|
|
646
|
-
paths.add(exact_path)
|
|
647
752
|
return sorted(paths, key=lambda path: _relative_to(path, dir))
|
|
648
753
|
|
|
649
754
|
|
|
@@ -892,13 +997,17 @@ __all__ = [
|
|
|
892
997
|
"ChangelogBoundary",
|
|
893
998
|
"ChangelogWeaver",
|
|
894
999
|
"ChangelogRevision",
|
|
1000
|
+
"PreparedChangelogFlow",
|
|
895
1001
|
"UnreleasedSection",
|
|
1002
|
+
"apply_changelog_updates",
|
|
896
1003
|
"apply_revisions",
|
|
897
1004
|
"detect_boundaries",
|
|
898
1005
|
"generate_changelog_entries",
|
|
1006
|
+
"generate_changelog_updates",
|
|
899
1007
|
"normalize_changelog_entry",
|
|
900
1008
|
"parse_changelog_revisions",
|
|
901
1009
|
"parse_unreleased_section",
|
|
1010
|
+
"prepare_changelog_flow",
|
|
902
1011
|
"run_changelog_flow",
|
|
903
1012
|
"stage_changelog_blob",
|
|
904
1013
|
"write_entries",
|