{{ message }}
Repository navigation
Expand file tree
/
Copy pathidd-lint.py
More file actions
executable file
·1872 lines (1590 loc) · 76.4 KB
/
Copy pathidd-lint.py
File metadata and controls
executable file
·1872 lines (1590 loc) · 76.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""idd-lint — IDD Spec conformance checker. No LLM, no network, no dependencies.
Validates Issue-Driven Development artifacts against the IDD Spec
(https://github.com/luongnv89/idd/blob/main/SPEC.md) from plain data:
idd-lint issue [FILE|-] lint an issue body (L1, §1–§2)
idd-lint branch NAME lint a branch name (L2, §3.1)
idd-lint commit MSG [MSG ...] lint commit message(s) (L2, §3.2)
idd-lint commit --range A..B lint a git commit range (L2, §3.2)
idd-lint pr [FILE|-] [--title T] [--type bug|...]
lint a PR body (+ title) (L2 §5, L3 §4)
idd-lint repo [--base REF] lint current branch + commits vs base
idd-lint stats [--branch REF] [--since DATE] [--no-github] [--json]
evidence report: trace-completeness,
Decision-Record coverage, run outcomes,
slowest recorded run phase
idd-lint corrections [--record] [--approve KEY | --reject KEY | --landed KEY]
recurring corrections → deduplicated,
approval-gated improvement proposals
(issue #524, docs/correction-guards.md)
FILE of `-` (or omitted) reads stdin. `--level L1|L2|L3` (default L3) selects
the conformance level to enforce; checks above the selected level are skipped.
Exit codes: 0 = conformant (warnings allowed), 1 = errors found, 2 = usage.
`stats` is a report, not a lint of issue/PR text — it exits 0 unless a run-log
row exceeds its class QA-cycle ceiling without `breach_reason` (issue #308).
`--since` accepts any git approxidate. Prefer an unambiguous absolute form —
`--since '2026-08-15 00:00:00'`. A bare `YYYY-MM-DD` is normalized to midnight
before it reaches git, because git otherwise fills the time of day from the
current wall clock and the window silently shifts with the hour you run it.
git reads that date in the *local* zone while a PR's `mergedAt` is UTC, so a PR
merged at `2026-08-14T23:00Z` is inside a `2026-08-15` window in UTC+2.
CI example (GitHub Actions):
gh pr view "$PR" --json body -q .body \\
| python3 scripts/idd-lint.py pr - --title "$(gh pr view "$PR" --json title -q .title)"
python3 scripts/idd-lint.py repo --base origin/main
"""
from __future__ import annotations
import argparse
import json
import os
import re
import statistics
import subprocess
import sys
from datetime import datetime, timezone
from typing import Callable, NamedTuple
from pathlib import Path
SPEC_VERSION = "1.1"
SPEC_URL = "https://github.com/luongnv89/idd/blob/main/SPEC.md"
MARKER_RE = re.compile(r"<!--\s*(?:gitissue|idd):normalized\s+v(\d+)\s*-->")
SECTION_RE = re.compile(r"^## +(.+?)\s*$")
CONFIDENCE_RE = re.compile(r"\((?:high|medium) confidence\)|\(needs review\)")
CHECKBOX_RE = re.compile(r"^\s*[-*] \[[ xX]\] \S", re.MULTILINE)
DEP_MARKER_RE = re.compile(r"(?i)\b(?:depends on|blocked by)\b")
CROSS_REPO_TOKEN_RE = re.compile(r"\S+/\S+#\d+")
BARE_ISSUE_RE = re.compile(r"(?<![\w/])#(\d+)")
PART_MARKER_RE = re.compile(r"\bpart of:?\s*(#\d+)", re.IGNORECASE)
ISSUE_TYPES = ("bug", "feature", "improvement")
BRANCH_TYPES = ("fix", "feat", "refactor", "docs", "test", "chore")
COMMIT_TYPES = ("feat", "fix", "refactor", "docs", "test", "chore", "style", "perf")
BRANCH_RE = re.compile(r"^(fix|feat|refactor|docs|test|chore)/(\d+)((?:-[a-z0-9]+)+)$")
BRANCH_EXEMPT_RE = re.compile(r"^(hotfix|release)/[a-z0-9][a-z0-9.-]*$")
COMMIT_RE = re.compile(
r"^(feat|fix|refactor|docs|test|chore|style|perf)" # type
r"(?:\(([a-z0-9._-]+)\))?" # optional scope
r": (.+?) \(#(\d+)\)$" # description + issue ref
)
DR_HEADING = "## Decision Record"
BARE_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
# Approxidate spellings that legitimately resolve to *now*, so a resolved
# timestamp of ~now from one of these is an answer, not a parse failure.
NOW_TOKENS = {"now", "today", "@now"}
ADR_NO_BACKFILL = "docs/decisions/no-backfill-merged-decision-records.md"
DR_FIELDS = ("Root cause", "Options considered", "Options rejected", "Selected option", "Residual risk")
AC_STATUSES = ("pass", "fail", "unverified")
NO_AC_NOTE_RE = re.compile(r"no acceptance criteria defined", re.IGNORECASE)
LEVELS = ("L1", "L2", "L3")
BRANCH_NAME_WARN_LENGTH = 50
COMMIT_SUBJECT_WARN_LENGTH = 72
COMMIT_LABEL_MAX_LENGTH = 60
SOFT_COMMAND_TIMEOUT_SECONDS = 60
APPROXIDATE_NOW_TOLERANCE_SECONDS = 2
MIN_ISSUE_FETCH_LIMIT = 500
PASS_PERCENT_THRESHOLD = 80
WARN_PERCENT_THRESHOLD = 40
DEFAULT_GITHUB_FETCH_LIMIT = 200
# Bounded tail over rotated run-log segments (F-PERF-006): the same newest-N
# window gi-runlog's readers scan, so every consumer sees one logical log.
MAX_RUN_SEGMENTS = 10
# Corrections subcommand (issue #524): key length cap and default history window.
CORRECTION_KEY_MAX_LENGTH = 40
DEFAULT_CORRECTION_COMMIT_LIMIT = 500
class Finding:
def __init__(self, severity: str, code: str, message: str) -> None:
self.severity = severity # "error" | "warn" | "info" | "ok"
self.code = code
self.message = message
def ok(code, msg):
return Finding("ok", code, msg)
def err(code, msg):
return Finding("error", code, msg)
def warn(code, msg):
return Finding("warn", code, msg)
def info(code, msg):
return Finding("info", code, msg)
# --- Parsing helpers ----------------------------------------------------------
def split_sections(text: str) -> dict[str, str]:
"""Split a markdown body into {heading: content} on `## ` headings.
Content before the first heading is stored under ''. First heading wins
on duplicates."""
sections: dict[str, str] = {}
current = ""
buf: list[str] = []
for line in text.splitlines():
m = SECTION_RE.match(line)
if m:
if current not in sections:
sections[current] = "\n".join(buf)
current = m.group(1)
buf = []
else:
buf.append(line)
if current not in sections:
sections[current] = "\n".join(buf)
return sections
def strip_confidence(value: str) -> str:
return CONFIDENCE_RE.sub("", value).strip()
def first_content_line(text: str) -> str:
for line in text.splitlines():
if line.strip():
return line.strip()
return ""
# --- Issue checks (L1, §1–§2) ---------------------------------------------------
class IssueLintContext:
def __init__(self, body: str) -> None:
self.body = body
self.sections = split_sections(body)
self.issue_type: str | None = None
def _check_issue_marker(context: IssueLintContext) -> list[Finding]:
m = MARKER_RE.search(context.body)
if not m:
return [err("I01", "normalization marker '<!-- idd:normalized v1 -->' missing (§1.1)")]
if not MARKER_RE.search(first_content_line(context.body)):
return [warn("I01", "normalization marker present but not on the first line (§1.1)")]
return [ok("I01", f"normalization marker present (v{m.group(1)}) (§1.1)")]
def _check_issue_type(context: IssueLintContext) -> list[Finding]:
if "Type" not in context.sections:
return [err("I02", "missing '## Type' section (§1.1)")]
raw = strip_confidence(first_content_line(context.sections["Type"]))
context.issue_type = raw.lower()
if context.issue_type in ISSUE_TYPES:
return [ok("I02", f"type is '{raw}' (§1.1)")]
if raw:
return [warn("I02", f"type '{raw}' is not one of Bug/Feature/Improvement — allowed only as a documented implementation extension (§1.1)")]
return [err("I02", "'## Type' section is empty (§1.1)")]
def _check_issue_description(context: IssueLintContext) -> list[Finding]:
if "Description" not in context.sections:
return [err("I03", "missing '## Description' section (§1.1)")]
return [ok("I03", "description section present (§1.1)")]
def _check_issue_type_fields(context: IssueLintContext) -> list[Finding]:
required_fields = {
"bug": ("**Current behavior:**", "**Expected behavior:**"),
"improvement": ("**Current state:**", "**Proposed change:**"),
}.get(context.issue_type or "", ())
findings: list[Finding] = []
for field in required_fields:
if field in context.body:
findings.append(ok("I04", f"{field} present (§1.1)"))
else:
findings.append(err("I04", f"{context.issue_type} issue missing required field {field} (§1.1)"))
return findings
def _check_reporter_context(context: IssueLintContext) -> list[Finding]:
if "> **Reporter Context**" in context.body:
return [ok("I05", "Reporter Context blockquote present (§1.1)")]
return [warn("I05", "no '> **Reporter Context**' blockquote — required when normalizing, recommended always (§1.1)")]
def _check_acceptance_criteria(context: IssueLintContext) -> list[Finding]:
section = context.sections.get("Acceptance Criteria")
if section is None:
return [err("I06", "missing '## Acceptance Criteria' section (§1.1)")]
if not CHECKBOX_RE.search(section):
return [err("I06", "'## Acceptance Criteria' has no '- [ ]' checkbox items (§1.1)")]
count = len(CHECKBOX_RE.findall(section))
return [ok("I06", f"acceptance criteria present ({count} checkbox{'es' if count != 1 else ''}) (§1.1)")]
def _check_issue_metadata(context: IssueLintContext) -> list[Finding]:
section = context.sections.get("Metadata")
if section is None:
return [err("I07", "missing '## Metadata' section (§1.1)")]
findings: list[Finding] = []
for label in ("**Priority:**", "**Effort:**", "**Labels:**"):
if label in section:
findings.append(ok("I07", f"metadata field {label} present (§1.1)"))
else:
findings.append(err("I07", f"metadata missing {label} line (§1.1)"))
return findings
def _check_issue_dependencies(context: IssueLintContext) -> list[Finding]:
deps: list[str] = []
seen_dep: set[str] = set()
for line in context.body.splitlines():
if not DEP_MARKER_RE.search(line):
continue
local_segment = CROSS_REPO_TOKEN_RE.sub("", line)
for match in BARE_ISSUE_RE.finditer(local_segment):
ref = f"#{match.group(1)}"
if ref not in seen_dep:
seen_dep.add(ref)
deps.append(ref)
return [info("I08", f"dependency markers found: {', '.join(deps)} (§2)")] if deps else []
def _check_issue_hierarchy(context: IssueLintContext) -> list[Finding]:
parents = [match.group(1) for match in PART_MARKER_RE.finditer(context.body)]
if not parents:
return []
return [info("I09", f"hierarchy marker: Part of {', '.join(parents)} (§2.1)")]
IssueCheck = Callable[[IssueLintContext], list[Finding]]
ISSUE_CHECKS: tuple[IssueCheck, ...] = (
_check_issue_marker,
_check_issue_type,
_check_issue_description,
_check_issue_type_fields,
_check_reporter_context,
_check_acceptance_criteria,
_check_issue_metadata,
_check_issue_dependencies,
_check_issue_hierarchy,
)
def lint_issue(body: str) -> list[Finding]:
context = IssueLintContext(body)
return [finding for check in ISSUE_CHECKS for finding in check(context)]
# --- Branch checks (L2, §3.1) ---------------------------------------------------
def lint_branch(name: str) -> list[Finding]:
findings: list[Finding] = []
if BRANCH_EXEMPT_RE.match(name):
findings.append(ok("B01", f"'{name}' is a workflow-driven hotfix/release branch — issue number optional (§3.1)"))
elif BRANCH_RE.match(name):
findings.append(ok("B01", f"'{name}' matches <type>/<issue>-<description> (§3.1)"))
else:
findings.append(err("B01", f"'{name}' does not match <type>/<issue-number>-<short-description> with type in {'/'.join(BRANCH_TYPES)} — lowercase, hyphen-separated (§3.1)"))
if len(name) > BRANCH_NAME_WARN_LENGTH:
findings.append(warn("B02", f"branch name is {len(name)} chars — should stay under {BRANCH_NAME_WARN_LENGTH} (§3.1)"))
return findings
# --- Commit checks (L2, §3.2) ---------------------------------------------------
def lint_commit(subject: str) -> list[Finding]:
findings: list[Finding] = []
subject = subject.strip().splitlines()[0] if subject.strip() else ""
label = (
subject
if len(subject) <= COMMIT_LABEL_MAX_LENGTH
else subject[:COMMIT_LABEL_MAX_LENGTH - len("...")] + "..."
)
if subject.startswith(("Merge ", "Revert ")):
findings.append(info("C01", f"'{label}' — merge/revert commit, skipped (§3.2)"))
return findings
m = COMMIT_RE.match(subject)
if not m:
findings.append(err("C01", f"'{label}' does not match <type>(<scope>): <description> (#N) with type in {'/'.join(COMMIT_TYPES)} (§3.2)"))
return findings
ctype, scope, desc, issue = m.groups()
findings.append(ok("C01", f"'{label}' matches the commit grammar (type={ctype}, issue=#{issue}) (§3.2)"))
if desc and desc[0].isupper():
findings.append(err("C02", f"'{label}' — description must be lowercase (§3.2)"))
if desc.rstrip().endswith("."):
findings.append(err("C03", f"'{label}' — description must not end with a period (§3.2)"))
if len(subject) > COMMIT_SUBJECT_WARN_LENGTH:
findings.append(warn("C04", f"'{label}' — first line is {len(subject)} chars, keep under {COMMIT_SUBJECT_WARN_LENGTH} (§3.2)"))
if not scope:
findings.append(info("C05", f"'{label}' — no scope; scope is optional but recommended (§3.2)"))
return findings
# --- PR checks (L2 §3.3+§5, L3 §4) ------------------------------------------------
CLOSING_KEYWORD_RE = r"(?i)\b(close[sd]?|fix(e[sd])?|resolve[sd]?)\s+#{n}\b"
def ac_verification_rows(body: str) -> list[list[str]]:
"""Data rows of the `## Acceptance Criteria Verification` table (§5.2)."""
acv = split_sections(body).get("Acceptance Criteria Verification") or ""
rows = [
[c.strip() for c in line.strip().strip("|").split("|")]
for line in acv.splitlines()
if line.strip().startswith("|") and "---" not in line
]
return [
r for r in rows
if len(r) >= 3 and not (r[0].lower() == "criterion" and r[1].lower() == "status")
]
def is_deferred_row(row: list[str]) -> bool:
"""A criterion the PR declares open: Status `unverified`, Evidence says `deferred` (§5.1)."""
return row[1].lower() == "unverified" and "deferred" in row[2].lower()
def intentional_reference_problem(body: str, n: str, title: str | None) -> str | None:
"""Why a `Refs #N` first line is not a valid intentional reference, or None (§5.1)."""
if title is not None:
m = COMMIT_RE.match(title.strip())
if m and m.group(4) != n:
return f"the title names #{m.group(4)}, not #{n}"
if re.search(CLOSING_KEYWORD_RE.format(n=n), body):
return f"the body also carries a closing keyword for #{n}"
rows = ac_verification_rows(body)
deferred = [r for r in rows if is_deferred_row(r)]
if not deferred:
return "no deferred acceptance-criteria row (Status 'unverified', Evidence 'deferred') declares what stays open"
if len(deferred) == len(rows):
return "every acceptance-criteria row is deferred — nothing is delivered"
return None
def lint_pr(body: str, title: str | None, issue_type: str | None, level: str) -> list[Finding]:
findings: list[Finding] = []
sections = split_sections(body)
# P01 (L2) — title follows the commit grammar (§3.3)
pr_is_fix = False
if title is None:
findings.append(info("P01", "no --title given — PR title check skipped (§3.3)"))
else:
m = COMMIT_RE.match(title.strip())
if m:
pr_is_fix = m.group(1) == "fix"
findings.append(ok("P01", f"title matches <type>(<scope>): <description> (#N) (§3.3)"))
else:
findings.append(err("P01", f"title '{title}' does not match <type>(<scope>): <description> (#N) (§3.3)"))
# P02 (L2) — first body line is `Closes #N`, or a valid intentional
# `Refs #N` partial delivery (§3.3, §5.1)
first = first_content_line(body)
refs = re.match(r"^Refs #(\d+)$", first)
if re.match(r"^Closes #\d+$", first):
findings.append(ok("P02", f"body first line is '{first}' (§5.1)"))
elif refs:
problem = intentional_reference_problem(body, refs.group(1), title)
if problem is None:
findings.append(ok("P02", f"body first line is '{first}' — intentional partial delivery (§5.1)"))
else:
findings.append(err("P02", f"'{first}' is not a valid intentional reference: {problem} (§5.1)"))
else:
findings.append(err("P02", "body must start with 'Closes #N' (or a valid intentional 'Refs #N') on its first line (§3.3, §5.1)"))
# P03 (L2) — Acceptance Criteria Verification table (§5.2)
acv = sections.get("Acceptance Criteria Verification")
if acv is None:
if NO_AC_NOTE_RE.search(body):
findings.append(ok("P03", "explicit no-acceptance-criteria note present (§5.2)"))
else:
findings.append(err("P03", "missing '## Acceptance Criteria Verification' table (or explicit no-criteria note) (§5.2)"))
else:
rows = [
[c.strip() for c in line.strip().strip("|").split("|")]
for line in acv.splitlines()
if line.strip().startswith("|") and "---" not in line
]
def _is_acv_header(r: list[str]) -> bool:
# The canonical header (§5.2). Detected by content, not position,
# so a headerless table keeps its first data row.
return (
len(r) >= 3
and r[0].lower() == "criterion"
and r[1].lower() == "status"
and r[2].lower() == "evidence"
)
data_rows = [r for r in rows if len(r) >= 3 and not _is_acv_header(r)]
if not data_rows:
if NO_AC_NOTE_RE.search(acv):
findings.append(ok("P03", "explicit no-acceptance-criteria note present (§5.2)"))
else:
findings.append(err("P03", "'## Acceptance Criteria Verification' has no data rows (§5.2)"))
else:
bad = [r for r in data_rows if r[1].lower() not in AC_STATUSES]
no_evidence = [r for r in data_rows if not r[2]]
if bad:
findings.append(err("P03", f"AC verification rows with status outside pass/fail/unverified: {len(bad)} (§5.2)"))
elif no_evidence:
findings.append(err("P03", f"AC verification rows without evidence: {len(no_evidence)} (§5.2)"))
else:
findings.append(ok("P03", f"AC verification table valid ({len(data_rows)} row{'s' if len(data_rows) != 1 else ''}) (§5.2)"))
if level in ("L1", "L2"):
return findings
# P04 (L3) — Decision Record fields (§4.1)
dr = sections.get("Decision Record")
if dr is None:
findings.append(err("P04", "missing '## Decision Record' section (§4.1)"))
else:
for field in DR_FIELDS:
if f"**{field}:**" in dr:
findings.append(ok("P04", f"Decision Record field **{field}:** present (§4.1)"))
else:
findings.append(err("P04", f"Decision Record missing **{field}:** (§4.1 — labels are string-matched, do not rename)"))
# P05 (L3) — Reproduction required for bug issues (§4.1)
is_bug = (issue_type or "").lower() == "bug" or (issue_type is None and pr_is_fix)
if is_bug:
if "**Reproduction:**" in dr:
findings.append(ok("P05", "Reproduction evidence present for bug fix (§4.1)"))
else:
findings.append(err("P05", "bug fix without **Reproduction:** field in the Decision Record (§4.1)"))
# P06 (L3) — Analyzed at line (§4.1, SHOULD)
if re.search(r"^Analyzed at:", dr, re.MULTILINE):
findings.append(ok("P06", "'Analyzed at:' line present (§4.1)"))
else:
findings.append(warn("P06", "no 'Analyzed at: `<branch> @ <sha>` (<date>)' line (§4.1, SHOULD)"))
return findings
# --- Git helpers (repo / --range modes) -----------------------------------------
def git(*args: str) -> str:
proc = subprocess.run(["git", *args], capture_output=True, text=True)
if proc.returncode != 0:
print(f"✗ git {' '.join(args)}: {proc.stderr.strip()}", file=sys.stderr)
sys.exit(2)
return proc.stdout
def commit_subjects(rev_range: str) -> list[str]:
out = git("log", "--no-merges", "--format=%s", rev_range)
return [line for line in out.splitlines() if line.strip()]
# --- Stats (evidence report) -----------------------------------------------------
SUCCESS_OUTCOMES = {"success", "merged"}
SKIP_OUTCOMES = {"skipped", "already_resolved"}
def _run_soft(cmd: list[str], input_text: str | None = None) -> str | None:
"""Run a command, returning stdout or None on any failure (soft probe)."""
try:
proc = subprocess.run(
cmd,
input=input_text,
capture_output=True,
text=True,
timeout=SOFT_COMMAND_TIMEOUT_SECONDS,
)
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
return None
return proc.stdout if proc.returncode == 0 else None
def _gh_json(*args: str) -> object | None:
out = _run_soft(["gh", *args])
if out is None:
return None
try:
return json.loads(out)
except json.JSONDecodeError:
return None
def normalize_since(since: str | None) -> str | None:
"""Pin a bare `YYYY-MM-DD` to midnight.
Git's approxidate parser fills an unstated time of day from the *current*
wall clock, so `--since 2026-08-15` means "2026-08-15 at whatever o'clock it
is now" and the same command returns different windows through the day.
Anything else (an explicit time, `6 months ago`, a ref-ish date) is passed
through untouched — git owns that grammar.
"""
if since is None:
return None
stripped = since.strip()
return f"{stripped} 00:00:00" if BARE_DATE_RE.match(stripped) else since
def _since_epoch(since: str | None) -> tuple[int | None, str | None]:
"""Resolve a git approxidate to a Unix timestamp via `git rev-parse --since=`.
Using git itself keeps the PR-side `mergedAt` filter and the git-side
`--since` window on exactly one date grammar.
Returns `(epoch, error)`. `error` is None when no window was asked for or
the window resolved; otherwise it is the reason the window could not be
applied. The two must stay distinguishable: a window that was requested and
failed to resolve is not the same report as one that was never requested,
and rendering them alike advises the reader to do what they just did.
git's approxidate never rejects input — `--since=garbage-typo` silently
resolves to *now*, which yields an empty window and a green report built
from nothing. Anything landing within a couple of seconds of now, from a
string that is not itself a now-token, is read as a parse failure.
Residual, accepted: approxidate's spellings of *now* are open-ended, so
`NOW_TOKENS` cannot be completed. `1 second ago` and `2 seconds ago` land
inside the ±2s band without being listed there, and are therefore reported
as unparseable. That is the safe direction of the error — the report
degrades to lifetime and says so, rather than claiming a window it did not
apply — and it is why this returns an error the caller renders instead of
exiting non-zero. Do not try to enumerate more tokens; widening the list
only moves the boundary, it does not remove it.
"""
if not since:
return None, None
out = _run_soft(["git", "rev-parse", f"--since={since}"])
m = re.search(r"--max-age=(\d+)", out) if out else None
if not m:
return None, "could not be resolved (not a git repository?)"
epoch = int(m.group(1))
now = int(datetime.now(timezone.utc).timestamp())
if (
since.strip().lower() not in NOW_TOKENS
and abs(now - epoch) <= APPROXIDATE_NOW_TOLERANCE_SECONDS
):
return None, "did not parse as a date"
return epoch, None
class SinceWindow(NamedTuple):
"""One resolution of `--since`, shared by every section of the report.
`stats` feeds `--since` to two independent consumers — the local git
history and the PR-side B1 join. Resolving it separately in each let them
disagree: git's approxidate accepts `garbage-typo` as *now* and zeroed the
git section, while the join detected the same string as unparseable and
printed "window not applied". One report, two answers.
So the string is resolved exactly once, in `cmd_stats`, and this is what
both consumers receive. `cutoff is None` means the window could not be
applied *anywhere*: every section falls back to lifetime and the caller
renders `error` once, at the top of the report.
"""
since: str # the normalized string, as it will be shown to the reader
cutoff: int | None # Unix timestamp, or None when the window did not resolve
error: str | None # why it did not resolve; None when `cutoff` is set
def resolve_since(raw: str | None) -> SinceWindow | None:
"""Normalize and resolve `--since` once. None means no window was asked for.
A returned window with `cutoff is None` is a *requested* window that failed
to resolve — deliberately distinct from this returning None, which means the
reader never asked for one. Rendering the two alike would advise them to run
with the flag they just ran with.
"""
since = normalize_since(raw)
if since is None:
return None
cutoff, error = _since_epoch(since)
return SinceWindow(since, cutoff, error)
def _merged_at_epoch(value: object) -> int | None:
"""`2026-08-14T19:33:53Z` → Unix timestamp; None when unparsable."""
if not isinstance(value, str):
return None
try:
dt = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
except ValueError:
return None
return int(dt.replace(tzinfo=timezone.utc).timestamp())
def _pct(n: int, d: int) -> int | None:
return round(100 * n / d) if d else None
def _median(values: list) -> float | None:
return statistics.median(values) if values else None
def _repo_name_from_remote() -> str | None:
"""Derive owner/repo from the git origin URL (works offline, no gh)."""
url = _run_soft(["git", "config", "--get", "remote.origin.url"])
if not url:
return None
url = url.strip().removesuffix(".git")
# git@host:owner/repo or https://host/owner/repo or ssh://host/owner/repo
m = re.search(r"[:/]([^/:]+/[^/:]+)$", url)
return m.group(1) if m else None
def collect_project_info(root: Path, use_github: bool = True) -> dict:
"""Identify the project being analyzed: filesystem location and a name.
Name preference: GitHub nameWithOwner (via gh, only when use_github) → origin
remote owner/repo → the checkout's directory basename. Never fails — a name
is always produced, and offline mode makes no network call.
"""
name = None
if use_github:
gh = _gh_json("repo", "view", "--json", "nameWithOwner")
if isinstance(gh, dict):
name = gh.get("nameWithOwner") or None
if not name:
name = _repo_name_from_remote()
if not name:
name = root.name
return {"name": name, "location": str(root)}
def detect_default_branch() -> str:
out = _run_soft(["git", "rev-parse", "--abbrev-ref", "origin/HEAD"])
if out and "/" in out.strip():
return out.strip().split("/", 1)[1]
for cand in ("main", "master"):
if _run_soft(["git", "rev-parse", "--verify", "--quiet", cand]) is not None:
return cand
return "HEAD"
def collect_commit_stats(branch: str, since: str | None) -> dict | None:
"""Trace-completeness and Decision-Record coverage from local git history.
The Decision-Record denominator is every **PR-derived** commit: one whose
subject carries a `(#N)` reference *or* whose body opens with `Closes #N`.
Keying it on `Closes #N` alone — as this did before #180 — silently drops
the failures out of the sample: a squash landed under GitHub's default
`squash_merge_commit_message=COMMIT_MESSAGES` carries a bullet list of
commit subjects and no `Closes #N`, so exactly the commits that *lost* their
Decision Record at the merge boundary left the denominator instead of
counting as misses, and the ratio measured the survivors against themselves.
This is a local proxy, not the verdict: a `(#N)` subject with no `Closes`
body may be a direct-to-main commit rather than a defeated merge. The
authoritative measurement is the per-PR join in `collect_dr_binding`.
`--no-merges` is deliberate. `grammar_pct` and `trace_pct` are claims about
*authored* commits; folding merge commits in would corrupt both.
"""
cmd = ["git", "log", "--no-merges", "--format=%s%x1f%b%x1e", branch]
if since:
cmd.insert(2, f"--since={since}")
out = _run_soft(cmd)
if out is None:
return None
records = [r for r in out.split("\x1e") if r.strip()]
total, grammar = len(records), 0
subject_ref = closes_body = both = pr_derived = dr = 0
for rec in records:
subject, _, body = rec.partition("\x1f")
subject = subject.strip()
if COMMIT_RE.match(subject):
grammar += 1
has_subject_ref = bool(re.search(r"\(#\d+\)", subject))
has_closes = bool(re.search(r"^Closes #\d+", body, re.MULTILINE))
subject_ref += has_subject_ref
closes_body += has_closes
both += has_subject_ref and has_closes
if has_subject_ref or has_closes:
pr_derived += 1
if DR_HEADING in body:
dr += 1
return {
"branch": branch,
"commits": total,
"grammar_ok": grammar,
"grammar_pct": _pct(grammar, total),
"issue_linked": subject_ref,
"trace_pct": _pct(subject_ref, total),
"subject_ref_commits": subject_ref,
"closes_body_commits": closes_body,
"subject_and_closes_commits": both,
"pr_derived_commits": pr_derived,
"decision_records": dr,
"dr_pct": _pct(dr, pr_derived),
}
DEFAULT_HIGH_CEILING = 5 # default resolve.qa_max_cycles; high-class policy cap
def policy_ceiling(profile: object, complexity: object, *, high: int = DEFAULT_HIGH_CEILING) -> int:
"""light → 1; full+high → high (default 5); omitted profile/complexity → 2."""
if profile == "light":
return 1
if complexity == "high":
return high
return 2
def row_ceiling(row: dict) -> int:
recorded = row.get("ceiling")
if isinstance(recorded, int) and not isinstance(recorded, bool) and recorded >= 1:
return recorded
return policy_ceiling(row.get("profile"), row.get("complexity"))
def _unexplained_ceiling_breach(row: dict) -> bool:
qa = row.get("qa_cycles")
if not isinstance(qa, int) or isinstance(qa, bool):
return False
if qa <= row_ceiling(row):
return False
reason = row.get("breach_reason")
return not (isinstance(reason, str) and reason.strip())
def load_run_rows(path: Path) -> list[dict] | None:
"""Parse the run log exactly once — active file plus rotated segments.
Rotation (F-PERF-006) splits one append-only file into timestamped
`runs-*.jsonl` segments plus the fresh active log, so a reader that opens
only the active path silently loses every record before the last rotation.
This reads the same bounded tail gi-runlog scans — newest segments first,
oldest to newest, then the active file — and skips malformed lines with the
no-schema-migration tolerance every runs.jsonl reader shares. Returns None
when nothing anywhere parsed to a row.
"""
segments = sorted(
candidate
for candidate in path.parent.glob(f"{path.stem}-*.jsonl")
if candidate.is_file()
)
rows: list[dict] = []
for candidate in (*segments[-MAX_RUN_SEGMENTS:], path):
if not candidate.is_file():
continue
try:
text = candidate.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
for line in text.splitlines():
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(row, dict):
rows.append(row)
return rows or None
def collect_phase_stats(rows: list[dict]) -> dict[str, dict]:
"""Per-phase seconds across rows carrying the optional `phases` map (#467).
Tolerant like every runs.jsonl reader: the raw-append fallback bypasses
gi-runlog's validation, so a non-object `phases` or an entry that is not a
non-negative integer is skipped, never raised on.
"""
seconds: dict[str, list[int]] = {}
for r in rows:
phases = r.get("phases")
if not isinstance(phases, dict):
continue
for name, value in phases.items():
if (
isinstance(name, str)
and isinstance(value, int)
and not isinstance(value, bool)
and value >= 0
):
seconds.setdefault(name, []).append(value)
return {
name: {"runs": len(values), "median_s": _median(values), "total_s": sum(values)}
for name, values in seconds.items()
}
def slowest_phase(phases: dict[str, dict]) -> str | None:
"""The phase with the highest median; ties go to the larger total, then name."""
if not phases:
return None
return min(
phases,
key=lambda name: (-phases[name]["median_s"], -phases[name]["total_s"], name),
)
def collect_run_stats(rows: list[dict] | None) -> dict | None:
"""Outcome/QA/duration aggregates over run-log rows parsed by load_run_rows."""
if not rows:
return None
outcomes: dict[str, int] = {}
for r in rows:
o = str(r.get("outcome", "unknown"))
outcomes[o] = outcomes.get(o, 0) + 1
attempted = [r for r in rows if r.get("outcome") not in SKIP_OUTCOMES]
succeeded = [r for r in attempted if r.get("outcome") in SUCCESS_OUTCOMES]
qa = [r["qa_cycles"] for r in rows if isinstance(r.get("qa_cycles"), int)]
dur = [r["duration_s"] for r in rows if isinstance(r.get("duration_s"), (int, float))]
by_complexity: dict[str, dict] = {}
for level in ("low", "medium", "high"):
sub = [r for r in rows if r.get("complexity") == level]
if sub:
sub_qa = [r["qa_cycles"] for r in sub if isinstance(r.get("qa_cycles"), int)]
by_complexity[level] = {"runs": len(sub), "median_qa": _median(sub_qa)}
unexplained = [r for r in rows if _unexplained_ceiling_breach(r)]
phases = collect_phase_stats(rows)
return {
"runs": len(rows),
"outcomes": dict(sorted(outcomes.items())),
"attempted": len(attempted),
"succeeded": len(succeeded),
"success_pct": _pct(len(succeeded), len(attempted)),
"median_qa_cycles": _median(qa),
"median_duration_s": _median(dur),
"by_complexity": by_complexity,
"phases": phases,
"slowest_phase": slowest_phase(phases),
"issues": sorted({r["issue"] for r in rows if isinstance(r.get("issue"), int)}),
"unexplained_ceiling_breaches": len(unexplained),
"ceiling_breach_issues": sorted(
{r["issue"] for r in unexplained if isinstance(r.get("issue"), int)}
),
}
def classify_merge_commits(oids: list[str | None]) -> list[str]:
"""Classify all landing commits with one soft `git log --stdin` probe.
`--ignore-missing` preserves the old per-PR behavior: an oid absent from a
shallow clone is omitted while resolvable siblings are still classified.
NUL framing keeps multiline commit messages from becoming record boundaries.
"""
wanted = list(dict.fromkeys(oid for oid in oids if oid))
if not wanted:
return ["no_sha" for _ in oids]
output = _run_soft(
[
"git",
"log",
"--no-walk=unsorted",
"--ignore-missing",
"-z",
"--format=%H%x00%B",
"--stdin",
],
"\n".join(wanted) + "\n",
)
by_oid: dict[str, str] = {}
if output is not None:
fields = output.split("\0")
if fields and fields[-1] == "":
fields.pop()
if len(fields) % 2 == 0:
for oid, body in zip(fields[0::2], fields[1::2]):
by_oid[oid] = "landed" if DR_HEADING in body else "lost"
return [
"no_sha" if not oid else by_oid.get(oid.lower(), "not_in_clone")
for oid in oids
]
def classify_merge_commit(oid: str | None) -> str:
"""Classify one commit, preserving support for refs and abbreviated oids."""
if not oid:
return "no_sha"
body = _run_soft(["git", "log", "-1", "--format=%B", oid])
if body is None:
return "not_in_clone"
return "landed" if DR_HEADING in body else "lost"
def collect_dr_binding(merged: list, limit: int, window: SinceWindow | None) -> dict:
"""Join each merged PR to its own landing commit to measure SPEC §4.3 B1.
The local git-side ratio can only guess which commits came from a PR. This
joins the two sides directly — PR body → `mergeCommit.oid` → commit message
— so `dr_lost` is a count of Decision Records demonstrably dropped at the
merge boundary rather than an inference from message shape.
Lifetime numbers are informational by design: this repo's B1 binding was
only repaired on 2026-08-15 and
`docs/decisions/no-backfill-merged-decision-records.md` accepts the
historical gap. A `--since` window is what makes a loss actionable.
`window` arrives already resolved (see `SinceWindow`). Re-resolving it here
is what let this section and the git-history section disagree about the same
string, so this must never call `_since_epoch` itself.
"""
with_dr = [p for p in merged if DR_HEADING in ((p or {}).get("body") or "")]
counts = {"no_sha": 0, "not_in_clone": 0, "landed": 0, "lost": 0}
merge_oids = []
for pr in with_dr:
mc = pr.get("mergeCommit")
merge_oids.append(mc.get("oid") if isinstance(mc, dict) else None)
verdict_by_pr: dict = {}
for pr, verdict in zip(with_dr, classify_merge_commits(merge_oids)):
counts[verdict] += 1
# Keyed on the PR number, not `id(pr)`: identity is only stable while
# this exact list of dicts is alive, and a future refactor that copies
# or re-parses a PR would silently miss every lookup.
verdict_by_pr[pr["number"]] = verdict
resolved = counts["landed"] + counts["lost"]
binding = {
"prs_with_dr": len(with_dr),
"merge_commit_resolved": resolved,
"unresolved_no_sha": counts["no_sha"],
"unresolved_not_in_clone": counts["not_in_clone"],
"dr_landed": counts["landed"],
"dr_lost": counts["lost"],
"landed_pct": _pct(counts["landed"], resolved),
# `gh pr list --limit N` returns the newest N. A client-side window over
# a capped page under-reports without saying so, so say so.
"truncated": len(merged) == limit,
"window": None,
# Present on every binding, exactly like `window` above. Absent-on-
# success made the two siblings behave differently: `b["window"]` is
# always safe to subscript while `b["window_error"]` raised KeyError on
# the common path, so consumers had to know which one they were holding.
"window_error": None,
"adr": ADR_NO_BACKFILL,
}
if window:
# `gh pr list` has no merged-date flag, so the window is applied here.
if window.cutoff is None:
# Say so in the document, not only on the terminal: the caller most
# likely to be misled is a JSON consumer gating on `dr_lost > 0`,
# and an absent window is indistinguishable from a clean one.
binding["window_error"] = {"since": window.since, "reason": window.error}
else:
in_window = [
p for p in with_dr
if (_merged_at_epoch(p.get("mergedAt")) or -1) >= window.cutoff
]
# Same buckets and the same key names as the lifetime numbers above,
# so the denominator is `landed + lost` on both sides. Counting the
# unresolved PRs as misses would render `✗ 0%` from unknown data —
# in a shallow clone every oid is `not_in_clone`.
w = {v: [p for p in in_window if verdict_by_pr[p["number"]] == v] for v in counts}
binding["window"] = {
"since": window.since,
"prs_with_dr": len(in_window),
"merge_commit_resolved": len(w["landed"]) + len(w["lost"]),
"unresolved_no_sha": len(w["no_sha"]),
You can’t perform that action at this time.
