hird-server 0.3.1

The central queue: hird served over HTTP for harnesses on other machines.
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hird · factory floor</title>
<style>
  :root {
    color-scheme: light dark;
    --bg: #f5f5f2; --panel: #ffffff; --ink: #1c1c1a; --muted: #6b6b66; --line: #dcdcd5; --soft: #efefea;
    --ready: #8a8a80; --claimed: #c98a06; --built: #2d6fb8; --in_review: #8e44ad;
    --approved: #13867f; --merged: #2e8b3e; --escalated: #c0392b; --cancelled: #9a9a92;
    --builder: #c98a06; --reviewer: #8e44ad; --ci: #2d6fb8; --human: #2e8b3e;
    --accent: #0b6e99; --shadow: 0 1px 2px rgba(0,0,0,.06), 0 2px 8px rgba(0,0,0,.05);
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #141412; --panel: #1d1d1a; --ink: #ecebe6; --muted: #9a9a92; --line: #34342f; --soft: #262622;
      --ready: #a3a39a; --claimed: #e2a92e; --built: #5c9be0; --in_review: #c58ae0;
      --approved: #3fbfb5; --merged: #5cc26c; --escalated: #e86a5c; --cancelled: #77776f;
      --builder: #e2a92e; --reviewer: #c58ae0; --ci: #5c9be0; --human: #5cc26c;
      --accent: #5fb3e0; --shadow: 0 1px 2px rgba(0,0,0,.4);
    }
  }
  * { box-sizing: border-box; }
  [hidden] { display: none !important; }
  html, body { height: 100%; margin: 0; }
  body {
    background: var(--bg); color: var(--ink);
    font: 13.5px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
    display: grid; grid-template-rows: auto auto 1fr; height: 100vh; overflow: hidden;
  }
  .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
  button { font: inherit; color: inherit; }

  /* ---------------------------------------------------------------- header */
  header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; padding: 8px 16px; background: var(--panel); border-bottom: 1px solid var(--line); }
  .brand { font-weight: 700; letter-spacing: .02em; }
  .brand small { font-weight: 500; color: var(--muted); margin-left: 4px; }
  #project { color: var(--muted); font-size: 12px; }
  #live { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--muted); }
  #live .dot { width: 9px; height: 9px; border-radius: 50%; background: #3cb371; box-shadow: 0 0 0 0 rgba(60,179,113,.5); animation: breathe 2s infinite; }
  #live.lost .dot { background: var(--escalated); animation: none; }
  #live.wait .dot { background: var(--muted); animation: none; }
  @keyframes breathe { 0% { box-shadow: 0 0 0 0 rgba(60,179,113,.45); } 70% { box-shadow: 0 0 0 7px rgba(60,179,113,0); } 100% { box-shadow: 0 0 0 0 rgba(60,179,113,0); } }
  .chips { display: flex; flex-wrap: wrap; gap: 6px; }
  .chip { display: inline-flex; align-items: center; gap: 4px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--line); font-size: 11.5px; color: var(--muted); background: var(--panel); white-space: nowrap; }
  .chip.on { color: var(--ink); }
  .chip.off { opacity: .6; text-decoration: line-through; }
  .role { display: inline-block; padding: 0 6px; border-radius: 4px; font-size: 10.5px; font-weight: 600; letter-spacing: .02em; color: #fff; text-transform: lowercase; }
  .role.builder { background: var(--builder); } .role.reviewer { background: var(--reviewer); }
  .role.ci { background: var(--ci); } .role.human { background: var(--human); }
  .role.none { background: var(--muted); }
  #me { margin-left: auto; font-size: 12.5px; color: var(--muted); display: flex; gap: 6px; align-items: center; }
  #me button { border: 1px solid var(--line); background: var(--panel); border-radius: 4px; padding: 1px 8px; cursor: pointer; font-size: 12px; color: var(--muted); }
  #banner { display: none; width: 100%; padding: 6px 10px; border-radius: 6px; background: var(--soft); color: var(--muted); font-size: 12.5px; }
  #banner.on { display: block; }

  /* -------------------------------------------------------------- pipeline */
  #pipeline { position: relative; display: flex; align-items: center; gap: 0; padding: 14px 16px 26px; background: var(--panel); border-bottom: 1px solid var(--line); overflow-x: auto; }
  .pnode { position: relative; min-width: 104px; padding: 8px 12px; border-radius: 10px; border: 1.5px solid var(--line); background: var(--panel); text-align: center; flex: 0 0 auto; transition: transform .2s; }
  .pnode .n { font-size: 22px; font-weight: 700; line-height: 1.1; font-variant-numeric: tabular-nums; }
  .pnode .l { font-size: 11px; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); }
  .pnode::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 4px; border-radius: 10px 0 0 10px; background: var(--c); }
  .pnode.bump { animation: bump .5s ease; }
  @keyframes bump { 0% { transform: scale(1); } 40% { transform: scale(1.09); box-shadow: 0 0 0 4px color-mix(in srgb, var(--c) 30%, transparent); } 100% { transform: scale(1); } }
  .parrow { flex: 1 0 22px; min-width: 22px; height: 2px; background: var(--line); position: relative; }
  .parrow::after { content: ""; position: absolute; right: -1px; top: -4px; border: 5px solid transparent; border-left-color: var(--line); border-right: 0; }
  .pgap { flex: 0 0 28px; }
  .pside { display: flex; gap: 10px; }
  #loop { position: absolute; left: 16px; bottom: 6px; font-size: 11.5px; color: var(--muted); }
  #loop b { color: var(--escalated); font-weight: 600; }
  .comet { position: absolute; left: 0; top: 0; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; background: var(--c); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c) 30%, transparent), 0 0 14px var(--c); pointer-events: none; z-index: 5; }
  .comet span { position: absolute; left: 14px; top: -5px; font-size: 10.5px; font-weight: 700; color: var(--c); white-space: nowrap; }

  /* ------------------------------------------------------------------ main */
  main { display: grid; grid-template-columns: 1fr 340px; min-height: 0; }
  @media (max-width: 1100px) { main { grid-template-columns: 1fr; grid-template-rows: 1fr 40%; } }
  #lanes { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(150px, 1fr); gap: 10px; padding: 12px 16px; overflow-x: auto; min-height: 0; }
  .lane { display: grid; grid-template-rows: auto 1fr; min-height: 0; background: var(--soft); border-radius: 10px; }
  .lane h2 { margin: 0; padding: 8px 10px; font-size: 11.5px; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--c); }
  .lane h2 b { color: var(--ink); font-variant-numeric: tabular-nums; }
  .lane .body { overflow-y: auto; padding: 8px; display: flex; flex-direction: column; gap: 8px; min-height: 60px; }
  .lane .empty { color: var(--muted); font-size: 12px; text-align: center; padding: 12px 4px; opacity: .7; }
  #lanes.hide-cancelled .lane.cancelled { display: none; }

  .card { position: relative; background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--c); border-radius: 8px; padding: 8px 9px 8px 10px; box-shadow: var(--shadow); cursor: pointer; }
  .card:hover { border-color: var(--accent); border-left-color: var(--c); }
  .card.held { opacity: .72; }
  .card.fresh { animation: arrive .7s ease; }
  @keyframes arrive { 0% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--c) 55%, transparent); } 100% { box-shadow: var(--shadow); } }
  .card .top { display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--muted); }
  .card .seq { font-weight: 700; color: var(--ink); }
  .card .right { margin-left: auto; display: flex; gap: 5px; align-items: center; }
  .card .title { margin: 3px 0 5px; font-weight: 550; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
  .card .line { font-size: 11.5px; color: var(--muted); display: flex; align-items: center; gap: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .card .line .who { overflow: hidden; text-overflow: ellipsis; }
  .tag { font-size: 10.5px; padding: 0 5px; border-radius: 4px; border: 1px solid var(--line); white-space: nowrap; }
  .tag.att { color: var(--escalated); border-color: color-mix(in srgb, var(--escalated) 45%, var(--line)); }
  .tag.pass { color: var(--merged); border-color: color-mix(in srgb, var(--merged) 45%, var(--line)); }
  .tag.fail { color: var(--escalated); border-color: color-mix(in srgb, var(--escalated) 45%, var(--line)); }
  .tag.prio { color: var(--claimed); }
  .lease { height: 3px; border-radius: 2px; background: var(--line); overflow: hidden; margin-top: 4px; }
  .lease i { display: block; height: 100%; background: var(--c); transition: width 1s linear; }
  .lease.low i { background: var(--escalated); }
  .left { font-variant-numeric: tabular-nums; }
  .left.low { color: var(--escalated); }
  a { color: var(--accent); text-decoration: none; }
  a:hover { text-decoration: underline; }

  /* ----------------------------------------------------------------- aside */
  aside { border-left: 1px solid var(--line); background: var(--panel); display: grid; grid-template-rows: auto auto auto 1fr; min-height: 0; }
  @media (max-width: 1100px) { aside { border-left: 0; border-top: 1px solid var(--line); } }
  aside h3 { margin: 0; padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--line); }
  aside h3 label { text-transform: none; letter-spacing: 0; font-size: 11.5px; display: inline-flex; gap: 4px; align-items: center; cursor: pointer; }
  #crew { max-height: 38vh; overflow-y: auto; padding: 6px 8px; display: flex; flex-direction: column; gap: 6px; }
  .member { border: 1px solid var(--line); border-radius: 8px; padding: 6px 8px; transition: box-shadow .3s; }
  .member.glow { animation: glow 1.2s ease; }
  @keyframes glow { 0% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 55%, transparent); } 100% { box-shadow: none; } }
  .member .name { display: flex; align-items: center; gap: 6px; font-weight: 600; }
  .member .name .pip { width: 8px; height: 8px; border-radius: 50%; background: var(--line); flex: 0 0 auto; }
  .member.active .name .pip { background: #3cb371; }
  .member .name .seen { margin-left: auto; font-weight: 400; font-size: 11px; color: var(--muted); }
  .member .model { font-size: 11px; color: var(--muted); }
  .member .doing { font-size: 12px; margin-top: 2px; color: var(--muted); }
  .member .doing b { color: var(--ink); font-weight: 600; cursor: pointer; }
  #trail { list-style: none; margin: 0; padding: 0; overflow-y: auto; min-height: 0; }
  #trail li { padding: 6px 12px; border-bottom: 1px solid var(--soft); font-size: 12px; display: grid; grid-template-columns: auto 1fr; gap: 2px 8px; cursor: pointer; }
  #trail li:hover { background: var(--soft); }
  #trail li.new { animation: slide .5s ease; }
  @keyframes slide { from { opacity: 0; transform: translateY(-6px); background: color-mix(in srgb, var(--accent) 14%, transparent); } to { opacity: 1; transform: none; } }
  #trail .t { color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
  #trail .what { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; }
  #trail .kind { font-weight: 600; }
  #trail .kind.claimed, #trail .kind.completed, #trail .kind.merged { color: var(--merged); }
  #trail .kind.failed, #trail .kind.lease_expired, #trail .kind.ground_shifted, #trail .kind.cancelled { color: var(--escalated); }
  #trail .kind.reviewed, #trail .kind.recused { color: var(--in_review); }
  #trail .kind.reported { color: var(--ci); }
  #trail .kind.linked { color: var(--accent); }
  #trail .move { color: var(--muted); font-size: 11px; }
  #trail .actor { grid-column: 2; color: var(--muted); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  #trail .detail { grid-column: 2; color: var(--ink); opacity: .85; font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }

  /* ---------------------------------------------------------------- drawer */
  #drawer { position: fixed; top: 0; right: 0; bottom: 0; width: min(560px, 100vw); background: var(--panel); border-left: 1px solid var(--line); box-shadow: -8px 0 24px rgba(0,0,0,.12); transform: translateX(100%); transition: transform .22s ease; z-index: 20; display: grid; grid-template-rows: auto 1fr; }
  #drawer.open { transform: none; }
  #drawer .bar { display: flex; gap: 8px; align-items: center; padding: 10px 14px; border-bottom: 1px solid var(--line); }
  #drawer .bar h2 { margin: 0; font-size: 15px; flex: 1; }
  #drawer .bar button { border: 0; background: transparent; font-size: 20px; color: var(--muted); cursor: pointer; line-height: 1; }
  #detail { overflow-y: auto; padding: 4px 14px 20px; }
  #detail h4 { margin: 14px 0 6px; font-size: 11px; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); }
  #detail pre { margin: 0; padding: 9px 10px; background: var(--soft); border-radius: 6px; white-space: pre-wrap; word-break: break-word; font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; max-height: 240px; overflow: auto; }
  #detail .kv { display: grid; grid-template-columns: 92px 1fr; gap: 3px 10px; font-size: 12.5px; }
  #detail .kv span:nth-child(odd) { color: var(--muted); }
  .stage { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; color: #fff; background: var(--c); }
  .attempt { border: 1px solid var(--line); border-left: 3px solid var(--escalated); border-radius: 6px; padding: 6px 8px; margin-bottom: 8px; font-size: 12px; }
  .attempt .h { display: flex; gap: 6px; flex-wrap: wrap; color: var(--muted); margin-bottom: 4px; }
  .attempt .h b { color: var(--ink); }
  .timeline { list-style: none; margin: 0; padding: 0 0 0 14px; border-left: 2px solid var(--line); }
  .timeline li { position: relative; padding: 0 0 10px 6px; font-size: 12px; }
  .timeline li::before { content: ""; position: absolute; left: -20px; top: 4px; width: 10px; height: 10px; border-radius: 50%; background: var(--panel); border: 2px solid var(--line); }
  .timeline li.mv::before { border-color: var(--accent); background: var(--accent); }
  .timeline .h { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
  .timeline .h .k { font-weight: 600; }
  .timeline .m { color: var(--muted); font-size: 11.5px; }
  .timeline .d { margin-top: 1px; white-space: pre-wrap; word-break: break-word; }

  /* ----------------------------------------------------------- gate, toasts */
  #gate { position: fixed; inset: 0; display: none; place-items: center; background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: blur(3px); z-index: 30; }
  #gate.open { display: grid; }
  #gate form { width: min(420px, 92vw); background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 20px; box-shadow: var(--shadow); }
  #gate h2 { margin: 0 0 6px; font-size: 16px; }
  #gate p { margin: 0 0 12px; color: var(--muted); font-size: 12.5px; }
  #gate input { width: 100%; padding: 8px 10px; font: 13px ui-monospace, SFMono-Regular, Menlo, monospace; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); }
  #gate button { margin-top: 10px; width: 100%; padding: 8px; border: 0; border-radius: 6px; background: var(--accent); color: #fff; font-weight: 600; cursor: pointer; }
  #gate .err { color: var(--escalated); min-height: 1.2em; margin-top: 8px; font-size: 12px; }
  #toasts { position: fixed; left: 16px; bottom: 16px; display: flex; flex-direction: column-reverse; gap: 6px; z-index: 25; pointer-events: none; }
  .toast { background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--c); border-radius: 8px; padding: 6px 10px; box-shadow: var(--shadow); font-size: 12.5px; animation: pop .25s ease; }
  .toast.out { opacity: 0; transform: translateY(6px); transition: all .3s; }
  @keyframes pop { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
  @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
</style>
</head>
<body>
<header>
  <span class="brand">hird<small>factory floor</small></span>
  <span id="project" class="mono"></span>
  <span id="live" class="wait"><span class="dot"></span><span id="livetext">connecting</span></span>
  <span class="chips" id="policy"></span>
  <span id="me"></span>
  <div id="banner"></div>
</header>

<div id="pipeline" aria-label="stages of the work">
  <div id="loop"></div>
</div>

<main>
  <section id="lanes" class="hide-cancelled" aria-label="work by stage"></section>
  <aside>
    <h3>Crew <span id="crewcount"></span></h3>
    <div id="crew"></div>
    <h3>Trail
      <span>
        <label><input type="checkbox" id="beats"> heartbeats</label>
        <label><input type="checkbox" id="showcancelled"> cancelled</label>
      </span>
    </h3>
    <ul id="trail" aria-live="polite"></ul>
  </aside>
</main>

<div id="drawer" role="dialog" aria-label="task detail">
  <div class="bar"><span id="dstage"></span><h2 id="dtitle"></h2><button id="dclose" title="close (Esc)">×</button></div>
  <div id="detail"></div>
</div>

<div id="gate">
  <form id="gateform">
    <h2>Watch the factory floor</h2>
    <p>The floor is read-only, but it is the queue's data: paste a token from this server's roster. It stays in this tab only.</p>
    <input id="token" type="password" autocomplete="off" placeholder="bearer token" required>
    <button type="submit">Watch</button>
    <div class="err" id="gateerr"></div>
  </form>
</div>

<div id="toasts" aria-live="polite"></div>

<script>
"use strict";
const STAGES = ["ready", "claimed", "built", "in_review", "approved", "merged", "escalated", "cancelled"];
const FLOW = ["ready", "claimed", "built", "in_review", "approved", "merged"];
const LABEL = { ready: "Ready", claimed: "Claimed", built: "Built", in_review: "In review", approved: "Approved", merged: "Merged", escalated: "Escalated", cancelled: "Cancelled" };
const MOVES = new Set(["created", "claimed", "status", "completed", "failed", "released", "lease_expired", "cancelled", "reopened", "reported", "merged", "reviewed", "linked", "asked", "answered", "verdict", "split"]);
const POLL_MS = 1000;
const TOKEN_KEY = "hird.watch.token";

const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
const cvar = (stage) => `--c: var(--${stage})`;

let token = sessionStorage.getItem(TOKEN_KEY) || "";
let cursor = null;
let skew = 0;                 // server clock minus ours, in ms
let floor = null;             // the last answer
let stageOf = new Map();      // seq -> stage, as last drawn
let signature = "";           // what the lanes were last drawn from
let openSeq = null;           // the task in the drawer
let polling = false;

// A token in the fragment (#token=…) never reaches a server log; take it and drop it.
(function takeTokenFromFragment() {
  const m = location.hash.match(/token=([^&]+)/);
  if (m) {
    token = decodeURIComponent(m[1]);
    sessionStorage.setItem(TOKEN_KEY, token);
    history.replaceState(null, "", location.pathname + location.search);
  }
})();

// ------------------------------------------------------------------ fetching

async function get(path) {
  const res = await fetch(path, { headers: { Authorization: `Bearer ${token}` }, cache: "no-store" });
  if (res.status === 401) { const e = new Error("unauthorized"); e.status = 401; throw e; }
  const body = await res.json().catch(() => ({}));
  if (!res.ok) { const e = new Error(body.error || res.statusText); e.status = res.status; throw e; }
  return body;
}

async function poll() {
  if (polling || !token) return;
  polling = true;
  try {
    const q = cursor == null ? "" : `?after=${cursor}`;
    const next = await get(`/watch/api/floor${q}`);
    skew = Date.parse(next.now) - Date.now();
    const first = floor == null;
    floor = next;
    cursor = next.cursor ?? cursor;
    setLive("live", "live");
    draw(next, first);
  } catch (e) {
    if (e.status === 401) { askForToken(floor ? "That token is no longer on the roster." : "That token is not on this server's roster."); }
    else { setLive("lost", "reconnecting…"); }
  } finally {
    polling = false;
    if (token) setTimeout(poll, POLL_MS);
  }
}

function setLive(cls, text) {
  $("live").className = cls === "live" ? "" : cls;
  $("livetext").textContent = text;
}

function askForToken(message) {
  sessionStorage.removeItem(TOKEN_KEY);
  token = "";
  $("gateerr").textContent = message || "";
  $("gate").classList.add("open");
  $("token").focus();
}

$("gateform").addEventListener("submit", (ev) => {
  ev.preventDefault();
  token = $("token").value.trim();
  if (!token) return;
  sessionStorage.setItem(TOKEN_KEY, token);
  $("token").value = "";
  $("gate").classList.remove("open");
  floor = null; cursor = null; stageOf = new Map(); signature = "";
  $("trail").innerHTML = "";
  setLive("wait", "connecting");
  poll();
});

// ------------------------------------------------------------------ time

const now = () => Date.now() + skew;
function ago(ts) {
  if (!ts) return "never";
  const s = Math.max(0, Math.round((now() - Date.parse(ts)) / 1000));
  if (s < 5) return "just now";
  if (s < 60) return `${s}s ago`;
  if (s < 3600) return `${Math.floor(s / 60)}m ago`;
  if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
  return `${Math.floor(s / 86400)}d ago`;
}
function left(ts) {
  const s = Math.round((Date.parse(ts) - now()) / 1000);
  if (s <= 0) return "lapsed";
  const m = Math.floor(s / 60);
  return m ? `${m}m${String(s % 60).padStart(2, "0")}s` : `${s}s`;
}
function clock(ts) {
  const d = new Date(ts);
  return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}

// Leases tick between polls; everything carrying data-until is redrawn each second.
const leaseMax = new Map();   // until -> the longest remaining we have seen, for the bar
setInterval(() => {
  for (const el of document.querySelectorAll("[data-until]")) {
    const until = el.dataset.until;
    const remaining = Date.parse(until) - now();
    const low = remaining < 60000;
    if (el.classList.contains("lease")) {
      const max = Math.max(leaseMax.get(until) || 0, remaining);
      leaseMax.set(until, max);
      el.firstElementChild.style.width = `${Math.max(0, Math.min(100, (remaining / max) * 100))}%`;
      el.classList.toggle("low", low);
    } else {
      el.textContent = left(until);
      el.classList.toggle("low", low);
    }
  }
  for (const el of document.querySelectorAll("[data-ago]")) el.textContent = ago(el.dataset.ago);
}, 1000);

// ------------------------------------------------------------------ drawing

function draw(f, first) {
  drawHeader(f);
  const moved = drawPipelineAndLanes(f, first);
  drawCrew(f, first);
  drawTrail(f.trail, first);
  if (openSeq != null && (moved.has(openSeq) || f.trail.some((e) => e.seq === openSeq))) openTask(openSeq, true);
}

function drawHeader(f) {
  $("project").textContent = f.project;
  const p = f.policy;
  const chip = (on, text) => `<span class="chip ${on ? "on" : "off"}">${esc(text)}</span>`;
  $("policy").innerHTML = f.factory ? [
    chip(p.reviewer_harness_differs, "reviewer harness differs"),
    chip(p.max_attempts > 0, `escalate after ${p.max_attempts}`),
    chip(p.require_ci_to_merge, "CI to merge"),
    chip(p.require_ci_before_review, "CI before review"),
  ].join("") : "";
  $("me").innerHTML = `watching as <b>${esc(f.me.identity)}</b> ${roles(f.me.roles)} <button id="leave" title="forget the token">leave</button>`;
  $("leave").onclick = () => askForToken("");
  const banner = $("banner");
  banner.classList.toggle("on", !f.factory);
  banner.textContent = f.factory ? "" : "The factory is off on this server: no roster entry has roles. Stages are derived under the default policy, and nothing is gated.";
}

function roles(list) {
  if (!list || !list.length) return `<span class="role none">no role</span>`;
  return list.map((r) => `<span class="role ${esc(r)}">${esc(r)}</span>`).join(" ");
}

function drawPipelineAndLanes(f, first) {
  const counts = Object.fromEntries(STAGES.map((s) => [s, 0]));
  for (const row of f.board) counts[row.stage]++;

  // The pipeline is built once and then only counted.
  const pipe = $("pipeline");
  if (!pipe.querySelector(".pnode")) {
    const node = (s) => `<div class="pnode" id="pn-${s}" style="${cvar(s)}"><div class="n">0</div><div class="l">${LABEL[s]}</div></div>`;
    pipe.insertAdjacentHTML("afterbegin",
      FLOW.map(node).join(`<div class="parrow"></div>`) +
      `<div class="pgap"></div><div class="pside">${node("escalated")}${node("cancelled")}</div>`);
  }
  for (const s of STAGES) {
    const n = $(`pn-${s}`).querySelector(".n");
    if (n.textContent !== String(counts[s])) n.textContent = counts[s];
  }
  const attempts = f.board.reduce((a, r) => a + r.attempts, 0);
  $("loop").innerHTML = attempts ? `↺ rejected and sent back <b>${attempts}</b> time${attempts === 1 ? "" : "s"} across the board` : "";

  // What moved since the last poll, by stage.
  const moved = new Map();
  const next = new Map(f.board.map((r) => [r.seq, r.stage]));
  if (!first) {
    for (const [seq, stage] of next) {
      const was = stageOf.get(seq);
      if (was !== stage) moved.set(seq, { from: was, to: stage });
    }
  }
  stageOf = next;

  // Redraw the lanes only when something on them changed; lease countdowns tick on their own.
  const sig = JSON.stringify(f.board);
  if (sig !== signature) {
    signature = sig;
    const before = new Map([...document.querySelectorAll(".card")].map((c) => [c.dataset.seq, c.getBoundingClientRect()]));
    renderLanes(f, counts);
    flip(before, moved);
  }

  for (const [seq, m] of moved) {
    const row = f.board.find((r) => r.seq === seq);
    if (m.from) comet(m.from, m.to, seq);
    toast(m.to, m.from ? `#${seq} ${LABEL[m.from]} → <b>${LABEL[m.to]}</b>` : `#${seq} filed: <b>${esc(row?.title)}</b>`);
    const node = $(`pn-${m.to}`);
    node.classList.remove("bump"); void node.offsetWidth; node.classList.add("bump");
  }
  return moved;
}

function renderLanes(f, counts) {
  const lanes = $("lanes");
  if (!lanes.children.length) {
    lanes.innerHTML = STAGES.map((s) =>
      `<div class="lane ${s}" style="${cvar(s)}"><h2>${LABEL[s]} <b id="lc-${s}">0</b></h2><div class="body" id="lane-${s}"></div></div>`).join("");
  }
  const by = Object.fromEntries(STAGES.map((s) => [s, []]));
  for (const row of f.board) by[row.stage].push(row);
  for (const s of STAGES) {
    by[s].sort((a, b) => (b.priority - a.priority) || (a.seq - b.seq));
    $(`lc-${s}`).textContent = counts[s];
    $(`lane-${s}`).innerHTML = by[s].length ? by[s].map(card).join("") : `<div class="empty">${emptyText(s)}</div>`;
  }
}

function emptyText(s) {
  return { ready: "nothing waiting", claimed: "nobody building", built: "nothing to review", in_review: "no review held",
           approved: "nothing to merge", merged: "nothing merged yet", escalated: "nothing needs you", cancelled: "none" }[s];
}

function card(r) {
  const lines = [];
  if (r.holder) {
    lines.push(`<div class="line">⚒ <span class="who mono">${esc(r.holder)}</span>${r.lease_expires_at ? ` · <span class="left" data-until="${esc(r.lease_expires_at)}">${left(r.lease_expires_at)}</span>` : ""}</div>`);
    if (r.lease_expires_at) lines.push(`<div class="lease" data-until="${esc(r.lease_expires_at)}"><i style="width:100%"></i></div>`);
  }
  if (r.review) {
    const rv = r.review;
    if (rv.holder) {
      lines.push(`<div class="line">◉ review #${rv.seq} · <span class="who mono">${esc(rv.holder)}</span>${rv.lease_expires_at ? ` · <span class="left" data-until="${esc(rv.lease_expires_at)}">${left(rv.lease_expires_at)}</span>` : ""}</div>`);
      if (rv.lease_expires_at) lines.push(`<div class="lease" data-until="${esc(rv.lease_expires_at)}"><i style="width:100%"></i></div>`);
    } else {
      lines.push(`<div class="line">◌ review #${rv.seq} waiting for a reviewer</div>`);
    }
  }
  if (r.waiting_on && r.waiting_on.length) {
    lines.push(`<div class="line">⏳ waits on ${r.waiting_on.map((d) => `#${d}`).join(", ")} to merge</div>`);
  }
  if (!r.holder && r.builders && r.builders.length && r.stage !== "ready") {
    lines.push(`<div class="line">built by <span class="who mono">${esc(r.builders.join(", "))}</span></div>`);
  }
  const l = r.links || {};
  const linkBits = [];
  if (l.branch) linkBits.push(`<span class="mono">⎇ ${esc(l.branch)}</span>`);
  if (l.pr_url) linkBits.push(`<a href="${esc(safeUrl(l.pr_url))}" target="_blank" rel="noopener noreferrer" onclick="event.stopPropagation()">PR ↗</a>`);
  if (linkBits.length) lines.push(`<div class="line">${linkBits.join(" · ")}</div>`);

  const tags = [];
  if (r.priority) tags.push(`<span class="tag prio" title="priority">P${r.priority}</span>`);
  if (r.attempts) tags.push(`<span class="tag att" title="rejected attempts">↺${r.attempts}</span>`);
  if (r.ci === true) tags.push(`<span class="tag pass" title="latest CI report">CI ✓</span>`);
  if (r.ci === false) tags.push(`<span class="tag fail" title="latest CI report">CI ✗</span>`);
  const held = r.stage === "ready" && r.waiting_on && r.waiting_on.length;
  return `<div class="card${held ? " held" : ""}" data-seq="${r.seq}" style="${cvar(r.stage)}" onclick="openTask(${r.seq})">
    <div class="top"><span class="seq">#${r.seq}</span><span class="right">${tags.join("")}</span></div>
    <div class="title">${esc(r.title)}</div>${lines.join("")}</div>`;
}

function safeUrl(u) { return /^https?:\/\//i.test(u) ? u : "#"; }

// Cards that changed lane slide from where they were; new ones glow in.
function flip(before, moved) {
  for (const el of document.querySelectorAll(".card")) {
    const seq = el.dataset.seq;
    const was = before.get(seq);
    if (!was) { if (before.size) el.classList.add("fresh"); continue; }
    const now = el.getBoundingClientRect();
    const dx = was.left - now.left, dy = was.top - now.top;
    if (Math.abs(dx) < 1 && Math.abs(dy) < 1) continue;
    const changedLane = moved.has(Number(seq));
    el.animate([{ transform: `translate(${dx}px, ${dy}px)`, zIndex: 3 }, { transform: "none", zIndex: 3 }],
      { duration: changedLane ? 650 : 250, easing: "cubic-bezier(.2,.7,.2,1)" });
    if (changedLane) el.classList.add("fresh");
  }
}

// A dot runs along the pipeline for every move; rejections loop back underneath it.
function comet(from, to, seq) {
  const pipe = $("pipeline");
  const a = $(`pn-${from}`), b = $(`pn-${to}`);
  if (!a || !b) return;
  const box = pipe.getBoundingClientRect();
  const centre = (el) => { const r = el.getBoundingClientRect(); return [r.left - box.left + pipe.scrollLeft + r.width / 2, r.top - box.top + r.height / 2]; };
  const [ax, ay] = centre(a), [bx, by] = centre(b);
  const dot = document.createElement("div");
  dot.className = "comet";
  dot.style.cssText = cvar(to);
  dot.innerHTML = `<span>#${seq}</span>`;
  pipe.appendChild(dot);
  const back = FLOW.indexOf(to) >= 0 && FLOW.indexOf(from) > FLOW.indexOf(to);
  const sideways = !FLOW.includes(to) || !FLOW.includes(from);
  const frames = back
    ? [[ax, ay], [ax, ay + 34], [bx, by + 34], [bx, by]]
    : sideways ? [[ax, ay], [(ax + bx) / 2, Math.min(ay, by) - 18], [bx, by]] : [[ax, ay], [bx, by]];
  const anim = dot.animate(frames.map(([x, y]) => ({ transform: `translate(${x}px, ${y}px)` })),
    { duration: back ? 1400 : 900, easing: "ease-in-out" });
  anim.onfinish = () => dot.remove();
}

function toast(stage, html) {
  const t = document.createElement("div");
  t.className = "toast";
  t.style.cssText = cvar(stage);
  t.innerHTML = html;
  const box = $("toasts");
  box.appendChild(t);
  while (box.children.length > 5) box.firstElementChild.remove();
  setTimeout(() => { t.classList.add("out"); setTimeout(() => t.remove(), 350); }, 4200);
}

// ------------------------------------------------------------------ crew

function drawCrew(f, first) {
  const holding = (prefix) => {
    const out = [];
    for (const r of f.board) {
      if (r.holder && r.holder.startsWith(prefix)) out.push(`building <b onclick="openTask(${r.seq})">#${r.seq}</b>`);
      if (r.review && r.review.holder && r.review.holder.startsWith(prefix)) out.push(`reviewing <b onclick="openTask(${r.seq})">#${r.seq}</b>`);
    }
    return out;
  };
  $("crewcount").textContent = f.crew.length ? `${f.crew.length}` : "";
  const active = new Set(f.trail.map((e) => e.actor));
  const html = f.crew.map((m) => {
    const doing = holding(m.prefix);
    const recent = m.last_seen && now() - Date.parse(m.last_seen) < 120000;
    return `<div class="member${doing.length || recent ? " active" : ""}" data-prefix="${esc(m.prefix)}">
      <div class="name"><span class="pip"></span>${esc(m.identity)}${m.harness ? ` <span class="mono" style="font-weight:400;color:var(--muted)">· ${esc(m.harness)}</span>` : ""}
        <span class="seen" data-ago="${esc(m.last_seen || "")}">${ago(m.last_seen)}</span></div>
      <div>${roles(m.roles)}${m.model ? ` <span class="model mono">${esc(m.model)}</span>` : ""}</div>
      <div class="doing">${doing.length ? doing.join(", ") : "idle"}</div></div>`;
  }).join("");
  const crew = $("crew");
  if (crew.dataset.sig !== html) { crew.innerHTML = html || `<div class="empty" style="color:var(--muted);padding:8px">no one on the roster for this project</div>`; crew.dataset.sig = html; }
  if (!first) {
    for (const el of crew.querySelectorAll(".member")) {
      const prefix = el.dataset.prefix;
      if ([...active].some((a) => a.startsWith(prefix))) { el.classList.remove("glow"); void el.offsetWidth; el.classList.add("glow"); }
    }
  }
}

// ------------------------------------------------------------------ trail

function drawTrail(entries, first) {
  const list = $("trail");
  const beats = $("beats").checked;
  for (const e of entries) {
    const li = document.createElement("li");
    li.dataset.kind = e.kind;
    if (!first) li.className = "new";
    if (e.kind === "lease_renewed" && !beats) li.hidden = true;
    const move = e.from_state && e.to_state && e.from_state !== e.to_state ? `<span class="move">${esc(e.from_state)} → ${esc(e.to_state)}</span>` : "";
    const ev = e.evidence ? (/^https?:\/\//i.test(e.evidence) ? ` <a href="${esc(e.evidence)}" target="_blank" rel="noopener noreferrer" onclick="event.stopPropagation()">evidence ↗</a>` : ` <span class="mono move">${esc(e.evidence)}</span>`) : "";
    li.innerHTML = `<span class="t">${clock(e.at)}</span>
      <span class="what"><b>#${e.seq}</b><span class="kind ${esc(e.kind)}">${esc(e.kind.replace(/_/g, " "))}</span>${move}${ev}</span>
      <span class="actor"><span class="mono">${esc(e.actor)}</span>${e.role ? ` <span class="role ${esc(e.role.split("+")[0])}">${esc(e.role)}</span>` : ""}${e.model ? ` <span class="mono">${esc(e.model)}</span>` : ""}</span>
      ${e.detail ? `<span class="detail">${esc(e.detail)}</span>` : ""}`;
    li.onclick = () => openTask(e.seq);
    list.prepend(li);
  }
  while (list.children.length > 400) list.lastElementChild.remove();
}

$("beats").addEventListener("change", () => {
  for (const li of $("trail").querySelectorAll('li[data-kind="lease_renewed"]')) li.hidden = !$("beats").checked;
});
$("showcancelled").addEventListener("change", () => $("lanes").classList.toggle("hide-cancelled", !$("showcancelled").checked));

// ------------------------------------------------------------------ detail

async function openTask(seq, quiet) {
  openSeq = seq;
  const drawer = $("drawer");
  if (!quiet) { drawer.classList.add("open"); $("dtitle").textContent = `#${seq}`; $("detail").innerHTML = `<p style="color:var(--muted)">loading…</p>`; }
  let v;
  try { v = await get(`/watch/api/task/${seq}`); }
  catch (e) {
    if (openSeq !== seq) return;
    $("detail").innerHTML = `<p style="color:var(--muted)">${esc(e.message)}</p>`;
    return;
  }
  if (openSeq !== seq) return;
  $("dstage").innerHTML = `<span class="stage" style="${cvar(v.stage)}">${LABEL[v.stage]}</span>`;
  $("dtitle").textContent = `#${v.seq} ${v.title}`;
  const kv = [];
  if (v.holder) kv.push(["held by", `<span class="mono">${esc(v.holder)}</span>${v.lease_expires_at ? ` · <span class="left" data-until="${esc(v.lease_expires_at)}">${left(v.lease_expires_at)}</span>` : ""}`]);
  if (v.builders.length) kv.push(["builders", `<span class="mono">${esc(v.builders.join(", "))}</span>`]);
  if (v.ci != null) kv.push(["latest CI", v.ci ? "pass" : "fail"]);
  if (v.attempts) kv.push(["attempts", String(v.attempts)]);
  if (v.waiting_on.length) kv.push(["waits on", v.waiting_on.map((d) => `<a href="#" onclick="openTask(${d});return false">#${d}</a>`).join(", ") + " to merge"]);
  const l = v.links || {};
  if (l.branch) kv.push(["branch", `<span class="mono">${esc(l.branch)}</span>`]);
  if (l.worktree) kv.push(["worktree", `<span class="mono">${esc(l.worktree)}</span>`]);
  if (l.pr_url) kv.push(["pull request", `<a href="${esc(safeUrl(l.pr_url))}" target="_blank" rel="noopener noreferrer">${esc(l.pr_url)}</a>`]);
  const reviews = v.reviews.map((r) => [`review #${r.seq}`, `${esc(r.status)}${r.holder ? ` · <span class="mono">${esc(r.holder)}</span>` : ""}`]);
  const html = [
    kv.length ? `<h4>Now</h4><div class="kv">${kv.map(([k, val]) => `<span>${k}</span><span>${val}</span>`).join("")}</div>` : "",
    reviews.length ? `<h4>Reviews</h4><div class="kv">${reviews.map(([k, val]) => `<span>${k}</span><span>${val}</span>`).join("")}</div>` : "",
    v.body ? `<h4>Brief</h4><pre>${esc(v.body)}</pre>` : "",
    v.result ? `<h4>Result</h4><pre>${esc(v.result)}</pre>` : "",
    attemptsHtml(v),
    `<h4>Trail</h4><ul class="timeline">${[...v.trail].reverse().map(step).join("")}</ul>`,
  ].join("");
  $("detail").innerHTML = html;
}

function attemptsHtml(v) {
  const list = Array.isArray(v.attempts_detail) ? v.attempts_detail : [];
  if (!list.length) return "";
  return `<h4>Rejected attempts</h4>` + list.map((a) => `<div class="attempt">
    <div class="h"><b>#${a.n}</b><span>${esc(a.outcome.replace(/_/g, " "))}</span><span>by ${esc(a.source || a.actor)}</span>
    <span>· work of <span class="mono">${esc(a.holder || "?")}</span>${a.model ? ` (${esc(a.model)})` : ""}</span><span>· ${ago(a.at)}</span></div>
    ${a.output ? `<pre>${esc(a.output)}</pre>` : ""}</div>`).join("");
}

function step(e) {
  const move = e.from_state && e.to_state && e.from_state !== e.to_state;
  return `<li class="${move ? "mv" : ""}"><div class="h"><span class="k">${esc(e.kind.replace(/_/g, " "))}</span>
    ${move ? `<span class="m">${esc(e.from_state)} → ${esc(e.to_state)}</span>` : ""}
    <span class="m">${clock(e.at)} · <span class="mono">${esc(e.actor)}</span>${e.role ? ` <span class="role ${esc(e.role.split("+")[0])}">${esc(e.role)}</span>` : ""}${e.model ? ` <span class="mono">${esc(e.model)}</span>` : ""}</span></div>
    ${e.detail ? `<div class="d">${esc(e.detail)}</div>` : ""}${e.evidence ? `<div class="m mono">evidence: ${esc(e.evidence)}</div>` : ""}</li>`;
}

function closeDrawer() { openSeq = null; $("drawer").classList.remove("open"); }
$("dclose").onclick = closeDrawer;
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeDrawer(); });
window.openTask = openTask;

// ------------------------------------------------------------------ start

if (token) poll(); else askForToken("");
</script>
</body>
</html>