gitstory-cli 0.2.2__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.
- gitstory/__init__.py +3 -0
- gitstory/__main__.py +8 -0
- gitstory/cli.py +196 -0
- gitstory/evidence.py +330 -0
- gitstory/gitops.py +366 -0
- gitstory/narrative.py +676 -0
- gitstory_cli-0.2.2.dist-info/METADATA +341 -0
- gitstory_cli-0.2.2.dist-info/RECORD +12 -0
- gitstory_cli-0.2.2.dist-info/WHEEL +5 -0
- gitstory_cli-0.2.2.dist-info/entry_points.txt +2 -0
- gitstory_cli-0.2.2.dist-info/licenses/LICENSE +21 -0
- gitstory_cli-0.2.2.dist-info/top_level.txt +1 -0
gitstory/narrative.py
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
"""Narrative assembly: evidence in, story out. Deterministic template.
|
|
2
|
+
|
|
3
|
+
HONESTY CONTRACT (this is the product's trust):
|
|
4
|
+
- EVIDENCE is quoted or cited with a short hash. INFERENCE is labeled
|
|
5
|
+
"INFERENCE" and kept to message-pattern classification only.
|
|
6
|
+
- A why that history does not document prints as "reason
|
|
7
|
+
undocumented in history" — never a reconstructed story.
|
|
8
|
+
- No LLM is ever called. The narrative is template assembly over
|
|
9
|
+
blame, commit messages, diffs, and optional gh titles.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import __version__, gitops
|
|
17
|
+
from . import evidence as ev
|
|
18
|
+
|
|
19
|
+
GENERIC_SUBJECTS = {
|
|
20
|
+
"fix stuff",
|
|
21
|
+
"fix",
|
|
22
|
+
"update",
|
|
23
|
+
"updates",
|
|
24
|
+
"change",
|
|
25
|
+
"changes",
|
|
26
|
+
"wip",
|
|
27
|
+
"stuff",
|
|
28
|
+
"misc",
|
|
29
|
+
"tweak",
|
|
30
|
+
"tweaks",
|
|
31
|
+
"fix things",
|
|
32
|
+
"minor fix",
|
|
33
|
+
"minor fixes",
|
|
34
|
+
"bugfix",
|
|
35
|
+
"bug fix",
|
|
36
|
+
"asdf",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
# Text-mode display caps. --json and --full always carry the complete
|
|
40
|
+
# evidence; caps only keep the narrative SHORT (June's bar: humans
|
|
41
|
+
# read stories, not dumps). Every cap names where the full text lives.
|
|
42
|
+
MAX_BODY_LINES = 6
|
|
43
|
+
MAX_SUBJECT_CHARS = 120
|
|
44
|
+
MAX_REPLACED_LINES = 20
|
|
45
|
+
MAX_IMPORTERS_SHOWN = 5
|
|
46
|
+
MAX_ENRICHED_REFS = 10
|
|
47
|
+
MAX_PR_BODY_LINES = 6
|
|
48
|
+
MAX_REVIEWS = 3
|
|
49
|
+
MAX_REVIEW_CHARS = 200
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def trunc_subject(subject: str) -> str:
|
|
53
|
+
"""Text-mode subject: capped, with ellipsis. Full text in --json."""
|
|
54
|
+
subject = subject or ""
|
|
55
|
+
if len(subject) <= MAX_SUBJECT_CHARS:
|
|
56
|
+
return subject
|
|
57
|
+
return subject[: MAX_SUBJECT_CHARS - 1] + "…"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def render_why(why: str) -> str:
|
|
61
|
+
"""Text-mode why: subject (capped) + first body lines, then a
|
|
62
|
+
truncation note pointing at --json/--full. The data dict keeps
|
|
63
|
+
the full message; nothing is lost, only folded."""
|
|
64
|
+
lines = (why or "").split("\n")
|
|
65
|
+
if not lines:
|
|
66
|
+
return why
|
|
67
|
+
lines[0] = trunc_subject(lines[0])
|
|
68
|
+
if len(lines) <= MAX_BODY_LINES + 1:
|
|
69
|
+
return "\n".join(lines)
|
|
70
|
+
kept = lines[: MAX_BODY_LINES + 1]
|
|
71
|
+
kept.append(" … (message truncated — full text in --json or --full)")
|
|
72
|
+
return "\n".join(kept)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def render_pr_quotes(ref: dict) -> list[str]:
|
|
76
|
+
"""PR body and review text, quoted verbatim (capped), never paraphrased."""
|
|
77
|
+
out: list[str] = []
|
|
78
|
+
body_lines = [ln for ln in (ref.get("body") or "").splitlines() if ln.strip()]
|
|
79
|
+
for line in body_lines[:MAX_PR_BODY_LINES]:
|
|
80
|
+
out.append(f" [PR #{ref['number']} body] {line}")
|
|
81
|
+
if len(body_lines) > MAX_PR_BODY_LINES:
|
|
82
|
+
out.append(" … (PR body truncated — full text in --json)")
|
|
83
|
+
reviews = [r for r in ref.get("reviews") or [] if r["body"].strip()]
|
|
84
|
+
for review in reviews[:MAX_REVIEWS]:
|
|
85
|
+
text = " ".join(review["body"].split())
|
|
86
|
+
if len(text) > MAX_REVIEW_CHARS:
|
|
87
|
+
text = text[: MAX_REVIEW_CHARS - 1] + "…"
|
|
88
|
+
out.append(f" [review by {review['author']}] {text}")
|
|
89
|
+
if len(reviews) > MAX_REVIEWS:
|
|
90
|
+
out.append(f" … {len(reviews) - MAX_REVIEWS} more review(s) in --json")
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def why_text(subject: str, body: str) -> str:
|
|
95
|
+
"""The documented why for a commit, or the honest absence of one."""
|
|
96
|
+
subject = (subject or "").strip()
|
|
97
|
+
body = (body or "").strip()
|
|
98
|
+
if body:
|
|
99
|
+
return f"{subject}\n{body}" if subject else body
|
|
100
|
+
if not subject or subject.lower() in GENERIC_SUBJECTS:
|
|
101
|
+
return "reason undocumented in history"
|
|
102
|
+
return f"{subject} (no extended message — reason undocumented beyond the subject line)"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def replaced_lines(diff: str) -> list[str]:
|
|
106
|
+
"""Removed lines from a diff, excluding the --- header."""
|
|
107
|
+
out = []
|
|
108
|
+
for line in (diff or "").splitlines():
|
|
109
|
+
if line.startswith("-") and not line.startswith("---"):
|
|
110
|
+
out.append(line[1:])
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def assemble(
|
|
115
|
+
repo: Path,
|
|
116
|
+
relpath: str,
|
|
117
|
+
start: int,
|
|
118
|
+
end: int,
|
|
119
|
+
gh_enabled: bool = True,
|
|
120
|
+
blame_only: bool = False,
|
|
121
|
+
ignore_revs: bool = True,
|
|
122
|
+
) -> dict:
|
|
123
|
+
"""Build the full evidence dict for a file + line range."""
|
|
124
|
+
revs_file, configured = gitops.ignore_revs_file(repo)
|
|
125
|
+
if not ignore_revs:
|
|
126
|
+
# An empty file name clears any configured list (git blame docs).
|
|
127
|
+
blame_extra = ["--ignore-revs-file="] if configured else []
|
|
128
|
+
ignore_info = None
|
|
129
|
+
elif revs_file:
|
|
130
|
+
blame_extra = [] if configured else ["--ignore-revs-file", revs_file]
|
|
131
|
+
ignore_info = {"file": revs_file, "count": gitops.count_revs(repo / revs_file)}
|
|
132
|
+
else:
|
|
133
|
+
blame_extra, ignore_info = [], None
|
|
134
|
+
blame_raw = gitops.blame_porcelain(repo, relpath, start, end, blame_extra)
|
|
135
|
+
blame = ev.parse_blame_porcelain(blame_raw)
|
|
136
|
+
if not blame:
|
|
137
|
+
raise gitops.GitError(f"no blame output for {relpath}:{start}-{end}")
|
|
138
|
+
|
|
139
|
+
uncommitted = [b["line"] for b in blame if b["uncommitted"]]
|
|
140
|
+
committed = [b for b in blame if not b["uncommitted"]]
|
|
141
|
+
|
|
142
|
+
# Introducing commits, in order of first appearance in the range.
|
|
143
|
+
intro_order: list[str] = []
|
|
144
|
+
for entry in committed:
|
|
145
|
+
if entry["hash"] not in intro_order:
|
|
146
|
+
intro_order.append(entry["hash"])
|
|
147
|
+
|
|
148
|
+
# Line-range history (newest first). May fail when the range
|
|
149
|
+
# covers only uncommitted lines or exceeds the committed file;
|
|
150
|
+
# blame evidence still stands on its own. --blame-only skips it
|
|
151
|
+
# deliberately: `git log -L` is the slow call on long histories,
|
|
152
|
+
# and blame alone still answers who/when/why for the current form.
|
|
153
|
+
history_note = None
|
|
154
|
+
if blame_only:
|
|
155
|
+
history_raw = ""
|
|
156
|
+
history = []
|
|
157
|
+
history_note = "line history skipped (--blame-only) — narrative uses blame only"
|
|
158
|
+
else:
|
|
159
|
+
try:
|
|
160
|
+
history_raw = gitops.line_history(repo, relpath, start, end)
|
|
161
|
+
history = ev.parse_line_history(history_raw)
|
|
162
|
+
except gitops.GitError:
|
|
163
|
+
history_raw = ""
|
|
164
|
+
history = []
|
|
165
|
+
history_note = (
|
|
166
|
+
"line history unavailable (range may cover uncommitted lines "
|
|
167
|
+
"or exceed the committed file) — narrative uses blame only"
|
|
168
|
+
)
|
|
169
|
+
history_by_hash = {r["hash"]: r for r in history}
|
|
170
|
+
|
|
171
|
+
def metadata_for(commit: str) -> dict:
|
|
172
|
+
if commit in history_by_hash:
|
|
173
|
+
rec = history_by_hash[commit]
|
|
174
|
+
return {
|
|
175
|
+
"hash": commit,
|
|
176
|
+
"author": rec["author"],
|
|
177
|
+
"date": rec["date"],
|
|
178
|
+
"subject": rec["subject"],
|
|
179
|
+
"body": rec["body"],
|
|
180
|
+
}
|
|
181
|
+
return gitops.commit_metadata(repo, commit)
|
|
182
|
+
|
|
183
|
+
introducing = []
|
|
184
|
+
for commit in intro_order:
|
|
185
|
+
meta = metadata_for(commit)
|
|
186
|
+
lines_here = [b["line"] for b in committed if b["hash"] == commit]
|
|
187
|
+
# What it replaced: prefer the range-scoped -L diff; fall back
|
|
188
|
+
# to the commit's diff for this path, then to the path the
|
|
189
|
+
# code moved from (blame 'previous' filename). moved_from is
|
|
190
|
+
# kept even when no diff is recovered: without it, moved code
|
|
191
|
+
# would render as "added new", which misleads (it HAD a prior
|
|
192
|
+
# version — elsewhere).
|
|
193
|
+
#
|
|
194
|
+
# CAREFUL — what 'previous' means (verified empirically,
|
|
195
|
+
# v0.2.0): blame emits previous on EVERY non-initial group,
|
|
196
|
+
# pointing at the parent commit and filename, with and
|
|
197
|
+
# without -C. It is NOT evidence of a move. Only a previous
|
|
198
|
+
# filename DIFFERENT from this file indicates a rename or a
|
|
199
|
+
# -C copy origin. Same-path previous is normal continuation
|
|
200
|
+
# and must never render as "moved into this file" — v0.2.0
|
|
201
|
+
# caught that mislabeling live on shortleash (a plain added
|
|
202
|
+
# import rendered as a move) and this filter is the fix.
|
|
203
|
+
diff = ""
|
|
204
|
+
diff_source = "range history"
|
|
205
|
+
if commit in history_by_hash:
|
|
206
|
+
diff = history_by_hash[commit]["diff"]
|
|
207
|
+
prev_files = {
|
|
208
|
+
b["previous"]["filename"]
|
|
209
|
+
for b in committed
|
|
210
|
+
if b["hash"] == commit and b["previous"] and b["previous"]["filename"] != relpath
|
|
211
|
+
}
|
|
212
|
+
if not diff:
|
|
213
|
+
diff = gitops.commit_diff_for_path(repo, commit, relpath)
|
|
214
|
+
diff_source = "commit diff for this file"
|
|
215
|
+
if not diff:
|
|
216
|
+
for prev in sorted(prev_files):
|
|
217
|
+
candidate = gitops.commit_diff_for_path(repo, commit, prev)
|
|
218
|
+
if candidate:
|
|
219
|
+
diff = candidate
|
|
220
|
+
diff_source = f"commit diff for {prev} (code moved into this file)"
|
|
221
|
+
break
|
|
222
|
+
files = gitops.commit_files(repo, commit)
|
|
223
|
+
test_files = [f for f in files if ev.is_test_path(f)]
|
|
224
|
+
introducing.append(
|
|
225
|
+
{
|
|
226
|
+
**meta,
|
|
227
|
+
"short": ev.short_hash(commit),
|
|
228
|
+
"lines": lines_here,
|
|
229
|
+
"why": why_text(meta["subject"], meta["body"]),
|
|
230
|
+
"reason_trailers": ev.parse_reason_trailers(meta["body"]),
|
|
231
|
+
"replaced": replaced_lines(diff),
|
|
232
|
+
"replaced_diff_source": diff_source,
|
|
233
|
+
"moved_from": sorted(prev_files),
|
|
234
|
+
"diff": diff,
|
|
235
|
+
"test_files": test_files,
|
|
236
|
+
"related_test_files": [f for f in test_files if ev.test_file_related(relpath, f)],
|
|
237
|
+
"other_test_file_count": len(
|
|
238
|
+
[f for f in test_files if not ev.test_file_related(relpath, f)]
|
|
239
|
+
),
|
|
240
|
+
}
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
# Full range history, newest first. "Later" means after FIRST
|
|
244
|
+
# appearance (the oldest record): a blame commit is the last
|
|
245
|
+
# change to its lines, so "changes after the blame commit" would
|
|
246
|
+
# be empty by definition — the meaningful story is first
|
|
247
|
+
# appearance -> now, with blame commits marked as the current form.
|
|
248
|
+
history_records = []
|
|
249
|
+
for rec in history:
|
|
250
|
+
history_records.append(
|
|
251
|
+
{
|
|
252
|
+
"hash": rec["hash"],
|
|
253
|
+
"short": ev.short_hash(rec["hash"]),
|
|
254
|
+
"author": rec["author"],
|
|
255
|
+
"date": rec["date"],
|
|
256
|
+
"subject": rec["subject"],
|
|
257
|
+
"body": rec["body"],
|
|
258
|
+
"kind": ev.classify_touch(rec["subject"], rec["body"]),
|
|
259
|
+
"mentions_breakage": ev.mentions_breakage(rec["subject"], rec["body"]),
|
|
260
|
+
"introduces_current": rec["hash"] in intro_order,
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
first_appearance = history_records[-1] if history_records else None
|
|
264
|
+
changes_since_first = history_records[:-1] if len(history_records) > 1 else []
|
|
265
|
+
|
|
266
|
+
# What breaks if you touch it — evidence only.
|
|
267
|
+
breaks: list[str] = []
|
|
268
|
+
for touch in changes_since_first:
|
|
269
|
+
if touch["kind"] in ("fix", "revert"):
|
|
270
|
+
breaks.append(
|
|
271
|
+
f"later {touch['kind']} {touch['short']} "
|
|
272
|
+
f"({touch['date'][:10]}): {touch['subject']} "
|
|
273
|
+
f"[classified by message pattern]"
|
|
274
|
+
)
|
|
275
|
+
elif touch["mentions_breakage"]:
|
|
276
|
+
breaks.append(f"later touch {touch['short']} mentions breakage: {touch['subject']}")
|
|
277
|
+
# Related test files, deduplicated across introducing commits:
|
|
278
|
+
# the same test file changed by two commits printed twice (once
|
|
279
|
+
# per commit) in v0.1.0 — noise, not information. Cite all
|
|
280
|
+
# introducing commits on one line instead.
|
|
281
|
+
related_map: dict[str, list[str]] = {}
|
|
282
|
+
for intro in introducing:
|
|
283
|
+
for test_file in intro["related_test_files"]:
|
|
284
|
+
related_map.setdefault(test_file, []).append(intro["short"])
|
|
285
|
+
for test_file, shorts in related_map.items():
|
|
286
|
+
cites = ", ".join(shorts)
|
|
287
|
+
breaks.append(
|
|
288
|
+
f"introducing commit(s) {cites} also changed test "
|
|
289
|
+
f"file {test_file} [related by name to this file — "
|
|
290
|
+
f"evidence that tests exist alongside this code, not "
|
|
291
|
+
f"proof they cover these lines]"
|
|
292
|
+
)
|
|
293
|
+
for intro in introducing:
|
|
294
|
+
if intro["other_test_file_count"]:
|
|
295
|
+
breaks.append(
|
|
296
|
+
f"introducing commit {intro['short']} also changed "
|
|
297
|
+
f"{intro['other_test_file_count']} other test file(s) "
|
|
298
|
+
f"(unrelated by name to this file — count only, not "
|
|
299
|
+
f"listed; full list in --json)"
|
|
300
|
+
)
|
|
301
|
+
# Files that import this module (heuristic git grep, best-effort):
|
|
302
|
+
# the most direct "what breaks" signal the basename heuristic
|
|
303
|
+
# misses — a test named test_login.py covers auth.py without
|
|
304
|
+
# sharing its name, but an importer is coupled whatever its name.
|
|
305
|
+
try:
|
|
306
|
+
importer_list = gitops.importers(repo, relpath)
|
|
307
|
+
importers_note = None
|
|
308
|
+
except gitops.GitError:
|
|
309
|
+
importer_list = []
|
|
310
|
+
importers_note = (
|
|
311
|
+
"importer search unavailable (git grep failed) — narrative uses blame only for coupling"
|
|
312
|
+
)
|
|
313
|
+
for importer in importer_list[:MAX_IMPORTERS_SHOWN]:
|
|
314
|
+
breaks.append(
|
|
315
|
+
f"file {importer} imports this module [heuristic: git grep "
|
|
316
|
+
f"for import statements — evidence of coupling, not proof "
|
|
317
|
+
f"these lines are covered]"
|
|
318
|
+
)
|
|
319
|
+
if len(importer_list) > MAX_IMPORTERS_SHOWN:
|
|
320
|
+
breaks.append(
|
|
321
|
+
f"{len(importer_list) - MAX_IMPORTERS_SHOWN} more file(s) "
|
|
322
|
+
f"import this module (count only, not listed; full list "
|
|
323
|
+
f"in --json)"
|
|
324
|
+
)
|
|
325
|
+
breaks_unknown = not breaks
|
|
326
|
+
|
|
327
|
+
# PR / issue references from every message in evidence.
|
|
328
|
+
all_messages = []
|
|
329
|
+
for intro in introducing:
|
|
330
|
+
all_messages.append(f"{intro['subject']}\n{intro['body']}")
|
|
331
|
+
for rec in history_records:
|
|
332
|
+
all_messages.append(f"{rec['subject']}\n{rec['body']}")
|
|
333
|
+
refs = ev.parse_pr_refs(*all_messages)
|
|
334
|
+
|
|
335
|
+
gh_note = None
|
|
336
|
+
enriched = []
|
|
337
|
+
lookup_notes: list[str] = []
|
|
338
|
+
if gh_enabled:
|
|
339
|
+
host, slug = gitops.parse_remote(repo)
|
|
340
|
+
if slug and gitops.gh_available():
|
|
341
|
+
# Cap: a message referencing 50 PRs would otherwise cost
|
|
342
|
+
# 50 sequential gh calls (up to 20s each). Enrich the
|
|
343
|
+
# first 10, show the rest unresolved with a note.
|
|
344
|
+
# Introducing commits with no #N in their message go first:
|
|
345
|
+
# ask GitHub which PR brought the commit in (shares the cap).
|
|
346
|
+
budget = MAX_ENRICHED_REFS
|
|
347
|
+
known = {(r["repo"], r["number"]) for r in refs}
|
|
348
|
+
for intro in introducing:
|
|
349
|
+
if budget == 0:
|
|
350
|
+
break
|
|
351
|
+
if ev.parse_pr_refs(f"{intro['subject']}\n{intro['body']}"):
|
|
352
|
+
continue
|
|
353
|
+
budget -= 1
|
|
354
|
+
pull = gitops.gh_commit_pull(slug, intro["hash"], host=host)
|
|
355
|
+
if not pull:
|
|
356
|
+
lookup_notes.append(
|
|
357
|
+
f"commit->PR lookup unresolved for {intro['short']} ("
|
|
358
|
+
+ ("GitHub lists no PR for it)" if pull is False else "gh lookup failed)")
|
|
359
|
+
)
|
|
360
|
+
continue
|
|
361
|
+
if (None, pull["number"]) in known:
|
|
362
|
+
continue
|
|
363
|
+
known.add((None, pull["number"]))
|
|
364
|
+
enriched.append(
|
|
365
|
+
{
|
|
366
|
+
**pull,
|
|
367
|
+
"repo": None,
|
|
368
|
+
"kind": "pr",
|
|
369
|
+
"resolved": True,
|
|
370
|
+
"found_via": "commit->PR lookup",
|
|
371
|
+
"commit": intro["hash"],
|
|
372
|
+
}
|
|
373
|
+
)
|
|
374
|
+
for ref in refs[:budget]:
|
|
375
|
+
target = ref["repo"] or slug
|
|
376
|
+
found = None
|
|
377
|
+
kind = None
|
|
378
|
+
for candidate_kind in ("pr", "issue"):
|
|
379
|
+
found = gitops.gh_view(target, candidate_kind, ref["number"], host=host)
|
|
380
|
+
if found:
|
|
381
|
+
kind = candidate_kind
|
|
382
|
+
break
|
|
383
|
+
enriched.append(
|
|
384
|
+
{**ref, "kind": kind, **(found or {}), "resolved": found is not None}
|
|
385
|
+
)
|
|
386
|
+
if len(refs) > budget:
|
|
387
|
+
enriched.extend(
|
|
388
|
+
{
|
|
389
|
+
**ref,
|
|
390
|
+
"kind": None,
|
|
391
|
+
"title": None,
|
|
392
|
+
"state": None,
|
|
393
|
+
"url": None,
|
|
394
|
+
"resolved": False,
|
|
395
|
+
}
|
|
396
|
+
for ref in refs[budget:]
|
|
397
|
+
)
|
|
398
|
+
gh_note = (
|
|
399
|
+
f"gh enrichment capped at {MAX_ENRICHED_REFS} "
|
|
400
|
+
"lookups — the rest are shown unresolved"
|
|
401
|
+
)
|
|
402
|
+
elif not refs:
|
|
403
|
+
pass
|
|
404
|
+
elif not slug:
|
|
405
|
+
gh_note = (
|
|
406
|
+
"PR/issue links unavailable: no GitHub remote — narrative uses local evidence only"
|
|
407
|
+
)
|
|
408
|
+
else:
|
|
409
|
+
gh_note = (
|
|
410
|
+
"PR/issue links unavailable: gh not installed — narrative uses local evidence only"
|
|
411
|
+
)
|
|
412
|
+
else:
|
|
413
|
+
gh_note = "PR/issue enrichment disabled (--no-gh) — narrative uses local evidence only"
|
|
414
|
+
if not enriched:
|
|
415
|
+
enriched = [
|
|
416
|
+
{**ref, "kind": None, "title": None, "state": None, "url": None, "resolved": False}
|
|
417
|
+
for ref in refs
|
|
418
|
+
]
|
|
419
|
+
if enriched and any(not ref["resolved"] for ref in enriched) and not gh_note:
|
|
420
|
+
gh_note = (
|
|
421
|
+
"some references could not be resolved via gh "
|
|
422
|
+
"(missing, private, or unauthenticated) — shown "
|
|
423
|
+
"unresolved, never fabricated"
|
|
424
|
+
)
|
|
425
|
+
if lookup_notes:
|
|
426
|
+
gh_note = "; ".join(([gh_note] if gh_note else []) + lookup_notes)
|
|
427
|
+
|
|
428
|
+
ai_trailers = ev.parse_ai_trailers(*all_messages)
|
|
429
|
+
ai_commit_hashes: set[str] = set()
|
|
430
|
+
for intro in introducing:
|
|
431
|
+
if ev.parse_ai_trailers(f"{intro['subject']}\n{intro['body']}"):
|
|
432
|
+
ai_commit_hashes.add(intro["hash"])
|
|
433
|
+
for rec in history_records:
|
|
434
|
+
if ev.parse_ai_trailers(f"{rec['subject']}\n{rec['body']}"):
|
|
435
|
+
ai_commit_hashes.add(rec["hash"])
|
|
436
|
+
|
|
437
|
+
return {
|
|
438
|
+
"gitstory_version": __version__,
|
|
439
|
+
"repo": str(repo),
|
|
440
|
+
"file": relpath,
|
|
441
|
+
"start": start,
|
|
442
|
+
"end": end,
|
|
443
|
+
"blame": [
|
|
444
|
+
{
|
|
445
|
+
"line": b["line"],
|
|
446
|
+
"hash": b["hash"],
|
|
447
|
+
"short": ev.short_hash(b["hash"]) if not b["uncommitted"] else "uncommitted",
|
|
448
|
+
"author": b["author"],
|
|
449
|
+
"date": ev.format_epoch(b["author_time"]),
|
|
450
|
+
"summary": b["summary"],
|
|
451
|
+
"content": b["content"],
|
|
452
|
+
"uncommitted": b["uncommitted"],
|
|
453
|
+
}
|
|
454
|
+
for b in blame
|
|
455
|
+
],
|
|
456
|
+
"uncommitted_lines": uncommitted,
|
|
457
|
+
"introducing": introducing,
|
|
458
|
+
"history": history_records,
|
|
459
|
+
"changes_since_first": changes_since_first,
|
|
460
|
+
"first_appearance": first_appearance,
|
|
461
|
+
"breaks": breaks,
|
|
462
|
+
"breaks_unknown": breaks_unknown,
|
|
463
|
+
"importers": importer_list,
|
|
464
|
+
"importers_note": importers_note,
|
|
465
|
+
"references": enriched,
|
|
466
|
+
"gh_note": gh_note,
|
|
467
|
+
"ai_trailers": ai_trailers,
|
|
468
|
+
"ai_trailer_commit_count": len(ai_commit_hashes),
|
|
469
|
+
"history_note": history_note,
|
|
470
|
+
"blame_only": blame_only,
|
|
471
|
+
"ignore_revs": ignore_info,
|
|
472
|
+
"blame_raw": blame_raw,
|
|
473
|
+
"history_raw": history_raw,
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def render_text(data: dict, full: bool = False) -> str:
|
|
478
|
+
"""Deterministic narrative text. Every claim cites a short hash."""
|
|
479
|
+
out: list[str] = []
|
|
480
|
+
rng = f"{data['start']}" if data["start"] == data["end"] else f"{data['start']}-{data['end']}"
|
|
481
|
+
out.append(f"gitstory: {data['file']}:{rng}")
|
|
482
|
+
out.append("")
|
|
483
|
+
|
|
484
|
+
if data["uncommitted_lines"]:
|
|
485
|
+
lines = ", ".join(str(n) for n in data["uncommitted_lines"])
|
|
486
|
+
out.append(
|
|
487
|
+
f"NOTE: line(s) {lines} have uncommitted changes — the "
|
|
488
|
+
"narrative below covers committed history only. Commit, "
|
|
489
|
+
"then re-run, for the full story."
|
|
490
|
+
)
|
|
491
|
+
out.append("")
|
|
492
|
+
if data["history_note"]:
|
|
493
|
+
out.append(f"NOTE: {data['history_note']}")
|
|
494
|
+
out.append("")
|
|
495
|
+
|
|
496
|
+
out.append("SUMMARY:")
|
|
497
|
+
if not data["history"]:
|
|
498
|
+
out.append(" line history unavailable — see blame below.")
|
|
499
|
+
else:
|
|
500
|
+
first = data["first_appearance"]
|
|
501
|
+
last = data["history"][0]
|
|
502
|
+
out.append(
|
|
503
|
+
f" First written by {first['author']} on "
|
|
504
|
+
f"{first['date'][:10]}: {trunc_subject(first['subject'])}"
|
|
505
|
+
)
|
|
506
|
+
if len(data["history"]) > 1:
|
|
507
|
+
out.append(
|
|
508
|
+
f" Last changed by {last['author']} on "
|
|
509
|
+
f"{last['date'][:10]}: {trunc_subject(last['subject'])}"
|
|
510
|
+
)
|
|
511
|
+
else:
|
|
512
|
+
out.append(" Unchanged since first appearance.")
|
|
513
|
+
first_why = why_text(first["subject"], first["body"])
|
|
514
|
+
first_trailers = ev.parse_reason_trailers(first["body"])
|
|
515
|
+
if first_trailers:
|
|
516
|
+
names = ", ".join(dict.fromkeys(t["name"] for t in first_trailers))
|
|
517
|
+
reason_line = f"Original reason: documented in trailer ({names})."
|
|
518
|
+
elif first_why == "reason undocumented in history":
|
|
519
|
+
reason_line = "Original reason: undocumented in history."
|
|
520
|
+
elif "no extended message" in first_why:
|
|
521
|
+
reason_line = "Original reason: subject line only, no extended message."
|
|
522
|
+
else:
|
|
523
|
+
reason_line = "Original reason: documented in the commit message."
|
|
524
|
+
out.append(f" {len(data['history'])} commit(s) in this range's history. {reason_line}")
|
|
525
|
+
if data.get("ignore_revs"):
|
|
526
|
+
revs = data["ignore_revs"]
|
|
527
|
+
out.append(
|
|
528
|
+
f" Blame ignored {revs['count']} formatting revision(s) "
|
|
529
|
+
f"from {revs['file']} (--no-ignore-revs to include them)."
|
|
530
|
+
)
|
|
531
|
+
out.append("")
|
|
532
|
+
|
|
533
|
+
out.append("LINES (blame, -w -C):")
|
|
534
|
+
for entry in data["blame"]:
|
|
535
|
+
out.append(
|
|
536
|
+
f" {entry['line']}: {entry['short']} {entry['author']} "
|
|
537
|
+
f"{entry['date']} — {entry['content']}"
|
|
538
|
+
)
|
|
539
|
+
out.append("")
|
|
540
|
+
|
|
541
|
+
if not data["introducing"]:
|
|
542
|
+
out.append("WHO WROTE IT: no committed history for these lines.")
|
|
543
|
+
out.append("")
|
|
544
|
+
else:
|
|
545
|
+
out.append("WHO WROTE IT, AND WHEN:")
|
|
546
|
+
for intro in data["introducing"]:
|
|
547
|
+
lines = ", ".join(str(n) for n in intro["lines"])
|
|
548
|
+
out.append(
|
|
549
|
+
f" {intro['short']} {intro['author']} "
|
|
550
|
+
f"{intro['date'][:10]} "
|
|
551
|
+
f"(line(s) {lines}): {trunc_subject(intro['subject'])}"
|
|
552
|
+
)
|
|
553
|
+
out.append("")
|
|
554
|
+
out.append("WHY (from the commit messages — quoted, not reconstructed):")
|
|
555
|
+
for intro in data["introducing"]:
|
|
556
|
+
out.append(f" [{intro['short']}] {render_why(intro['why'])}")
|
|
557
|
+
for trailer in intro.get("reason_trailers") or []:
|
|
558
|
+
out.append(f" [trailer {trailer['name']}] {trailer['value']}")
|
|
559
|
+
out.append("")
|
|
560
|
+
out.append("WHAT IT REPLACED:")
|
|
561
|
+
for intro in data["introducing"]:
|
|
562
|
+
if intro["replaced"]:
|
|
563
|
+
out.append(f" [{intro['short']}] replaced ({intro['replaced_diff_source']}):")
|
|
564
|
+
for line in intro["replaced"][:MAX_REPLACED_LINES]:
|
|
565
|
+
out.append(f" - {line}")
|
|
566
|
+
if len(intro["replaced"]) > MAX_REPLACED_LINES:
|
|
567
|
+
out.append(
|
|
568
|
+
f" … and "
|
|
569
|
+
f"{len(intro['replaced']) - MAX_REPLACED_LINES} "
|
|
570
|
+
"more removed lines (full diff in --json or --full)"
|
|
571
|
+
)
|
|
572
|
+
elif intro["moved_from"]:
|
|
573
|
+
out.append(
|
|
574
|
+
f" [{intro['short']}] these lines moved into this "
|
|
575
|
+
f"file from {', '.join(intro['moved_from'])} — prior "
|
|
576
|
+
"version not recovered from history"
|
|
577
|
+
)
|
|
578
|
+
else:
|
|
579
|
+
out.append(
|
|
580
|
+
f" [{intro['short']}] these lines were added new — "
|
|
581
|
+
"no prior version in this file "
|
|
582
|
+
f"({intro['replaced_diff_source']})"
|
|
583
|
+
)
|
|
584
|
+
out.append("")
|
|
585
|
+
|
|
586
|
+
out.append(
|
|
587
|
+
"WHAT CHANGED SINCE FIRST APPEARANCE (kind labels are message-pattern inference, not fact):"
|
|
588
|
+
)
|
|
589
|
+
if not data["history"]:
|
|
590
|
+
out.append(" line history unavailable (see note above).")
|
|
591
|
+
elif not data["changes_since_first"]:
|
|
592
|
+
first = data["first_appearance"]
|
|
593
|
+
out.append(
|
|
594
|
+
" no changes since first appearance — these lines are as "
|
|
595
|
+
f"first written ({first['short']}, {first['date'][:10]})."
|
|
596
|
+
)
|
|
597
|
+
else:
|
|
598
|
+
for touch in data["changes_since_first"]:
|
|
599
|
+
marker = " [current form]" if touch["introduces_current"] else ""
|
|
600
|
+
out.append(
|
|
601
|
+
f" {touch['short']} {touch['author']} "
|
|
602
|
+
f"{touch['date'][:10]} [{touch['kind']}, classified by "
|
|
603
|
+
f"message pattern]{marker}: {trunc_subject(touch['subject'])}"
|
|
604
|
+
)
|
|
605
|
+
first = data["first_appearance"]
|
|
606
|
+
out.append(
|
|
607
|
+
f" first appearance: {first['short']} {first['author']} "
|
|
608
|
+
f"{first['date'][:10]}: {trunc_subject(first['subject'])}"
|
|
609
|
+
)
|
|
610
|
+
out.append("")
|
|
611
|
+
|
|
612
|
+
out.append("WHAT BREAKS IF YOU TOUCH IT:")
|
|
613
|
+
if data["breaks_unknown"]:
|
|
614
|
+
out.append(
|
|
615
|
+
" unknown from history — no later fix, revert, test, or "
|
|
616
|
+
"linked reference in history says what breaks. That absence "
|
|
617
|
+
"is itself a finding: touch it carefully."
|
|
618
|
+
)
|
|
619
|
+
else:
|
|
620
|
+
for item in data["breaks"]:
|
|
621
|
+
out.append(f" - {item}")
|
|
622
|
+
if data.get("importers_note"):
|
|
623
|
+
out.append(f" note: {data['importers_note']}")
|
|
624
|
+
out.append("")
|
|
625
|
+
|
|
626
|
+
out.append("LINKED PRS / ISSUES:")
|
|
627
|
+
if not data["references"]:
|
|
628
|
+
out.append(" none referenced in the commit messages.")
|
|
629
|
+
else:
|
|
630
|
+
for ref in data["references"]:
|
|
631
|
+
label = f"#{ref['number']}"
|
|
632
|
+
if ref["repo"]:
|
|
633
|
+
label = f"{ref['repo']}#{ref['number']}"
|
|
634
|
+
if ref["resolved"]:
|
|
635
|
+
via = ""
|
|
636
|
+
if ref.get("found_via"):
|
|
637
|
+
via = f" [found via {ref['found_via']} for {ev.short_hash(ref['commit'])}]"
|
|
638
|
+
out.append(
|
|
639
|
+
f" {label} — {ref['kind']} '{ref['title']}' ({ref['state']}) {ref['url']}{via}"
|
|
640
|
+
)
|
|
641
|
+
out.extend(render_pr_quotes(ref))
|
|
642
|
+
else:
|
|
643
|
+
out.append(f" {label} — unresolved (see note below)")
|
|
644
|
+
if data["gh_note"]:
|
|
645
|
+
out.append(f" note: {data['gh_note']}")
|
|
646
|
+
out.append("")
|
|
647
|
+
|
|
648
|
+
if data["ai_trailers"]:
|
|
649
|
+
out.append(
|
|
650
|
+
"AGENT-AUTHORSHIP NOTE (from commit metadata only, never guessed from code style):"
|
|
651
|
+
)
|
|
652
|
+
count = data.get("ai_trailer_commit_count", 0)
|
|
653
|
+
if count:
|
|
654
|
+
out.append(f" {count} commit(s) in this range's history carry AI-assistance trailers:")
|
|
655
|
+
for trailer in data["ai_trailers"]:
|
|
656
|
+
out.append(f" {trailer}")
|
|
657
|
+
out.append("")
|
|
658
|
+
|
|
659
|
+
out.append(
|
|
660
|
+
"Method: blame -w -C + line history + commit messages; "
|
|
661
|
+
"deterministic template assembly, no LLM. INFERENCE is limited "
|
|
662
|
+
"to message-pattern classification, labeled above."
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
if full:
|
|
666
|
+
out.append("")
|
|
667
|
+
out.append("=== RAW EVIDENCE ===")
|
|
668
|
+
out.append("--- blame --porcelain ---")
|
|
669
|
+
out.append(data["blame_raw"].rstrip("\n"))
|
|
670
|
+
out.append("--- line history ---")
|
|
671
|
+
out.append(data["history_raw"].rstrip("\n") or "(unavailable)")
|
|
672
|
+
for intro in data["introducing"]:
|
|
673
|
+
out.append(f"--- diff for {intro['short']} ---")
|
|
674
|
+
out.append(intro["diff"] or "(no diff for this path)")
|
|
675
|
+
|
|
676
|
+
return "\n".join(out) + "\n"
|