-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear
More file actions
executable file
·2997 lines (2644 loc) · 118 KB
/
Copy pathlinear
File metadata and controls
executable file
·2997 lines (2644 loc) · 118 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
"""linear - Task management CLI for AI agent teams.
General-purpose Linear CLI designed for orchestrating work across teams of
AI agents. Each agent can query its work queue, pick up tasks, report progress,
and see the full team board.
Commands:
setup Configure Linear connection
tasks List/view/board tasks (paginated; --cycle
active|next|all|none|<name|id>, --since, --assignee)
update Modify one or many issues (status, comment, relations);
bulk via multiple ids or --stdin
create Create a new issue
cycles List / create / update / delete cycles
projects List / show / create / archive / delete projects
milestones List / create / move / retarget / delete milestones
labels List / create / update / delete labels
users List assignable users
agents List agent members you can --delegate to (auto-detected)
states List the team's workflow states
Config: ~/.linear-cli/config.json
"""
from __future__ import annotations
import argparse
import difflib
import json
import mimetypes
import os
import subprocess
import sys
from datetime import date, datetime, timezone
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import URLError
__version__ = "0.9.0"
# Sentinel for "flag not supplied" — distinct from None, which means an explicit
# clear (e.g. `--project none`). Lets update pre-resolve a field once and pass
# the result down without re-deriving whether the flag was present.
_UNSET = object()
CONFIG_PATH = Path.home() / ".linear-cli" / "config.json"
LEGACY_CONFIG_PATH = Path.home() / ".agents" / "linear.json"
API_URL = "https://api.linear.app/graphql"
# How long a cached agent roster stays fresh before an auto-refresh. Agent apps
# (Claude, Codex, Kimi, …) are installed/removed rarely, so a periodic refresh
# keeps `--delegate <name>` resolving without a per-call lookup.
AGENTS_TTL_SECONDS = 6 * 3600
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
def load_config() -> dict:
if CONFIG_PATH.exists():
return json.loads(CONFIG_PATH.read_text())
if LEGACY_CONFIG_PATH.exists():
cfg = json.loads(LEGACY_CONFIG_PATH.read_text())
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(json.dumps(cfg, indent=2) + "\n")
print(f"Migrated config: {LEGACY_CONFIG_PATH} -> {CONFIG_PATH}", file=sys.stderr)
return cfg
return {}
def save_config(cfg: dict):
# Volatile cfg (e.g. --team override) opts out of persistence.
if cfg.get("__volatile__"):
return
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
CONFIG_PATH.write_text(json.dumps(cfg, indent=2) + "\n")
def get_api_key(cfg: dict) -> str:
"""Resolve API key: config > env > Keychain."""
key = cfg.get("apiKey") or os.environ.get("LINEAR_API_KEY")
if key:
return key
try:
result = subprocess.run(
["security", "find-generic-password", "-s", "linear-api-key", "-w"],
capture_output=True, text=True,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except FileNotFoundError:
pass
return ""
def get_team_id(cfg: dict) -> str:
"""Resolve team ID: config > env > Keychain."""
tid = cfg.get("teamId") or os.environ.get("LINEAR_TEAM_ID")
if tid:
return tid
try:
result = subprocess.run(
["security", "find-generic-password", "-s", "linear-team-id", "-w"],
capture_output=True, text=True,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except FileNotFoundError:
pass
return ""
# ---------------------------------------------------------------------------
# GraphQL client
# ---------------------------------------------------------------------------
def gql(api_key: str, query: str, variables: dict | None = None) -> dict:
payload: dict = {"query": query}
if variables:
payload["variables"] = variables
body = json.dumps(payload).encode()
req = Request(API_URL, data=body, method="POST")
req.add_header("Content-Type", "application/json")
req.add_header("Authorization", api_key)
try:
with urlopen(req) as resp:
return json.loads(resp.read())
except URLError as e:
# HTTPError has a response body with actual GraphQL error details
body = ""
if hasattr(e, "read"):
try:
body = e.read().decode("utf-8", errors="replace")
parsed = json.loads(body)
if "errors" in parsed:
return parsed
except (json.JSONDecodeError, Exception):
pass
detail = body if body else str(e)
return {"errors": [{"message": detail}]}
def check_errors(data: dict) -> bool:
errors = data.get("errors")
if errors:
print(f"Error: {errors[0].get('message', 'Unknown error')}", file=sys.stderr)
return True
return False
# ---------------------------------------------------------------------------
# State resolution (dynamic, not hardcoded)
# ---------------------------------------------------------------------------
def get_states(api_key: str, team_id: str, cfg: dict) -> dict:
cached = cfg.get("states")
if cached:
return cached
data = gql(api_key, """
query($teamId: ID!) {
workflowStates(filter: { team: { id: { eq: $teamId } } }) {
nodes { id name type }
}
}
""", {"teamId": team_id})
if check_errors(data):
return {}
states = {}
for node in data["data"]["workflowStates"]["nodes"]:
states[node["name"]] = {"id": node["id"], "type": node["type"]}
cfg["states"] = states
save_config(cfg)
return states
def resolve_state_id(states: dict, name: str) -> str | None:
if name in states:
return states[name]["id"]
for k, v in states.items():
if k.lower() == name.lower():
return v["id"]
aliases = {
"progress": "In Progress",
"in-progress": "In Progress",
"wip": "In Progress",
}
mapped = aliases.get(name.lower(), "")
if mapped in states:
return states[mapped]["id"]
return None
# ---------------------------------------------------------------------------
# Viewer + user resolution (for auto-assign on create)
# ---------------------------------------------------------------------------
def get_viewer_id(api_key: str, cfg: dict) -> str | None:
"""Return the API-key owner's user ID. Cached in config after first lookup."""
cached = cfg.get("viewerId")
if cached:
return cached
data = gql(api_key, "{ viewer { id name email } }")
if check_errors(data):
return None
viewer = data.get("data", {}).get("viewer") or {}
vid = viewer.get("id")
if vid:
cfg["viewerId"] = vid
# Stash email too for setup output; not load-bearing.
if viewer.get("email"):
cfg["viewerEmail"] = viewer["email"]
save_config(cfg)
return vid
def resolve_team_id_by_key(api_key: str, value: str) -> str | None:
"""Resolve --team to a team ID. Accepts team key (e.g. 'ANT') or UUID."""
if not value:
return None
if len(value) == 36 and value.count("-") == 4:
return value
data = gql(api_key, """
query($key: String!) {
teams(filter: { key: { eqIgnoreCase: $key } }) {
nodes { id name key }
}
}
""", {"key": value})
if check_errors(data):
return None
nodes = (data.get("data") or {}).get("teams", {}).get("nodes", [])
if not nodes:
print(f"Warning: team '{value}' not found.", file=sys.stderr)
return None
return nodes[0]["id"]
def resolve_user_id_by_email(api_key: str, email: str) -> str | None:
"""Look up a user by email address. Returns user ID or None."""
data = gql(api_key, """
query($email: String!) {
users(filter: { email: { eq: $email } }) {
nodes { id name email }
}
}
""", {"email": email})
if check_errors(data):
return None
nodes = data.get("data", {}).get("users", {}).get("nodes", [])
if not nodes:
return None
return nodes[0]["id"]
def list_workspace_users(api_key: str) -> list[dict]:
"""All active workspace members, carrying the `app` flag so callers can split
humans (assignable) from agents (delegatable). Fully paginated."""
query = """query($cursor: String) {
users(filter: { active: { eq: true } }, first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes { id name email displayName app }
}
}"""
return paginate_connection(api_key, query, ["users"]) or []
def resolve_assignee_id(api_key: str, value: str) -> str | None:
"""Resolve --assign to a user ID. Accepts an email, or a human's name /
displayName (case-insensitive) so `--assign bisma` works like `--delegate
claude`. Agents (app users) are excluded on purpose — delegate those instead.
Exact match wins over substring; ambiguous names note the pick to stderr."""
v = (value or "").strip()
if not v:
return None
if "@" in v:
return resolve_user_id_by_email(api_key, v)
humans = [u for u in list_workspace_users(api_key) if not u.get("app")]
lv = v.lower()
matches = [u for u in humans
if lv in (u["name"].lower(), (u.get("displayName") or "").lower())]
if not matches:
matches = [u for u in humans
if lv in u["name"].lower() or lv in (u.get("displayName") or "").lower()]
if not matches:
return None
if len(matches) > 1:
print(f"Note: '{value}' matched {len(matches)} people; picked '{matches[0]['name']}'.",
file=sys.stderr)
return matches[0]["id"]
# ---------------------------------------------------------------------------
# Agent detection (Linear app users you can delegate to)
# ---------------------------------------------------------------------------
def get_agents(api_key: str, cfg: dict, force: bool = False) -> list[dict]:
"""Return the workspace's agent members — Linear app users (Claude, Codex,
Kimi, Antigravity, Grok, Droid, …). Detected via the `app` user flag, cached
in config, and auto-refreshed every AGENTS_TTL_SECONDS so the roster tracks
apps installed/removed without a manual step. Pass force=True to refresh now.
"""
cached = cfg.get("agents")
fetched = cfg.get("agentsFetchedAt")
if cached is not None and not force and fetched:
try:
age = (datetime.now(timezone.utc) - datetime.fromisoformat(fetched)).total_seconds()
if age < AGENTS_TTL_SECONDS:
return cached
except ValueError:
pass # unparseable timestamp — fall through and refresh
data = gql(api_key, """
query {
users(filter: { app: { eq: true }, active: { eq: true } }, first: 100) {
nodes { id name }
}
}
""")
if check_errors(data):
return cached or [] # keep serving the stale roster on a transient error
nodes = (data.get("data") or {}).get("users", {}).get("nodes", []) or []
agents = sorted(
[{"id": n["id"], "name": n["name"]} for n in nodes],
key=lambda a: a["name"].lower(),
)
cfg["agents"] = agents
cfg["agentsFetchedAt"] = datetime.now(timezone.utc).isoformat()
save_config(cfg)
return agents
def resolve_agent_id(api_key: str, cfg: dict, name: str) -> str | None:
"""Resolve an agent name (e.g. 'claude') to its Linear user id, case- and
space-insensitive. On a cache miss, refreshes once — a freshly-installed
agent shouldn't have to wait out the TTL to be delegatable."""
want = name.strip().lower()
for force in (False, True):
for agent in get_agents(api_key, cfg, force=force):
if agent["name"].lower() == want:
return agent["id"]
# only bother with the forced refresh if the first pass missed
return None
# ---------------------------------------------------------------------------
# Cycle resolution (for auto-attach on create, move on update, listing)
# ---------------------------------------------------------------------------
def get_cycle_id(api_key: str, team_id: str, which: str) -> str | None:
"""Return the active or next cycle ID for a team. Never cached (cycles rotate)."""
if which not in ("active", "next"):
return None
if which == "active":
data = gql(api_key, f"""{{
team(id: "{team_id}") {{ activeCycle {{ id name }} }}
}}""")
if check_errors(data):
return None
cycle = (data.get("data") or {}).get("team", {}).get("activeCycle")
return cycle.get("id") if cycle else None
# "next" — Linear has no team.nextCycle field. Find the first cycle whose
# startsAt is after the active cycle's endsAt, ordered ascending.
active_query = gql(api_key, f"""{{
team(id: "{team_id}") {{
activeCycle {{ endsAt }}
}}
}}""")
if check_errors(active_query):
return None
active_ends = (
((active_query.get("data") or {}).get("team", {}) or {})
.get("activeCycle", {}) or {}
).get("endsAt")
if not active_ends:
return None
data = gql(api_key, """
query($teamId: ID!, $after: DateTimeOrDuration!) {
cycles(
filter: {
team: { id: { eq: $teamId } }
startsAt: { gte: $after }
}
orderBy: updatedAt
first: 20
) {
nodes { id name startsAt }
}
}
""", {"teamId": team_id, "after": active_ends})
if check_errors(data):
return None
nodes = (data.get("data") or {}).get("cycles", {}).get("nodes", []) or []
nodes = [n for n in nodes if n.get("startsAt") and n["startsAt"] >= active_ends]
nodes.sort(key=lambda n: n["startsAt"])
return nodes[0]["id"] if nodes else None
def list_team_projects(api_key: str, team_id: str) -> list[dict]:
"""All projects accessible to a team. Sorted most-recently-updated first.
Fully paginated — no silent truncation at Linear's default page size."""
query = """query($teamId: String!, $cursor: String) {
team(id: $teamId) {
projects(first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes {
id name state progress scope
startDate targetDate updatedAt
lead { name }
}
}
}
}"""
projects = paginate_connection(api_key, query, ["team", "projects"], {"teamId": team_id})
if projects is None:
return []
projects.sort(key=lambda p: p.get("updatedAt") or "", reverse=True)
return projects
def _suggest(value: str, names: list[str]) -> str:
"""A ' Did you mean: a, b?' hint for a name that didn't resolve — fuzzy
close-matches first, then substring, so a typo or partial name is actionable
instead of a dead end."""
close = difflib.get_close_matches(value, names, n=3, cutoff=0.5)
if not close:
close = [n for n in names if value.lower() in n.lower()][:3]
return f" Did you mean: {', '.join(close)}?" if close else ""
def resolve_project_id(api_key: str, team_id: str, value: str,
strict: bool = False) -> str | None:
"""Resolve --project to a projectId. Accepts UUID or name (exact match
preferred, then substring). On ambiguity, picks the most-recently-active
match and notes it to stderr.
On no match: when strict, raise LookupError with close-match suggestions so
the caller aborts instead of silently proceeding — a mistyped or not-yet-
created project must never no-op an issue create/update (RUSH-1496). When
not strict, warn to stderr and return None."""
if not value:
return None
# Looks like a UUID? Pass through.
if len(value) == 36 and value.count("-") == 4:
return value
projects = list_team_projects(api_key, team_id)
matches = [p for p in projects if p["name"].lower() == value.lower()]
if not matches:
# Substring fallback so 'phoenix' matches 'Phoenix Horizon'.
matches = [p for p in projects if value.lower() in p["name"].lower()]
if not matches:
msg = f"project '{value}' not found.{_suggest(value, [p['name'] for p in projects])}"
if strict:
raise LookupError(msg)
print(f"Warning: {msg} Skipping.", file=sys.stderr)
return None
if len(matches) > 1:
print(f"Note: '{value}' matched {len(matches)} projects; "
f"picked '{matches[0]['name']}' (most recent).", file=sys.stderr)
return matches[0]["id"]
def resolve_milestone_id(api_key: str, team_id: str, name: str,
project_id: str | None,
strict: bool = False) -> str | None:
"""Resolve --milestone to a projectMilestoneId. If project_id is given,
look only there. Else search all team projects and pick the
most-recently-updated match.
On no match: when strict, raise LookupError with suggestions (so a batch
aborts rather than silently dropping the milestone); else warn and return
None."""
if not name:
return None
if len(name) == 36 and name.count("-") == 4:
return name
if project_id:
data = gql(api_key, """
query($id: String!) {
project(id: $id) {
projectMilestones(first: 100) {
nodes { id name updatedAt }
}
}
}
""", {"id": project_id})
if check_errors(data):
return None
nodes = (
((data.get("data") or {}).get("project") or {})
.get("projectMilestones", {}).get("nodes", [])
)
else:
projects = list_team_projects(api_key, team_id)
nodes = []
for p in projects:
data = gql(api_key, """
query($id: String!) {
project(id: $id) {
projectMilestones(first: 100) {
nodes { id name updatedAt }
}
}
}
""", {"id": p["id"]})
if check_errors(data):
continue
for m in (((data.get("data") or {}).get("project") or {})
.get("projectMilestones", {}).get("nodes", [])):
m["_projectName"] = p["name"]
nodes.append(m)
matches = [m for m in nodes if m["name"].lower() == name.lower()]
if not matches:
matches = [m for m in nodes if name.lower() in m["name"].lower()]
if not matches:
msg = f"milestone '{name}' not found.{_suggest(name, [m['name'] for m in nodes])}"
if strict:
raise LookupError(msg)
print(f"Warning: {msg} Skipping.", file=sys.stderr)
return None
matches.sort(key=lambda m: m.get("updatedAt") or "", reverse=True)
if len(matches) > 1:
proj = matches[0].get("_projectName", "")
suffix = f" in project '{proj}'" if proj else ""
print(f"Note: '{name}' matched {len(matches)} milestones; "
f"picked '{matches[0]['name']}'{suffix} (most recent).", file=sys.stderr)
return matches[0]["id"]
def list_team_cycles(api_key: str, team_id: str) -> list[dict]:
"""Return all cycles for a team, fully paginated (no 50-cycle truncation)."""
query = """query($teamId: ID!, $cursor: String) {
cycles(
filter: { team: { id: { eq: $teamId } } }
orderBy: updatedAt
first: 100
after: $cursor
) {
pageInfo { hasNextPage endCursor }
nodes {
id number name startsAt endsAt completedAt
issueCountHistory
}
}
}"""
return paginate_connection(api_key, query, ["cycles"], {"teamId": team_id}) or []
# ---------------------------------------------------------------------------
# File upload
# ---------------------------------------------------------------------------
def upload_file(api_key: str, filepath: str) -> str | None:
"""Upload a file to Linear and return the asset URL."""
path = Path(filepath)
if not path.exists():
print(f"File not found: {filepath}", file=sys.stderr)
return None
size = path.stat().st_size
content_type = mimetypes.guess_type(filepath)[0] or "application/octet-stream"
data = gql(api_key, """
mutation($filename: String!, $contentType: String!, $size: Int!) {
fileUpload(filename: $filename, contentType: $contentType, size: $size) {
success
uploadFile { uploadUrl assetUrl headers { key value } }
}
}
""", {"filename": path.name, "contentType": content_type, "size": size})
if check_errors(data):
return None
upload = data["data"]["fileUpload"]
if not upload["success"]:
print("Failed to get upload URL.", file=sys.stderr)
return None
uf = upload["uploadFile"]
file_bytes = path.read_bytes()
req = Request(uf["uploadUrl"], data=file_bytes, method="PUT")
req.add_header("Content-Type", content_type)
for h in uf.get("headers") or []:
req.add_header(h["key"], h["value"])
try:
with urlopen(req) as resp:
if resp.status not in (200, 201):
print(f"Upload failed: HTTP {resp.status}", file=sys.stderr)
return None
except URLError as e:
print(f"Upload failed: {e}", file=sys.stderr)
return None
return uf["assetUrl"]
def build_proof_comment(api_key: str, proofs: list[str]) -> str:
"""Build a markdown comment body from proof items.
Each item is auto-detected:
- File path (exists on disk) -> upload and embed as image/link
- URL (starts with http) -> embed as link
- Plain text -> inline as-is
"""
parts = []
for i, proof in enumerate(proofs, 1):
label = f"**Proof {i}:**" if len(proofs) > 1 else "**Proof:**"
path = Path(proof)
if path.exists() and path.is_file():
asset_url = upload_file(api_key, proof)
if not asset_url:
parts.append(f"{label} (upload failed: {path.name})")
continue
ct = mimetypes.guess_type(proof)[0] or ""
if ct.startswith("image/"):
parts.append(f"{label}\n")
else:
parts.append(f"{label} [{path.name}]({asset_url})")
elif proof.startswith("http://") or proof.startswith("https://"):
parts.append(f"{label} {proof}")
else:
parts.append(f"{label} {proof}")
return "\n\n".join(parts)
# ---------------------------------------------------------------------------
# Issue resolution
# ---------------------------------------------------------------------------
def resolve_issue(api_key: str, team_id: str, identifier: str) -> dict | None:
number = identifier.split("-")[-1]
try:
number = int(number)
except ValueError:
print(f"Invalid identifier: {identifier}", file=sys.stderr)
return None
data = gql(api_key, f"""{{
issues(filter: {{
team: {{ id: {{ eq: "{team_id}" }} }}
number: {{ eq: {number} }}
}}) {{
nodes {{ id identifier title }}
}}
}}""")
if check_errors(data):
return None
nodes = data.get("data", {}).get("issues", {}).get("nodes", [])
return nodes[0] if nodes else None
def _warn_sub_issue(child: str, parent_ident: str):
"""Non-blocking nudge when an issue is nested under a parent. Sub-issues add
hierarchy that's easy to lose track of; a flat issue under a project/milestone
is usually clearer. A stderr tip (not a prompt) keeps bulk/agent runs
unblocked while still discouraging casual nesting."""
print(f"Tip: making '{child}' a sub-issue of {parent_ident}. "
f"Sub-issues add nesting — prefer a top-level issue under a "
f"project/milestone unless you truly need it.", file=sys.stderr)
# ---------------------------------------------------------------------------
# Formatters
# ---------------------------------------------------------------------------
PRIORITY_MAP = {0: "-", 1: "Urgent", 2: "High", 3: "Medium", 4: "Low"}
PRIORITY_NAMES = {
"urgent": 1, "high": 2, "medium": 3, "med": 3, "low": 4,
"none": 0, "no": 0, "no-priority": 0,
}
def parse_priority(value: str) -> int:
"""Accept named priorities: urgent, high, medium, low, none."""
v = str(value).strip().lower()
if v in PRIORITY_NAMES:
return PRIORITY_NAMES[v]
raise SystemExit(
f"Invalid --priority '{value}'. Use: urgent, high, medium, low, or none."
)
def derive_title(description: str) -> str:
"""Pull a sensible title out of a description body. First sentence or first
line, stripped of markdown bullets/headers, capped at 80 chars."""
text = description.strip()
# First newline-bounded line
first_line = text.split("\n", 1)[0].strip()
# Strip leading markdown noise: headers, bullets, blockquotes
while first_line and first_line[0] in "#*->":
first_line = first_line[1:].lstrip()
# First sentence within that line
for sep in (". ", "! ", "? "):
idx = first_line.find(sep)
if 0 < idx < 80:
first_line = first_line[: idx + 1]
break
if len(first_line) > 80:
first_line = first_line[:79].rstrip() + "…"
return first_line or "Untitled"
def read_description(inline: str | None, path: str | None) -> str | None:
"""Resolve description from --description (inline), --description-file PATH,
or stdin via --description-file -. Inline wins if both are given."""
if inline is not None:
return inline
if path is None:
return None
if path == "-":
return sys.stdin.read()
p = Path(path)
if not p.exists():
raise SystemExit(f"--description-file: {path} not found")
return p.read_text()
def parse_due_date(value: str) -> str | None:
"""Accept YYYY-MM-DD, or 'none' to clear. Returns the validated string,
or None when clearing. Linear's dueDate is a TimelessDate (date-only)."""
v = str(value).strip()
if v.lower() in ("none", ""):
return None
try:
date.fromisoformat(v)
except ValueError:
raise SystemExit(
f"Invalid --due-date '{value}'. Use YYYY-MM-DD (e.g. 2026-04-28) or 'none'."
)
return v
ISSUE_FIELDS = """
identifier title description state { name type }
priority labels { nodes { name } }
assignee { name }
delegate { name }
project { name id }
dueDate createdAt url
"""
# Sort sentinel for missing due dates — push them to the end of their tier.
_NO_DUE = "9999-99-99"
def issue_sort_key(node: dict) -> tuple:
"""Primary: priority (Urgent=1 first, No-priority=4 last).
Secondary: due date ascending (earliest first, nulls last).
Tertiary: identifier so ties are deterministic."""
priority = node.get("priority") or 4
due = node.get("dueDate") or _NO_DUE
ident = node.get("identifier") or ""
return (priority, due, ident)
def format_due(due: str | None) -> str:
"""Compact due date display: '--' if missing, 'today' / 'tomorrow' / relative
within a week, otherwise MM-DD."""
if not due:
return " -- "
try:
from datetime import date, datetime
today = date.today()
d = datetime.fromisoformat(due.replace("Z", "+00:00")).date() if "T" in due else date.fromisoformat(due)
delta = (d - today).days
if delta < 0:
return f"{-delta}d overdue".ljust(10)
if delta == 0:
return "today "
if delta == 1:
return "tomorrow "
if delta <= 7:
return f"in {delta}d "[:10]
return d.strftime("%b %d ")[:10]
except Exception:
return (due[:10] + " ")[:10]
def format_issue_row(node: dict) -> str:
ident = node["identifier"]
title = node["title"]
state = node["state"]["name"]
pri = PRIORITY_MAP.get(node.get("priority", 0), "-")
due = format_due(node.get("dueDate"))
labels = [l["name"] for l in node.get("labels", {}).get("nodes", [])]
label_str = f" [{', '.join(labels)}]" if labels else ""
assignee = (node.get("assignee") or {}).get("name") or "unassigned"
# Delegate (the agent handed the issue) rides alongside the human assignee:
# "Muqsit → claude". Both are distinct Linear fields; showing only assignee
# hid every delegation, so the column now carries whoever is actually on it.
delegate = (node.get("delegate") or {}).get("name")
who = f"{assignee} → {delegate}" if delegate else assignee
return f" {ident:<8} {pri:<7} {state:<12} {due} {who:<22} {title}{label_str}"
# ---------------------------------------------------------------------------
# Paginated issue fetch
# ---------------------------------------------------------------------------
# Linear caps a connection at 50 nodes by default and 250 max per page. Without
# following pageInfo, any list silently truncates — which breaks "search before
# you create" and produces duplicate tickets. paginate_issues walks every page.
_PAGE_SIZE = 100
_MAX_PAGES = 100 # 10k-issue safety rail; warns if ever hit (no silent caps).
def paginate_issues(api_key: str, filter_str: str) -> list[dict] | None:
"""Fetch every issue matching a root-level filter, following pagination.
`filter_str` is the inner body of the GraphQL `filter:` object (no braces).
The opaque cursor is passed as a variable; only the static filter is
interpolated. Returns None on API error (caller already printed it).
"""
nodes: list[dict] = []
cursor: str | None = None
pages = 0
query = f"""query($cursor: String) {{
issues(first: {_PAGE_SIZE}, after: $cursor, filter: {{ {filter_str} }}) {{
pageInfo {{ hasNextPage endCursor }}
nodes {{ {ISSUE_FIELDS} }}
}}
}}"""
while True:
data = gql(api_key, query, {"cursor": cursor})
if check_errors(data):
return None
conn = (data.get("data") or {}).get("issues") or {}
nodes.extend(conn.get("nodes", []))
pages += 1
page_info = conn.get("pageInfo") or {}
cursor = page_info.get("endCursor")
if not page_info.get("hasNextPage"):
break
if pages >= _MAX_PAGES:
print(
f"Warning: stopped after {pages * _PAGE_SIZE} issues "
f"(pagination safety rail). Narrow your filter to see the rest.",
file=sys.stderr,
)
break
return nodes
def resolve_cycle_meta(api_key: str, team_id: str, which: str) -> dict | None:
"""Resolve 'active'/'next' to {id, name, startsAt, endsAt}. None when none."""
cid = get_cycle_id(api_key, team_id, which)
if not cid:
return None
data = gql(
api_key,
"query($id: String!) { cycle(id: $id) { id name startsAt endsAt } }",
{"id": cid},
)
fallback = f"{which.capitalize()} cycle"
if check_errors(data):
return {"id": cid, "name": fallback, "startsAt": None, "endsAt": None}
c = (data.get("data") or {}).get("cycle") or {}
return {
"id": cid,
"name": c.get("name") or fallback,
"startsAt": c.get("startsAt"),
"endsAt": c.get("endsAt"),
}
def paginate_connection(api_key: str, query: str, path: list[str],
variables: dict | None = None) -> list[dict] | None:
"""Generic relay-cursor paginator for any connection (cycles, users,
projects, labels, ...). Companion to paginate_issues for the issue path.
`query` must declare `$cursor: String`, pass `after: $cursor` to the target
connection, and select `pageInfo { hasNextPage endCursor }` next to `nodes`.
`path` is the key sequence from the `data` root to the connection object
(e.g. ["team", "projects"] or ["cycles"]). Returns every node across all
pages, or None on API error (caller already printed it).
"""
nodes: list[dict] = []
cursor: str | None = None
pages = 0
base_vars = dict(variables or {})
while True:
v = dict(base_vars)
v["cursor"] = cursor
data = gql(api_key, query, v)
if check_errors(data):
return None
conn: dict | None = data.get("data") or {}
for key in path:
conn = (conn or {}).get(key)
conn = conn or {}
nodes.extend(conn.get("nodes", []))
pages += 1
info = conn.get("pageInfo") or {}
cursor = info.get("endCursor")
if not info.get("hasNextPage"):
break
if pages >= _MAX_PAGES:
print(
f"Warning: stopped after {pages * _PAGE_SIZE} rows "
f"(pagination safety rail).",
file=sys.stderr,
)
break
return nodes
def list_team_labels(api_key: str, team_id: str) -> list[dict]:
"""All labels visible to a team (team-scoped + workspace-wide), paginated.
The single source of truth for label lookups across list/create/update and
the label-resolution used by `update --label`."""
query = """query($teamId: ID!, $cursor: String) {
issueLabels(
filter: {
or: [
{ team: { id: { eq: $teamId } } }
{ team: { null: true } }
]
}
first: 100
after: $cursor
) {
pageInfo { hasNextPage endCursor }
nodes { id name description color }
}
}"""
return paginate_connection(api_key, query, ["issueLabels"], {"teamId": team_id}) or []
def resolve_cycle_by_value(api_key: str, team_id: str, value: str) -> dict | None:
"""Resolve a non-keyword --cycle value to a cycle node {id, name, ...}.
Accepts a UUID (passthrough), a cycle number, or a fuzzy name match.
Warns and returns None when nothing matches."""
if not value:
return None
if len(value) == 36 and value.count("-") == 4:
return {"id": value, "name": None, "startsAt": None, "endsAt": None}
cycles = list_team_cycles(api_key, team_id)
matches = [c for c in cycles if (c.get("name") or "").lower() == value.lower()]
if not matches and value.isdigit():
matches = [c for c in cycles if str(c.get("number")) == value]
if not matches:
matches = [c for c in cycles if value.lower() in (c.get("name") or "").lower()]
if not matches:
print(f"Warning: cycle '{value}' not found.", file=sys.stderr)
return None
if len(matches) > 1:
matches.sort(key=lambda c: c.get("startsAt") or "", reverse=True)
print(f"Note: '{value}' matched {len(matches)} cycles; "
f"picked '{matches[0].get('name')}' (most recent).", file=sys.stderr)
return matches[0]
def resolve_label_by_value(api_key: str, team_id: str, value: str) -> dict | None:
"""Resolve a label id-or-name to a label node {id, name, ...}. UUID passes
through; otherwise exact (case-insensitive) name wins, then a unique
substring match. Ambiguous or missing -> warn and return None."""
if not value:
return None
if len(value) == 36 and value.count("-") == 4:
return {"id": value, "name": value}
labels = list_team_labels(api_key, team_id)
exact = [l for l in labels if l["name"].lower() == value.lower()]
if exact:
return exact[0]
subs = [l for l in labels if value.lower() in l["name"].lower()]
if len(subs) == 1:
return subs[0]
if len(subs) > 1:
names = ", ".join(l["name"] for l in subs[:5])
print(f"Warning: label '{value}' is ambiguous ({names}). "
f"Use the exact name or ID.", file=sys.stderr)
return None
print(f"Warning: label '{value}' not found.", file=sys.stderr)
return None
def build_cycle_scope(api_key: str, team_id: str,