-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear
More file actions
executable file
·1266 lines (1057 loc) · 42.6 KB
/
linear
File metadata and controls
executable file
·1266 lines (1057 loc) · 42.6 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
update Modify an issue (status, comment)
create Create a new issue
cycles List cycles for the team
Config: ~/.linear-cli/config.json
"""
from __future__ import annotations
import argparse
import json
import mimetypes
import os
import subprocess
import sys
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import URLError
__version__ = "0.1.2"
CONFIG_PATH = Path.home() / ".linear-cli" / "config.json"
LEGACY_CONFIG_PATH = Path.home() / ".agents" / "linear.json"
API_URL = "https://api.linear.app/graphql"
# ---------------------------------------------------------------------------
# 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):
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_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"]
# ---------------------------------------------------------------------------
# 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_cycles(api_key: str, team_id: str) -> list[dict]:
"""Return all cycles for a team, most recent first."""
data = gql(api_key, """
query($teamId: ID!) {
cycles(
filter: { team: { id: { eq: $teamId } } }
orderBy: updatedAt
first: 50
) {
nodes {
id number name startsAt endsAt completedAt
issueCountHistory
}
}
}
""", {"teamId": team_id})
if check_errors(data):
return []
return data.get("data", {}).get("cycles", {}).get("nodes", []) 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
# ---------------------------------------------------------------------------
# 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."
)
ISSUE_FIELDS = """
identifier title description state { name type }
priority labels { nodes { name } }
assignee { 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"
return f" {ident:<8} {pri:<7} {state:<12} {due} {assignee:<14} {title}{label_str}"
# ---------------------------------------------------------------------------
# setup
# ---------------------------------------------------------------------------
def cmd_setup(args, cfg):
api_key = args.api_key or input("Linear API key: ").strip()
if not api_key:
print("API key required.")
sys.exit(1)
cfg["apiKey"] = api_key
data = gql(api_key, "{ teams { nodes { id name key } } }")
if check_errors(data):
sys.exit(1)
teams = data["data"]["teams"]["nodes"]
if not teams:
print("No teams found.")
sys.exit(1)
if len(teams) == 1:
team = teams[0]
print(f"Found team: {team['name']} ({team['key']})")
else:
print("Teams:")
for i, t in enumerate(teams):
print(f" {i + 1}. {t['name']} ({t['key']})")
choice = input(f"Select team [1-{len(teams)}]: ").strip()
try:
team = teams[int(choice) - 1]
except (ValueError, IndexError):
print("Invalid selection.")
sys.exit(1)
cfg["teamId"] = team["id"]
cfg["teamKey"] = team["key"]
agent = args.agent or input("Default agent identity (e.g. claude, codex) [skip]: ").strip()
if agent:
cfg["agent"] = agent
cfg.pop("states", None)
states = get_states(api_key, team["id"], cfg)
save_config(cfg)
print(f"\nConfigured: team={team['name']}, states={len(states)}")
if agent:
print(f"Agent identity: {agent}")
print(f"Config: {CONFIG_PATH}")
# ---------------------------------------------------------------------------
# tasks - list, view, board
# ---------------------------------------------------------------------------
def cmd_tasks(args, cfg, api_key, team_id):
# If an identifier is given, show detail view
if args.identifier:
return show_issue_detail(args, api_key, team_id)
# If --board, show team board
if args.board:
return show_board(args, api_key, team_id, cfg)
# Otherwise, list tasks
return list_tasks(args, cfg, api_key, team_id)
def list_tasks(args, cfg, api_key, team_id):
"""Default view: my agent's tasks + tasks with no agent:* label (unowned).
`--agent X` narrows to a specific agent. `--all` shows literally every task.
Tasks are sorted by priority, then due date (earliest first), then id.
"""
filters = []
# Resolve which agent filter to apply (if any). `--all` overrides config default.
if args.all:
explicit_agent = None
include_unowned = False # --all means show everything including other agents
elif args.agent:
explicit_agent = args.agent
include_unowned = False # explicit agent request — just show their queue
elif cfg.get("agent"):
explicit_agent = cfg.get("agent")
include_unowned = True # default view = my queue + unowned
else:
explicit_agent = None
include_unowned = False
if args.label and not explicit_agent:
filters.append(f'labels: {{ name: {{ eq: "{args.label}" }} }}')
if args.status:
status = args.status.lower()
if status == "open":
filters.append('state: { type: { nin: ["completed", "canceled"] } }')
elif status == "done":
filters.append('state: { type: { eq: "completed" } }')
else:
states = get_states(api_key, team_id, cfg)
sid = resolve_state_id(states, status)
if sid:
filters.append(f'state: {{ id: {{ eq: "{sid}" }} }}')
else:
filters.append(f'state: {{ name: {{ eqi: "{status}" }} }}')
else:
filters.append('state: { type: { nin: ["completed", "canceled"] } }')
filter_str = ", ".join(filters)
if filter_str:
filter_str = f", {filter_str}"
cycle_field = "activeCycle" if args.cycle != "next" else "nextCycle"
query = f"""{{
team(id: "{team_id}") {{
{cycle_field} {{
name startsAt endsAt
issues(filter: {{
team: {{ id: {{ eq: "{team_id}" }} }}
{filter_str}
}}) {{
nodes {{ {ISSUE_FIELDS} }}
}}
}}
}}
}}"""
data = gql(api_key, query)
if check_errors(data):
return
team = data.get("data", {}).get("team", {})
cycle = team.get(cycle_field)
if not cycle:
which = "active" if cycle_field == "activeCycle" else "next"
print(f"No {which} cycle found.")
return
nodes = cycle.get("issues", {}).get("nodes", [])
cycle_name = cycle.get("name", "Cycle")
# Apply agent ownership filter client-side so "my tasks + unowned" is expressible.
if explicit_agent:
target_label = f"agent:{explicit_agent}"
def match(n):
names = [l["name"] for l in n.get("labels", {}).get("nodes", [])]
has_target = target_label in names
has_any_agent = any(x.startswith("agent:") for x in names)
if has_target:
return True
if include_unowned and not has_any_agent:
return True
return False
nodes = [n for n in nodes if match(n)]
if args.json:
print(json.dumps({
"cycle": {
"name": cycle_name,
"startsAt": cycle.get("startsAt"),
"endsAt": cycle.get("endsAt"),
},
"issues": nodes,
}, indent=2))
return
nodes.sort(key=issue_sort_key)
if not nodes:
print(f"No matching tasks in {cycle_name}.")
return
header_note = ""
if explicit_agent and include_unowned:
owned = sum(1 for n in nodes if any(l["name"] == f"agent:{explicit_agent}" for l in n.get("labels", {}).get("nodes", [])))
unowned = len(nodes) - owned
header_note = f" ({owned} yours, {unowned} unowned)"
print(f"{cycle_name} -- {len(nodes)} task(s){header_note}")
print()
for n in nodes:
print(format_issue_row(n))
def show_board(args, api_key, team_id, cfg):
cycle_field = "activeCycle" if args.cycle != "next" else "nextCycle"
query = f"""{{
team(id: "{team_id}") {{
{cycle_field} {{
name startsAt endsAt
issues(filter: {{
team: {{ id: {{ eq: "{team_id}" }} }}
state: {{ type: {{ nin: ["completed", "canceled"] }} }}
}}) {{
nodes {{ {ISSUE_FIELDS} }}
}}
}}
}}
}}"""
data = gql(api_key, query)
if check_errors(data):
return
team = data.get("data", {}).get("team", {})
cycle = team.get(cycle_field)
if not cycle:
print("No active cycle found.")
return
nodes = cycle.get("issues", {}).get("nodes", [])
cycle_name = cycle.get("name", "Cycle")
if args.json:
print(json.dumps({
"cycle": {
"name": cycle_name,
"startsAt": cycle.get("startsAt"),
"endsAt": cycle.get("endsAt"),
},
"issues": nodes,
}, indent=2))
return
if not nodes:
print(f"No open tasks in {cycle_name}.")
return
agents: dict[str, list] = {}
unassigned: list = []
for n in nodes:
labels = [l["name"] for l in n.get("labels", {}).get("nodes", [])]
agent_labels = [l for l in labels if l.startswith("agent:")]
if agent_labels:
for al in agent_labels:
agent_name = al.split(":", 1)[1]
agents.setdefault(agent_name, []).append(n)
else:
unassigned.append(n)
print(f"{cycle_name} -- {len(nodes)} task(s)")
print()
for agent_name in sorted(agents.keys()):
issues = agents[agent_name]
issues.sort(key=issue_sort_key)
print(f" @{agent_name} ({len(issues)})")
for n in issues:
pri = PRIORITY_MAP.get(n.get("priority", 0), "-")
state = n["state"]["name"]
due = format_due(n.get("dueDate"))
print(f" {n['identifier']:<8} {pri:<7} {state:<12} {due} {n['title']}")
print()
if unassigned:
unassigned.sort(key=issue_sort_key)
print(f" unassigned ({len(unassigned)})")
for n in unassigned:
pri = PRIORITY_MAP.get(n.get("priority", 0), "-")
state = n["state"]["name"]
due = format_due(n.get("dueDate"))
labels = [l["name"] for l in n.get("labels", {}).get("nodes", [])]
label_str = f" [{', '.join(labels)}]" if labels else ""
print(f" {n['identifier']:<8} {pri:<7} {state:<12} {due} {n['title']}{label_str}")
print()
def show_issue_detail(args, api_key, team_id):
identifier = args.identifier
number = identifier.split("-")[-1]
try:
number = int(number)
except ValueError:
print(f"Invalid identifier: {identifier}", file=sys.stderr)
sys.exit(1)
data = gql(api_key, f"""{{
issues(filter: {{
team: {{ id: {{ eq: "{team_id}" }} }}
number: {{ eq: {number} }}
}}) {{
nodes {{
id identifier title description
state {{ name }}
priority
labels {{ nodes {{ name }} }}
assignee {{ name }}
createdAt updatedAt
comments {{ nodes {{ body createdAt user {{ name }} }} }}
}}
}}
}}""")
if check_errors(data):
return
nodes = data.get("data", {}).get("issues", {}).get("nodes", [])
if not nodes:
print(f"Issue {identifier} not found.")
return
n = nodes[0]
if args.json:
print(json.dumps(n, indent=2))
return
pri = PRIORITY_MAP.get(n.get("priority", 0), "-")
labels = ", ".join(l["name"] for l in n.get("labels", {}).get("nodes", []))
assignee = n.get("assignee")
assignee_name = assignee.get("name", "Unassigned") if assignee else "Unassigned"
print(f"{n['identifier']} {n['title']}")
print(f" Status: {n['state']['name']}")
print(f" Priority: {pri}")
print(f" Labels: {labels or '-'}")
print(f" Assignee: {assignee_name}")
print()
desc = n.get("description", "")
if desc:
print("Description:")
for line in desc.split("\n"):
print(f" {line}")
print()
comments = n.get("comments", {}).get("nodes", [])
if comments:
print(f"Comments ({len(comments)}):")
for c in comments:
user = c.get("user", {}).get("name", "Unknown")
body = c.get("body", "").strip().replace("\n", "\n ")
print(f" [{user}] {body}")
print()
# ---------------------------------------------------------------------------
# update - all mutations on an existing issue
# ---------------------------------------------------------------------------
def cmd_update(args, cfg, api_key, team_id):
# Require proof when marking done
if args.done and not args.proof:
print("Cannot mark done without proof. Provide at least one --proof:", file=sys.stderr)
print(" --proof /path/to/screenshot.png (file upload)", file=sys.stderr)
print(" --proof https://example.com/result (URL)", file=sys.stderr)
print(' --proof "Sent 15/30 emails" (text)', file=sys.stderr)
sys.exit(1)
issue = resolve_issue(api_key, team_id, args.identifier)
if not issue:
print(f"Issue {args.identifier} not found.")
sys.exit(1)
did_something = False
# Post proof as a comment before status change
if args.proof:
proof_body = build_proof_comment(api_key, args.proof)
if args.comment:
proof_body = f"{args.comment}\n\n{proof_body}"
data = gql(api_key, """
mutation($input: CommentCreateInput!) {
commentCreate(input: $input) { success }
}
""", {"input": {"issueId": issue["id"], "body": proof_body}})
if check_errors(data):
return
if data["data"]["commentCreate"]["success"]:
print(f"Proof posted to {args.identifier}.")
else:
print("Proof comment failed.", file=sys.stderr)
sys.exit(1)
did_something = True
# Comment already included in proof, don't post separately
args.comment = None
# Status change
target_state = None
if args.done:
target_state = "Done"
elif args.pickup:
target_state = "In Progress"
elif args.todo:
target_state = "Todo"
elif args.status:
target_state = args.status
if target_state:
states = get_states(api_key, team_id, cfg)
state_id = resolve_state_id(states, target_state)
if not state_id:
print(f"State '{target_state}' not found. Available: {', '.join(states.keys())}", file=sys.stderr)
sys.exit(1)
data = gql(api_key, """
mutation($id: String!, $stateId: String!) {
issueUpdate(id: $id, input: { stateId: $stateId }) {
success
issue { identifier title state { name } }
}
}
""", {"id": issue["id"], "stateId": state_id})
if check_errors(data):
return
result = data["data"]["issueUpdate"]
if result["success"]:
i = result["issue"]
print(f"{i['identifier']} -> {i['state']['name']}")
else:
print("Status update failed.")
did_something = True
# Labels
if args.label:
label_data = gql(api_key, """
query($teamId: ID!) {
issueLabels(
filter: {
or: [
{ team: { id: { eq: $teamId } } }
{ team: { null: true } }
]
}
first: 200
) {
nodes { id name }
}
}
""", {"teamId": team_id})
if not check_errors(label_data):
all_labels = label_data["data"]["issueLabels"]["nodes"]
label_map = {l["name"]: l["id"] for l in all_labels}
# Also get current labels on the issue
issue_data = gql(api_key, f"""{{
issue(id: "{issue['id']}") {{
labels {{ nodes {{ id name }} }}
}}
}}""")
current_ids = []
if not check_errors(issue_data):
current_ids = [l["id"] for l in issue_data["data"]["issue"]["labels"]["nodes"]]
label_ids = list(current_ids)
added = []
for lbl in args.label:
if lbl in label_map:
if label_map[lbl] not in label_ids:
label_ids.append(label_map[lbl])
added.append(lbl)
else:
print(f"Warning: label '{lbl}' not found, skipping.", file=sys.stderr)
if added:
data = gql(api_key, """
mutation($id: String!, $labelIds: [String!]!) {
issueUpdate(id: $id, input: { labelIds: $labelIds }) {
success
}
}
""", {"id": issue["id"], "labelIds": label_ids})
if not check_errors(data) and data["data"]["issueUpdate"]["success"]:
print(f"Labels added to {args.identifier}: {', '.join(added)}")
else:
print("Label update failed.")
did_something = True
# Cycle move: --cycle active | next | none
if args.cycle:
choice = args.cycle.lower()
new_cycle_id: str | None = None
if choice == "none":
new_cycle_id = None
elif choice in ("active", "next"):
new_cycle_id = get_cycle_id(api_key, team_id, choice)
if not new_cycle_id:
print(f"Warning: no {choice} cycle found; skipping cycle move.", file=sys.stderr)
new_cycle_id = ... # sentinel — skip mutation below
if new_cycle_id is not ...:
data = gql(api_key, """
mutation($id: String!, $cycleId: String) {
issueUpdate(id: $id, input: { cycleId: $cycleId }) {
success
issue { identifier cycle { name } }
}
}
""", {"id": issue["id"], "cycleId": new_cycle_id})
if not check_errors(data) and data["data"]["issueUpdate"]["success"]:
i = data["data"]["issueUpdate"]["issue"]
cyc = (i.get("cycle") or {}).get("name") or "no cycle"
print(f"{i['identifier']} -> cycle: {cyc}")
did_something = True
else:
print("Cycle update failed.")
# Comment
if args.comment:
comment_body = args.comment
data = gql(api_key, """
mutation($input: CommentCreateInput!) {
commentCreate(input: $input) { success }