Repository navigation
Expand file tree
/
Copy pathlinear
More file actions
executable file
·7317 lines (6475 loc) · 306 KB
/
Copy pathlinear
File metadata and controls
executable file
·7317 lines (6475 loc) · 306 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 cycles
projects List / show / create / update / archive / delete projects
milestones List / create / move / retarget / delete milestones
initiatives List / show / create / update / link / unlink / archive
goals Company, week and day goals; `set` and `todo` write yours
labels List / create / update / delete labels
users List assignable users
agents List agent members you can --delegate to (auto-detected)
migrate-agent-labels
One-time: move legacy agent:<name> labels onto delegates
states List the team's workflow states
queue Durable local queue for closes that hit rate limits
(`queue drain` applies pending closes)
Config: ~/.linear-cli/config.json
Cache (team board for --similar, optional embedding vectors): ~/.linear-cli/cache.sqlite
"""
from __future__ import annotations
import argparse
import array
import contextlib
import difflib
import errno
import hashlib
import json
import math
import mimetypes
import os
import re
import sqlite3
import subprocess
import sys
from datetime import date, datetime, timedelta, timezone, tzinfo
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import URLError
# File locking is platform-split: fcntl on POSIX, msvcrt on Windows. Importing
# fcntl unconditionally at module scope took the whole CLI down on Windows —
# every command, not just `queue` — so both are optional and the lock helpers
# below dispatch on whichever landed.
try:
import fcntl
except ImportError: # Windows
fcntl = None
try:
import msvcrt
except ImportError: # POSIX
msvcrt = None
# msvcrt.locking reports contention as EDEADLOCK (Windows spells it that way;
# POSIX errno only has EDEADLK) or EACCES. Resolved once, defensively, so the
# lookup can't AttributeError on whichever platform is running.
_LOCK_CONTENDED_ERRNOS = tuple(
e for e in (getattr(errno, "EDEADLOCK", None), getattr(errno, "EDEADLK", None),
getattr(errno, "EACCES", None))
if e is not None
)
__version__ = "0.31.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"
API_TIMEOUT = 20
# Config holds the Linear API key — keep it private on multi-user boxes.
CONFIG_DIR_MODE = 0o700
CONFIG_FILE_MODE = 0o600
# 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
# Durable local queue for closes that could not be written immediately (e.g.
# Linear rate limit). One JSON intent per issue identifier; the directory is
# kept private because it carries proof URLs/text from the user's workflow.
QUEUE_DIR = Path.home() / ".linear-cli" / "queue"
MAX_QUEUE_SIZE = 1000
MAX_QUEUE_ATTEMPTS = 10
QUEUE_BACKOFF_BASE_SECONDS = 2
QUEUE_BACKOFF_MAX_SECONDS = 300 # 5 minutes
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
def _harden_config_perms() -> None:
"""Best-effort: force 0700/0600 on an existing config tree.
Upgrades written before this release (or created with a loose umask) stay
world-readable until the next `save_config`. Touching modes on every load
closes that window without requiring a re-setup.
"""
try:
if CONFIG_PATH.parent.exists():
CONFIG_PATH.parent.chmod(CONFIG_DIR_MODE)
if CONFIG_PATH.exists():
CONFIG_PATH.chmod(CONFIG_FILE_MODE)
except OSError:
pass
def write_config_file(cfg: dict) -> None:
"""Write config.json with private dir/file modes (API key lives here)."""
CONFIG_PATH.parent.mkdir(mode=CONFIG_DIR_MODE, parents=True, exist_ok=True)
# mkdir(mode=…) is ignored when the dir already exists — always re-assert.
CONFIG_PATH.parent.chmod(CONFIG_DIR_MODE)
data = (json.dumps(cfg, indent=2) + "\n").encode()
# O_CREAT with mode is masked by umask; chmod after write is the real gate.
fd = os.open(CONFIG_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, CONFIG_FILE_MODE)
try:
os.write(fd, data)
finally:
os.close(fd)
CONFIG_PATH.chmod(CONFIG_FILE_MODE)
def load_config() -> dict:
if CONFIG_PATH.exists():
_harden_config_perms()
return json.loads(CONFIG_PATH.read_text())
if LEGACY_CONFIG_PATH.exists():
cfg = json.loads(LEGACY_CONFIG_PATH.read_text())
write_config_file(cfg)
print(f"Migrated config: {LEGACY_CONFIG_PATH} -> {CONFIG_PATH}", file=sys.stderr)
return cfg
return {}
def save_config(cfg: dict) -> bool:
"""Persist config. Returns False when the file could not be written.
Most writes are cache refreshes (the agent roster, the states map) on a
read path. A read-only or unwritable config dir must not take down the
command that triggered the refresh — the in-memory values are still good for
this run. `setup` checks the return value, because there persistence IS the
operation.
Always writes dir `0700` and file `0600` so the API key is not world-readable.
"""
# Volatile cfg (e.g. --team override) opts out of persistence.
if cfg.get("__volatile__"):
return True
try:
write_config_file(cfg)
return True
except OSError as e:
print(f"Warning: could not write {CONFIG_PATH}: {e}", file=sys.stderr)
return False
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 _header_retry_after(err: BaseException) -> int | None:
"""Parse Retry-After (seconds) from an HTTPError-like response, if present."""
headers = getattr(err, "headers", None)
if headers is None:
return None
raw = None
try:
raw = headers.get("Retry-After") or headers.get("retry-after")
except Exception:
return None
if raw is None:
return None
try:
seconds = int(str(raw).strip())
except (TypeError, ValueError):
return None
if seconds < 0:
return None
return seconds
def _annotate_error_extensions(err: dict, status: int | None,
retry_after: int | None) -> None:
"""Attach HTTP status / Retry-After onto a GraphQL error's extensions."""
if not isinstance(err, dict):
return
if status is None and retry_after is None:
return
ext = err.setdefault("extensions", {})
if status is not None:
ext.setdefault("status", status)
if retry_after is not None:
ext.setdefault("retry_after", retry_after)
# Linear's "duplicate" state type is closed work, like completed and canceled.
OPEN_STATE_FILTER = 'state: { type: { nin: ["completed", "canceled", "duplicate"] } }'
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, timeout=API_TIMEOUT) as resp:
return json.loads(resp.read())
except (URLError, TimeoutError) as e:
# HTTPError has a response body with actual GraphQL error details
body = ""
status = getattr(e, "code", None)
retry_after = _header_retry_after(e)
if hasattr(e, "read"):
try:
body = e.read().decode("utf-8", errors="replace")
parsed = json.loads(body)
if "errors" in parsed:
# Surface the HTTP status / Retry-After so callers can
# distinguish rate-limit (429) and honor server backoff.
for err in parsed.get("errors", []):
_annotate_error_extensions(err, status, retry_after)
return parsed
except (json.JSONDecodeError, Exception):
pass
timed_out = isinstance(e, TimeoutError) or isinstance(getattr(e, "reason", None), TimeoutError)
detail = (f"Linear API timeout after {API_TIMEOUT} seconds"
if timed_out else body if body else str(e))
err: dict = {"message": detail}
_annotate_error_extensions(err, status, retry_after)
return {"errors": [err]}
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
def _error_status(err: dict) -> int | None:
"""HTTP status carried by a GraphQL error extension, if any."""
ext = err.get("extensions") or {}
status = ext.get("status")
return int(status) if isinstance(status, int) or (isinstance(status, str) and status.isdigit()) else None
def _error_message(err: dict) -> str:
return str(err.get("message", "")).lower()
def _error_retry_after(err: dict) -> int | None:
"""Retry-After seconds from a GraphQL error extension, if any."""
ext = err.get("extensions") or {}
raw = ext.get("retry_after")
if raw is None:
return None
try:
seconds = int(raw)
except (TypeError, ValueError):
return None
return seconds if seconds >= 0 else None
def is_rate_limited(data: dict) -> bool:
"""True when Linear answered 429 or the error text names a rate limit."""
for err in data.get("errors", []):
if not isinstance(err, dict):
continue
if _error_status(err) == 429:
return True
msg = _error_message(err)
if "rate limit" in msg or "too many requests" in msg:
return True
return False
def is_transient_error(data: dict) -> bool:
"""True for errors where a retry may reasonably succeed: 429/502/503/504,
timeouts, and network blips. Permanent GraphQL validation errors are not."""
if is_rate_limited(data):
return True
transient_statuses = {429, 502, 503, 504}
transient_phrases = ("timeout", "temporary", "unreachable", "connection",
"name or service not known", "nodename nor servname")
for err in data.get("errors", []):
if not isinstance(err, dict):
continue
status = _error_status(err)
if status in transient_statuses:
return True
msg = _error_message(err)
if any(p in msg for p in transient_phrases):
return True
return False
def response_retry_after_seconds(data: dict) -> int | None:
"""Best Retry-After (seconds) from a GraphQL error response, if any."""
best: int | None = None
for err in data.get("errors", []):
if not isinstance(err, dict):
continue
seconds = _error_retry_after(err)
if seconds is None:
continue
if best is None or seconds > best:
best = seconds
return best
# ---------------------------------------------------------------------------
# Durable close queue
# ---------------------------------------------------------------------------
def queue_dir() -> Path:
"""Return the directory that holds queued close intents."""
return QUEUE_DIR
def _intent_path(identifier: str) -> Path:
"""Safe filename for an intent: one JSON file per identifier."""
safe = identifier.replace("/", "_").replace("\\", "_")
return queue_dir() / f"{safe}.json"
def _ensure_queue_dir() -> None:
"""Create the queue directory with the same private mode as config."""
qd = queue_dir()
qd.mkdir(mode=CONFIG_DIR_MODE, parents=True, exist_ok=True)
try:
qd.chmod(CONFIG_DIR_MODE)
except OSError:
pass
def list_queue_intents() -> list[dict]:
"""Return all queued intents, oldest first (by filename for stability)."""
qd = queue_dir()
if not qd.exists():
return []
intents = []
for path in sorted(qd.glob("*.json")):
try:
intents.append(json.loads(path.read_text()))
except (json.JSONDecodeError, OSError):
# Corrupt file: leave it; a human can inspect, and we won't lose it.
pass
return intents
def save_queue_intent(intent: dict) -> bool:
"""Persist an intent to disk. Overwrites any existing intent for the same
identifier so duplicate closes collapse to the latest desired state.
Returns False only when the queue is at MAX_QUEUE_SIZE and this would add
a new file (existing intents can still be updated).
"""
_ensure_queue_dir()
identifier = intent.get("identifier", "")
if not identifier:
return False
path = _intent_path(identifier)
qd = queue_dir()
existing = set(qd.glob("*.json"))
is_new = path not in existing
if is_new and len(existing) >= MAX_QUEUE_SIZE:
return False
tmp = path.with_suffix(".tmp")
try:
tmp.write_text(json.dumps(intent, indent=2) + "\n")
tmp.replace(path)
return True
except OSError:
return False
def remove_queue_intent(identifier: str) -> None:
"""Delete an intent once it has been successfully applied."""
path = _intent_path(identifier)
if path.exists():
try:
path.unlink()
except OSError:
pass
def queue_backoff_delay(attempts: int) -> int:
"""Exponential backoff, bounded by QUEUE_BACKOFF_MAX_SECONDS."""
return min(
QUEUE_BACKOFF_BASE_SECONDS * (2 ** max(0, attempts - 1)),
QUEUE_BACKOFF_MAX_SECONDS,
)
def resolve_backoff_delay(attempts: int, retry_after: int | None = None) -> int:
"""Prefer server Retry-After when present; otherwise exponential backoff.
Both paths are capped at QUEUE_BACKOFF_MAX_SECONDS so a pathological
Retry-After cannot stall the queue indefinitely.
"""
if retry_after is not None:
try:
seconds = int(retry_after)
except (TypeError, ValueError):
seconds = -1
if seconds >= 0:
return min(max(seconds, 0), QUEUE_BACKOFF_MAX_SECONDS)
return queue_backoff_delay(attempts)
def _now_utc() -> datetime:
return datetime.now(timezone.utc)
def _lock_fd(fd: int, blocking: bool) -> bool:
"""Take an exclusive OS lock on fd. True when held, False when another
process holds it. Both backends release on process death, so a killed drain
cannot wedge the queue behind a stale lock."""
if fcntl is not None:
flags = fcntl.LOCK_EX if blocking else fcntl.LOCK_EX | fcntl.LOCK_NB
try:
fcntl.flock(fd, flags)
return True
except (BlockingIOError, OSError):
return False
if msvcrt is not None:
# Byte-range lock on the first byte, from the current file position —
# hence the seek before both lock and unlock.
#
# LK_LOCK is NOT flock's LOCK_EX: it retries for ~10s and then raises,
# where LOCK_EX waits forever. Loop it so blocking=True means blocking
# on both platforms instead of quietly returning "not held" after 10s.
while True:
os.lseek(fd, 0, os.SEEK_SET)
try:
msvcrt.locking(fd, msvcrt.LK_LOCK if blocking else msvcrt.LK_NBLCK, 1)
return True
except OSError as exc:
if not blocking:
return False
# Contention is EDEADLOCK (LK_LOCK gave up after its own ~10s of
# retries) or EACCES. Keep waiting on those, the way LOCK_EX
# would. Anything else is a real I/O failure — surface it rather
# than retry a broken fd forever.
if exc.errno not in _LOCK_CONTENDED_ERRNOS:
raise
# Ctrl-C during the wait propagates, same as on POSIX.
# Neither backend exists (not a platform Python actually ships today: POSIX
# has fcntl, Windows has msvcrt). Nothing serializes concurrent drains here,
# so warn rather than let a caller believe it holds an exclusive lock.
print("Warning: no file-locking primitive on this platform; concurrent "
"`queue drain` runs are not serialized.", file=sys.stderr)
return True
def _unlock_fd(fd: int) -> None:
try:
if fcntl is not None:
fcntl.flock(fd, fcntl.LOCK_UN)
elif msvcrt is not None:
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
except OSError:
pass
@contextlib.contextmanager
def queue_drain_lock(blocking: bool = False):
"""Exclusive lock around drain so concurrent drains on one machine are safe.
Yields True when the lock is held. Yields False when non-blocking and another
drain already holds the lock (caller should skip, not corrupt intents).
"""
_ensure_queue_dir()
lock_path = queue_dir() / ".drain.lock"
fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o600)
held = False
try:
held = _lock_fd(fd, blocking)
yield held
finally:
if held:
_unlock_fd(fd)
try:
os.close(fd)
except OSError:
pass
def build_close_intent(identifier: str, issue_id: str, state: str,
proof: list[str] | None = None,
comment: str | None = None) -> dict:
"""Construct a durable intent for closing an issue with proof.
The intent never stores the API key or any credential; only the public
issue identifier, the resolved issue id, the desired state name, proof
items, and an optional comment.
"""
return {
"identifier": identifier,
"issue_id": issue_id,
"state": state,
"proof": list(proof or []),
"comment": comment,
"proof_posted": False,
"created_at": _now_utc().isoformat(),
"attempts": 0,
"next_attempt": None,
}
def apply_close_intent(api_key: str, team_id: str, cfg: dict,
intent: dict) -> tuple[bool, bool]:
"""Apply one queued close intent. Returns (success, transient).
* success = the issue is now in the desired state (or already was).
* transient = the failure should be retried later (rate limit / network).
Idempotent: if the issue already has the desired state, the intent is
considered successful and no duplicate proof is posted.
On a transient failure, any server Retry-After is stashed on the intent as
``last_retry_after`` so drain can honor it.
"""
identifier = intent.get("identifier", "")
issue_id = intent.get("issue_id")
desired_state = intent.get("state", "")
intent.pop("last_retry_after", None)
def _transient(data: dict | None = None) -> tuple[bool, bool]:
if data is not None:
ra = response_retry_after_seconds(data)
if ra is not None:
intent["last_retry_after"] = ra
return False, True
# Resolve fresh state each attempt so a close that already landed is a no-op.
issue = resolve_issue(api_key, team_id, identifier)
if not issue:
# resolve_issue already printed the error. Treat as transient because
# "not found" after a rate limit is often a misleading symptom.
return _transient()
current_state = (issue.get("state") or {}).get("name", "")
if current_state == desired_state:
return True, False
# Issue id can change if an issue is moved teams; prefer the fresh one.
issue_id = issue.get("id") or issue_id
states = get_states(api_key, team_id, cfg)
state_id = resolve_state_id(states, desired_state)
if not state_id:
print(f"State '{desired_state}' not found. Available: {', '.join(states.keys())}",
file=sys.stderr)
return False, False
proof = intent.get("proof") or []
comment = intent.get("comment")
proof_posted = intent.get("proof_posted", False)
if proof and not proof_posted:
proof_body = build_proof_comment(api_key, proof)
if comment:
proof_body = f"{comment}\n\n{proof_body}"
data = gql(api_key, """
mutation($input: CommentCreateInput!) {
commentCreate(input: $input) { success }
}
""", {"input": {"issueId": issue_id, "body": proof_body}})
if is_transient_error(data):
return _transient(data)
if check_errors(data):
# A non-transient proof failure (e.g. missing file) should not
# block forever; the caller will count attempts and eventually drop.
return False, False
if not data.get("data", {}).get("commentCreate", {}).get("success"):
return False, False
intent["proof_posted"] = True
save_queue_intent(intent)
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 is_transient_error(data):
return _transient(data)
if check_errors(data):
return False, False
result = data.get("data", {}).get("issueUpdate") or {}
if result.get("success"):
return True, False
return False, False
def drain_queue(api_key: str, team_id: str, cfg: dict,
quiet: bool = False, once: bool = False,
acquire_lock: bool = True) -> tuple[int, int]:
"""Apply queued intents that are due. Returns (applied, remaining).
Each intent is retried with exponential backoff (or server Retry-After)
up to MAX_QUEUE_ATTEMPTS. Intents that exhaust attempts are dropped so the
queue cannot grow forever on permanently stuck items.
Concurrent drains on one machine serialize via ``queue_drain_lock``. When
another drain holds the lock, this call is a no-op (returns 0, remaining).
Pass ``once=True`` to process at most one due intent.
"""
if acquire_lock:
with queue_drain_lock(blocking=False) as held:
if not held:
if not quiet:
print("Another drain holds the queue lock; skipping.",
file=sys.stderr)
return 0, len(list_queue_intents())
return drain_queue(api_key, team_id, cfg, quiet=quiet, once=once,
acquire_lock=False)
intents = list_queue_intents()
if not intents:
if not quiet:
print("Queue empty.")
return 0, 0
applied = 0
remaining = 0
processed_due = 0
for intent in intents:
identifier = intent.get("identifier", "")
attempts = intent.get("attempts", 0) or 0
next_attempt = intent.get("next_attempt")
if next_attempt and _now_utc().isoformat() < next_attempt:
remaining += 1
continue
if once and processed_due >= 1:
remaining += 1
continue
processed_due += 1
ok, transient = apply_close_intent(api_key, team_id, cfg, intent)
if ok:
remove_queue_intent(identifier)
applied += 1
if not quiet:
print(f"Applied {identifier} -> {intent.get('state', 'Done')}")
continue
if transient:
attempts += 1
if attempts >= MAX_QUEUE_ATTEMPTS:
remove_queue_intent(identifier)
if not quiet:
print(f"Gave up on {identifier} after {attempts} attempts.",
file=sys.stderr)
else:
delay = resolve_backoff_delay(
attempts, intent.get("last_retry_after"),
)
intent.pop("last_retry_after", None)
intent["attempts"] = attempts
intent["next_attempt"] = (
_now_utc() + timedelta(seconds=delay)
).isoformat()
save_queue_intent(intent)
remaining += 1
if not quiet:
print(f"Retained {identifier} in queue (retry {attempts} in {delay}s)")
else:
remove_queue_intent(identifier)
if not quiet:
print(f"Dropped {identifier}: permanent failure.", file=sys.stderr)
return applied, remaining
def queue_close_and_try(api_key: str, team_id: str, cfg: dict,
issue: dict, state: str,
proof: list[str] | None = None,
comment: str | None = None,
quiet: bool = False) -> bool:
"""Persist a close intent, attempt it immediately, and keep it on transient
failure. Returns True when the issue is applied or durably queued; False on
a permanent failure (e.g. unknown state or queue full).
"""
identifier = issue.get("identifier", "")
intent = build_close_intent(identifier, issue.get("id"), state,
proof=proof, comment=comment)
if not save_queue_intent(intent):
print(f"Queue full; could not queue close for {identifier}.",
file=sys.stderr)
return False
ok, transient = apply_close_intent(api_key, team_id, cfg, intent)
if ok:
remove_queue_intent(identifier)
if not quiet:
print(f"{identifier} -> {state}")
return True
if transient:
if not quiet:
print(f"{identifier} -> queued for retry (rate limited / transient)")
return True
remove_queue_intent(identifier)
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 guest avatarUrl }
}
}"""
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
def resolve_agent_name(api_key: str, cfg: dict, name: str) -> str | None:
"""Resolve an agent name to the roster's canonical spelling ('claude' ->
'Claude'), case- and space-insensitive. Ownership is Linear's native
`delegate` field and delegate names come back in roster spelling, so a queue
filter has to compare against the canonical name, not the raw argument."""
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["name"]
return None
def delegate_of(node: dict) -> str | None:
"""The agent an issue is delegated to, or None when it is unowned.
Unowned means exactly one thing: the native `delegate` field is null."""
return (node.get("delegate") or {}).get("name") or None
def delegated_to(node: dict, agent_name: str) -> bool:
"""True when this issue's native delegate is `agent_name` (case-insensitive)."""
dn = delegate_of(node)
return dn is not None and dn.lower() == agent_name.lower()
# ---------------------------------------------------------------------------
# Cycle resolution (for auto-attach on create, move on update, listing)
# ---------------------------------------------------------------------------