-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlink_tickets.py
More file actions
218 lines (184 loc) · 6.82 KB
/
Copy pathlink_tickets.py
File metadata and controls
218 lines (184 loc) · 6.82 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
#!/usr/bin/env python3
"""
Enrichment: Linear Ticket ↔ GitHub Work Semantic Linker
For each (Linear ticket, GitHub PR) candidate pair that appears in the same
time window, asks Claude to confirm or deny whether the PR actually implements
the ticket. Replaces the naive date-proximity heuristic in gap detection with
confirmed semantic links.
Only fires for pairs where the time-proximity heuristic already flags them as
candidates (ticket creation within 7 days of PR creation).
Input:
--linear path to linear.json (output of fetch_linear.py)
--github path to github.json (output of fetch_github.py)
--since YYYY-MM-DD
--until YYYY-MM-DD
Output (stdout): JSON
{
"enrichment": "link_tickets",
"since": "...",
"until": "...",
"results": [
{
"ticket_id": "ENG-412",
"pr_url": "https://github.com/...",
"linked": true,
"confidence": "high|medium|low",
"reason": "PR title and commits directly reference JWT auth refactor described in ticket."
},
...
]
}
"""
import json
import argparse
import sys
import subprocess
from datetime import datetime
from collections import defaultdict
def days_apart(date_a, date_b):
"""Return absolute number of days between two YYYY-MM-DD strings. Returns 9999 on parse error."""
try:
d1 = datetime.strptime(date_a, "%Y-%m-%d")
d2 = datetime.strptime(date_b, "%Y-%m-%d")
return abs((d1 - d2).days)
except ValueError:
return 9999
def call_claude(prompt):
"""Run claude -p and return the response text, or None on failure."""
result = subprocess.run(
["claude", "-p", prompt],
capture_output=True, text=True, timeout=90
)
if result.returncode != 0:
print(f"[link_tickets] claude error: {result.stderr.strip()[:120]}", file=sys.stderr)
return None
return result.stdout.strip()
def extract_json(text):
"""Extract a JSON object from Claude's response (handles ```json fences)."""
if not text:
return None
s = text.strip()
if "```" in s:
parts = s.split("```")
for part in parts:
candidate = part.lstrip("json").strip()
try:
return json.loads(candidate)
except json.JSONDecodeError:
continue
try:
return json.loads(s)
except json.JSONDecodeError:
start = s.find("{")
end = s.rfind("}") + 1
if start >= 0 and end > start:
try:
return json.loads(s[start:end])
except json.JSONDecodeError:
pass
return None
def classify_link(ticket, pr, commit_messages):
"""Ask Claude whether this PR implements the given ticket."""
ticket_id = ticket.get("identifier", ticket.get("id", "?"))
ticket_title = ticket.get("title", "?")
ticket_desc = (ticket.get("description") or "")[:200]
labels = ", ".join(
label["name"]
for label in (ticket.get("labels") or {}).get("nodes", [])
)
pr_url = pr.get("url", "?")
pr_title = pr.get("title", "?")
commit_block = "\n".join(f"- {m}" for m in commit_messages[:5]) if commit_messages else "(none)"
prompt = f"""Determine if this GitHub PR implements the given Linear ticket.
Linear ticket:
ID: {ticket_id}
Title: {ticket_title}
Description: {ticket_desc if ticket_desc else "(none)"}
Labels: {labels if labels else "(none)"}
GitHub PR:
Title: {pr_title}
Commits:
{commit_block}
Return ONLY a valid JSON object — no explanation, no markdown:
{{
"ticket_id": "{ticket_id}",
"pr_url": "{pr_url}",
"linked": true or false,
"confidence": "high|medium|low",
"reason": "one sentence explaining your conclusion"
}}"""
raw = call_claude(prompt)
result = extract_json(raw)
if result and isinstance(result, dict) and "linked" in result:
return result
return None
def main():
parser = argparse.ArgumentParser(description="Linear ↔ GitHub semantic ticket linker enrichment")
parser.add_argument("--linear", required=True, help="Path to linear.json from fetch_linear.py")
parser.add_argument("--github", required=True, help="Path to github.json from fetch_github.py")
parser.add_argument("--since", required=True, help="Start date YYYY-MM-DD")
parser.add_argument("--until", required=True, help="End date YYYY-MM-DD")
args = parser.parse_args()
try:
with open(args.linear) as f:
linear_data = json.load(f)
with open(args.github) as f:
github_data = json.load(f)
except Exception as e:
print(f"[link_tickets] Could not load input files: {e}", file=sys.stderr)
sys.exit(1)
# Collect all Linear tickets (deduplicated)
seen_ids = set()
tickets = []
for issue in linear_data.get("issues_assigned", []) + linear_data.get("issues_created_only", []):
tid = issue.get("id", "")
if tid and tid not in seen_ids:
seen_ids.add(tid)
tickets.append(issue)
prs = github_data.get("prs_opened", [])
# Build commit-messages lookup by (repo, date-window) for associating with PRs
# Key: repo nameWithOwner -> list of (date, message)
commits_by_repo = defaultdict(list)
for c in github_data.get("commits", []):
repo = c.get("repo", "")
if repo:
commits_by_repo[repo].append((c.get("date", ""), c.get("message", "")))
results = []
candidate_count = 0
for ticket in tickets:
ticket_created = (ticket.get("createdAt") or "")[:10]
ticket_updated = (ticket.get("updatedAt") or "")[:10]
if not ticket_created:
continue
for pr in prs:
pr_date = (pr.get("createdAt") or "")[:10]
if not pr_date:
continue
# Only evaluate pairs where dates are close (time-proximity heuristic)
if days_apart(ticket_created, pr_date) > 7 and days_apart(ticket_updated, pr_date) > 7:
continue
candidate_count += 1
# Get commit messages for this PR's repo near the PR date
pr_repo = (pr.get("repository") or {}).get("nameWithOwner", "")
commit_msgs = [
msg for date, msg in commits_by_repo.get(pr_repo, [])
if days_apart(date, pr_date) <= 3
][:5]
result = classify_link(ticket, pr, commit_msgs)
if result:
results.append(result)
output = {
"enrichment": "link_tickets",
"since": args.since,
"until": args.until,
"results": results,
}
print(json.dumps(output, indent=2))
linked = sum(1 for r in results if r.get("linked"))
print(
f"[link_tickets] {candidate_count} candidate pair(s), "
f"{linked} confirmed link(s), {len(results)-linked} unlinked",
file=sys.stderr
)
if __name__ == "__main__":
main()