Repository navigation
Expand file tree
/
Copy pathlinear-dash
More file actions
executable file
·1551 lines (1467 loc) · 54.6 KB
/
Copy pathlinear-dash
File metadata and controls
executable file
·1551 lines (1467 loc) · 54.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 node
// linear-dash — Linear project dashboard with live GitHub merge readiness.
//
// Usage:
// linear-dash [project] [--repo owner/name] [--watch [secs]] [--all]
//
// project Linear project URL, UUID, or name. Defaults to $LINEAR_DASH_PROJECT;
// with neither set, shows your open Linear tickets grouped by project
// and sorted by priority.
// --repo GitHub repo to resolve PRs against (default: LupaPets/lupa).
// --watch Self-refreshing interactive loop (default 60s). Without it, renders
// once (plain text, safe to pipe). The in-script --watch is what powers
// the TUI below — prefer it over an external `watch -c -n 60 linear-dash`,
// which can't do navigation, live resize, or clickable links.
// --all,-a Expand the extra PR sections (in --watch, press m to toggle live).
// --group-by priority|status|project
// How to group the rows into sections (default: priority). In --watch,
// Tab cycles through the three groupings live.
// --hide-merged
// Hide rows whose PR has merged (landed on main / GitHub MERGED). Off by
// default; in --watch, M toggles it live.
// --show-cancelled
// Include cancelled and Duplicate tickets, which are dropped from the
// list by default (bucketed with completed when shown).
//
// Interactive --watch keys (TTY only):
// j / k move row by row (↓ / ↑ also work)
// h / l jump to prev / next block (← / → also work)
// Ctrl-d / -u half-page down / up
// g / G first / last row
// / search; type to filter, Enter to confirm, Esc to cancel/clear
// n / N next / previous search match
// ↵ Enter open the details page for the selected row
// Tab cycle grouping: priority → status → project
// m show / hide the extra PR sections
// M hide / show merged rows
// q / Ctrl-C quit · resizing the terminal re-renders
//
// Details page (↵ from the list): CI outline (failing/running + passing count),
// unresolved review comments, then Linear comments — all lazily loaded and cached
// for the session. j/k (Ctrl-d/u, g/G) scroll; r refetches; Esc returns. The header
// links to GitHub · Linear; CI rows link to their GitHub Actions run.
//
// Clickable links (OSC 8, in supporting terminals): the ticket id/title → Linear,
// and the PR #number → GitHub. Set NO_HYPERLINKS=1 to disable.
//
// Config (no secrets in this file):
// LINEAR_API_KEY Linear personal API key, or put it in
// ~/.config/linear/api_key (chmod 600).
// LINEAR_DASH_PROJECT Default Linear project (URL, UUID, or name) when no
// project argument is given.
// LUPA_DASH_REPO_DIR Local checkout used to cross-check closed PRs
// against origin/main (default: ~/workspace/lupa).
//
// Fallback: the last successful Linear fetch is cached in ~/.cache/linear-dash/
// and used when Linear is unreachable; GitHub statuses stay live either way.
// Merge truth: the merge process can land commits on main while leaving the PR
// CLOSED on GitHub, so closed PRs are cross-checked against origin/main history.
//
// Speed: terminal PRs (merged; closed for 24h) are cached in ~/.cache/linear-dash/
// so only open/unknown PRs hit GitHub, and the PR-numbers-on-main set is cached
// per SHA so only commits since the last run are scanned.
import { execFile } from 'node:child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import {
blue,
bold,
computeSearchMatches,
cyan,
cycleMatch,
dim,
enterAltScreen,
green,
halfPage,
jumpSection,
jumpToMatch,
leaveAltScreen,
link,
magenta,
padEnd,
red,
relTime,
scrollView,
stripAnsi,
truncate,
viewport,
wrapText,
writeFrame,
yellow,
} from './lib/dash-tui.mjs';
const execFileP = promisify(execFile);
const DEFAULT_REPO = 'LupaPets/lupa';
const CACHE_DIR = join(homedir(), '.cache', 'linear-dash');
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// ---------- args ----------
function parseArgs(argv) {
const args = { project: null, repo: DEFAULT_REPO, watch: null, all: false, showCancelled: false, groupBy: 'priority', hideMerged: false, json: false, branches: [] };
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a === '--repo') {
args.repo = argv[++i];
} else if (a === '--watch') {
const next = Number(argv[i + 1]);
args.watch = Number.isFinite(next) && next > 0 ? Number(argv[++i]) : 60;
} else if (a === '--all' || a === '-a') {
args.all = true;
} else if (a === '--show-cancelled' || a === '--show-canceled') {
args.showCancelled = true;
} else if (a === '--group-by' || a === '--group') {
const v = (argv[++i] || '').toLowerCase();
if (['priority', 'status', 'project'].includes(v)) {
args.groupBy = v;
}
} else if (a === '--hide-merged') {
args.hideMerged = true;
} else if (a === '--help' || a === '-h') {
console.log('Usage: linear-dash [project url|uuid|name] [--repo owner/name] [--watch [secs]] [--all]');
console.log(' --repo GitHub repo for PRs (default: LupaPets/lupa)');
console.log(' --watch interactive self-refreshing TUI (default 60s)');
console.log(' --all,-a expand the extra PR sections (in --watch, m toggles)');
console.log(' --group-by group rows by priority|status|project (default: priority)');
console.log(' --hide-merged hide rows whose PR has merged (in --watch, M toggles)');
console.log(' --show-cancelled include cancelled/duplicate tickets (hidden by default)');
console.log('');
console.log(' --watch keys: j/k move · h/l section · Ctrl-d/u half-page · g/G ends');
console.log(' / search · n/N next match · ↵ details · Tab group');
console.log(' m extras · M hide-merged · r refresh · q quit');
process.exit(0);
} else if (a === '--json') {
args.json = true;
} else if (a === '--branches') {
args.branches = (argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
} else {
args.project = a;
}
}
return args;
}
const ARGS = parseArgs(process.argv);
// Extra PR sections collapse to a one-line summary unless --all is passed; in
// --watch mode the 'm' key toggles this live (see the watch loop below).
let showExtras = ARGS.all;
// How rows are grouped into sections, and whether merged rows are hidden. Both are
// seeded from flags and toggled live in --watch (Tab cycles grouping, M hides merged).
let groupBy = ARGS.groupBy;
let hideMerged = ARGS.hideMerged;
// ---------- Linear ----------
function linearKey() {
if (process.env.LINEAR_API_KEY) {
return process.env.LINEAR_API_KEY.trim();
}
try {
return readFileSync(join(homedir(), '.config', 'linear', 'api_key'), 'utf8').trim();
} catch {
return null;
}
}
async function gql(query, variables) {
const key = linearKey();
if (!key) {
throw new Error('no API key');
}
const res = await fetch('https://api.linear.app/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: key },
body: JSON.stringify({ query, variables }),
signal: AbortSignal.timeout(10_000),
});
const body = await res.json();
if (body.errors) {
throw new Error(body.errors.map((e) => e.message).join('; '));
}
return body.data;
}
// Project to show: CLI arg wins, then $LINEAR_DASH_PROJECT; null → "my open tickets" mode.
function projectArg() {
return ARGS.project ?? process.env.LINEAR_DASH_PROJECT ?? null;
}
let resolvedProjectId = null;
async function resolveProjectId(arg) {
if (resolvedProjectId) {
return resolvedProjectId;
}
if (UUID_RE.test(arg)) {
resolvedProjectId = arg;
return arg;
}
const urlMatch = arg.match(/linear\.app\/[^/]+\/project\/([^/?#]+)/);
const slug = (urlMatch ? urlMatch[1] : arg).toLowerCase();
const data = await gql('{ projects(first: 250) { nodes { id name url } } }');
const nodes = data.projects.nodes;
const hit =
nodes.find((p) => p.url.toLowerCase().endsWith(`/${slug}`)) ??
nodes.find((p) => p.name.toLowerCase() === arg.toLowerCase()) ??
nodes.find((p) => p.name.toLowerCase().includes(arg.toLowerCase()));
if (!hit) {
throw new Error(`no Linear project matching "${arg}"`);
}
resolvedProjectId = hit.id;
return hit.id;
}
function groupForState(state) {
if (state.type === 'completed' || state.name === 'Merged') {
return 'completed';
}
if (state.type === 'started') {
return 'inProgress';
}
// Cancelled and Duplicate are terminal noise — drop them from the list entirely.
// (Linear's "Duplicate" state isn't always typed 'canceled', so match it by name
// too.) --show-cancelled brings them back, bucketed with completed.
const terminal = ['cancelled', 'canceled', 'duplicate'].includes(state.type) || state.name.trim().toLowerCase() === 'duplicate';
if (terminal) {
return ARGS.showCancelled ? 'completed' : null;
}
return 'todo';
}
function ticketsFromIssues(issueNodes) {
const prUrlRe = new RegExp(`github\\.com/${ARGS.repo}/pull/(\\d+)`, 'i');
const tickets = [];
for (const issue of issueNodes) {
const group = groupForState(issue.state);
if (group === null) {
continue;
}
let prNumber = null;
for (const a of issue.attachments.nodes) {
const m = a.url.match(prUrlRe);
if (m) {
prNumber = Number(m[1]);
break;
}
}
tickets.push({
id: issue.identifier,
url: issue.url,
title: issue.title,
priority: issue.priority,
status: issue.state.name,
group,
branch: issue.branchName,
prNumber,
projectName: issue.project?.name,
});
}
return tickets;
}
async function fetchLinearProject(id) {
const query = `
query($id: String!) {
project(id: $id) {
name
targetDate
issues(first: 100) {
nodes {
identifier
url
title
priority
branchName
state { name type }
attachments(first: 20) { nodes { url } }
}
}
}
}`;
const project = (await gql(query, { id })).project;
return { id, name: project.name, targetDate: project.targetDate, tickets: ticketsFromIssues(project.issues.nodes) };
}
// Default mode (no project arg/env): my open tickets, grouped by project.
async function fetchMyTickets() {
const query = `{
viewer {
assignedIssues(
first: 100
filter: { state: { type: { in: ["triage", "backlog", "unstarted", "started"] } } }
) {
nodes {
identifier
url
title
priority
branchName
project { name }
state { name type }
attachments(first: 20) { nodes { url } }
}
}
}
}`;
const nodes = (await gql(query)).viewer.assignedIssues.nodes;
return { id: 'my-open-tickets', name: 'My open tickets', targetDate: null, mode: 'mine', tickets: ticketsFromIssues(nodes) };
}
async function fetchLinearData() {
const arg = projectArg();
return arg ? fetchLinearProject(await resolveProjectId(arg)) : fetchMyTickets();
}
// ---------- fallback cache ----------
function cachePath(projectId) {
return join(CACHE_DIR, `${projectId}.json`);
}
function writeCache(data) {
try {
mkdirSync(CACHE_DIR, { recursive: true });
writeFileSync(cachePath(data.id), JSON.stringify({ ...data, fetchedAt: new Date().toISOString() }));
} catch {
// cache is best-effort
}
}
function readCache() {
// Without Linear we can only read a cache for a UUID-addressed project (or "mine" mode).
const arg = projectArg();
const id = arg == null ? 'my-open-tickets' : UUID_RE.test(arg) ? arg : null;
if (!id) {
return null;
}
try {
return JSON.parse(readFileSync(cachePath(id), 'utf8'));
} catch {
return null;
}
}
// ---------- GitHub ----------
const PR_JSON_FIELDS = 'number,state,isDraft,reviewDecision,mergeStateStatus,statusCheckRollup,url,headRefName,baseRefName';
// Terminal PRs never change (merged) or change rarely (closed → reopened), so
// cache them and only hit GitHub for the delta: open and not-yet-seen PRs.
const CLOSED_PR_TTL_MS = 24 * 60 * 60 * 1000;
const repoSlug = () => ARGS.repo.replace('/', '--');
function readJsonCache(file) {
try {
return JSON.parse(readFileSync(join(CACHE_DIR, file), 'utf8'));
} catch {
return null;
}
}
function writeJsonCache(file, data) {
try {
mkdirSync(CACHE_DIR, { recursive: true });
writeFileSync(join(CACHE_DIR, file), JSON.stringify(data));
} catch {
// cache is best-effort
}
}
const prCacheFile = () => `prs-${repoSlug()}.json`;
function prCacheKey(ticket) {
return ticket.prNumber != null ? `#${ticket.prNumber}` : ticket.branch ? `branch:${ticket.branch}` : null;
}
const NO_PR_TTL_MS = 60 * 60 * 1000;
// undefined → cache miss, go fetch; null → known "no PR"; object → usable PR.
function cachedPr(cache, key) {
const hit = cache[key];
if (!hit) {
return undefined;
}
const fresh = (ttl) => Date.now() - Date.parse(hit.cachedAt) < ttl;
if (hit.pr === null) {
return fresh(NO_PR_TTL_MS) ? null : undefined;
}
if (hit.pr.state === 'MERGED') {
return hit.pr;
}
if (hit.pr.state === 'CLOSED' && fresh(CLOSED_PR_TTL_MS)) {
return hit.pr;
}
return undefined;
}
// Resolution order: in-memory match against the open-PR list (free), then the
// terminal/no-PR cache, then a live `gh pr view` (the delta) whose terminal
// result is cached for next time.
async function fetchPr(ticket, cache, openPrs) {
const open =
(ticket.prNumber != null && openPrs.byNumber.get(ticket.prNumber)) ||
(ticket.branch && openPrs.byBranch.get(ticket.branch)) ||
null;
if (open) {
return open;
}
const key = prCacheKey(ticket);
if (!key) {
return null;
}
const cached = cachedPr(cache, key);
if (cached !== undefined) {
return cached;
}
const ref = ticket.prNumber != null ? String(ticket.prNumber) : ticket.branch;
try {
const { stdout } = await execFileP('gh', ['pr', 'view', ref, '--repo', ARGS.repo, '--json', PR_JSON_FIELDS]);
const pr = JSON.parse(stdout);
if (pr.state === 'MERGED' || pr.state === 'CLOSED') {
cache[key] = { pr, cachedAt: new Date().toISOString() };
}
return pr;
} catch {
cache[key] = { pr: null, cachedAt: new Date().toISOString() };
return null;
}
}
// The merge process can land commits on main while leaving the PR CLOSED (not MERGED)
// on GitHub, so cross-check closed PRs against origin/main commit subjects.
// PR numbers already seen on main stay on main, so the set is cached per SHA and
// only commits since the cached SHA are scanned (full 5000-commit rescan on force-push).
async function fetchMainPrNumbers() {
const repoDir = process.env.LUPA_DASH_REPO_DIR || join(homedir(), 'workspace', 'lupa');
try {
await execFileP('git', ['-C', repoDir, 'fetch', 'origin', 'main', '--quiet']);
} catch {
// offline / fetch failed — fall back to whatever origin/main we have locally
}
const cacheFile = `main-prs-${repoSlug()}.json`;
const cached = readJsonCache(cacheFile);
const numbers = new Set(cached?.numbers ?? []);
try {
const { stdout: shaOut } = await execFileP('git', ['-C', repoDir, 'rev-parse', 'origin/main']);
const sha = shaOut.trim();
if (cached?.sha === sha) {
return numbers;
}
let range = null;
if (cached?.sha) {
try {
await execFileP('git', ['-C', repoDir, 'merge-base', '--is-ancestor', cached.sha, sha]);
range = `${cached.sha}..origin/main`;
} catch {
// cached SHA no longer an ancestor (force-push / gc) — full rescan
}
}
const logArgs = range ? ['log', range, '--pretty=%s'] : ['log', 'origin/main', '-n', '5000', '--pretty=%s'];
const { stdout } = await execFileP('git', ['-C', repoDir, ...logArgs], { maxBuffer: 64 * 1024 * 1024 });
for (const match of stdout.matchAll(/\(#(\d+)\)/g)) {
numbers.add(Number(match[1]));
}
writeJsonCache(cacheFile, { sha, numbers: [...numbers] });
return numbers;
} catch {
return numbers;
}
}
const CI_PASS = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);
const CI_FAIL = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE']);
const CI_COUNT_FIELDS = `commits(last: 1) { nodes { commit { statusCheckRollup {
contexts(first: 1) {
checkRunCountsByState { state count }
statusContextCountsByState { state count }
}
} } } }`;
// Aggregate CI counts for many PRs in one batched GraphQL query — asking
// `gh pr list` for statusCheckRollup pulls every individual check context
// (~1600 nodes across ~50 PRs) and dominates the whole run time.
async function fetchCiCounts(numbers) {
const counts = new Map();
if (numbers.length === 0) {
return counts;
}
const [owner, name] = ARGS.repo.split('/');
const aliases = numbers.map((n) => `p${n}: pullRequest(number: ${n}) { ${CI_COUNT_FIELDS} }`).join('\n');
const query = `query { repository(owner: "${owner}", name: "${name}") { ${aliases} } }`;
try {
const { stdout } = await execFileP('gh', ['api', 'graphql', '-f', `query=${query}`], { maxBuffer: 16 * 1024 * 1024 });
const repo = JSON.parse(stdout).data.repository;
for (const n of numbers) {
const contexts = repo[`p${n}`]?.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
if (!contexts) {
counts.set(n, null); // no checks
continue;
}
const c = { pass: 0, fail: 0, pending: 0 };
for (const { state, count } of [...contexts.checkRunCountsByState, ...contexts.statusContextCountsByState]) {
c[CI_PASS.has(state) ? 'pass' : CI_FAIL.has(state) ? 'fail' : 'pending'] += count;
}
counts.set(n, c);
}
} catch {
// enrichment is best-effort — affected rows render as "no checks"
}
return counts;
}
// `gh pr list` is authoritative for which PRs exist (GitHub search-index lag
// silently drops recent ones); CI counts are enriched in a second batched call.
async function fetchMyOpenPrs() {
try {
const { stdout } = await execFileP('gh', [
'pr',
'list',
'--repo',
ARGS.repo,
'--author',
'@me',
'--state',
'open',
'--limit',
'200',
'--json',
'number,state,isDraft,reviewDecision,mergeStateStatus,url,title,headRefName,baseRefName',
]);
const prs = JSON.parse(stdout);
const ciCounts = await fetchCiCounts(prs.map((pr) => pr.number));
return prs.map((pr) => ({ ...pr, ciCounts: ciCounts.get(pr.number) ?? null }));
} catch {
return [];
}
}
// Graphite stacks are PR chains by base branch: a stacked PR's baseRefName is the
// parent PR's headRefName (rather than trunk). Walk those links among the open PRs
// to find, per PR, how many open PRs sit below/above it and the nearest unmerged
// one below (the blocker). Trunk needs no special-casing — the chain just ends when
// a base branch isn't another open PR's head.
function buildStacks(prs) {
const byHead = new Map();
const childrenOf = new Map();
for (const p of prs) {
if (p.headRefName) {
byHead.set(p.headRefName, p);
}
if (!childrenOf.has(p.baseRefName)) {
childrenOf.set(p.baseRefName, []);
}
childrenOf.get(p.baseRefName).push(p);
}
const info = new Map();
for (const p of prs) {
let below = 0;
let blocker = null;
let cur = p;
const seenDown = new Set([p.headRefName]);
for (let guard = 0; guard < 100; guard++) {
const parent = byHead.get(cur.baseRefName);
if (!parent || seenDown.has(parent.headRefName)) {
break;
}
seenDown.add(parent.headRefName);
below++;
if (!blocker && parent.state !== 'MERGED') {
blocker = { number: parent.number, title: parent.title };
}
cur = parent;
}
let above = 0;
const queue = [...(childrenOf.get(p.headRefName) || [])];
const seenUp = new Set();
for (let guard = 0; queue.length && guard < 500; guard++) {
const c = queue.pop();
if (seenUp.has(c.headRefName)) {
continue;
}
seenUp.add(c.headRefName);
above++;
queue.push(...(childrenOf.get(c.headRefName) || []));
}
if (below || above) {
info.set(p.number, { below, above, blocker });
}
}
return info;
}
// Ticket reference from PR title (ENG-1234 / [QA-336]) or branch (matt/eng-1234-...).
function ticketIdFromPr(pr) {
const fromTitle = pr.title.match(/\b([A-Z]{2,7}-\d{2,6})\b/);
if (fromTitle) {
return fromTitle[1];
}
const fromBranch = pr.headRefName.toLowerCase().match(/([a-z]{2,7})-(\d{2,6})/);
if (fromBranch) {
return `${fromBranch[1].toUpperCase()}-${fromBranch[2]}`;
}
return null;
}
// Best-effort Linear lookup (status/priority) for ticket ids outside the project.
async function fetchLinearIssuesByIds(ids) {
const byId = new Map();
if (ids.length === 0) {
return byId;
}
try {
const teams = [...new Set(ids.map((id) => id.split('-')[0]))];
const numbers = [...new Set(ids.map((id) => Number(id.split('-')[1])))];
const query = `
query($teams: [String!], $numbers: [Float!]) {
issues(first: 250, filter: { team: { key: { in: $teams } }, number: { in: $numbers } }) {
nodes { identifier url priority state { name type } }
}
}`;
const data = await gql(query, { teams, numbers });
for (const issue of data.issues.nodes) {
byId.set(issue.identifier, issue);
}
} catch {
// enrichment only — sections still render without Linear
}
return byId;
}
// Machine-readable per-branch ticket+PR snapshot for the dev urgency board.
// Input: branch names. Output (stdout): JSON array, no ANSI, safe to pipe.
async function emitBoardJson(branches) {
const PRIORITY_LABEL = { 0: null, 1: 'Urgent', 2: 'High', 3: 'Medium', 4: 'Low' };
// Each entry may be:
// "branch" — plain; ticket derived from branch name
// "branch|ticket" — explicit ticket, PR looked up by branch
// "branch|ticket|pr" — explicit ticket AND explicit PR number; gh pr view <pr> used instead of branch
// Split on '|' into up to 3 parts.
const entries = branches.map((raw) => {
const parts = raw.split('|');
const branch = parts[0];
const rawTicket = parts[1]?.trim() ?? '';
const rawPr = parts[2]?.trim() ?? '';
let ticket;
if (rawTicket) {
ticket = rawTicket;
} else {
const m = branch.toLowerCase().match(/([a-z]{2,7})-(\d{2,6})/);
ticket = m ? `${m[1].toUpperCase()}-${m[2]}` : null;
}
// prRef: if a PR number is explicitly provided, use it for gh pr view; else use the branch.
const prRef = rawPr || null;
return { branch, ticket, prRef };
});
const ids = [...new Set(entries.map((e) => e.ticket).filter(Boolean))];
const linear = await fetchLinearIssuesByIds(ids);
const out = [];
for (const { branch, ticket, prRef } of entries) {
const issue = ticket ? linear.get(ticket) : null;
let pr = null;
// Use explicit PR number if provided, otherwise look up by branch name.
const ghRef = prRef ?? branch;
try {
const { stdout } = await execFileP('gh', ['pr', 'view', ghRef, '--repo', ARGS.repo, '--json', PR_JSON_FIELDS]);
const p = JSON.parse(stdout);
pr = { number: p.number, state: p.state, isDraft: p.isDraft, reviewDecision: p.reviewDecision, mergeStateStatus: p.mergeStateStatus };
} catch (err) {
pr = null;
// "no PR for this branch" is the normal case (gh exits non-zero); only warn on
// anything that doesn't look like that, so auth/network failures stay visible.
const stderr = String(err?.stderr ?? '');
if (stderr && !/no (open )?pull requests? found/i.test(stderr)) {
process.stderr.write(`linear-dash --json: gh pr view ${ghRef} failed: ${stderr.trim().split('\n')[0]}\n`);
}
}
out.push({
branch,
ticket,
priority: issue ? issue.priority : 0,
priorityLabel: issue ? PRIORITY_LABEL[issue.priority] : null,
linearState: issue?.state?.name ?? null,
linearStateType: issue?.state?.type ?? null,
pr,
});
}
process.stdout.write(JSON.stringify(out) + '\n');
}
// ---------- details page data (lazy, on Enter) ----------
const githubPrUrl = (num) => `https://github.com/${ARGS.repo}/pull/${num}`;
// CI checks split into failing / running, with a count of the passing ones.
async function fetchPrCi(num) {
const { stdout } = await execFileP('gh', ['pr', 'view', String(num), '--repo', ARGS.repo, '--json', 'statusCheckRollup'], {
maxBuffer: 16 * 1024 * 1024,
});
const rollup = JSON.parse(stdout).statusCheckRollup || [];
const failing = [];
const pending = [];
let pass = 0;
for (const ch of rollup) {
// CheckRun → detailsUrl (Actions run); StatusContext → targetUrl (external CI).
const check = { name: ch.name || ch.context || 'check', url: ch.detailsUrl || ch.targetUrl || null };
const running = ch.status && ch.status !== 'COMPLETED';
const result = ch.conclusion || ch.state || '';
if (running) {
pending.push(check);
} else if (CI_PASS.has(result)) {
pass++;
} else if (CI_FAIL.has(result)) {
failing.push(check);
} else {
pending.push(check);
}
}
return { failing, pending, pass };
}
// Unresolved inline review threads (path/line, the commented code line, comments).
async function fetchReviewThreads(num) {
const [owner, name] = ARGS.repo.split('/');
const query = `query($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
pullRequest(number: ${num}) {
reviewDecision
reviewThreads(first: 100) {
nodes {
isResolved
path
line
originalLine
comments(first: 10) { nodes { author { login } body diffHunk } }
}
}
}
}
}`;
const { stdout } = await execFileP('gh', ['api', 'graphql', '-f', `owner=${owner}`, '-f', `name=${name}`, '-f', `query=${query}`], {
maxBuffer: 16 * 1024 * 1024,
});
const pr = JSON.parse(stdout).data.repository.pullRequest;
return { decision: pr.reviewDecision, threads: pr.reviewThreads.nodes.filter((t) => !t.isResolved) };
}
// Linear comments for an issue identifier (ENG-123 → team ENG, number 123).
async function fetchLinearComments(identifier) {
const [team, numStr] = identifier.split('-');
const number = Number(numStr);
const query = `query($team: String!, $number: Float!) {
issues(filter: { team: { key: { eq: $team } }, number: { eq: $number } }) {
nodes { comments(first: 50) { nodes { body createdAt user { displayName } } } }
}
}`;
const data = await gql(query, { team, number });
const issue = data.issues.nodes[0];
return issue ? issue.comments.nodes : [];
}
// Fetch the three sections concurrently; each settles independently so one failure
// (or a missing PR / ticket) never blocks the others. Returns settled results.
async function fetchDetails(meta) {
const [ci, review, linear] = await Promise.allSettled([
meta.prNumber != null ? fetchPrCi(meta.prNumber) : Promise.resolve(null),
meta.prNumber != null ? fetchReviewThreads(meta.prNumber) : Promise.resolve(null),
meta.ticketId != null ? fetchLinearComments(meta.ticketId) : Promise.resolve(null),
]);
return { ci, review, linear };
}
function ciCountsFromRollup(rollup) {
if (!rollup || rollup.length === 0) {
return null;
}
const counts = { pass: 0, fail: 0, pending: 0 };
for (const check of rollup) {
const s = check.conclusion || check.state || check.status || '';
counts[CI_PASS.has(s) ? 'pass' : CI_FAIL.has(s) ? 'fail' : 'pending']++;
}
return counts;
}
function ciSummary(pr) {
// ciCounts comes pre-aggregated from the GraphQL list; `gh pr view` results
// (and older cache entries) carry the raw statusCheckRollup instead.
const counts = pr.ciCounts !== undefined ? pr.ciCounts : ciCountsFromRollup(pr.statusCheckRollup);
if (!counts || counts.pass + counts.fail + counts.pending === 0) {
return { label: dim('no checks'), ok: true };
}
if (counts.fail > 0) {
return { label: red(`✗ CI ${counts.fail} failing`), ok: false };
}
if (counts.pending > 0) {
return { label: yellow(`● CI ${counts.pending} running`), ok: false };
}
return { label: green(`✓ CI ${counts.pass}`), ok: true };
}
function reviewSummary(pr) {
switch (pr.reviewDecision) {
case 'APPROVED':
return { label: green('✓ approved'), ok: true };
case 'CHANGES_REQUESTED':
return { label: red('✗ changes requested'), ok: false };
default:
return { label: yellow('○ needs review'), ok: false };
}
}
function mergeReadiness(pr, onMain, prNumber = pr?.number) {
const num = prNumber != null ? link(githubPrUrl(prNumber), cyan(`#${prNumber}`)) : dim('—');
// `onMain` (PR landed on origin/main) is the authoritative "merged" signal for
// Graphite-closed PRs, and it holds even when the live `gh pr view` failed and
// left us without a PR object — so honour it before bailing on a missing pr.
if (pr?.state === 'MERGED' || onMain) {
return { pr: num, status: magenta('⬢ merged') };
}
if (!pr) {
return { pr: dim('—'), status: dim('no PR') };
}
if (pr.state === 'CLOSED') {
return { pr: num, status: dim('closed (unmerged)') };
}
const ci = ciSummary(pr);
const review = reviewSummary(pr);
const parts = [ci.label, review.label];
if (pr.isDraft) {
parts.unshift(dim('draft'));
} else if (pr.mergeStateStatus === 'DIRTY') {
parts.push(red('⚠ conflicts'));
} else if (pr.mergeStateStatus === 'BEHIND') {
parts.push(yellow('↓ behind base'));
} else if (ci.ok && review.ok) {
parts.push(bold(green('► READY TO MERGE')));
}
return { pr: num, status: parts.join(' ') };
}
// ---------- Grouping / sorting ----------
function priorityBadge(ticket) {
switch (ticket.priority) {
case 1:
return red(bold('▲ Urgent'));
case 2:
return yellow('▲ High ');
case 3:
return blue('■ Medium');
case 4:
return dim('▽ Low ');
default:
return dim('· — ');
}
}
const prioritySortKey = (ticket) => (ticket.priority === 0 ? 5 : ticket.priority);
// Group rows into [label, list, colorFn] sections per the active grouping. The
// caller sorts each list afterwards. Empty buckets are dropped for priority/project
// (avoids noise); status keeps all three so the familiar shape is stable.
function groupRows(rows, mode) {
if (mode === 'project') {
const colors = [yellow, blue, magenta, cyan, green];
const byProject = new Map();
for (const row of rows) {
const key = row.ticket.projectName ?? '(no project)';
if (!byProject.has(key)) {
byProject.set(key, []);
}
byProject.get(key).push(row);
}
const names = [...byProject.keys()].sort(
(a, b) => (a === '(no project)') - (b === '(no project)') || a.localeCompare(b),
);
return names.map((name, i) => [name.toUpperCase(), byProject.get(name), colors[i % colors.length]]);
}
if (mode === 'priority') {
const buckets = [
[1, 'URGENT', red],
[2, 'HIGH', yellow],
[3, 'MEDIUM', blue],
[4, 'LOW', dim],
];
const sections = buckets.map(([p, label, color]) => [label, rows.filter((r) => r.ticket.priority === p), color]);
sections.push(['NONE', rows.filter((r) => !r.ticket.priority), dim]);
return sections.filter(([, list]) => list.length > 0);
}
// status (default): the familiar three state buckets.
const groups = { inProgress: [], todo: [], completed: [] };
for (const row of rows) {
groups[row.group].push(row);
}
return [
['IN PROGRESS', groups.inProgress, yellow],
['TODO', groups.todo, blue],
['COMPLETED', groups.completed, green],
];
}
// Live status: GitHub PR state wins over Linear.
function liveGroupAndStatus(ticket, pr, onMain) {
if (pr?.state === 'MERGED' || onMain) {
return { group: 'completed', status: 'Merged' };
}
if (pr?.state === 'OPEN') {
return { group: 'inProgress', status: pr.isDraft ? 'Draft PR' : 'PR Review' };
}
return { group: ticket.group, status: ticket.status };
}
// ---------- Render ----------
function renderRow(ticket, status, readiness, titleWidth, stack) {
// ↓N = this PR is stacked on N open PRs below it (Graphite stack depth).
const stackMark = stack?.below ? `${cyan(`↓${stack.below}`)} ` : '';
const cols = [
padEnd(priorityBadge(ticket), 9),
padEnd(ticket.id ? link(ticket.url, cyan(ticket.id)) : dim('—'), 9),
padEnd(link(ticket.url, truncate(ticket.title, titleWidth)), titleWidth + 1),
padEnd(dim(status), 12),
padEnd(readiness.pr, 7),
stackMark + readiness.status,
];
return ` ${cols.join(' ')}`;
}
// Returns a structured list of line items. Each item has a `kind`:
// fixed — always-visible top header (summary + rule)
// section — a section/group header (used as the sticky line when its rows show)
// row — a selectable data row (carries `section` = its header text)
// blank/sep/note — decorative, non-selectable
// flatten() joins them for one-shot/piped output; viewport() scrolls them in --watch.
function render(project, rows, sourceLabel, extras, now) {
const width = Math.min(process.stdout.columns || Number(process.env.COLUMNS) || 130, 160);
const byPriority = (a, b) => prioritySortKey(a.ticket) - prioritySortKey(b.ticket) || a.ticket.id.localeCompare(b.ticket.id);
// Hide-merged drops merged rows before grouping (the header reports how many).
const mergedCount = rows.filter((row) => row.isMerged).length;
const visibleRows = hideMerged ? rows.filter((row) => !row.isMerged) : rows;
const sections = groupRows(visibleRows, groupBy);
const doneCount = visibleRows.filter((row) => row.group === 'completed').length;
for (const [, list] of sections) {
list.sort(byPriority);
}
const items = [];
items.push({
kind: 'fixed',
text:
bold(` ${project.name}`) +
dim(
` · target ${project.targetDate ?? '—'} · ${doneCount}/${visibleRows.length} done · by ${groupBy}` +
(hideMerged && mergedCount ? ` · ${mergedCount} merged hidden` : '') +
` · refreshed ${now} · `,
) +
sourceLabel,
});
items.push({ kind: 'fixed', text: dim(' ' + '─'.repeat(width - 4)) });
const titleWidth = Math.max(30, width - 78);
const rule = () => dim(' ' + '─'.repeat(width - 4));
const addSection = (headerText, list, withRule) => {
items.push({ kind: 'blank', text: '' });
if (withRule) {
items.push({ kind: 'sep', text: rule() });
}
items.push({ kind: 'section', text: headerText });
if (list.length === 0) {
items.push({ kind: 'note', text: dim(' (none)') });
return;
}
for (const row of list) {
const { ticket, status, readiness } = row;
items.push({
kind: 'row',
text: renderRow(ticket, status, readiness, titleWidth, row.stack),
section: headerText,
meta: {
ticketId: ticket.id ?? null,
title: ticket.title ?? '',
linearUrl: ticket.url ?? null,
prNumber: row.pr?.number ?? row.prNumber ?? null,
stack: row.stack ?? null,
},
});
}
};
for (const [title, list, color] of sections) {
addSection(` ${color(bold(`${title} (${list.length})`))}`, list, false);
}
const extraSections = [
['MY OTHER OPEN PRS — WITH TICKET', extras.withTicket, magenta],
['MY OPEN PRS — NO LINEAR TICKET', extras.noTicket, cyan],
];
const nonEmptyExtras = extraSections.filter(([, list]) => list.length > 0);