fwdloop 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/bin/fwdloop +136 -21
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +101 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +2 -1
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +41 -3
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/liveness.js +1 -1
  13. package/src/model-step.js +30 -4
  14. package/src/monthly.js +58 -13
  15. package/src/panel/author.js +482 -0
  16. package/src/panel/authorcard.js +297 -0
  17. package/src/panel/authorflows.js +312 -0
  18. package/src/panel/authorresume.js +149 -0
  19. package/src/panel/authorstart.js +257 -0
  20. package/src/panel/authorvalues.js +110 -0
  21. package/src/panel/data.js +228 -34
  22. package/src/panel/index.html +1745 -127
  23. package/src/panel/resume.js +6 -8
  24. package/src/panel/server.js +119 -119
  25. package/src/panel/settings.js +7 -5
  26. package/src/panel/spawn.js +77 -0
  27. package/src/provider.js +12 -17
  28. package/src/runner.js +639 -85
  29. package/src/runvalues.js +178 -0
  30. package/src/send.js +10 -3
  31. package/src/setup.js +120 -0
  32. package/types/authoring.d.ts +24 -2
  33. package/types/books.d.ts +14 -2
  34. package/types/canrun.d.ts +32 -0
  35. package/types/config.d.ts +1 -0
  36. package/types/declaration.d.ts +9 -1
  37. package/types/drafter.d.ts +15 -1
  38. package/types/draftspend.d.ts +21 -0
  39. package/types/flow.d.ts +23 -0
  40. package/types/liveness.d.ts +2 -2
  41. package/types/model-step.d.ts +3 -1
  42. package/types/monthly.d.ts +21 -0
  43. package/types/panel/author.d.ts +335 -0
  44. package/types/panel/authorcard.d.ts +120 -0
  45. package/types/panel/authorflows.d.ts +175 -0
  46. package/types/panel/authorresume.d.ts +32 -0
  47. package/types/panel/authorstart.d.ts +115 -0
  48. package/types/panel/authorvalues.d.ts +62 -0
  49. package/types/panel/data.d.ts +103 -12
  50. package/types/panel/server.d.ts +11 -33
  51. package/types/panel/spawn.d.ts +30 -0
  52. package/types/provider.d.ts +6 -9
  53. package/types/runner.d.ts +120 -5
  54. package/types/runvalues.d.ts +97 -0
  55. package/types/send.d.ts +5 -1
  56. package/types/setup.d.ts +83 -0
@@ -33,6 +33,7 @@
33
33
  --magenta:#bb9af7;
34
34
  --accent:#7aa2f7;
35
35
  --btn-bg:#1f2335; --btn-text:#c0caf5;
36
+ --field-bg:var(--bg); --field-soft-bg:var(--bg); --field-border:var(--text-dim);
36
37
  --primary-bg:#7aa2f7; --primary-text:#1a1b26; --primary-border:#7aa2f7;
37
38
  font: 14px/1.5 "Courier Prime", "Courier New", Courier, ui-monospace, monospace;
38
39
  }
@@ -74,6 +75,7 @@
74
75
  --magenta:#9854f1;
75
76
  --accent:#2668c2;
76
77
  --btn-bg:#e9e9ed; --btn-text:#3760bf;
78
+ --field-bg:#ffffff; --field-soft-bg:#f7f7f9;
77
79
  --primary-bg:#2668c2; --primary-text:#e1e2e7; --primary-border:#2668c2;
78
80
  }
79
81
  }
@@ -88,6 +90,7 @@
88
90
  --magenta:#9854f1;
89
91
  --accent:#2668c2;
90
92
  --btn-bg:#e9e9ed; --btn-text:#3760bf;
93
+ --field-bg:#ffffff; --field-soft-bg:#f7f7f9;
91
94
  --primary-bg:#2668c2; --primary-text:#e1e2e7; --primary-border:#2668c2;
92
95
  }
93
96
  .theme-toggle{padding:4px 9px;min-height:32px;border:1px solid var(--border-strong);background:var(--btn-bg);color:var(--text);}
@@ -157,6 +160,11 @@
157
160
  /* M4c amendment 2: stuck — answer saved, nobody carrying the run on. Its own glyph,
158
161
  amber like the other "needs you" signs; it pulses (server-decided, glyphPulses). */
159
162
  .dot.stuck::before{content:"[II]";color:var(--amber);}
163
+ /* M4e amendment 4: stopped — by you, or at the money cap; Resume goes on. Grey like the other quiet end, never the red [✗]. */
164
+ .dot.stopped::before{content:"[■]";color:var(--grey-dot);}
165
+ /* the Run tab's top action row (Stop, Resume) */
166
+ .run-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:8px;}
167
+ .run-actions .answer-msg{margin-top:0;flex:1 1 100%;}
160
168
  /* M4c: only the two "alive" signs pulse — [▶] running and [·] waiting on
161
169
  you — keyed to `.pulse`, which the server decides (glyphPulses), never to
162
170
  a colour class (.grey is also the placeholder dot). A gentle opacity wave on the existing colors;
@@ -186,6 +194,7 @@
186
194
  .badge.cyan{color:var(--cyan);}
187
195
 
188
196
  .hint{font-size:11px;color:var(--text-faint);margin-top:4px;}
197
+ .hint.money-red{color:var(--red);}
189
198
  .btn{padding:8px 14px;min-height:44px;border:1px solid var(--border-strong);background:var(--panel2);color:var(--text);white-space:nowrap;flex:none;position:relative;}
190
199
  .btn::before{content:"[ ";color:var(--text-faint);}
191
200
  .btn::after{content:" ]";color:var(--text-faint);}
@@ -227,11 +236,11 @@
227
236
  the same behavior fix #7 already gave phone width alone. */
228
237
  .wf-meta-line{white-space:normal;overflow:visible;text-overflow:clip;min-width:0;}
229
238
  /* M4c-fix amendment 2 (g), line 2 of a run row: **word** — plain why. Wraps, never clips. */
230
- .wf-sign-line{font-size:12px;color:var(--text-dim);white-space:normal;overflow-wrap:anywhere;min-width:0;}
239
+ .wf-sign-line{font-size:12px;color:var(--text-dim);white-space:normal;overflow-wrap:anywhere;}
231
240
  .wf-sign-line .sign-word,.hdr-verdict .sign-word{color:var(--text);}
232
241
  .hdr-verdict{font-size:12px;color:var(--text-dim);min-width:0;overflow-wrap:anywhere;}
233
242
  .wf-meta{font-size:12px;color:var(--text-dim);}
234
- .wf-meta + .wf-meta::before{content:" · ";color:var(--text-faint);}
243
+ .wf-sep{font-size:12px;color:var(--text-faint);}
235
244
  .wf-row.selected,.hist-row.selected{border:2px solid var(--accent);border-radius:4px;}
236
245
  /* item 2 (2026-09-26 merge): a Workflows-view job row expands inline to
237
246
  list ALL its runs (build spec's own design) — the caret glyph on the
@@ -296,7 +305,7 @@
296
305
  `[✓]`, so it draws no second pair of brackets (`.sign-badge`). */
297
306
  .step-card .step-head{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;text-transform:none;font-weight:700;}
298
307
  .step-card h4{margin:0;font-size:13px;text-transform:none;letter-spacing:normal;}
299
- .step-card .sign-badge::before,.step-card .sign-badge::after{content:none;}
308
+ .sign-badge::before,.sign-badge::after{content:none;}
300
309
  /* Every OTHER line on the card (goal, actions, granted, stopped reason) —
301
310
  lower case exactly as the data reads, normal weight; never inherits the
302
311
  header's uppercase/bold (same ruling, the non-header half of it). */
@@ -342,7 +351,8 @@
342
351
  .audit-group h4::before{content:"┤ ";color:var(--text-faint);}
343
352
  .audit-group h4::after{content:" ├";color:var(--text-faint);}
344
353
  /* hamr's 2026-09-27 review: the Audit-group's own state header ("[done] ·
345
- step · ...", built by buildAuditGroupHeaderEl) is NOT bold — a plain h4
354
+ step · ...", built by buildAuditGroupHeaderEl): M4e amendment 10 made its STATUS bold (the `> .badge`,
355
+ weight 700); the rest of the line stays normal — a plain h4
346
356
  is bold by default, so its own class (`.audit-status-header`, NOT the
347
357
  shared `.audit-group h4`, which the Ask tab's `.ask-question-heading`
348
358
  h4 also matches and must stay bold per review #3) overrides it back to
@@ -350,6 +360,7 @@
350
360
  `.audit-group h4` (0,1,1) and `.ask-question-heading` (0,1,0) alone, so
351
361
  this never un-bolds the ask question heading. */
352
362
  .audit-group h4.audit-status-header{font-weight:400;}
363
+ .audit-group h4.audit-status-header > .badge{font-weight:700;}
353
364
  /* M4c-fix amendment 2 (f): a foldable step group. The header sits IN the box (not pinned over its top edge),
354
365
  so a long header wraps inside its own box and never lands on the next group; a closed group is that one
355
366
  header line with a caret and no empty table under it. */
@@ -359,6 +370,7 @@
359
370
  .audit-group.audit-fold h4.audit-status-header > .badge,.audit-group.audit-fold h4.audit-status-header::before{flex:none;white-space:pre;}
360
371
  .audit-fold-name{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
361
372
  .audit-fold-tail{flex:none;white-space:nowrap;}
373
+ .audit-fold-dot{flex:none;}
362
374
  .audit-group.audit-fold h4.audit-status-header::before{content:"\25B6 ";color:var(--text-faint);}
363
375
  .audit-group.audit-fold h4.audit-status-header[aria-expanded="true"]::before{content:"\25BC ";}
364
376
  .audit-group.audit-fold h4.audit-status-header::after{content:none;}
@@ -369,8 +381,13 @@
369
381
  .audit-group.audit-fold h4.audit-status-header > .badge{padding-left:0;padding-right:0;font-size:10px;}
370
382
  .audit-group.audit-fold h4.audit-status-header::before{content:"\25B6";}
371
383
  .audit-group.audit-fold h4.audit-status-header[aria-expanded="true"]::before{content:"\25BC";}
372
- .audit-fold-sep,.audit-fold-try{display:none;}
373
- .audit-fold-n{margin-left:.4em;}
384
+ .audit-fold-sep{display:none;}
385
+ .audit-fold-try{margin-left:.4em;} /* the cost and the try count never touch: "$0.0010" + "1" must not read $0.00101 */
386
+ /* the tail wraps inside the header (never spills or is cut): it may break at its spaces and shrink */
387
+ .audit-fold-tail{flex:0 1 auto;min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;}
388
+ /* a narrow header WRAPS (amendment 7 walk): the name keeps a readable line of its own and the tail drops under it, never a one-letter name */
389
+ .audit-group.audit-fold h4.audit-status-header{flex-wrap:wrap;row-gap:2px;}
390
+ .audit-fold-name{flex:0 1 auto;max-width:100%;white-space:normal;overflow:visible;text-overflow:clip;overflow-wrap:anywhere;}
374
391
  }
375
392
  .audit-group.audit-fold table{margin-top:8px;}
376
393
  .audit-group.audit-fold table[hidden]{display:none !important;}
@@ -409,11 +426,129 @@
409
426
  line) so it reads as a clear, bold heading without a second border. */
410
427
  .ask-question-heading{margin:6px 0 0;font-size:13px;font-weight:700;color:var(--text);}
411
428
  .ro-value{padding:6px 8px;min-height:32px;box-sizing:border-box;border:1px solid var(--border);background:var(--bg);color:var(--text-dim);}
429
+ .art-head{color:var(--accent);}
430
+ .ro-value.sub{margin-left:20px;min-height:0;padding-top:2px;padding-bottom:2px;border-top-width:0;overflow-wrap:anywhere;}
412
431
  .ro-value.scroll{max-height:160px;overflow-y:auto;white-space:pre-wrap;word-break:break-word;}
413
432
  .field-row{display:flex;flex-wrap:wrap;gap:10px;}
414
433
  .field-row .field{flex:1 1 140px;margin-bottom:10px;}
415
434
 
416
- .chat-thread{padding:20px 8px;color:var(--text-faint);font-size:13px;}
435
+ /* borrowed-from: bareloop src/panel/index.html@ca7195e — the Chat card's CSS (job card, radio row, cap row, the one progress
436
+ list, the ask box, the one wide button, field colours, .locked, the one focus rule). fwdloop's own tokens win where both define
437
+ one; the global `input,select` rule is scoped to #panel-chat so no other panel box is restyled. */
438
+ #panel-chat input,#panel-chat select{font:inherit;padding:6px 8px;border:1px solid var(--border-strong);border-radius:0;background:var(--bg);color:var(--text);}
439
+ #panel-chat input::placeholder,#panel-chat textarea::placeholder{color:var(--text-faint);}
440
+ .job-card .card-clear{position:absolute;top:-13px;right:10px;padding:1px 8px;font-size:11px;line-height:1.4;background:var(--panel2);}
441
+ .job-card .locked{opacity:.55;cursor:not-allowed;}
442
+ .field input,.field select{width:100%;}
443
+ .job-card.compact{padding:14px 8px 8px;}
444
+ .job-card.compact .field{margin-bottom:6px;}
445
+ .job-card.compact label{margin-bottom:1px;font-size:11px;}
446
+ .job-card.compact input,
447
+ .job-card.compact select{padding:5px 7px;}
448
+ .radio-row{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin-bottom:10px;}
449
+ .radio-row label{display:flex;align-items:center;gap:5px;font-size:13px;color:var(--text);margin:0;text-transform:none;}
450
+ .radio-row input{width:auto;}
451
+ @media (max-width:400px){.job-card .radio-row{padding-right:76px;}}
452
+ .cap-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:6px;margin-bottom:6px;}
453
+ .cap-field label{display:block;font-size:11px;font-weight:700;color:var(--text-dim);margin-bottom:1px;}
454
+ .cap-field input{width:100%;padding:5px 6px;box-sizing:border-box;}
455
+ .btn.primary{background:var(--primary-bg);color:var(--primary-text);border-color:var(--primary-border);font-weight:700;}
456
+ .btn.primary::before,.btn.primary::after{color:var(--primary-text);opacity:0.6;}
457
+ #panel-chat .btn:disabled{opacity:0.5;cursor:not-allowed;}
458
+ .btn.primary:disabled{background:var(--btn-bg);color:var(--text-faint);border-color:var(--border);}
459
+ .btn.primary:disabled::before,.btn.primary:disabled::after{color:var(--text-faint);opacity:0.4;}
460
+ #chat-action-error:empty{display:none;}
461
+ #chat-action-error{font-size:12px;color:var(--red);margin:4px 0;overflow-wrap:anywhere;white-space:pre-wrap;}
462
+ #chat-card-error:empty{display:none;}
463
+ #chat-card-error{overflow-wrap:anywhere;white-space:pre-wrap;}
464
+
465
+ /* the ONE progress list: a step per line — label, then dots while running / check / cross, then its reason */
466
+ .chat-steps{list-style:none;margin:2px 0 10px;padding:0;font-size:12px;}
467
+ .chat-steps .step{padding:1px 0;}
468
+ .chat-steps .step-line{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 10px;}
469
+ .chat-steps .step-label{color:var(--text);min-width:11em;overflow-wrap:anywhere;}
470
+ .chat-steps .step-sign{font-weight:700;}
471
+ .chat-steps .step.run .step-sign{color:var(--amber);}
472
+ .chat-steps .step.ok .step-sign{color:var(--green);}
473
+ .chat-steps .step.bad .step-sign{color:var(--red);}
474
+ .chat-steps .step.wait .step-label{color:var(--amber);}
475
+ .chat-steps .step-detail{display:block;flex-basis:100%;min-width:0;padding-left:1.2em;color:var(--text-faint);word-break:break-word;white-space:pre-wrap;}
476
+ .chat-steps .step.bad .step-detail{color:var(--red);}
477
+ .chat-steps .step.run .step-sign::after{content:"\2026";}
478
+ @keyframes step-dots{0%{content:"";}25%{content:".";}50%{content:"..";}75%{content:"...";}}
479
+ @media (prefers-reduced-motion: no-preference){
480
+ .chat-steps .step.run .step-sign::after{content:"";animation:step-dots 1.2s steps(1,end) infinite;}
481
+ }
482
+
483
+ .chat-thread{display:flex;flex-direction:column;gap:10px;margin-bottom:10px;}
484
+ .chat-thread:empty{display:none;}
485
+ .msg{padding:8px 10px;border:1px solid var(--border);max-width:100%;background:var(--panel2);font-size:13px;word-break:break-word;white-space:pre-wrap;}
486
+ .msg.bot{border-left:3px solid var(--border-strong);}
487
+ .msg.bot .who::before{content:"$ ";}
488
+ .msg .who{font-size:11px;color:var(--text-faint);margin-bottom:3px;text-transform:none;font-weight:400;}
489
+ /* borrowed-from: bareloop src/panel/index.html@c1d87ce (the "you" bubble: indented, accent left border) */
490
+ .msg.you{background:var(--bg);margin-left:20px;border-left:3px solid var(--accent);}
491
+ .msg.you .who::before{content:"> ";}
492
+ .chat-input-row{margin-top:10px;border-top:1px dotted var(--border-strong);padding-top:10px;}
493
+ .chat-input-row input{width:100%;box-sizing:border-box;}
494
+ /* borrowed-from: bareloop src/panel/index.html@d151ec7 (the ask box: a wrapping textarea, 2x height, thick border, dimmed while it cannot be used).
495
+ M4e amendment 3 item 3: it opens only on a green plan ("Ask for a change to the plan"); `hidden` closes it. */
496
+ .chat-input-row[hidden]{display:none;}
497
+ textarea[data-testid="chat-msg"]{width:100%;box-sizing:border-box;font:inherit;color:var(--text);resize:vertical;overflow-y:auto;max-height:200px;}
498
+ #chat-msg{min-height:64px;padding:8px 12px;border:2px solid var(--field-border);background:var(--field-bg);}
499
+ #chat-msg:read-only{background:var(--bg);opacity:.55;cursor:not-allowed;}
500
+ /* the card's free-text boxes wrap (textarea): grow a few rows (fitBox), then scroll inside */
501
+ .job-card textarea.jf-wrap{width:100%;box-sizing:border-box;font:inherit;padding:6px 8px;border:1px solid var(--border-strong);border-radius:0;background:var(--bg);color:var(--text);resize:vertical;overflow-y:auto;max-height:200px;}
502
+ /* the focused/selected Chat-card field gets a blue border (the accent), no outline ring */
503
+ #panel-chat :is(input,select,textarea):focus{border-color:var(--accent);outline:none;}
504
+ /* amendment 2: the job and inputs boxes have a gutter OUTSIDE them on the left (`N >` per step, `~` per guardrail; a number per input
505
+ line), one entry per logical line, as tall as that line wraps (measured from a hidden mirror, see paintGutter) */
506
+ .jf-gutbox{position:relative;display:flex;align-items:stretch;gap:4px;}
507
+ .jf-gutbox textarea.jf-wrap{flex:1 1 auto;min-width:0;width:auto;overflow-wrap:break-word;word-wrap:break-word;white-space:pre-wrap;}
508
+ .jf-gut{flex:0 0 1.8em;overflow:hidden;position:relative;color:var(--text-faint);text-align:left;user-select:none;-webkit-user-select:none;font:inherit;}
509
+ .jf-gut-in{position:absolute;left:0;right:0;top:0;}
510
+ .jf-gut-in div{white-space:nowrap;overflow:hidden;}
511
+ .jf-mirror{position:absolute;left:0;top:0;visibility:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;word-wrap:break-word;box-sizing:content-box;padding:0;border:0;margin:0;}
512
+ .jf-mirror div{margin:0;padding:0;}
513
+ /* editable Chat-card fields get the standard soft white (a step below the ask box); disabled/readonly keep the base colour */
514
+ #panel-chat input:not(:disabled):not([readonly]):not(#chat-msg):not([type="radio"]):not([type="checkbox"]),
515
+ #panel-chat select:not(:disabled),
516
+ #panel-chat textarea:not(:disabled):not([readonly]):not(#chat-msg){background:var(--field-soft-bg);}
517
+ /* ONE wide button below the message box; its wording comes from mainButtonFor */
518
+ .btn.wide{width:100%;margin-top:10px;white-space:normal;}
519
+ /* amendment 2 item 7: the main button's label ("Sign <hash8> & run · $<cap>") stays on ONE line inside the card */
520
+ #chat-main-btn{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;max-width:100%;}
521
+ /* fwdloop's own additions (not bareloop): input rows, per-box refusal lines, the read-only Run-mode cap */
522
+ .jf-inrow{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr) auto;gap:6px;margin-bottom:4px;align-items:start;}
523
+ .jf-inrow .btn.small{height:32px;padding:0 8px;}
524
+ .jf-inrow .jf-role-ro{padding:5px 7px;min-height:32px;overflow-wrap:anywhere;border:1px solid var(--border);background:var(--bg);color:var(--text-dim);}
525
+ .jf-inrow .jf-err{grid-column:1 / -1;}
526
+ /* M4e amendment 4/5: what a Run or a Resume cannot change shows dimmed (the signature fixes it); only the open boxes are bright */
527
+ .field.dimmed{opacity:.6;}
528
+ /* borrowed-from: bareloop src/panel/index.html@b5e37b8 — the Reuse workflow picker (search box + list, then the picked box) */
529
+ .rw-box{position:relative;margin-top:6px;}
530
+ .rw-box input{width:100%;box-sizing:border-box;}
531
+ .rw-list{list-style:none;margin:0;padding:0;border:1px solid var(--border-strong);border-top:none;background:var(--bg);max-height:220px;overflow:auto;}
532
+ .rw-list li{padding:7px 8px;border-bottom:1px dotted var(--border);cursor:pointer;}
533
+ .rw-list li:hover,.rw-list li.hl{background:var(--panel2);}
534
+ .rw-name{font-weight:700;overflow-wrap:anywhere;} .rw-name mark{background:none;color:var(--accent);text-decoration:underline;}
535
+ .rw-meta{font-size:11px;color:var(--text-dim);margin-top:2px;overflow-wrap:anywhere;}
536
+ .rw-empty{padding:7px 8px;font-size:12px;color:var(--text-dim);}
537
+ .rw-picked{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:6px;padding:6px 8px;border:1px solid var(--accent);}
538
+ .rw-picked span{overflow-wrap:anywhere;}
539
+ .rw-picked a{font-size:12px;cursor:pointer;flex:none;}
540
+ .ro-lines{padding:6px 8px;border:1px solid var(--border);background:var(--bg);color:var(--text-dim);font-size:12px;overflow-wrap:anywhere;max-height:160px;overflow-y:auto;}
541
+ .ro-lines .ro-line{display:flex;gap:8px;}
542
+ .ro-lines .ro-n{flex:none;min-width:1.4em;color:var(--text-faint);}
543
+ .jf-waitrow{margin-bottom:4px;}
544
+ .jf-err{font-size:11px;color:var(--red);margin-top:2px;overflow-wrap:anywhere;}
545
+ .jf-err:empty{display:none;}
546
+ .dest-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr);gap:6px;}
547
+ @media (max-width: 899px){
548
+ .jf-inrow{grid-template-columns:minmax(0,1fr) auto;}
549
+ .jf-inrow .jf-path{grid-column:1 / -1;order:3;}
550
+ .jf-inrow .jf-err{order:4;}
551
+ }
417
552
 
418
553
  @media (max-width: 899px){
419
554
  .main{flex-direction:column;}
@@ -465,10 +600,11 @@
465
600
  [data-testid="audit-table"] td[data-label="Step"], .audit-group table td[data-label="Step"],
466
601
  [data-testid="audit-table"] td[data-label="Verdict"], .audit-group table td[data-label="Verdict"]{display:block;}
467
602
  [data-testid="audit-table"] td[data-label="Attempt"]::before, .audit-group table td[data-label="Attempt"]::before{content:"#";}
603
+ [data-testid="audit-table"] td[data-label="Attempt"]:empty::before, .audit-group table td[data-label="Attempt"]:empty::before{content:none;}
468
604
  [data-testid="audit-table"] td.am-glyph, .audit-group table td.am-glyph{order:1;flex:0 0 auto;}
469
605
  [data-testid="audit-table"] td[data-label="Attempt"], .audit-group table td[data-label="Attempt"]{order:2;flex:0 0 auto;color:var(--text-dim);}
470
606
  [data-testid="audit-table"] td[data-label="Step"], .audit-group table td[data-label="Step"]{order:3;flex:1 1 0;overflow:hidden;text-overflow:ellipsis;}
471
- [data-testid="audit-table"] td[data-label="Verdict"], .audit-group table td[data-label="Verdict"]{order:4;flex:0 1 auto;max-width:9em;overflow:hidden;text-overflow:ellipsis;}
607
+ [data-testid="audit-table"] td[data-label="Verdict"], .audit-group table td[data-label="Verdict"]{order:4;flex:0 1 auto;max-width:9em;white-space:normal;overflow-wrap:anywhere;}
472
608
  [data-testid="audit-table"] td.am-cost, .audit-group table td.am-cost{order:5;flex:0 0 auto;}
473
609
  [data-testid="audit-table"] td.am-time, .audit-group table td.am-time{order:6;flex:0 0 auto;color:var(--text-dim);}
474
610
  /* no step cell (grouped view): the verdict takes the slack so cost and time sit at the right */
@@ -561,7 +697,7 @@
561
697
  <div class="table-wrap" data-testid="provider-table-wrap">
562
698
  <table class="pv-table" data-testid="provider-table">
563
699
  <thead>
564
- <tr><th>Key</th><th>Name</th><th>API shape</th><th>Base URL</th><th>Test</th><th>Tokens used</th><th>Balance</th><th>In $/1M</th><th>Cached in $/1M</th><th>Out $/1M</th></tr>
700
+ <tr><th>Key</th><th>Name</th><th>API shape</th><th>Base URL</th><th>Test</th><th>Tokens used</th><th>Balance</th><th>In $/1M</th><th>Out $/1M</th></tr>
565
701
  </thead>
566
702
  <tbody id="pv-rows"></tbody>
567
703
  </table>
@@ -611,13 +747,161 @@
611
747
  <div class="pane-body" id="left-pane-body">
612
748
 
613
749
  <section id="panel-chat" class="tabpanel active" role="tabpanel" aria-labelledby="tab-chat">
614
- <div class="chat-thread">
615
- Authoring a flow from this page isn't built yet — the drafter is a POC. This
616
- panel shows flows and runs already started from the
617
- <code>fwdloop</code> CLI, and lets you answer an ask that is waiting on you
618
- (accept, redo or rerun, with a reason). It cannot start a run. Use the Runs
619
- tab to open one, or the Inbox tab for anything waiting on you.
750
+ <!-- borrowed-from: bareloop src/panel/index.html@ca7195e (Chat markup: the one always-there card, top-right Abandon/Clear,
751
+ the thread, the one progress list, the action-error line the poll never wipes, the ask box, the ONE wide button).
752
+ fwdloop fields: Flow name, The job, Cap $, Destination, Inputs (New job) or a signed flow's inputs (Run a signed flow). -->
753
+ <div class="job-card compact" id="chat-job-card" data-testid="job-card">
754
+ <h4 id="job-card-title">Job card</h4>
755
+ <button class="btn card-clear" type="button" id="chat-clear-btn" data-testid="chat-clear">Clear</button>
756
+
757
+ <div class="radio-row" id="jf-mode-row" role="radiogroup" aria-label="What to do" data-testid="jf-mode">
758
+ <label><input type="radio" name="jf-mode" value="new" checked> New job</label>
759
+ <label><input type="radio" name="jf-mode" value="run"> Run a signed flow</label>
760
+ </div>
761
+
762
+ <div id="jf-new" data-testid="jf-new">
763
+ <div class="field">
764
+ <label for="jf-name">Flow name</label>
765
+ <input id="jf-name" type="text" placeholder="lowercase letters, digits, - or _" autocomplete="off" spellcheck="false" data-testid="jf-name">
766
+ <div class="jf-err" id="jf-err-flowName" data-testid="jf-err-flowName"></div>
767
+ </div>
768
+ <div class="field">
769
+ <label for="jf-job">The job</label>
770
+ <div class="jf-gutbox">
771
+ <div class="jf-gut" id="jf-job-gut" data-testid="jf-job-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
772
+ <textarea class="jf-wrap" id="jf-job" rows="6" data-testid="jf-job" autocomplete="off" spellcheck="false" placeholder="Read my resume&#10;~keep it under 600 words&#10;Ask: check it with me&#10;Write it out"></textarea>
773
+ </div>
774
+ <div class="hint">One step per line. A line starting with <code>~</code> is a guardrail of the step above it. <code>Ask:</code> stops for you; <code>Ask 2h:</code> sets that ask's own wait.</div>
775
+ <div class="jf-err" id="jf-err-job" data-testid="jf-err-job"></div>
776
+ </div>
777
+ <div class="field">
778
+ <label for="jf-dest-folder">Destination</label>
779
+ <input id="jf-dest-folder" type="text" placeholder="/full/path/to/a/folder" autocomplete="off" spellcheck="false" data-testid="jf-dest-folder">
780
+ <div class="hint">Where the accepted result is placed, at the last step. Leave empty for no send.</div>
781
+ <div class="jf-err" id="jf-err-destination" data-testid="jf-err-destination"></div>
782
+ </div>
783
+ <div class="field">
784
+ <label for="jf-inputs">Inputs</label>
785
+ <div class="jf-gutbox">
786
+ <div class="jf-gut" id="jf-inputs-gut" data-testid="jf-inputs-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
787
+ <textarea class="jf-wrap" id="jf-inputs" rows="3" data-testid="jf-inputs" autocomplete="off" spellcheck="false" placeholder="resume: /full/path/to/resume.md"></textarea>
788
+ </div>
789
+ <div class="hint">One line per file: a name, a colon, its full path starting with /. The page never reads the file.</div>
790
+ <div class="jf-err" id="jf-err-inputs" data-testid="jf-err-inputs"></div>
791
+ </div>
792
+ <div class="cap-row" data-testid="cap-row">
793
+ <div class="cap-field">
794
+ <label for="jf-cap-money">Cap $</label>
795
+ <input id="jf-cap-money" type="text" inputmode="decimal" placeholder="per run" data-testid="jf-cap-money">
796
+ <div class="hint" id="jf-cap-note" data-testid="cap-note"></div>
797
+ <div class="jf-err" id="jf-err-capUsd" data-testid="jf-err-capUsd"></div>
798
+ </div>
799
+ <div class="cap-field">
800
+ <label for="jf-ask-wait">Ask wait</label>
801
+ <input id="jf-ask-wait" type="text" value="1h" autocomplete="off" spellcheck="false" data-testid="jf-ask-wait">
802
+ <div class="hint">For each <code>Ask:</code> step. Number + m or h.</div>
803
+ <div class="jf-err" id="jf-err-askWait" data-testid="jf-err-askWait"></div>
804
+ </div>
805
+ </div>
806
+ </div>
807
+
808
+ <div id="jf-run" data-testid="jf-run" hidden>
809
+ <div class="field">
810
+ <label for="jf-run-flow">Signed flow</label>
811
+ <!-- borrowed-from: bareloop src/panel/index.html@b5e37b8 (its job picker): a search box over the list, then the picked box with `change` -->
812
+ <div class="rw-box" id="rw-search" data-testid="rw-search">
813
+ <input id="jf-run-flow" type="text" placeholder="type part of a flow or run name (run-2)…" autocomplete="off" spellcheck="false" data-testid="jf-run-flow">
814
+ <ul class="rw-list" id="rw-list" data-testid="rw-list"></ul>
815
+ </div>
816
+ <div class="rw-picked" id="rw-picked" data-testid="rw-picked" hidden><span id="rw-picked-txt" data-testid="rw-picked-txt"></span><a id="rw-change" data-testid="rw-change" role="button" tabindex="0">change</a></div>
817
+ <div class="hint" id="jf-run-empty" data-testid="jf-run-empty"></div>
818
+ <div class="jf-err" id="jf-err-flow" data-testid="jf-err-flow"></div>
819
+ </div>
820
+ <div class="field dimmed" data-testid="jf-run-job-field">
821
+ <label>The job</label>
822
+ <div class="ro-lines" id="jf-run-job" data-testid="jf-run-job"></div>
823
+ <div class="hint">Fixed by the signature (the steps, the job lines and the asks). To change one, start a new job.</div>
824
+ </div>
825
+ <div class="field">
826
+ <label for="jf-run-dest">Destination</label>
827
+ <input id="jf-run-dest" type="text" placeholder="/full/path/to/a/folder" autocomplete="off" spellcheck="false" data-testid="jf-run-dest">
828
+ <div class="hint" id="jf-run-dest-hint" data-testid="jf-run-dest-hint"></div>
829
+ <div class="jf-err" id="jf-err-run-destination" data-testid="jf-err-run-destination"></div>
830
+ </div>
831
+ <div class="field">
832
+ <label>Inputs</label>
833
+ <div id="jf-run-inputs" data-testid="jf-run-inputs"></div>
834
+ <div class="jf-err" id="jf-err-run-inputs" data-testid="jf-err-run-inputs"></div>
835
+ </div>
836
+ <div class="cap-row">
837
+ <div class="cap-field">
838
+ <label for="jf-run-cap">Cap $</label>
839
+ <input id="jf-run-cap" type="text" inputmode="decimal" autocomplete="off" data-testid="jf-run-cap">
840
+ <div class="hint" id="jf-run-left" data-testid="jf-run-left"></div>
841
+ <div class="jf-err" id="jf-err-run-capUsd" data-testid="jf-err-run-capUsd"></div>
842
+ </div>
843
+ <div class="cap-field" id="jf-run-waits" data-testid="jf-run-waits"></div>
844
+ </div>
845
+ <div class="jf-err" id="jf-err-run-askWaits" data-testid="jf-err-run-askWaits"></div>
846
+ <div class="hint" id="jf-run-sign-hint" data-testid="jf-run-sign-hint">A different destination, cap or ask wait is signed for this run only: two clicks. The flow's own values never change.</div>
847
+ <div class="field">
848
+ <label for="jf-run-id">Run id</label>
849
+ <input id="jf-run-id" type="text" autocomplete="off" spellcheck="false" data-testid="jf-run-id">
850
+ <div class="jf-err" id="jf-err-runId" data-testid="jf-err-runId"></div>
851
+ </div>
852
+ </div>
853
+
854
+ <div id="jf-resume" data-testid="jf-resume" hidden>
855
+ <div class="field dimmed" data-testid="jf-resume-job-field">
856
+ <label>The job</label>
857
+ <div class="ro-lines" id="jf-resume-job" data-testid="jf-resume-job"></div>
858
+ </div>
859
+ <div class="field dimmed">
860
+ <label>Destination</label>
861
+ <div class="ro-lines" id="jf-resume-dest" data-testid="jf-resume-dest"></div>
862
+ </div>
863
+ <div class="field dimmed">
864
+ <label>Inputs</label>
865
+ <div class="ro-lines" id="jf-resume-inputs" data-testid="jf-resume-inputs"></div>
866
+ </div>
867
+ <div class="field dimmed">
868
+ <label>Ask wait</label>
869
+ <div class="ro-lines" id="jf-resume-waits" data-testid="jf-resume-waits"></div>
870
+ </div>
871
+ <div class="cap-row">
872
+ <div class="cap-field">
873
+ <label for="jf-resume-cap">Cap $</label>
874
+ <input id="jf-resume-cap" type="text" inputmode="decimal" autocomplete="off" data-testid="jf-resume-cap">
875
+ <div class="hint" id="jf-resume-left" data-testid="jf-resume-left"></div>
876
+ <div class="jf-err" id="jf-err-resume-capUsd" data-testid="jf-err-resume-capUsd"></div>
877
+ </div>
878
+ </div>
879
+ <div class="hint" id="jf-resume-hint" data-testid="jf-resume-hint"></div>
880
+ </div>
881
+
882
+ <div class="hint" id="chat-card-error" data-testid="chat-card-error"></div>
620
883
  </div>
884
+
885
+ <!-- ONE progress list: every step is one line that updates in place; a waiting step has no check -->
886
+ <ol class="chat-steps" id="chat-progress-row" data-testid="chat-steps" aria-live="polite" hidden></ol>
887
+
888
+ <!-- M4e amendment 6 item 3: bubbles (oldest first), then the current plan, then the note box and the main button: the plan sits next to Sign & run -->
889
+ <div class="chat-thread" id="chat-thread" data-testid="chat-thread"></div>
890
+
891
+ <!-- a refused draft / run / sign / abandon POST (or a refused start) shows here and STAYS: set only by this tab's own
892
+ action handlers, never cleared by the poll (the poll owns #chat-card-error instead) -->
893
+ <div class="hint" id="chat-action-error" data-testid="chat-action-error"></div>
894
+
895
+ <!-- M4e amendment 3 item 3: opens when a green plan shows (bareloop's ask box); a typed note turns the main button into Send -->
896
+ <div class="chat-input-row" id="chat-msg-row" data-testid="chat-msg-row" hidden>
897
+ <label for="chat-msg" style="display:none">Message</label>
898
+ <textarea id="chat-msg" rows="2" placeholder="Ask for a change to the plan" autocomplete="off" data-testid="chat-msg"></textarea>
899
+ </div>
900
+ <button class="btn primary wide" type="button" id="chat-main-btn" data-testid="chat-main" disabled>Draft</button>
901
+ <div class="hint" id="chat-main-hint" data-testid="chat-main-hint"></div>
902
+ <!-- M4e amendment 4 item 3: after the second change the ask box is closed; Start over drafts again from the card as it is (a fresh draft) -->
903
+ <button class="btn wide" type="button" id="chat-startover-btn" data-testid="chat-startover" hidden>Start over</button>
904
+ <div class="hint">Only your click signs.</div>
621
905
  </section>
622
906
 
623
907
  <section id="panel-inbox" class="tabpanel" role="tabpanel" aria-labelledby="tab-inbox" hidden>
@@ -668,6 +952,7 @@
668
952
  <section id="panel-run" class="tabpanel active" role="tabpanel" aria-labelledby="tab-run">
669
953
  <div id="run-empty" class="hint" style="font-size:13px;padding:24px 0;">select a run from Workflows or History</div>
670
954
  <div id="run-content" hidden>
955
+ <div class="run-actions" id="run-actions" data-testid="run-actions" hidden></div>
671
956
  <div class="counters" id="run-counters" data-testid="live-counters"></div>
672
957
  <div class="summary-box" id="run-summary" data-testid="run-summary"></div>
673
958
  <div class="map-box" data-testid="step-map" id="map-box"><div id="map-mount"></div></div>
@@ -724,7 +1009,7 @@
724
1009
  piece within a field — replaces the old split asks/sends/
725
1010
  sources/signed-lines blocks. Field order (signed): Job
726
1011
  (prose) · Ask · Model · $ cap (+ redo cap) · Source ·
727
- Destination · Guardrails · Success · Signed. At 390px every
1012
+ Destination · Success · Signed (M4e amendment 6: each guardrail sits under its own line in Job). At 390px every
728
1013
  field's own `label` already sits above its value (the
729
1014
  existing global `label{display:block}` rule — no separate
730
1015
  narrow-width override needed). -->
@@ -737,7 +1022,6 @@
737
1022
  <div class="field"><label>Ask</label><div id="details-asks"></div></div>
738
1023
  <div class="field"><label>Source</label><div id="details-sources"></div></div>
739
1024
  <div class="field"><label>Destination</label><div id="details-sends"></div></div>
740
- <div class="field"><label>Guardrails</label><div id="details-guardrails"></div></div>
741
1025
  <div class="field"><label>Success</label><div id="details-success"></div></div>
742
1026
  <div class="field"><label>Signed</label><div class="ro-value" id="details-signature">—</div></div>
743
1027
  </div>
@@ -775,8 +1059,7 @@
775
1059
  "use strict";
776
1060
 
777
1061
  var PORT = "__FWDLOOP_PANEL_PORT__";
778
- // M4c-fix item 2: the page carries NO token. The panel link sets an HttpOnly cookie; every
779
- // request (reads and the two POSTs) is authenticated by that cookie, sent by the browser itself.
1062
+ // No token, no cookie (M4e amendment 4 item 8): the panel is local and trusted; the server checks Host and, on a POST, Origin.
780
1063
  document.getElementById("host-line").textContent = "127.0.0.1:" + PORT;
781
1064
 
782
1065
  function wireTabs(tabButtons){
@@ -799,8 +1082,8 @@
799
1082
 
800
1083
  // ---- fetch helpers. Reads are GET. The ONLY non-GET requests on this page are
801
1084
  // the two POSTs below (M4b): /api/answer (a human clicking a door) and
802
- // /api/resume ("try the resume again"). Auth is the HttpOnly cookie
803
- // (never the DOM, a URL, storage or a log). Same-origin. ----
1085
+ // /api/resume ("try the resume again"). No auth header (the server checks Host and
1086
+ // Origin). Same-origin. ----
804
1087
  function getJSON(path){
805
1088
  return fetch(path, { method: "GET", headers: { accept: "application/json" } }).then(function(r){
806
1089
  if(!r.ok){ var err = new Error(path + ": HTTP " + r.status); err.status = r.status; throw err; }
@@ -811,7 +1094,7 @@
811
1094
  // message (it carries the path and the HTTP code), never a status number.
812
1095
  function loadFailureText(e){
813
1096
  var status = e && e.status;
814
- if(status === 403) return "The panel does not recognise this page. Open the link the terminal printed.";
1097
+ if(status === 403) return "The panel does not recognise this page. Reload it.";
815
1098
  if(status === 404) return "This run is no longer there.";
816
1099
  return "Could not load this; reload the page.";
817
1100
  }
@@ -854,7 +1137,15 @@
854
1137
  // recorded" in that middle slot instead of a number; a row with no model
855
1138
  // call at all (an ask/hitl row) drops the tokens slot entirely — never a
856
1139
  // fake "0 tokens".
1140
+ // a Sign & run row's ask waits read through plainWait (same as the Job tab); every other row's gap is as recorded
1141
+ function auditGapText(r){
1142
+ if(!Array.isArray(r.gapWaits) || !r.gapWaits.length) return r.gap || "";
1143
+ var waits = r.gapWaits.map(function(w){ return "line " + w.line + ": " + (typeof w.waitMs === "number" ? plainWait(w.waitMs) : w.wait); }).join(", ");
1144
+ return (r.gapHead || []).concat(["ask waits " + waits]).join(" · ");
1145
+ }
857
1146
  function auditCostCellText(r){
1147
+ if(r.setup && typeof r.usd !== "number" && r.verdict === "hitl") return "—"; // a setup row you wrote (card, note, sign) has no cost
1148
+ if(r.setup) return money(r.usd, r.spendComplete) + (typeof r.wallMs === "number" ? " \u00b7 " + duration(r.wallMs) : ""); // a draft/change row: its own booked cost ("unknown" when nobody booked it) and time (left out when not recorded)
858
1149
  var bits = [money(r.usd, r.spendComplete)];
859
1150
  var td = r.tokensDisplay;
860
1151
  if(td && td.kind === "total") bits.push(td.total + " tokens");
@@ -905,6 +1196,76 @@
905
1196
  if(m >= 1 && Number.isInteger(m)) return m + " min";
906
1197
  return duration(ms);
907
1198
  }
1199
+ // M4e amendment 7 item 7 (hamr's ruling 2026-10-06): the second line of a Signed flow row — bareloop's reuse-estimate shape
1200
+ // (borrowed-from: bareloop src/panel/server.js@1927350 `reuseLine`) with fwdloop's own first part. What is unknown is said, never
1201
+ // rendered as $0 or 0 time; the money and the time go through the page's one money() and duration().
1202
+ function countWord(n, word){ return n + " " + word + (n === 1 ? "" : "s"); }
1203
+ function flowStatLine(f){
1204
+ var s = (f && f.stats) || {};
1205
+ var head = countWord(s.steps || 0, "step") + " · " + countWord(s.asks || 0, "ask") + " · " + (s.green || 0) + " green · " + (s.notGreen || 0) + " not green";
1206
+ var cost = typeof s.avgSpendUsd === "number" ? money(s.avgSpendUsd) : null;
1207
+ var time = typeof s.avgWallMs === "number" ? duration(s.avgWallMs) : null;
1208
+ if(cost !== null && time !== null) return head + " · about " + cost + " and " + time + " a run";
1209
+ if(cost !== null) return head + " · about " + cost + " a run, time not recorded";
1210
+ if(time !== null) return head + " · about " + time + " a run, cost not recorded";
1211
+ return head + " · cost and time not recorded";
1212
+ }
1213
+ // The rows the Signed flow search shows for what is typed: a flow whose name has the text; and, for any text, each passed run whose
1214
+ // name has it (`run-2` lists every flow's run-2 as "<flow> (run-2)"; typing the whole "<flow> (run-2)" finds it too). Empty text = every flow.
1215
+ function flowChoices(flows, text){
1216
+ var q = String(text || "").trim().toLowerCase();
1217
+ var out = [];
1218
+ (flows || []).forEach(function(f){
1219
+ if(q === "" || f.flow.toLowerCase().indexOf(q) !== -1) out.push({flow: f.flow, runId: null, label: f.flow, meta: flowStatLine(f)});
1220
+ });
1221
+ if(q !== ""){
1222
+ (flows || []).forEach(function(f){
1223
+ (f.runs || []).forEach(function(r){
1224
+ var label = f.flow + " (" + r.runId + ")";
1225
+ if(r.runId.toLowerCase().indexOf(q) !== -1 || (q.indexOf("(") !== -1 && label.toLowerCase().indexOf(q) !== -1)) out.push({flow: f.flow, runId: r.runId, label: label, meta: flowStatLine(f)});
1226
+ });
1227
+ });
1228
+ }
1229
+ return out;
1230
+ }
1231
+ // M4e amendment 9: the model-calls words, ONE function for the card's line 2 and the Audit header: `<n> model calls` (`1 model call`), `at least <n> model calls`
1232
+ // when a draft/change row recorded no `calls` (it counts 1), `calls unknown` with no model row.
1233
+ function draftCallsWord(d){
1234
+ if(typeof d.calls !== "number") return "calls unknown";
1235
+ return (d.callsAtLeast ? "at least " : "") + countWord(d.calls, "model call");
1236
+ }
1237
+ // M4e amendment 7 item 2 / 9: the Draft's one line in the Audit group's header: `drafting · <time> · $<cost> · <n> model calls · ✓`.
1238
+ // `d` is the server's one Draft summary (src/panel/data.js `draftTotals`): a figure not recorded reads "unknown", never 0; a flow signed before
1239
+ // amendment 6 reads "no draft record" and no cost.
1240
+ // The Draft's three figures, ONE function for the card's line 2, the Audit header and its aria: `<time> · $<cost> · <n> model calls`.
1241
+ function draftFigures(d){
1242
+ return [typeof d.timeMs === "number" ? duration(d.timeMs) : "time unknown", d.cost || "cost unknown", draftCallsWord(d)];
1243
+ }
1244
+ // M4e amendment 11: the human-checks words, ONE function for the drafting card's line 2 and the Audit Draft header (`1 human check`, `2 human checks`).
1245
+ function draftHumanWord(d){
1246
+ return typeof d.humanChecks === "number" ? countWord(d.humanChecks, "human check") : "human checks unknown";
1247
+ }
1248
+ // M4e amendment 10 item 2: with the step card's status first: `[✓] passed · drafting · <time> · $<cost> · <n> model calls ✓` (signed), `not signed · drafting · ...`
1249
+ // plain (no sign row, no mark), `drafting · no draft record` (no draft record, no status). The Audit header's visible words come from the same
1250
+ // `auditGroupHeaderParts`, so this is the aria line too.
1251
+ function draftLineText(d){
1252
+ var p = auditGroupHeaderParts({draft: true, summary: d});
1253
+ return [p.status, p.name].concat(p.draftFigs || [p.why]).filter(function(x){ return x; }).join(" \u00b7 ") + (p.passed ? " \u2713" : "");
1254
+ }
1255
+ // M4e amendment 9: the drafting card, step 0 of the Run tab, from ONE function: `title` (`0 · drafting`, bold h4), `status` (the step card's `stateWord`: `[✓] passed`
1256
+ // with a sign row, plain `not signed` without; none for a flow with no draft record), then `lines`: `<time> · $<cost> · <n> model calls · <h> human checks · ✓`
1257
+ // (a figure not recorded reads unknown, never 0; the mark only on passed) and what happened (`d.happened`, joined by ` · `). Same `draftTotals` as the Audit header.
1258
+ function draftCardLines(d){
1259
+ if(!d || !d.present) return {title: "0 \u00b7 drafting", status: null, passed: false, lines: [(d && d.why) || "no draft record"]};
1260
+ var passed = d.ended === "done";
1261
+ var figs = draftFigures(d).concat([draftHumanWord(d)]);
1262
+ if(passed) figs.push("\u2713");
1263
+ return {title: "0 \u00b7 drafting", status: passed ? stateWord("done") : "not signed", passed: passed, lines: [figs.join(" \u00b7 "), (d.happened || []).join(" \u00b7 ")]};
1264
+ }
1265
+ // The Map's first box: the Draft, then step 1. A box with no audit attempts of its own; its state word says "no draft record" when there is none.
1266
+ function draftBox(d){
1267
+ return {draft: true, emits: "drafting", goal: "", closeClass: null, primitives: [], attempts: [], tryCount: 0, tryMarks: [], state: d && d.present ? "done" : "pending", noRecord: !(d && d.present), n: 0};
1268
+ }
908
1269
  // A readable local date/time instead of a raw ISO timestamp (fix #5) — an
909
1270
  // unparseable value still shows the raw string (never blank/nothing), so
910
1271
  // a books bug is visible rather than silently swallowed.
@@ -923,7 +1284,7 @@
923
1284
  // M4c-fix amendment 2 (g): a step's own sign + word come from the SAME one table the run rows use (the server's
924
1285
  // SIGN_WORDS, sent on the run detail as `signWords`); the page keeps no table of its own. Not started: no sign.
925
1286
  var signWords = {};
926
- var STEP_SIGN = { done: "[\u2713]", stopped: "[\u2717]", waiting: "[\u00b7]" };
1287
+ var STEP_SIGN = { done: "[\u2713]", stopped: "[\u2717]", waiting: "[\u00b7]", "user-stopped": "[\u25a0]" };
927
1288
  function stateWord(state){
928
1289
  if(state === "pending") return "not started";
929
1290
  var g = STEP_SIGN[state];
@@ -990,6 +1351,9 @@
990
1351
  if(verdict === "ask-timeout" || verdict === "ask-expired") return "expired waiting for you";
991
1352
  if(verdict === "ask-reopened") return "reopened by you";
992
1353
  if(verdict === "lock-removed") return "old lock removed by you";
1354
+ if(verdict === "stop-asked") return "stop asked by you";
1355
+ if(verdict === "stopped") return "stopped by you";
1356
+ if(verdict === "stop-not-honoured") return "stop not honoured";
993
1357
  if(verdict === "green") return "passed";
994
1358
  if(verdict === "hitl") return "human check";
995
1359
  if(verdict === "not-done") return "not done";
@@ -1003,6 +1367,7 @@
1003
1367
  function verdictGlyph(verdict, closeClass){
1004
1368
  if(closeClass === "hitl" && verdict === "red") return null;
1005
1369
  if(verdict === "paused" || verdict === "refused" || verdict === "ask-timeout" || verdict === "ask-expired" || verdict === "ask-reopened" || verdict === "lock-removed") return null;
1370
+ if(verdict === "stop-asked" || verdict === "stopped" || verdict === "stop-not-honoured") return null; // amendment 7 item 8: a Stop is neither a pass nor a failure
1006
1371
  return verdictPassed(verdict) ? "✓" : "✗";
1007
1372
  }
1008
1373
  // The run-row glyph strings src/panel/data.js's computeGlyph emits are
@@ -1030,6 +1395,7 @@
1030
1395
  // (never "amber", which draws the reserved running arrow [▶]).
1031
1396
  if(g === "[!]") return "expired";
1032
1397
  if(g === "[II]") return "stuck";
1398
+ if(g === "[■]") return "stopped";
1033
1399
  return "grey"; // "[·]" — waiting on a human, or answered-not-resumed
1034
1400
  }
1035
1401
 
@@ -1041,6 +1407,7 @@
1041
1407
  if(state === "done") return {stroke:"var(--green)", textFill:"#2e7d32"};
1042
1408
  if(state === "stopped") return {stroke:"var(--red)", textFill:"var(--red)"};
1043
1409
  if(state === "waiting") return {stroke:"var(--amber)", textFill:"#b8860b"};
1410
+ if(state === "user-stopped") return {stroke:"var(--grey-dot)", textFill:"var(--grey-dot)"}; // a Stop the human asked: grey, never red
1044
1411
  return {stroke:"var(--border-strong)", textFill:"var(--text-faint)"}; // not started yet
1045
1412
  }
1046
1413
  var stepMapUidCounter = 0;
@@ -1075,24 +1442,14 @@
1075
1442
  // step number + name + try N + state, kept short so naturalBoxWidth stays
1076
1443
  // small and the map stays compact instead of stretching to the pane width.
1077
1444
  function stepTitleText(idx, s){
1078
- var base = (idx + 1) + ' ' + s.emits;
1445
+ if(s.draft) return "drafting";
1446
+ var base = (s.n || idx + 1) + ' ' + s.emits;
1079
1447
  var tryText = tryCountText(s.tryCount, s.attempts);
1080
1448
  if(tryText) base += ' — ' + tryText;
1081
1449
  return base;
1082
1450
  }
1083
- // The declared step's own run-state, for the map box and the summary's
1084
- // "which step stopped and why" (M4a exit: "say which step stopped it and
1085
- // why, from one screen"): `pending` (no attempt yet), `done` (last
1086
- // attempt passed), `waiting` (the run is currently parked ON this step —
1087
- // its last attempt's verdict is `paused`/`refused`, i.e. it went to a
1088
- // human ask and hasn't been answered/resolved yet), `stopped` (a real
1089
- // stop — the last attempt failed for any other reason).
1090
- function stepBoxState(s){
1091
- if(!s.attempts || !s.attempts.length) return "pending";
1092
- var last = s.attempts[s.attempts.length - 1];
1093
- if(last.verdict === "paused" || last.verdict === "refused") return "waiting";
1094
- return verdictPassed(last.verdict) ? "done" : "stopped";
1095
- }
1451
+ // The declared step's own run-state (map box, card, "which step stopped and why") is the server's `groupState` (src/panel/data.js
1452
+ // `deriveStepGroupState`, M4e amendment 10: the one decider): `pending` (no row yet), `done`, `waiting`, `stopped` (red), `user-stopped` (a Stop).
1096
1453
  // hamr's 2026-09-27 review: a step with a server-computed `tryCount > 1`
1097
1454
  // (M2/M3's runner already counts retries/redraft attempts honestly — never
1098
1455
  // recounted here from `attempts.length`, which double-counts an ask step's
@@ -1121,7 +1478,7 @@
1121
1478
  // book-derived list, never guessed from `primitives` by exclusion.
1122
1479
  toolsTotal: s.toolsTotal || null, toolsWhy: s.toolsWhy || null, ungranted: s.ungranted || [],
1123
1480
  stoppedReason: s.stoppedReason || null,
1124
- state: stepBoxState(s),
1481
+ state: s.groupState || "pending", // the server's one decider (deriveStepGroupState); no group = no row yet = not started
1125
1482
  };
1126
1483
  });
1127
1484
  }
@@ -1220,7 +1577,7 @@
1220
1577
  '" text-anchor="middle" font-size="12" fill="var(--text)">' + escapeXml(lines[1]) + '</text>';
1221
1578
  }
1222
1579
  body += '<text x="' + (x + boxW / 2) + '" y="' + stateY +
1223
- '" text-anchor="middle" font-size="10" fill="' + colors.textFill + '">' + escapeXml(stateWord(s.state)) + '</text>';
1580
+ '" text-anchor="middle" font-size="10" fill="' + colors.textFill + '">' + escapeXml(s.noRecord ? "no draft record" : stateWord(s.state)) + '</text>';
1224
1581
  body += '</g>';
1225
1582
  // hamr's 2026-09-27 retry-loop review: a step whose server-computed
1226
1583
  // tryCount is >1 gets a dashed grey self-loop under its box, labelled
@@ -1321,7 +1678,8 @@
1321
1678
  // Workflows view's per-flow expansion — the two never drift on how a run
1322
1679
  // row reads. Rekeyed from bareloop's job/runid to fwdloop's flow/runId
1323
1680
  // (GET /api/runs row shape: src/panel/data.js's listRuns).
1324
- function buildRunRowEl(r){
1681
+ // opts.sub (amendment 12): a Workflows sub-card drops the flow name from its visible text; no other caller passes opts.
1682
+ function buildRunRowEl(r, opts){
1325
1683
  var row = document.createElement("div");
1326
1684
  // Selected state is computed here, off the module's own `currentRunId`,
1327
1685
  // so a row freshly built by a RE-RENDER (switching Runs view mode, or a
@@ -1346,14 +1704,21 @@
1346
1704
  row.removeAttribute("role");
1347
1705
  return row;
1348
1706
  }
1349
- row.innerHTML =
1350
- '<span class="wf-line1"><span class="' + dotClass(r.glyph, r.pulse) + '"></span>' +
1351
- '<span class="wf-name" title="' + escapeXml(fullName) + '">' + escapeXml(fullName) + '</span></span>' +
1352
- '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(r.word, r.line, r.label) + '</span>' +
1353
- '<span class="wf-meta-line">' +
1354
- '<span class="wf-meta">' + escapeXml(runSpendText(r)) + '</span>' +
1355
- '<span class="wf-meta">' + escapeXml(runAtText(r)) + '</span>' +
1356
- '</span>';
1707
+ if(opts && opts.sub){
1708
+ // amendment 12: line 1 `(run-<n>) <word> — <label>`; the flow name stays in title/aria only
1709
+ row.setAttribute("aria-label", fullName);
1710
+ row.innerHTML =
1711
+ '<span class="wf-line1"><span class="' + dotClass(r.glyph, r.pulse) + '"></span>' +
1712
+ '<span class="wf-name" title="' + escapeXml(fullName) + '">(' + escapeXml(r.runId) + ')</span> ' +
1713
+ '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(r.word, (r.word === 'passed' && r.glyph === '[✓]' && !r.line) ? 'goal met' : r.line, r.label) + '</span></span>' +
1714
+ runMetaLineHtml(r, null);
1715
+ } else {
1716
+ row.innerHTML =
1717
+ '<span class="wf-line1"><span class="' + dotClass(r.glyph, r.pulse) + '"></span>' +
1718
+ '<span class="wf-name" title="' + escapeXml(fullName) + '">' + escapeXml(fullName) + '</span></span>' +
1719
+ '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(r.word, r.line, r.label) + '</span>' +
1720
+ runMetaLineHtml(r, null);
1721
+ }
1357
1722
  row.addEventListener("click", function(){ openRunFromRuns(r, row); });
1358
1723
  row.addEventListener("keydown", function(e){ if(e.key === "Enter" || e.key === " "){ e.preventDefault(); row.click(); } });
1359
1724
  return row;
@@ -1409,6 +1774,16 @@
1409
1774
  function runSpendText(r){
1410
1775
  return r.spend || r.spendWhy || "unknown";
1411
1776
  }
1777
+ // M4e amendment 7 item 5: a run's wall time in plain units ("6m23s"), the ONE formatter (`duration`); unrecorded = no part, never a made-up one.
1778
+ function runWallText(r){
1779
+ return typeof r.wallMs === "number" ? duration(r.wallMs) : null;
1780
+ }
1781
+ // ONE builder for a Runs card's last line, job card and sub-card alike: "$0.0616 · 6m23s · 2026-10-06 · 1 run". The separators are real
1782
+ // text between the parts (a CSS ::before is not text: a text read of the card ran "2026-10-061 run" together).
1783
+ function runMetaLineHtml(r, extra){
1784
+ var bits = [runSpendText(r), runWallText(r), runAtText(r), extra].filter(function(b){ return b !== null && b !== undefined; });
1785
+ return '<span class="wf-meta-line">' + bits.map(function(b){ return '<span class="wf-meta">' + escapeXml(b) + '</span>'; }).join('<span class="wf-sep"> · </span>') + '</span>';
1786
+ }
1412
1787
  function runAtText(r){
1413
1788
  return r.at ? r.at.slice(0,10) : (r.askedAt ? "asked " + readableDateTime(r.askedAt) : (r.startedAt ? "started " + readableDateTime(r.startedAt) : (r.atWhy || "unknown")));
1414
1789
  }
@@ -1535,11 +1910,7 @@
1535
1910
  '<span class="wf-line1"><span class="wf-caret">' + (hasOtherRuns ? (expanded ? "▼" : "▶") : "") + '</span><span class="' + dotClass(g.lastGlyph, g.lastRow.pulse) + '"></span>' +
1536
1911
  '<span class="wf-name" title="' + escapeXml(wfFullName) + '">' + escapeXml(wfFullName) + '</span></span>' +
1537
1912
  '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(g.lastRow.word, g.lastRow.line, g.lastLabel) + '</span>' +
1538
- '<span class="wf-meta-line">' +
1539
- '<span class="wf-meta">' + escapeXml(runSpendText(g.lastRow)) + '</span>' +
1540
- '<span class="wf-meta">' + escapeXml(runAtText(g.lastRow)) + '</span>' +
1541
- '<span class="wf-meta">' + g.runCount + ' run' + (g.runCount === 1 ? '' : 's') + '</span>' +
1542
- '</span>';
1913
+ runMetaLineHtml(g.lastRow, g.runCount + ' run' + (g.runCount === 1 ? '' : 's'));
1543
1914
  row.addEventListener("click", function(){
1544
1915
  // a single-run flow has nothing to expand — the click still opens
1545
1916
  // the run, it just never toggles `wfExpanded` for it.
@@ -1553,7 +1924,7 @@
1553
1924
  if(expanded){
1554
1925
  var runsWrap = document.createElement("div");
1555
1926
  runsWrap.className = "wf-runs";
1556
- childRuns.forEach(function(r){ runsWrap.appendChild(buildRunRowEl(r)); });
1927
+ childRuns.forEach(function(r){ runsWrap.appendChild(buildRunRowEl(r, { sub: true })); });
1557
1928
  wrap.appendChild(runsWrap);
1558
1929
  }
1559
1930
  el.appendChild(wrap);
@@ -1575,6 +1946,7 @@
1575
1946
  '<div class="chips" role="group" aria-label="Filter">' +
1576
1947
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[✓]" title="passed" data-testid="chip-' + scope + '-res-pass">✓</button>' +
1577
1948
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[✗]" title="stopped" data-testid="chip-' + scope + '-res-fail">✗</button>' +
1949
+ '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[■]" title="stopped, can be resumed" data-testid="chip-' + scope + '-res-stopped">■</button>' +
1578
1950
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[·]" title="waiting on a human" data-testid="chip-' + scope + '-res-waiting">&middot;</button>' +
1579
1951
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[▶]" title="running" data-testid="chip-' + scope + '-res-running">▶</button>' +
1580
1952
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[?]" title="died or unknown" data-testid="chip-' + scope + '-res-unknown">?</button>' +
@@ -1846,10 +2218,13 @@
1846
2218
  '<div class="summary-row" data-testid="summary-close"><span class="sum-label">close:</span><span class="sum-val">' + escapeXml(closeText) + '</span></div>' +
1847
2219
  '<div class="summary-row" data-testid="summary-spend"><span class="sum-label">spend:</span><span class="sum-val">' + spendSummaryText(detail.spendSummary) + '</span></div>';
1848
2220
 
1849
- renderStepMap(stepBoxes);
2221
+ renderRunActions(detail);
2222
+ // amendment 7 item 2: the Draft is the first box of the Map (an arrow runs on to step 1); the steps keep their own numbers
2223
+ renderStepMap(stepBoxes.length ? [draftBox(detail.draft)].concat(stepBoxes.map(function(b, i){ return Object.assign({}, b, {n: i + 1}); })) : stepBoxes);
1850
2224
 
1851
2225
  var listEl = document.getElementById("step-list");
1852
2226
  listEl.innerHTML = "";
2227
+ if(stepBoxes.length) listEl.appendChild(buildDraftCardEl(detail.draft));
1853
2228
  stepBoxes.forEach(function(box, idx){
1854
2229
  var card = document.createElement("div");
1855
2230
  card.className = "step-card" + (box.state === "waiting" ? " running" : "");
@@ -1883,6 +2258,51 @@
1883
2258
  listEl.appendChild(card);
1884
2259
  });
1885
2260
  }
2261
+ // M4e amendment 4 item 4: the Run tab's top action row. Stop shows only while the server says the run is running or waiting at its ask
2262
+ // (`detail.controls.canStop`, the same decision the door reads; amendment 13) and reads "stopping after this step…" once asked;
2263
+ // Resume shows on a stopped or cap-halted run. The server is the arbiter: a refusal is shown in its own words.
2264
+ var stopSay = null;
2265
+ // Walk fix 4: after Sign & resume click 2 is accepted the run is still "stopped" for a few seconds. `window.fwdloopResuming`
2266
+ // ({key, at}, set by the Chat card, the one writer) keeps Resume from being offered again until a detail read shows the run live or
2267
+ // ended (canResume false), or the start was refused, or 30 s pass (a child that died leaves the run stopped; Resume must come back).
2268
+ var RESUMING_MAX_MS = 30000;
2269
+ function resumeWaiting(m, key, canResume, now){
2270
+ return !!m && m.key === key && canResume && now - m.at < RESUMING_MAX_MS;
2271
+ }
2272
+ function renderRunActions(detail){
2273
+ var el = document.getElementById("run-actions");
2274
+ var c = detail.controls || {};
2275
+ el.innerHTML = "";
2276
+ // amendment 7 item 6: Run again sits first, with Stop and Resume — every run control in this one row
2277
+ el.appendChild(makeButton("Run again", "run-again", function(){ if(window.fwdloopRunAgain) window.fwdloopRunAgain(detail); }));
2278
+ if(stopSay && stopSay.key !== detail.flow + "/" + detail.runId) stopSay = null;
2279
+ if(c.canStop){
2280
+ var stopBtn = makeButton(c.stopRequested ? "stopping after this step\u2026" : "Stop", "run-stop", function(){
2281
+ stopBtn.disabled = true;
2282
+ postJSON("/api/stop", { flow: detail.flow, runId: detail.runId }).then(function(r){
2283
+ if(r.status === 202 && r.body && r.body.ok){ stopSay = null; }
2284
+ else { stopSay = { key: detail.flow + "/" + detail.runId, text: (r.body && r.body.say) || "The run could not be stopped." }; }
2285
+ return reloadRun(detail.flow, detail.runId);
2286
+ }).catch(function(){
2287
+ stopSay = { key: detail.flow + "/" + detail.runId, text: networkText() };
2288
+ return reloadRun(detail.flow, detail.runId);
2289
+ });
2290
+ });
2291
+ stopBtn.disabled = !!c.stopRequested;
2292
+ el.appendChild(stopBtn);
2293
+ }
2294
+ var runKey = detail.flow + "/" + detail.runId;
2295
+ if(window.fwdloopResuming && window.fwdloopResuming.key === runKey && !c.canResume) window.fwdloopResuming = null;
2296
+ if(resumeWaiting(window.fwdloopResuming, runKey, !!c.canResume, Date.now())){
2297
+ var rb = makeButton("resuming\u2026", "run-resuming", function(){});
2298
+ rb.disabled = true;
2299
+ el.appendChild(rb);
2300
+ } else if(c.canResume){
2301
+ el.appendChild(makeButton("Resume", "run-resume", function(){ if(window.fwdloopOpenResume) window.fwdloopOpenResume(detail); }));
2302
+ }
2303
+ if(stopSay){ var m = document.createElement("div"); m.className = "answer-msg refused"; m.setAttribute("data-testid", "run-stop-say"); m.textContent = stopSay.text; el.appendChild(m); }
2304
+ el.hidden = el.children.length === 0;
2305
+ }
1886
2306
  // A plain lower-case, non-bold data line (hamr's 2026-09-27 styling
1887
2307
  // ruling: only the header is upper case/bold) — every non-header line on
1888
2308
  // a step card is built through this ONE helper so none of them can drift
@@ -1894,6 +2314,35 @@
1894
2314
  div.textContent = text;
1895
2315
  return div;
1896
2316
  }
2317
+ // M4e amendment 9: the first card under the Map, shaped like a step card: head `0 · drafting` (bold h4) + status (`draftCardLines`), then its two lines; the rows
2318
+ // stay in Audit → Draft. A click opens the Audit tab on that group, like a step card's.
2319
+ function buildDraftCardEl(d){
2320
+ var card = document.createElement("div");
2321
+ card.className = "step-card";
2322
+ card.setAttribute("data-testid", "step-card-draft");
2323
+ var c = draftCardLines(d);
2324
+ var head = document.createElement("div");
2325
+ head.className = "step-head";
2326
+ var h4 = document.createElement("h4");
2327
+ h4.textContent = c.title;
2328
+ head.appendChild(h4);
2329
+ if(c.status !== null){
2330
+ var badge = document.createElement("span");
2331
+ badge.className = "badge " + (c.passed ? auditStateClass("done") + " sign-badge" : auditStateClass("pending"));
2332
+ badge.setAttribute("data-testid", "step-card-draft-state");
2333
+ badge.textContent = c.status;
2334
+ head.appendChild(badge);
2335
+ }
2336
+ card.appendChild(head);
2337
+ c.lines.forEach(function(t, i){
2338
+ if(t !== "") card.appendChild(textLineEl("step-meta", t, "step-card-draft-line-" + (i + 2)));
2339
+ });
2340
+ card.setAttribute("tabindex", "0");
2341
+ card.setAttribute("role", "button");
2342
+ card.addEventListener("click", function(){ openAuditGroup("drafting"); });
2343
+ card.addEventListener("keydown", function(e){ if(e.key === "Enter" || e.key === " "){ e.preventDefault(); card.click(); } });
2344
+ return card;
2345
+ }
1897
2346
  // The card's HEADER line: "N · step-name [state] [close class]" — real
1898
2347
  // case, bold from CSS (`.step-card .step-head`), the state/close chips
1899
2348
  // keeping their own `.badge` color. `auditStateClass` is the SAME
@@ -2019,13 +2468,13 @@
2019
2468
  // What a phone tap shows under the one-line entry: everything the line cut short, in full, as wrapped lines.
2020
2469
  // Only fields the row actually has — a line with nothing to say is left out, never filled with a made-up value.
2021
2470
  function auditDetailHtml(r, word, actionText, isRejectRow){
2022
- var lines = [["step", r.step], ["result", word], ["action", actionText]];
2023
- if(!isRejectRow && r.gap) lines.push(["gap", r.gap]);
2471
+ var lines = (typeof r.step === "string" && r.step.length > 0 ? [["step", r.step]] : []).concat([["result", word], ["action", actionText]]);
2472
+ if(!isRejectRow && r.gap) lines.push(["gap", auditGapText(r)]);
2024
2473
  if(Array.isArray(r.refused) && r.refused.length > 0){
2025
2474
  lines.push(["refused", r.refused.map(function(x){ return x.verb + " " + x.path + " (" + x.rule + ")"; }).join("; ")]);
2026
2475
  }
2027
2476
  if(Array.isArray(r.ungranted) && r.ungranted.length > 0) lines.push(["not granted, called anyway", r.ungranted.join(", ")]);
2028
- lines.push(["close", closeClassLabel(r.class)], ["cost", auditCostCellText(r)]);
2477
+ lines.push(["close", auditCloseText(r)], ["cost", auditCostCellText(r)]);
2029
2478
  var when = readableDateTime(r.at);
2030
2479
  lines.push(["time", (typeof r.atWhy === "string" && r.atWhy.length > 0) ? r.atWhy : (when || "unknown")]);
2031
2480
  return lines.map(function(l){ return "<div class=\"am-d\"><b>" + escapeXml(l[0]) + ":</b> " + escapeXml(l[1]) + "</div>"; }).join("");
@@ -2037,6 +2486,10 @@
2037
2486
  // the mobile (max-width:480px) stacked-card CSS reads via `attr()` —
2038
2487
  // review item #4: the Time cell (and every other cell) must stay inside
2039
2488
  // its own card at 390px, never truncated or pushed off the page edge.
2489
+ // The one place the Attempt and Close cells get their text: a row that is not an attempt (a Stop's note, a setup row) has no attempt
2490
+ // number and no close class — it shows nothing / "—", never "null", "unknown" or "#null".
2491
+ function auditAttemptText(r){ return (typeof r.attempt === "number" || (typeof r.attempt === "string" && r.attempt.length > 0)) ? String(r.attempt) : ""; }
2492
+ function auditCloseText(r){ return (r.setup || r.class === null || r.class === undefined) ? "—" : closeClassLabel(r.class); }
2040
2493
  function buildAuditRowEl(r, includeStep){
2041
2494
  var tr = document.createElement("tr");
2042
2495
  var glyph = verdictGlyph(r.verdict, r.class);
@@ -2050,17 +2503,17 @@
2050
2503
  // pre-M4a-3 row or a non-model row appends nothing at all.
2051
2504
  var actionText = action + (typeof r.toolsPhrase === "string" ? " · " + r.toolsPhrase : "");
2052
2505
  var cells =
2053
- "<td data-label=\"Attempt\">" + escapeXml(String(r.attempt)) + "</td>" +
2054
- (includeStep ? "<td data-label=\"Step\">" + escapeXml(r.step) + "</td>" : "") +
2506
+ "<td data-label=\"Attempt\">" + escapeXml(auditAttemptText(r)) + "</td>" +
2507
+ (includeStep ? "<td data-label=\"Step\">" + escapeXml(r.stepName || r.step) + "</td>" : "") +
2055
2508
  "<td data-label=\"Action\">" + escapeXml(actionText) + "</td>" +
2056
- "<td data-label=\"Gap\">" + escapeXml(isRejectRow ? "" : (r.gap || "")) + "</td>" +
2509
+ "<td data-label=\"Gap\">" + escapeXml(isRejectRow ? "" : auditGapText(r)) + "</td>" +
2057
2510
  "<td data-label=\"Cost\">" + escapeXml(auditCostCellText(r)) + "</td>" +
2058
2511
  "<td data-label=\"Verdict\"><span class=\"badge " + badgeClass + "\">" + escapeXml(word) + "</span></td>" +
2059
- "<td data-label=\"Close\">" + escapeXml(closeClassLabel(r.class)) + "</td>" +
2512
+ "<td data-label=\"Close\">" + escapeXml(auditCloseText(r)) + "</td>" +
2060
2513
  "<td data-label=\"Time\">" + auditTimeCellHtml(r) + "</td>" +
2061
2514
  // phone-only one-line cells (CSS shows these and hides the rest below 640px; hidden on desktop)
2062
2515
  "<td class=\"am am-glyph\" aria-hidden=\"true\">" + escapeXml(glyph || "·") + "</td>" +
2063
- "<td class=\"am am-cost\">" + escapeXml(money(r.usd, r.spendComplete)) + "</td>" +
2516
+ "<td class=\"am am-cost\">" + escapeXml(r.setup ? auditCostCellText(r) : money(r.usd, r.spendComplete)) + "</td>" +
2064
2517
  "<td class=\"am am-time\">" + escapeXml(auditShortTime(r)) + "</td>" +
2065
2518
  "<td class=\"am am-detail\">" + auditDetailHtml(r, word, actionText, isRejectRow) + "</td>";
2066
2519
  tr.innerHTML = cells;
@@ -2102,13 +2555,27 @@
2102
2555
  // presentational formatter; nothing here re-derives state/cost/tries).
2103
2556
  // Tokens are appended ONLY when the server sent a real total (omitted,
2104
2557
  // never "0 tokens", for a pre-M4a-2 row or a no-model-call step).
2558
+ // M4e amendment 10: ONE function for each header line's words, `auditGroupHeaderParts` (status in the step card's `stateWord`, name, then the Draft's figures
2559
+ // or the step's cost and tries); `buildAuditGroupHeaderEl` draws these parts and `auditGroupHeaderText` joins them, so the visible line and its aria are
2560
+ // the same words. `status` is null with no draft record; `state` colors it (`auditStateClass`); `signed`: the status carries its own brackets.
2561
+ function auditGroupHeaderParts(g){
2562
+ var AUDIT_DOT = "\u00b7"; // the separator between the status badge and the name, read by the visible header and the aria line alike
2563
+ if(g.draft){
2564
+ var ds = g.summary;
2565
+ if(!(ds && ds.present)) return {status: null, name: "drafting", why: (ds && ds.why) || "no draft record"};
2566
+ var passed = ds.ended === "done";
2567
+ return {status: passed ? stateWord("done") : "not signed", state: passed ? "done" : "pending", signed: true, name: "drafting", dot: AUDIT_DOT, draftFigs: draftFigures(ds).concat([draftHumanWord(ds)]), passed: passed};
2568
+ }
2569
+ var parts = {status: stateWord(g.state), state: g.state, signed: true, dot: AUDIT_DOT, name: g.step, cost: g.cost || "cost unknown"};
2570
+ if(!g.run) parts.tries = {n: g.tryCount, marks: g.tryMarks}; // the run's own group has no tries
2571
+ return parts;
2572
+ }
2105
2573
  function auditGroupHeaderText(g){
2106
- var bits = [
2107
- "[" + g.state + "]", g.step, duration(g.timeMs), (g.cost || "cost unknown"),
2108
- "try " + g.tryCount + " " + g.tryMarks.join(""),
2109
- ];
2110
- if(typeof g.tokensTotal === "number") bits.splice(4, 0, g.tokensTotal + " tokens");
2111
- return bits.join(" · ");
2574
+ var p = auditGroupHeaderParts(g);
2575
+ if(g.draft) return draftLineText(g.summary);
2576
+ var line = [p.status, p.name, p.cost].join(" " + p.dot + " ");
2577
+ if(p.tries) line += " \u00b7 try " + p.tries.n + " " + p.tries.marks.join("");
2578
+ return line;
2112
2579
  }
2113
2580
  // hamr's 2026-09-27 review: the header's status word gets the SAME color
2114
2581
  // vocabulary the runs list already uses (glyphClass's green/red/amber/
@@ -2120,51 +2587,70 @@
2120
2587
  if(state === "done") return "green";
2121
2588
  if(state === "waiting") return "amber";
2122
2589
  if(state === "stopped") return "red";
2123
- return "grey";
2590
+ return "grey"; // user-stopped (the same --grey-dot as the [■] dot), pending
2124
2591
  }
2125
2592
  function auditMarkClass(mark){
2126
2593
  if(mark === "✓") return "green";
2127
2594
  if(mark === "✗") return "red";
2128
2595
  return "grey"; // "·" — still open, no resolution row yet
2129
2596
  }
2597
+ // The Draft group's header tail (amendment 7 item 2, 10): `· <time> · $<cost> · <n> model calls ✓` from `auditGroupHeaderParts`' figures (the one
2598
+ // `draftFigures`, `draftCallsWord`); a flow with no draft record says so and has no cost. Apart from buildAuditGroupHeaderEl so the step groups' title keeps no time in it.
2599
+ function draftTailInto(tail, p){
2600
+ function part(cls, text){ var sp = document.createElement("span"); sp.className = cls; sp.textContent = text; tail.appendChild(sp); }
2601
+ part("audit-fold-sep", "\u00b7 ");
2602
+ if(!p.draftFigs){ tail.appendChild(document.createTextNode(p.why)); return; }
2603
+ tail.appendChild(document.createTextNode(p.draftFigs.join(" \u00b7 ") + (p.passed ? " " : "")));
2604
+ if(p.passed) part("mark green", "\u2713");
2605
+ }
2130
2606
  // Builds the SAME header line `auditGroupHeaderText` renders as plain
2131
2607
  // text (used as this header's aria-label, for a screen reader), but as
2132
- // real DOM: the status word is its own `<span class="badge STATE">`
2133
- // (reusing the existing `.badge` bracket/color CSS, never a second
2134
- // "[state]" string built here) and each try mark is its own colored
2608
+ // real DOM: the status (the step card's sign and word, amendment 10) is its own `<span class="badge STATE sign-badge">`
2609
+ // (the sign carries its own brackets, so `.sign-badge` draws no second pair) and each try mark is its own colored
2135
2610
  // `<span class="mark STATE">` — built directly off `g.state`/`g.tryMarks`,
2136
2611
  // never by parsing `auditGroupHeaderText`'s own string back apart.
2137
2612
  function buildAuditGroupHeaderEl(g){
2138
2613
  var h4 = document.createElement("h4");
2139
2614
  h4.className = "audit-status-header";
2140
- var stateSpan = document.createElement("span");
2141
- stateSpan.className = "badge " + auditStateClass(g.state);
2142
- stateSpan.setAttribute("data-testid", "audit-group-state");
2143
- stateSpan.textContent = g.state;
2144
- h4.appendChild(stateSpan);
2615
+ var p = auditGroupHeaderParts(g);
2616
+ if(p.status !== null){
2617
+ var stateSpan = document.createElement("span");
2618
+ stateSpan.className = "badge " + auditStateClass(p.state) + " sign-badge";
2619
+ stateSpan.setAttribute("data-testid", "audit-group-state");
2620
+ stateSpan.textContent = p.status;
2621
+ h4.appendChild(stateSpan);
2622
+ var dotSpan = document.createElement("span");
2623
+ dotSpan.className = "audit-fold-dot";
2624
+ dotSpan.textContent = p.dot;
2625
+ h4.appendChild(dotSpan);
2626
+ }
2145
2627
  // M4c-fix amendment 2 (l): the title is `[sign] name · cost · try N ✗✓` — the name alone is cut with … (own flex child),
2146
2628
  // cost and tries never; time and tokens live in each try's detail. The whole name is in the title attribute and aria-label.
2147
2629
  var nameSpan = document.createElement("span");
2148
2630
  nameSpan.className = "audit-fold-name";
2149
2631
  nameSpan.setAttribute("data-testid", "audit-group-name");
2150
- nameSpan.title = g.step;
2151
- nameSpan.textContent = g.step;
2632
+ nameSpan.title = p.name;
2633
+ nameSpan.textContent = p.name;
2152
2634
  h4.appendChild(nameSpan);
2153
2635
  var tail = document.createElement("span");
2154
2636
  tail.className = "audit-fold-tail";
2155
2637
  // the dots and the word "try" are their own spans so a phone can drop them (keeping cost, N and the marks)
2156
2638
  function tailPart(cls, text){ var sp = document.createElement("span"); sp.className = cls; sp.textContent = text; tail.appendChild(sp); }
2157
- tailPart("audit-fold-sep", "· ");
2158
- tail.appendChild(document.createTextNode(g.cost || "cost unknown"));
2159
- tailPart("audit-fold-sep", " · ");
2160
- tailPart("audit-fold-try", "try ");
2161
- tailPart("audit-fold-n", g.tryCount + " ");
2162
- g.tryMarks.forEach(function(mark){
2163
- var markSpan = document.createElement("span");
2164
- markSpan.className = "mark " + auditMarkClass(mark);
2165
- markSpan.textContent = mark;
2166
- tail.appendChild(markSpan);
2167
- });
2639
+ if(g.draft) draftTailInto(tail, p);
2640
+ else if(!p.tries){ tailPart("audit-fold-sep", "· "); tail.appendChild(document.createTextNode(p.cost)); } // the run's own group: no tries, no dots
2641
+ else {
2642
+ tailPart("audit-fold-sep", "· ");
2643
+ tail.appendChild(document.createTextNode(p.cost));
2644
+ tailPart("audit-fold-sep", " · ");
2645
+ tailPart("audit-fold-try", "try ");
2646
+ tailPart("audit-fold-n", p.tries.n + " ");
2647
+ p.tries.marks.forEach(function(mark){
2648
+ var markSpan = document.createElement("span");
2649
+ markSpan.className = "mark " + auditMarkClass(mark);
2650
+ markSpan.textContent = mark;
2651
+ tail.appendChild(markSpan);
2652
+ });
2653
+ }
2168
2654
  h4.appendChild(tail);
2169
2655
  return h4;
2170
2656
  }
@@ -2179,10 +2665,17 @@
2179
2665
  if(auditExpandedRun !== runKey){ auditExpanded = {}; auditExpandedRun = runKey; }
2180
2666
  var container = document.getElementById("audit-groups");
2181
2667
  container.innerHTML = "";
2182
- if(!result || result.empty) return;
2668
+ if(!result) return;
2183
2669
  var anyVisible = false;
2184
- (result.groups || []).forEach(function(g){
2670
+ // amendment 7 item 2: the Draft is the first group, a normal card (collapsed by default); a run with no audit rows yet still has it
2671
+ var draftG = draftGroupFor(result);
2672
+ var groups = (draftG ? [draftG] : []).concat(result.empty ? [] : (result.groups || []));
2673
+ groups.forEach(function(g){
2185
2674
  var rows = (g.rows || []).filter(auditRowMatchesFilter);
2675
+ // a flow with no draft record: a header-only card that says so (shown under All; there is nothing to filter)
2676
+ var noRecord = !!g.draft && !(g.summary && g.summary.present);
2677
+ if(noRecord && auditFilterMode !== "all") return;
2678
+ if(noRecord) rows = [{}]; // one placeholder so the card is drawn; it has no table
2186
2679
  if(rows.length === 0) return; // a group with no matching rows is hidden, never an empty shell
2187
2680
  anyVisible = true;
2188
2681
  var wrap = document.createElement("div");
@@ -2197,8 +2690,9 @@
2197
2690
  // map/step-card jump) does, never the initial state.
2198
2691
  // M4c-fix amendment 2 (f): a step with any failed try (a row with a gap) starts OPEN so its gap is
2199
2692
  // seen without a click; the rest start closed. A manual toggle wins on re-render (auditExpanded).
2200
- var failed = (g.rows || []).some(function(r){ return !!r.gap; });
2693
+ var failed = (g.rows || []).some(function(r){ return !!r.gap && !/^stop/.test(r.verdict || ""); }); // a Stop's own words are not a failed try
2201
2694
  var isOpen = Object.prototype.hasOwnProperty.call(auditExpanded, g.step) ? auditExpanded[g.step] : failed;
2695
+ if(g.draft && !Object.prototype.hasOwnProperty.call(auditExpanded, g.step)) isOpen = false; // the Draft starts closed: its card row has a "gap" (the job text)
2202
2696
  wrap.classList.add("audit-fold");
2203
2697
  if(!isOpen) wrap.classList.add("closed");
2204
2698
  var header = buildAuditGroupHeaderEl(g);
@@ -2208,6 +2702,7 @@
2208
2702
  header.setAttribute("aria-label", auditGroupHeaderText(g));
2209
2703
  header.style.cursor = "pointer";
2210
2704
  wrap.appendChild(header);
2705
+ if(noRecord){ container.appendChild(wrap); return; } // nothing to open: the header already says "no draft record"
2211
2706
  var table = document.createElement("table");
2212
2707
  table.hidden = !isOpen;
2213
2708
  table.innerHTML = "<thead><tr><th>Attempt</th><th>Action</th><th>Gap</th><th>Cost</th><th>Verdict</th><th>Close</th><th>Time</th></tr></thead><tbody></tbody>";
@@ -2243,8 +2738,9 @@
2243
2738
  function renderAuditFlat(result){
2244
2739
  var tbody = document.getElementById("audit-tbody");
2245
2740
  tbody.innerHTML = "";
2246
- if(!result || result.empty) return false;
2247
- var rows = result.rows.filter(auditRowMatchesFilter);
2741
+ if(!result) return false;
2742
+ var dr = result.draft && result.draft.present ? result.draft.rows : [];
2743
+ var rows = dr.concat(result.empty ? [] : result.rows).filter(auditRowMatchesFilter);
2248
2744
  rows.forEach(function(r){ tbody.appendChild(buildAuditRowEl(r, true)); });
2249
2745
  return rows.length > 0;
2250
2746
  }
@@ -2277,17 +2773,27 @@
2277
2773
  filterEmpty.hidden = true;
2278
2774
  }
2279
2775
  }
2776
+ // M4e amendment 7 item 2: the Draft as the first Audit group (one card like the steps', collapsed by default): the group header reads the server's one
2777
+ // Draft summary; its rows (card, draft, notes, changes, sign, then this run's own Sign & run rows) come from the same row builder as the run's rows.
2778
+ function draftGroupFor(result){
2779
+ var d = result && result.draft;
2780
+ if(!d) return null;
2781
+ return {step: "drafting", draft: true, summary: d.summary, rows: d.rows || []};
2782
+ }
2280
2783
  function renderAudit(result){
2281
2784
  var empty = document.getElementById("audit-empty");
2282
2785
  var content = document.getElementById("audit-content");
2283
2786
  lastAuditResult = result;
2284
- if(!result || result.empty){
2787
+ // a run with no audit rows yet still has its Draft: say so in words, and show the card
2788
+ var hasDraft = !!(result && result.draft);
2789
+ if(!result || (result.empty && !hasDraft)){
2285
2790
  empty.hidden = false;
2286
2791
  empty.textContent = (result && result.why) || "no audit rows for this run";
2287
2792
  content.hidden = true;
2288
2793
  return;
2289
2794
  }
2290
- empty.hidden = true;
2795
+ empty.hidden = !result.empty;
2796
+ if(result.empty) empty.textContent = result.why || "no audit rows for this run";
2291
2797
  content.hidden = false;
2292
2798
  // a fresh run's own view keeps whatever mode (Grouped/Flat) the chips
2293
2799
  // are already showing, defaulting to Grouped on first load.
@@ -2300,9 +2806,13 @@
2300
2806
  // getRunJob (src/panel/data.js), which reads fwdloop's own signed
2301
2807
  // declaration.json + signature.json (one per flow, unlike bareloop's
2302
2808
  // multi-source provenance chain — DROPPED per the M4a fit-check). ----
2303
- function ttlLabel(ms){
2304
- if(typeof ms !== "number") return "unknown";
2305
- return duration(ms);
2809
+ // M4e amendment 6 item 6: ONE wait formatter for the Job block's "~ waits" row and the Ask row: "1h", "30m", "1h 30m", never "60m00s".
2810
+ // A wait that is not a whole number of seconds falls back to `duration`.
2811
+ function plainWait(ms){
2812
+ if(typeof ms !== "number" || !(ms > 0)) return "unknown";
2813
+ if(ms % 1000 !== 0) return duration(ms);
2814
+ var t = ms / 1000, h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), sec = t % 60;
2815
+ return [h ? h + "h" : "", m ? m + "m" : "", sec ? sec + "s" : ""].filter(Boolean).join(" ");
2306
2816
  }
2307
2817
  // hamr's 2026-09-27 exit-check review #5: ONE row-per-piece renderer,
2308
2818
  // shared by every multi-row Job field (prose/asks/sources/sends/
@@ -2331,12 +2841,29 @@
2331
2841
  document.getElementById("details-title").textContent = "Job — " + job.flow + " (signed)";
2332
2842
  // review #5: "Job (prose)" — the signed lines, numbered, WITHOUT their
2333
2843
  // guardrail mixed in (guardrails get their own field below).
2334
- renderRowsField("details-prose", job.prose, "no signed prose lines", function(l){
2335
- return l.line + ". " + l.text;
2336
- });
2844
+ // M4e amendment 6 item 6: the Job block reads like the card: each numbered line, then its own `~` rows: its guardrail, an ask line's
2845
+ // wait, a send line's destination. (The separate Guardrails field is gone.) `job` already carries the values in force for this run.
2846
+ var jobEl = document.getElementById("details-prose");
2847
+ jobEl.innerHTML = "";
2848
+ if(!job.prose || !job.prose.length){
2849
+ jobEl.appendChild(textDiv("hint", "no signed prose lines"));
2850
+ } else {
2851
+ job.prose.forEach(function(l){
2852
+ jobEl.appendChild(textDiv("ro-value", l.line + ". " + l.text));
2853
+ (job.guardrails || []).filter(function(g){ return g.line === l.line; }).forEach(function(g){
2854
+ jobEl.appendChild(textDiv("ro-value sub", "~ " + g.guardrail));
2855
+ });
2856
+ (job.asks || []).filter(function(ak){ return ak.line === l.line; }).forEach(function(ak){
2857
+ jobEl.appendChild(textDiv("ro-value sub", "~ waits " + plainWait(ak.waitMs)));
2858
+ });
2859
+ (job.sends || []).filter(function(sd){ return sd.line === l.line; }).forEach(function(sd){
2860
+ jobEl.appendChild(textDiv("ro-value sub", "~ writes out to " + (sd.target || "unknown")));
2861
+ });
2862
+ });
2863
+ }
2337
2864
  // review #5: "Ask" — one row per signed ask line.
2338
2865
  renderRowsField("details-asks", job.asks, "no signed asks", function(ak){
2339
- return "line " + ak.line + " · \"" + ak.question + "\" · waits " + ttlLabel(ak.waitMs);
2866
+ return "line " + ak.line + " · \"" + ak.question + "\" · waits " + plainWait(ak.waitMs);
2340
2867
  });
2341
2868
  // hamr review #7: no declaration/signature book records a model on the
2342
2869
  // flow itself (checked against `src/panel/data.js`'s own
@@ -2345,17 +2872,13 @@
2345
2872
  document.getElementById("details-model").textContent = job.model
2346
2873
  ? ("model used: " + job.model + " (from this run's rows)")
2347
2874
  : (job.modelWhy || "no model call recorded yet");
2348
- // hamr's 2026-09-27 final tweak #1: "$ cap" — bareloop-style "$ cap /
2349
- // Time cap" row: money (signed capUsd + redo cap) THEN time. Checked
2350
- // against src/declaration.js and src/types.js's own Arbiter typedef:
2351
- // fwdloop's signed arbiter carries `capUsd`/`redoCap` (and per-ask
2352
- // `ttlMs`, which is an ask's own wait, not a run-wide time cap) — there
2353
- // is no signed run-wide time-cap field anywhere in the grammar, so this
2354
- // NEVER invents one; it says so in words instead.
2875
+ // M4e amendment 6 item 5 + amendment 7 item 4: "$<cap> per run · 1h wait · redo up to <n>"; several asks: "waits 1h, 30m", each through plainWait.
2876
+ // fwdloop has no run-wide time limit (each ask has its own wait), so no ask means no wait part at all.
2877
+ var waitParts = (job.asks || []).filter(function(ak){ return typeof ak.waitMs === "number"; }).map(function(ak){ return plainWait(ak.waitMs); });
2878
+ var waitText = waitParts.length === 0 ? "" : (waitParts.length === 1 ? waitParts[0] + " wait" : "waits " + waitParts.join(", "));
2355
2879
  document.getElementById("details-cap").textContent =
2356
2880
  (typeof job.capUsd === "number" ? ("$" + job.capUsd.toFixed(2)) : "unknown")
2357
- + " · redo cap " + (typeof job.redoCap === "number" ? job.redoCap : "unknown")
2358
- + " · time cap: no time cap signed";
2881
+ + " per run" + (waitText ? " · " + waitText : "") + " · redo up to " + (typeof job.redoCap === "number" ? job.redoCap : "unknown");
2359
2882
  // review #5: "Source" — role -> basename only (never the full signed path).
2360
2883
  renderRowsField("details-sources", job.sources, "no signed sources", function(s){
2361
2884
  return s.role + " → " + s.basename;
@@ -2364,10 +2887,6 @@
2364
2887
  renderRowsField("details-sends", job.sends, "no signed sends", function(s){
2365
2888
  return "line " + s.line + " · " + (s.kind || "unknown") + " → " + (s.target || "unknown");
2366
2889
  });
2367
- // review #5: "Guardrails" — ONE field, one row per numbered-line guardrail.
2368
- renderRowsField("details-guardrails", job.guardrails, "no numbered-line guardrails signed", function(g){
2369
- return "line " + g.line + " · " + g.guardrail;
2370
- });
2371
2890
  // review #5: "Success" — one row per declared step, off data.js's own
2372
2891
  // deriveStepSuccessText (never re-derived client-side).
2373
2892
  renderRowsField("details-success", job.success, "no declared steps", function(s){
@@ -2479,7 +2998,7 @@
2479
2998
  var wasHidden = false;
2480
2999
  // One writer of `openRunLive`: every paint of the open run's detail goes through here.
2481
3000
  function paintRun(d){
2482
- openRunLive = !(d && (d.glyph === "[\u2713]" || d.glyph === "[\u2717]"));
3001
+ openRunLive = !(d && (d.glyph === "[\u2713]" || d.glyph === "[\u2717]" || d.glyph === "[\u25A0]"));
2483
3002
  var next = sig(d);
2484
3003
  if(next !== null && next === lastSig.detail) return;
2485
3004
  lastSig.detail = next;
@@ -2560,6 +3079,7 @@
2560
3079
  if(detail && detail.glyph === "[✓]") return { done: true, cls: "info", text: "run finished [✓] — the sent artifact is in the Run tab" };
2561
3080
  if(detail && detail.outcome === "rerun") return { done: true, cls: "info", text: "rerun: this run ended and a fresh run was started — find it in Runs" };
2562
3081
  if(detail && detail.glyph === "[✗]") return { done: true, cls: "info", text: "run ended [✗] " + (detail.label || "") };
3082
+ if(detail && detail.glyph === "[■]") return { done: true, cls: "info", text: "run stopped [■] — " + (detail.line || detail.label || "") };
2563
3083
  var st = asks && asks.resume ? asks.resume.label : null;
2564
3084
  return { done: false, cls: "info", text: (st || "answer applied") + " — run: " + ((detail && detail.label) || "state unknown") };
2565
3085
  }
@@ -2601,7 +3121,7 @@
2601
3121
  runsFilterBar.setItems(runs);
2602
3122
  var first = runs.find(function(r){ return r.runId !== null; });
2603
3123
  if(first){
2604
- document.getElementById("tab-runs").click();
3124
+ // the LEFT side is not switched here: a load or refresh always opens on the Chat tab (hamr 2026-10-06)
2605
3125
  // newest run overall, opened directly — the Workflows view starts
2606
3126
  // collapsed, but its flow row still renders "selected" since
2607
3127
  // `runsFilterBar.refresh()` re-renders AFTER currentFlow/currentRunId
@@ -2830,9 +3350,8 @@
2830
3350
  "askid-required": "That click was not understood. Reload the page and try again.",
2831
3351
  "body-not-json": "That click was not understood. Reload the page and try again.",
2832
3352
  "body-too-large": "That is too long to send. Please shorten your reason.",
2833
- "cookie-missing-or-wrong": "The panel does not recognise this page. Open the link the terminal printed.",
2834
- "origin-not-own": "The panel does not recognise this page. Open the link the terminal printed.",
2835
- "host-not-own-address": "The panel does not recognise this page. Open the link the terminal printed.",
3353
+ "origin-not-own": "The panel does not recognise this page. Reload it.",
3354
+ "host-not-own-address": "The panel does not recognise this page. Reload it.",
2836
3355
  "internal": "Something went wrong inside the panel. Nothing was changed."
2837
3356
  };
2838
3357
  var byWords = [
@@ -3043,7 +3562,7 @@
3043
3562
  if(evidence.draft){
3044
3563
  var draftEl = document.createElement("div");
3045
3564
  draftEl.className = "ro-value scroll";
3046
- draftEl.textContent = evidence.draft;
3565
+ fillArtifactText(draftEl, evidence.draft);
3047
3566
  // hamr's 2026-09-27 exit-check review #3: "the box headers should be
3048
3567
  // bolder" — a real heading class (same weight/size/uppercase posture
3049
3568
  // as the Job tab's own field `<label>`s), never the plain `.hint`
@@ -3069,11 +3588,54 @@
3069
3588
  }
3070
3589
  var art = document.createElement("div");
3071
3590
  art.className = "ro-value scroll";
3072
- art.textContent = typeof u.text === "string" ? u.text : "no artifact text on file";
3591
+ if(typeof u.text === "string"){ fillArtifactText(art, u.text); } else { art.textContent = "no artifact text on file"; }
3073
3592
  ev.appendChild(art);
3074
3593
  });
3075
3594
  return ev;
3076
3595
  }
3596
+ // M4e amendment 4 item 7: a section header of the artifact shows in the panel's blue accent. The signed text gives no
3597
+ // rule for what a header is, so the simplest honest one: a paragraph (text between blank lines) that is one short line
3598
+ // (60 characters or fewer), does not end in a sentence stop, and has another paragraph after it. The text itself is
3599
+ // untouched (textContent still equals the artifact, byte for byte); only the colour of those lines changes.
3600
+ var ART_HEAD_MAX = 60;
3601
+ // A markdown heading line (1-6 "#", a space, then text) is a header wherever it sits, single newlines included, last paragraph too.
3602
+ var ART_MD_HEAD = /^#{1,6} \S/;
3603
+ function isArtifactHeader(para, hasNext){
3604
+ if(ART_MD_HEAD.test(para) && para.indexOf("\n") === -1) return true;
3605
+ return hasNext && para.length > 0 && para.length <= ART_HEAD_MAX && para.indexOf("\n") === -1 && !/[.!?:;,]$/.test(para.trim());
3606
+ }
3607
+ function fillArtifactText(el, text){
3608
+ el.textContent = "";
3609
+ var paras = String(text).split("\n\n");
3610
+ paras.forEach(function(para, i){
3611
+ if(i > 0) el.appendChild(document.createTextNode("\n\n"));
3612
+ if(para.indexOf("\n") !== -1){
3613
+ // several lines in one paragraph: only markdown heading lines are headers; the "\n" between lines stays in the text
3614
+ var plain = "";
3615
+ para.split("\n").forEach(function(line, j){
3616
+ var sep = j > 0 ? "\n" : "";
3617
+ if(ART_MD_HEAD.test(line)){
3618
+ el.appendChild(document.createTextNode(plain + sep));
3619
+ plain = "";
3620
+ var hh = document.createElement("span");
3621
+ hh.className = "art-head";
3622
+ hh.textContent = line;
3623
+ el.appendChild(hh);
3624
+ } else {
3625
+ plain += sep + line;
3626
+ }
3627
+ });
3628
+ if(plain !== "") el.appendChild(document.createTextNode(plain));
3629
+ } else if(isArtifactHeader(para, i < paras.length - 1)){
3630
+ var h = document.createElement("span");
3631
+ h.className = "art-head";
3632
+ h.textContent = para;
3633
+ el.appendChild(h);
3634
+ } else {
3635
+ el.appendChild(document.createTextNode(para));
3636
+ }
3637
+ });
3638
+ }
3077
3639
  // M4c item 5: "your answers so far" — one line per answered draft, every field from
3078
3640
  // the server's block (data.js groupAskBlocks); the page only lays it out.
3079
3641
  function answerLineText(a){
@@ -3225,6 +3787,1062 @@
3225
3787
  return true;
3226
3788
  }
3227
3789
 
3790
+ // ---- Chat tab: describe, draft, sign and run a job from this page (M4e piece 3). ----
3791
+ // borrowed-from: bareloop src/panel/index.html@ca7195e — `mainButtonFor`, `renderMain`, `renderProgress`, the
3792
+ // scroll-on-change block in `renderActions`, `attachSession`/`reattachLive` (without the reuse/auto-sign branch), `syncCardLock`,
3793
+ // `CLIENT_TERMINAL_PHASES`, `openNewCard`/`resetCard`/`refreshStartEnabled`, `authorPost`/`authorGet`, `fitBox`. fwdloop differs where its shape does: the draft is a detached CLI child whose state is
3794
+ // READ from files (GET /api/author/live and /:id), a start is polled (GET /api/author/start/:id), no token or cookie. Sign is two clicks, no typed name (M4e amendment 2); the ask box is bareloop's "Ask for a change to the plan" (amendment 3 item 3).
3795
+ (function(){
3796
+ var card = document.getElementById("chat-job-card");
3797
+ var clearBtn = document.getElementById("chat-clear-btn");
3798
+ var thread = document.getElementById("chat-thread");
3799
+ var jobEl = document.getElementById("jf-job");
3800
+ var inputsBox = document.getElementById("jf-inputs"); // the New-job inputs textarea (`name: path` per line)
3801
+ var destEl = document.getElementById("jf-dest-folder");
3802
+ var askWaitEl = document.getElementById("jf-ask-wait");
3803
+ var mainBtn = document.getElementById("chat-main-btn");
3804
+ var mainHint = document.getElementById("chat-main-hint");
3805
+ var startOverBtn = document.getElementById("chat-startover-btn");
3806
+ var msgEl = document.getElementById("chat-msg"); // the ask box: a note asking for a change to the green plan
3807
+ var msgRow = document.getElementById("chat-msg-row");
3808
+ var errEl = document.getElementById("chat-card-error"); // POLL-OWNED: the draft's own sentence (red / stopped)
3809
+ var actionErrEl = document.getElementById("chat-action-error"); // ACTION-OWNED: only a click's refusal; the poll never wipes it
3810
+ var progressRow = document.getElementById("chat-progress-row");
3811
+ var newBox = document.getElementById("jf-new");
3812
+ var runBox = document.getElementById("jf-run");
3813
+ var runInputsEl = document.getElementById("jf-run-inputs");
3814
+ var runFlowSel = document.getElementById("jf-run-flow"); // the Signed flow search box (amendment 7 item 7); nothing is picked until the human picks
3815
+ var rwSearchEl = document.getElementById("rw-search");
3816
+ var rwListEl = document.getElementById("rw-list");
3817
+ var rwPickedEl = document.getElementById("rw-picked");
3818
+ var rwPickedTxt = document.getElementById("rw-picked-txt");
3819
+ var capNoteEl = document.getElementById("jf-cap-note");
3820
+ var runDestEl = document.getElementById("jf-run-dest"); // Run a signed flow: the open Destination box (amendment 5)
3821
+ var runCapEl = document.getElementById("jf-run-cap"); // ... and the open Cap $ box
3822
+ var runWaitsEl = document.getElementById("jf-run-waits"); // ... and one wait box per ask
3823
+ var resumeBox = document.getElementById("jf-resume"); // the "Resume run-<n>" form (amendment 4 item 4): only Cap $ is open
3824
+ var resumeCapEl = document.getElementById("jf-resume-cap");
3825
+ var modeRow = document.getElementById("jf-mode-row");
3826
+ var titleEl = document.getElementById("job-card-title");
3827
+
3828
+ var mode = "new"; // "new" | "run" | "resume"
3829
+ var runSignInfo = null; // Run form, first Sign & run click: { hash } (cleared by any edit)
3830
+ var resumeCtx = null; // the run being resumed: { flow, runId, form }
3831
+ var resumeSignInfo = null; // Resume form, first Sign & resume click: { hash }
3832
+ var modeBeforeResume = "new";
3833
+ var mainAction = "none";
3834
+ var startOk = false;
3835
+ var sessionId = null; // the draft's id (GET /api/author/<id>)
3836
+ var sessionLive = false; // a draft exists that is not abandoned or signed
3837
+ var lastState = null; // the draft as the server last described it
3838
+ var signInfo = null; // the first Sign click's reply: { hash, flowName, capUsd, runId }
3839
+ var signClickedOnce = false;
3840
+ var busy = false; // a POST is in flight (disabled from the click until the reply)
3841
+ var startId = null; // the run start being watched (GET /api/author/start/<id>)
3842
+ var refusedStartId = null; // a refused start whose sentence is on the card; Clear dismisses it on the server (cleared.json)
3843
+ var pollTimer = null;
3844
+ var startTimer = null;
3845
+ var drafterModel = "";
3846
+ var flows = [];
3847
+ // a draft that is abandoned or signed ends the card's life; red/stopped drafts stay on the card (to read, to fix, to retry)
3848
+ var CLIENT_TERMINAL_PHASES = ["abandoned", "signed"];
3849
+
3850
+ function authorPost(path, body){
3851
+ return postJSON(path, body || {}).then(function(r){ return {status: r.status, body: r.body}; });
3852
+ }
3853
+ function authorGet(path){
3854
+ return fetch(path, { method: "GET", headers: { accept: "application/json" } }).then(function(r){
3855
+ return r.text().then(function(t){
3856
+ var j = null;
3857
+ try{ j = JSON.parse(t); }catch(e){}
3858
+ return j;
3859
+ });
3860
+ });
3861
+ }
3862
+
3863
+ // ---- the pure decisions (no DOM) ----
3864
+ // ONE wide button below the card. Its wording, action and enabled state are ONE pure function of
3865
+ // state = { mode, session, startOk, busy, phase, signClicked, hash, capUsd }.
3866
+ // Actions: draft | run | run-sign-prepare | run-sign | resume-sign-prepare | resume-sign | revise | sign-prepare | sign | none.
3867
+ function mainButtonFor(st){
3868
+ var cap = st.capUsd;
3869
+ var spends = (cap !== undefined && cap !== null && cap !== "") ? " — spends up to $" + cap : "";
3870
+ var blocked = !st.startOk || !!st.busy;
3871
+ if(st.mode === "run"){
3872
+ // amendment 5 item 3: inputs alone = Run (one click); a Destination, Cap $ or ask wait different from the flow's = Sign & run (two clicks, bound to a hash)
3873
+ if(st.runDiffers){
3874
+ if(st.runSignClicked){
3875
+ var runCap = (cap !== undefined && cap !== null && cap !== "") ? " \u00b7 $" + cap : "";
3876
+ return {text: "Sign " + String(st.hash || "").slice(0, 8) + " & run" + runCap, action: "run-sign", disabled: !!st.busy};
3877
+ }
3878
+ return {text: "Sign & run", action: "run-sign-prepare", disabled: blocked};
3879
+ }
3880
+ return {text: "Run" + spends, action: "run", disabled: blocked};
3881
+ }
3882
+ if(st.mode === "resume"){
3883
+ if(st.runSignClicked){
3884
+ var resCap = (cap !== undefined && cap !== null && cap !== "") ? " \u00b7 $" + cap : "";
3885
+ return {text: "Sign " + String(st.hash || "").slice(0, 8) + " & resume" + resCap, action: "resume-sign", disabled: !!st.busy};
3886
+ }
3887
+ return {text: "Sign & resume", action: "resume-sign-prepare", disabled: blocked};
3888
+ }
3889
+ if(!st.session){
3890
+ return {text: "Draft", action: "draft", disabled: blocked};
3891
+ }
3892
+ if(st.phase === "drafting"){
3893
+ return {text: "Draft", action: "none", disabled: true};
3894
+ }
3895
+ if(st.phase === "red"){
3896
+ return {text: "Fix and draft again", action: "draft", disabled: blocked};
3897
+ }
3898
+ if(st.phase === "stopped"){
3899
+ return {text: "Draft again", action: "draft", disabled: blocked};
3900
+ }
3901
+ if(st.phase === "revising"){
3902
+ return {text: "Sign & run", action: "none", disabled: true};
3903
+ }
3904
+ if(st.phase === "green"){
3905
+ // amendment 3 item 3: a note in the ask box makes the one button Send (a change to the plan); empty, it is Sign & run
3906
+ if(st.boxOpen && !st.textEmpty){
3907
+ return {text: "Send", action: "revise", disabled: !!st.busy};
3908
+ }
3909
+ if(st.signClicked){
3910
+ var signCap = (cap !== undefined && cap !== null && cap !== "") ? " \u00b7 $" + cap : "";
3911
+ return {text: "Sign " + String(st.hash || "").slice(0, 8) + " & run" + signCap, action: "sign", disabled: !!st.busy};
3912
+ }
3913
+ return {text: "Sign & run", action: "sign-prepare", disabled: !!st.busy};
3914
+ }
3915
+ return {text: "Draft", action: "none", disabled: true};
3916
+ }
3917
+ // pure: the ask box is open on a green plan with changes left (bareloop: it closes at 0); the hint under the button says how many.
3918
+ function askBoxOpenFor(st){
3919
+ return st.mode === "new" && !!st.session && st.phase === "green" && (st.left || 0) > 0;
3920
+ }
3921
+ // pure: Start over shows only when the plan on show has used both changes (the ask box is closed): the second choice beside Sign & run
3922
+ function startOverShownFor(st){
3923
+ return st.mode === "new" && !!st.session && st.phase === "green" && st.left === 0;
3924
+ }
3925
+ // borrowed-from: bareloop src/panel/index.html@c1d87ce (renderMessages: "you" / bot bubbles, each with a who label)
3926
+ // pure: the bubbles above the plan (amendment 6 item 3), from the draft's notes: each note is a you bubble in the human's words, each green change a fwdloop bubble.
3927
+ // A red or stopped change gets no bubble of its own: its reds are in the progress list, shown once.
3928
+ function bubblesFor(state){
3929
+ var out = [];
3930
+ if(!state || (state.phase !== "green" && state.phase !== "revising")) return out;
3931
+ (state.notes || []).forEach(function(nt){
3932
+ out.push({role: "you", who: "you", text: String(nt.text || "").replace(/\s+$/, "")});
3933
+ if(nt.phase === "green") out.push({role: "bot", who: "fwdloop", text: "New plan, hash " + String(nt.hash || "").slice(0, 8) + ". " + changesLeftText(nt.left) + "."});
3934
+ });
3935
+ return out;
3936
+ }
3937
+ function changesLeftText(left){
3938
+ return left + (left === 1 ? " change left" : " changes left");
3939
+ }
3940
+ // pure: the gutter beside a box (amendment 2, plain numbers by amendment 3), one entry per LOGICAL line. The job: `N` on a step line (numbers go on), `~` on a
3941
+ // guardrail line, nothing on an empty line. The inputs: a number per non-empty line.
3942
+ function gutterMarks(kind, text){
3943
+ var n = 0;
3944
+ return String(text).split("\n").map(function(line){
3945
+ var t = line.trim();
3946
+ if(t === "") return "";
3947
+ if(kind === "job" && t.charAt(0) === "~") return "~";
3948
+ n += 1;
3949
+ return String(n);
3950
+ });
3951
+ }
3952
+ // pure: the progress list for a draft. Chronological; a waiting step has no check; a step's detail lines sit under it; no two
3953
+ // identical lines in a row. `ctx` = { model, starting }.
3954
+ function stepsFor(state, ctx){
3955
+ var out = [];
3956
+ var who = ctx.model ? ctx.model : "the drafter";
3957
+ var cap = state && state.card && state.card.capUsd !== undefined && state.card.capUsd !== "" ? state.card.capUsd : "";
3958
+ var capPart = cap !== "" ? ", run cap $" + cap : "";
3959
+ if(state){
3960
+ if(state.phase === "drafting"){
3961
+ out.push({id: "drafting", label: "drafting with " + who + capPart, status: "running", details: []});
3962
+ } else if(state.phase === "red"){
3963
+ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
3964
+ out.push({id: "checks", label: "plan checks", status: "failed", details: (state.reds || []).slice()});
3965
+ } else if(state.phase === "stopped"){
3966
+ out.push({id: "drafting", label: "drafting with " + who + capPart, status: "failed", details: []});
3967
+ } else if(state.phase === "green" || state.phase === "revising"){
3968
+ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
3969
+ // amendment 3 item 3: each note the human sent is a line of its own, with its result (a red change shows its reds)
3970
+ (state.notes || []).forEach(function(nt){
3971
+ var body = String(nt.text || "").replace(/\s+$/, "");
3972
+ var label = "change " + nt.n + ": " + body;
3973
+ if(nt.phase === "running") out.push({id: "change-" + nt.n, label: label, status: "running", details: []});
3974
+ else if(nt.phase === "green") out.push({id: "change-" + nt.n, label: label, status: "done", details: []});
3975
+ else out.push({id: "change-" + nt.n, label: label, status: "failed", details: (nt.reds && nt.reds.length ? nt.reds.slice() : []).concat(nt.say ? [nt.say] : [])});
3976
+ });
3977
+ if(state.phase === "revising"){
3978
+ // the last green plan stays on show; nothing to sign until the change comes back
3979
+ } else if(ctx.starting){
3980
+ out.push({id: "signed", label: "signed", status: "done", details: []});
3981
+ } else {
3982
+ out.push({id: "sign", label: ctx.signClicked ? "waiting for your second click" : "waiting for your signature", status: "waiting", details: []});
3983
+ }
3984
+ }
3985
+ }
3986
+ if(ctx.starting) out.push({id: "starting", label: "starting the run", status: "running", details: []});
3987
+ return out.filter(function(s, i){ return i === 0 || JSON.stringify(s) !== JSON.stringify(out[i - 1]); });
3988
+ }
3989
+ // pure: did this POST succeed (one decision for every handler)
3990
+ function chatPostOutcome(r){
3991
+ var ok = !!(r && r.status >= 200 && r.status < 300 && r.body && r.body.ok === true);
3992
+ return {ok: ok, error: ok ? "" : refusalText(r)};
3993
+ }
3994
+ var FIX_BOXES_SAY = "Not started. Fix the marked boxes. Nothing spent.";
3995
+ // the banner that only points at marked boxes goes when the last marked box clears; any other sentence (a refusal with no box) stays
3996
+ function dropFixBoxesBanner(){
3997
+ if(actionErrEl.textContent !== FIX_BOXES_SAY) return;
3998
+ var any = false;
3999
+ card.querySelectorAll(".jf-err").forEach(function(x){ if(x.textContent) any = true; });
4000
+ if(!any) actionErrEl.textContent = "";
4001
+ }
4002
+ // pure: the one sentence for a refused call — the server's own `say`, else its field refusals, else a plain fallback
4003
+ function refusalText(r){
4004
+ var b = r && r.body;
4005
+ if(b && typeof b.say === "string" && b.say !== "") return b.say;
4006
+ if(b && Array.isArray(b.refusals) && b.refusals.length) return FIX_BOXES_SAY;
4007
+ return "The request failed. Nothing was sent.";
4008
+ }
4009
+
4010
+ // grow a text box with its text (a few rows, then it scrolls inside); ONE function for the card boxes.
4011
+ // A box that is hidden (or not laid out) measures 0 and gets no inline height.
4012
+ function fitBox(el){
4013
+ el.style.height = "auto";
4014
+ if(!el.scrollHeight){ el.style.height = ""; return; }
4015
+ var border = el.offsetHeight - el.clientHeight;
4016
+ el.style.height = Math.min(el.scrollHeight + border, 200) + "px";
4017
+ }
4018
+ // Paint a gutter: a hidden mirror of the textarea (same font, same content width, same wrapping) measures each logical line's height;
4019
+ // the gutter gets one entry of exactly that height, its mark on the first visual line. Re-run on every input, resize and fit.
4020
+ function paintGutter(ta, kind){
4021
+ var gut = document.getElementById(ta.id + "-gut");
4022
+ if(!gut || !ta.clientWidth) return; // hidden (the other mode): painted when it is shown
4023
+ var inner = gut.firstChild;
4024
+ var cs = getComputedStyle(ta);
4025
+ var mir = ta.jfMirror;
4026
+ if(!mir){ mir = document.createElement("div"); mir.className = "jf-mirror"; ta.parentNode.appendChild(mir); ta.jfMirror = mir; }
4027
+ ["fontFamily", "fontSize", "fontWeight", "fontStyle", "letterSpacing", "wordSpacing", "lineHeight", "tabSize"].forEach(function(k){ mir.style[k] = cs[k]; });
4028
+ gut.style.lineHeight = cs.lineHeight;
4029
+ var padT = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.borderTopWidth) || 0);
4030
+ mir.style.width = Math.max(0, ta.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0)) + "px";
4031
+ mir.innerHTML = "";
4032
+ var lines = ta.value.split("\n");
4033
+ lines.forEach(function(l){ var d = document.createElement("div"); d.textContent = l === "" ? "\u200b" : l; mir.appendChild(d); });
4034
+ var marks = gutterMarks(kind, ta.value);
4035
+ var hs = Array.prototype.map.call(mir.children, function(d){ return d.getBoundingClientRect().height; });
4036
+ inner.innerHTML = "";
4037
+ inner.style.paddingTop = padT + "px";
4038
+ marks.forEach(function(m, i){ var d = document.createElement("div"); d.style.height = hs[i] + "px"; d.textContent = m; inner.appendChild(d); });
4039
+ inner.style.transform = "translateY(" + (-ta.scrollTop) + "px)";
4040
+ }
4041
+ function fitCardBoxes(){
4042
+ fitBox(jobEl); fitBox(inputsBox);
4043
+ paintGutter(jobEl, "job"); paintGutter(inputsBox, "inputs");
4044
+ }
4045
+ [[jobEl, "job"], [inputsBox, "inputs"]].forEach(function(pair){
4046
+ pair[0].addEventListener("scroll", function(){
4047
+ var inner = document.getElementById(pair[0].id + "-gut").firstChild;
4048
+ inner.style.transform = "translateY(" + (-pair[0].scrollTop) + "px)";
4049
+ });
4050
+ });
4051
+
4052
+ // ---- the card's boxes ----
4053
+ function byId(id){ return document.getElementById(id); }
4054
+ function setVal(id, v){ byId(id).value = (v === undefined || v === null) ? "" : String(v); }
4055
+ function makeInput(cls, placeholder, value){
4056
+ var el = document.createElement("input");
4057
+ el.type = "text"; el.className = cls; el.placeholder = placeholder; el.autocomplete = "off"; el.spellcheck = false;
4058
+ el.value = (value === undefined || value === null) ? "" : String(value);
4059
+ return el;
4060
+ }
4061
+ function makeErr(){ var d = document.createElement("div"); d.className = "jf-err"; return d; }
4062
+ // Run a signed flow: one row per DECLARED role (the role is fixed), the path prefilled from the last run
4063
+ function paintRunRows(f, sources){
4064
+ runInputsEl.innerHTML = "";
4065
+ ((f && f.roles) || []).forEach(function(role){
4066
+ var row = document.createElement("div");
4067
+ row.className = "jf-inrow";
4068
+ var ro = document.createElement("div");
4069
+ ro.className = "jf-role-ro"; ro.textContent = role; ro.setAttribute("data-role", role);
4070
+ row.appendChild(ro);
4071
+ row.appendChild(makeInput("jf-path", "/full/path/to/file", sources ? sources[role] : ""));
4072
+ row.appendChild(makeErr());
4073
+ runInputsEl.appendChild(row);
4074
+ });
4075
+ syncCardLock();
4076
+ }
4077
+ function readRows(container){
4078
+ return Array.prototype.map.call(container.children, function(row){
4079
+ var roleEl = row.querySelector(".jf-role");
4080
+ var role = roleEl ? roleEl.value.trim() : row.querySelector(".jf-role-ro").getAttribute("data-role");
4081
+ return {role: role, path: row.querySelector(".jf-path").value.trim()};
4082
+ });
4083
+ }
4084
+ function currentCard(){
4085
+ return {
4086
+ flowName: byId("jf-name").value.trim(),
4087
+ job: jobEl.value,
4088
+ destination: destEl.value.trim(),
4089
+ inputs: inputsBox.value,
4090
+ capUsd: byId("jf-cap-money").value.trim(),
4091
+ askWait: askWaitEl.value.trim()
4092
+ };
4093
+ }
4094
+ function runWaits(){
4095
+ var waits = {};
4096
+ runWaitsEl.querySelectorAll("input.jf-wait").forEach(function(el){ waits[el.getAttribute("data-line")] = el.value.trim(); });
4097
+ return waits;
4098
+ }
4099
+ function currentRun(){
4100
+ return {
4101
+ flow: pickedFlow || "", inputs: readRows(runInputsEl), runId: (byId("jf-run-id").value.trim() === autoRunId ? "" : byId("jf-run-id").value.trim()),
4102
+ destination: runDestEl.value.trim(), capUsd: runCapEl.value.trim(), askWaits: runWaits()
4103
+ };
4104
+ }
4105
+ // pure-ish (reads the boxes): does the Run form differ from the flow's own signed values? Only a convenience that picks the button's wording
4106
+ // (Run vs Sign & run); the server decides again and never trusts this.
4107
+ function runDiffers(){
4108
+ var f = selectedFlow();
4109
+ if(!f || !f.values) return false;
4110
+ var dest = runDestEl.value.trim();
4111
+ if(f.hasSend && dest !== "" && dest !== f.values.destination) return true;
4112
+ var cap = runCapEl.value.trim();
4113
+ if(cap !== "" && !(isFinite(Number(cap)) && Number(cap) === f.values.capUsd)) return true;
4114
+ var waits = runWaits();
4115
+ return Object.keys(waits).some(function(k){ return waits[k] !== "" && waits[k].toLowerCase() !== f.values.askWaits[k]; });
4116
+ }
4117
+ function capValid(text){
4118
+ var v = Number(text);
4119
+ return text !== "" && isFinite(v) && v > 0;
4120
+ }
4121
+ function selectedFlow(){
4122
+ if(pickedFlow === null) return null;
4123
+ for(var i = 0; i < flows.length; i++){ if(flows[i].flow === pickedFlow) return flows[i]; }
4124
+ return (againEntry && againEntry.flow === pickedFlow) ? againEntry : null;
4125
+ }
4126
+ // client-side convenience only (the server's $0 checks are the real gate): is there enough on the card to click?
4127
+ function startReady(){
4128
+ if(moneyRed) return false; // amendment 4 item 1: a cap that does not fit this month stops you before the click (the server still refuses)
4129
+ if(mode === "run"){
4130
+ return !!selectedFlow() && readRows(runInputsEl).every(function(r){ return r.path !== ""; }) && capValid(runCapEl.value.trim());
4131
+ }
4132
+ if(mode === "resume"){
4133
+ return !!resumeCtx && capValid(resumeCapEl.value.trim());
4134
+ }
4135
+ var c = currentCard();
4136
+ var v = Number(c.capUsd);
4137
+ return c.flowName !== "" && c.job.trim() !== "" && c.capUsd !== "" && isFinite(v) && v > 0;
4138
+ }
4139
+
4140
+ // ---- the money note under Cap (M4e amendment 4 items 1-2) ----
4141
+ // borrowed-from: bareloop src/panel/index.html@c1d87ce — `refreshCapNote` (debounced re-read as the cap is typed), without its
4142
+ // plain-text-only rule: here a note that is red turns the main button off. The words and the numbers come from the server
4143
+ // (GET /api/author/monthly-check, one read-only check); the page decides nothing but where to show them. A fetch error clears the note.
4144
+ var moneyRed = false;
4145
+ var capNoteSeq = 0;
4146
+ var capNoteTimer = null;
4147
+ function setMoneyNote(text, red){
4148
+ var els = [capNoteEl, byId("jf-run-left"), byId("jf-resume-left")];
4149
+ els.forEach(function(el){ el.textContent = ""; el.classList.remove("money-red"); });
4150
+ var el = els[mode === "run" ? 1 : (mode === "resume" ? 2 : 0)];
4151
+ el.textContent = text;
4152
+ el.classList.toggle("money-red", !!red && text !== "");
4153
+ var was = moneyRed;
4154
+ moneyRed = !!red && text !== "";
4155
+ if(was !== moneyRed) refreshStartEnabled();
4156
+ }
4157
+ // a job with a step that is not an Ask needs a model round (the server's own rule decides; this only skips the floor line for an empty box)
4158
+ function jobHasModelStep(){
4159
+ return byId("jf-job").value.split("\n").some(function(l){ var t = l.trim(); return t !== "" && t.charAt(0) !== "~" && !/^ask\b/i.test(t); });
4160
+ }
4161
+ function refreshCapNote(){
4162
+ var cap = mode === "run" ? runCapEl.value.trim() : (mode === "resume" ? resumeCapEl.value.trim() : byId("jf-cap-money").value.trim());
4163
+ var seq = ++capNoteSeq;
4164
+ if(cap === ""){ setMoneyNote("", false); return; }
4165
+ // a Resume holds only what the run has still to spend (amendment 4 item 1): the server is told what is already spent
4166
+ var spent = (mode === "resume" && resumeCtx) ? "&spent=" + encodeURIComponent(String(resumeCtx.form.spentUsd)) : "";
4167
+ authorGet("/api/author/monthly-check?cap=" + encodeURIComponent(cap) + spent).then(function(j){
4168
+ if(seq !== capNoteSeq) return;
4169
+ if(!j || j.ok !== true){ setMoneyNote("", false); return; }
4170
+ var v = Number(cap);
4171
+ if(mode === "new" && j.floorText && isFinite(v) && v > 0 && v < j.floorUsd && jobHasModelStep()){ setMoneyNote(j.floorText, true); return; }
4172
+ // a Run's own cap is never judged against the floor (an old flow signed lower still runs plain); a changed cap below it is red
4173
+ var sf = selectedFlow();
4174
+ if(mode === "run" && sf && j.floorText && isFinite(v) && v > 0 && v !== sf.capUsd && v < sf.capFloorUsd){ setMoneyNote(sf.floorText, true); return; }
4175
+ if(mode === "resume" && resumeCtx && j.floorText && isFinite(v) && v > resumeCtx.form.spentUsd && v < resumeCtx.form.floorUsd){ setMoneyNote(resumeCtx.form.floorText, true); return; }
4176
+ setMoneyNote(typeof j.text === "string" ? j.text : "", j.red === true);
4177
+ }).catch(function(){ if(seq === capNoteSeq) setMoneyNote("", false); });
4178
+ }
4179
+ function scheduleCapNote(){
4180
+ if(capNoteTimer) clearTimeout(capNoteTimer);
4181
+ capNoteTimer = setTimeout(refreshCapNote, 250);
4182
+ }
4183
+
4184
+ // ---- a refusal shows next to its box ----
4185
+ function clearFieldErrors(){
4186
+ card.querySelectorAll(".jf-err").forEach(function(e){ e.textContent = ""; });
4187
+ }
4188
+ function errElFor(field){
4189
+ var m = /^inputs\.(\d+)$/.exec(field);
4190
+ if(m){ // a Run-a-signed-flow row (the New job card reports "inputs" by line number)
4191
+ var row = runInputsEl.children[Number(m[1])];
4192
+ return row ? row.querySelector(".jf-err") : null;
4193
+ }
4194
+ if(field === "inputs") return byId(mode === "run" ? "jf-err-run-inputs" : "jf-err-inputs");
4195
+ if(mode === "run" && (field === "destination" || field === "capUsd")) return byId("jf-err-run-" + field);
4196
+ if(mode === "run" && /^askWaits/.test(field)) return byId("jf-err-run-askWaits");
4197
+ if(mode === "resume" && field === "capUsd") return byId("jf-err-resume-capUsd");
4198
+ return byId("jf-err-" + field);
4199
+ }
4200
+ // returns the sentences that had no box to sit next to
4201
+ function showRefusals(list){
4202
+ var unplaced = [];
4203
+ list.forEach(function(r){
4204
+ var el = errElFor(String(r.field));
4205
+ if(el){ el.textContent = el.textContent ? el.textContent + " " + r.say : r.say; } else { unplaced.push(r.say); }
4206
+ });
4207
+ return unplaced;
4208
+ }
4209
+
4210
+ // ---- the lock: while a draft is drafting or waiting to be signed, a start is in flight, or a POST is out, NOTHING on the card
4211
+ // is editable (the draft was made from these values). ONE function owns it. A red or stopped draft unlocks the card (fix, draft again).
4212
+ function cardLocked(){
4213
+ var ph = (sessionLive && lastState) ? lastState.phase : null;
4214
+ return busy || startId !== null || (mode === "new" && (ph === "drafting" || ph === "revising" || ph === "green"));
4215
+ }
4216
+ function syncCardLock(){
4217
+ var on = cardLocked();
4218
+ card.querySelectorAll("input[type=text], textarea").forEach(function(el){ el.readOnly = on; el.classList.toggle("locked", on); });
4219
+ runFlowSel.disabled = on;
4220
+ runFlowSel.classList.toggle("locked", on);
4221
+ rwPickedEl.classList.toggle("locked", on);
4222
+ card.querySelectorAll('input[name="jf-mode"]').forEach(function(r){ r.disabled = on || sessionLive; });
4223
+ }
4224
+ // top-right: Abandon while a draft is live and unsigned, else Clear
4225
+ function clearButtonFor(live, hasId){
4226
+ return live ? {text: "Abandon", disabled: !hasId || busy} : {text: "Clear", disabled: busy};
4227
+ }
4228
+ function refreshClearBtn(){
4229
+ var b = mode === "resume" ? {text: "Cancel", disabled: busy} : clearButtonFor(sessionLive, !!sessionId);
4230
+ clearBtn.textContent = b.text;
4231
+ clearBtn.disabled = b.disabled;
4232
+ }
4233
+ function refreshStartEnabled(){
4234
+ startOk = startReady();
4235
+ syncCardLock();
4236
+ renderMain();
4237
+ refreshClearBtn();
4238
+ }
4239
+
4240
+ // ---- Run a signed flow: the list comes from the server (only flows whose signature checks out) ----
4241
+ var paintedFlow = null;
4242
+ // the Signed flow search (amendment 7 item 7): what is picked is a flow, and optionally one of its runs (then that run's values fill the boxes)
4243
+ var pickedFlow = null, pickedRun = null, pickedLabel = "", againEntry = null, rwShown = [], rwHl = 0;
4244
+ function pickedKey(){ return pickedFlow === null ? "" : pickedFlow + "/" + (pickedRun ? pickedRun.runId : ""); }
4245
+ var autoRunId = ""; // the prefilled next name (amendment 3): an untouched box sends "" and the server claims the next number itself
4246
+ // the signed job as the dimmed read-only block both forms show (amendment 4/5: what a run cannot change is shown, not editable)
4247
+ function paintJobDim(el, lines){
4248
+ el.innerHTML = "";
4249
+ (lines || []).forEach(function(l){
4250
+ var row = document.createElement("div");
4251
+ row.className = "ro-line";
4252
+ var n = document.createElement("span"); n.className = "ro-n"; n.textContent = String(l.n);
4253
+ var t = document.createElement("span"); t.textContent = (l.ask ? "Ask: " : "") + l.text + (l.guardrail ? " ~ " + l.guardrail : "");
4254
+ row.appendChild(n); row.appendChild(t);
4255
+ el.appendChild(row);
4256
+ });
4257
+ }
4258
+ function paintRunFlow(){
4259
+ var f = selectedFlow();
4260
+ var v = f ? (pickedRun ? pickedRun.values : f.values) : null; // a picked run's own values, else the flow's own
4261
+ paintedFlow = pickedKey();
4262
+ runSignInfo = null;
4263
+ paintJobDim(byId("jf-run-job"), f ? f.jobLines : []);
4264
+ runDestEl.value = v && v.destination ? v.destination : "";
4265
+ runDestEl.readOnly = !(f && f.hasSend);
4266
+ runDestEl.classList.toggle("locked", !(f && f.hasSend));
4267
+ byId("jf-run-dest-hint").textContent = !f ? "" : (f.hasSend ? "Where the accepted result is placed, at the last step. A different folder is signed for this run only." : "This flow has no send step, so there is no destination to set.");
4268
+ runCapEl.value = v ? String(v.capUsd) : "";
4269
+ runWaitsEl.innerHTML = "";
4270
+ Object.keys((v && v.askWaits) || {}).forEach(function(line){
4271
+ var row = document.createElement("div");
4272
+ row.className = "jf-waitrow";
4273
+ var lab = document.createElement("label");
4274
+ lab.textContent = "Ask wait \u00b7 line " + line;
4275
+ var inp = makeInput("jf-wait", "e.g. 30m", v.askWaits[line]);
4276
+ inp.setAttribute("data-line", line);
4277
+ inp.setAttribute("data-testid", "jf-run-wait-" + line);
4278
+ row.appendChild(lab); row.appendChild(inp);
4279
+ runWaitsEl.appendChild(row);
4280
+ });
4281
+ paintRunRows(f, pickedRun ? pickedRun.sources : (f ? f.lastSources : null));
4282
+ autoRunId = f && f.nextRunId ? f.nextRunId : "";
4283
+ byId("jf-run-id").value = autoRunId;
4284
+ clearFieldErrors();
4285
+ refreshCapNote();
4286
+ }
4287
+ // borrowed-from: bareloop src/panel/index.html@b5e37b8 — the Reuse workflow picker: ONE function shows the search box + list before a pick and the
4288
+ // picked box after; a row is the name (the typed part marked) over the flow's track record line.
4289
+ function rwMark(name, q){
4290
+ var i = q ? name.toLowerCase().indexOf(q.toLowerCase()) : -1;
4291
+ if(i < 0) return escapeXml(name);
4292
+ return escapeXml(name.slice(0, i)) + "<mark>" + escapeXml(name.slice(i, i + q.length)) + "</mark>" + escapeXml(name.slice(i + q.length));
4293
+ }
4294
+ function renderFlowSearch(){
4295
+ var picked = pickedFlow !== null;
4296
+ rwSearchEl.hidden = picked;
4297
+ rwPickedEl.hidden = !picked;
4298
+ rwPickedTxt.innerHTML = picked ? "<b>" + escapeXml(pickedLabel) + "</b>" : "";
4299
+ if(picked) return;
4300
+ var q = runFlowSel.value.trim();
4301
+ rwShown = flowChoices(flows, q);
4302
+ if(rwHl >= rwShown.length) rwHl = 0;
4303
+ rwListEl.innerHTML = rwShown.length ? rwShown.map(function(c, i){
4304
+ return '<li data-i="' + i + '" data-testid="rw-item" class="' + (i === rwHl ? "hl" : "") + '"><div class="rw-name">' + rwMark(c.label, q) + '</div><div class="rw-meta">' + escapeXml(c.meta) + "</div></li>";
4305
+ }).join("") : '<div class="rw-empty" data-testid="rw-empty">' + (flows.length === 0 ? "No signed flow has a passed run yet." : 'No flow or run matches "' + escapeXml(q) + '".') + "</div>";
4306
+ }
4307
+ function pickFlowChoice(c){
4308
+ if(!c || cardLocked()) return;
4309
+ var entry = null;
4310
+ flows.forEach(function(f){ if(f.flow === c.flow) entry = f; });
4311
+ if(entry === null) return;
4312
+ var run = null;
4313
+ (entry.runs || []).forEach(function(r){ if(r.runId === c.runId) run = r; });
4314
+ pickedFlow = c.flow; pickedRun = c.runId ? run : null; pickedLabel = c.label; againEntry = null;
4315
+ runFlowSel.value = c.label;
4316
+ byId("jf-err-flow").textContent = "";
4317
+ renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4318
+ }
4319
+ function unpickFlow(){
4320
+ if(cardLocked()) return;
4321
+ pickedFlow = null; pickedRun = null; pickedLabel = ""; againEntry = null; rwHl = 0;
4322
+ runFlowSel.value = "";
4323
+ renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4324
+ }
4325
+ function loadFlows(force){
4326
+ authorGet("/api/author/flows").then(function(j){
4327
+ if(!j || j.ok !== true) return;
4328
+ flows = j.flows || [];
4329
+ if(pickedFlow !== null && !selectedFlow()){ pickedFlow = null; pickedRun = null; againEntry = null; pickedLabel = ""; runFlowSel.value = ""; }
4330
+ byId("jf-run-empty").textContent = flows.length ? "" : "No signed flow has a passed run yet. Run a job first, or use Run again on one of its runs.";
4331
+ renderFlowSearch();
4332
+ if(force || paintedFlow !== pickedKey() || (flows.length === 0 && runInputsEl.children.length > 0)) paintRunFlow();
4333
+ refreshCapNote();
4334
+ refreshStartEnabled();
4335
+ }).catch(function(){ /* the card keeps what it had */ });
4336
+ }
4337
+ // the drafting line names the model the drafter really uses (Settings' deepseek row), never a guess
4338
+ function loadModel(){
4339
+ authorGet("/api/settings/providers").then(function(j){
4340
+ var rows = (j && j.ok === true && Array.isArray(j.rows)) ? j.rows : [];
4341
+ for(var i = 0; i < rows.length; i++){ if(rows[i].slot === "deepseek" && rows[i].model){ drafterModel = String(rows[i].model); } }
4342
+ }).catch(function(){ /* the line then says "the drafter" */ });
4343
+ }
4344
+ function setMode(m){
4345
+ mode = m;
4346
+ runSignInfo = null; resumeSignInfo = null;
4347
+ document.querySelectorAll('input[name="jf-mode"]').forEach(function(r){ r.checked = (r.value === m); });
4348
+ newBox.hidden = (m !== "new");
4349
+ runBox.hidden = (m !== "run");
4350
+ resumeBox.hidden = (m !== "resume");
4351
+ modeRow.hidden = (m === "resume");
4352
+ titleEl.textContent = (m === "resume" && resumeCtx) ? "Resume " + resumeCtx.runId + " \u00b7 " + resumeCtx.flow : "Job card";
4353
+ clearFieldErrors();
4354
+ if(m === "run") loadFlows();
4355
+ refreshCapNote();
4356
+ refreshStartEnabled();
4357
+ fitCardBoxes();
4358
+ }
4359
+
4360
+ // ---- render: the progress list, the readout and the one main button ----
4361
+ // Returns true when the list's content actually changed (a new line, or the latest line changed) so the caller can scroll only
4362
+ // then; an identical poll tick returns false and leaves the person's scroll position alone.
4363
+ function renderProgress(steps){
4364
+ var before = progressRow.innerHTML;
4365
+ progressRow.hidden = steps.length === 0;
4366
+ progressRow.innerHTML = steps.map(function(st){
4367
+ var cls = st.status === "waiting" ? "wait" : (st.status === "running" ? "run" : (st.status === "failed" ? "bad" : "ok"));
4368
+ var sign = cls === "ok" ? "✓" : (cls === "bad" ? "✗" : "");
4369
+ return '<li class="step ' + cls + '" data-step="' + escapeXml(st.id) + '"><div class="step-line"><span class="step-label">' + escapeXml(st.label) + '</span>' +
4370
+ '<span class="step-sign">' + sign + '</span></div>' +
4371
+ (st.details || []).map(function(d){ return '<div class="step-detail">' + escapeXml("> " + d) + '</div>'; }).join("") + '</li>';
4372
+ }).join("");
4373
+ return progressRow.innerHTML !== before;
4374
+ }
4375
+ // the plan the human is about to sign: the drafter's readout and the hash; nothing else goes in the thread
4376
+ var threadKey = "";
4377
+ // M4e amendment 7 item 3: the readout is plain text; the server names which lines are headings (one list, authoring.js), shown bold.
4378
+ function readoutHtml(state){
4379
+ var heads = Array.isArray(state.readoutHeads) ? state.readoutHeads : [];
4380
+ return String(state.readout).replace(/\s+$/, "").split("\n").map(function(l, i){
4381
+ return heads.indexOf(i) >= 0 ? '<b class="readout-head">' + escapeXml(l) + '</b>' : escapeXml(l);
4382
+ }).join("\n");
4383
+ }
4384
+ function renderThread(state){
4385
+ var html = "";
4386
+ if(state && (state.phase === "green" || state.phase === "revising") && state.readout){
4387
+ // M4e amendment 6 item 3: bubbles (oldest first), THEN the current plan, so the plan sits right above the note box and the button
4388
+ html = bubblesFor(state).map(function(m){
4389
+ return '<div class="msg ' + m.role + '"><div class="who">' + escapeXml(m.who) + '</div>' + escapeXml(m.text) + '</div>';
4390
+ }).join("") +
4391
+ '<div class="msg bot" data-testid="chat-plan"><div class="who">fwdloop</div>' + readoutHtml(state) +
4392
+ '\n\nPlan hash: ' + escapeXml(state.hash || "") + '</div>';
4393
+ }
4394
+ if(html !== threadKey){ threadKey = html; thread.innerHTML = html; }
4395
+ }
4396
+ function renderMain(){
4397
+ var st = {mode: mode, session: sessionLive, startOk: startOk, busy: busy || startId !== null, signClicked: signClickedOnce, textEmpty: msgEl.value.trim() === ""};
4398
+ if(sessionLive && lastState){
4399
+ st.phase = lastState.phase;
4400
+ st.hash = signInfo ? signInfo.hash : lastState.hash;
4401
+ st.left = lastState.changesLeft;
4402
+ }
4403
+ st.boxOpen = askBoxOpenFor(st);
4404
+ if(mode === "run"){
4405
+ st.capUsd = runCapEl.value.trim();
4406
+ st.runDiffers = runDiffers();
4407
+ st.runSignClicked = !!runSignInfo;
4408
+ st.hash = runSignInfo ? runSignInfo.hash : "";
4409
+ } else if(mode === "resume"){
4410
+ st.capUsd = resumeCapEl.value.trim();
4411
+ st.runSignClicked = !!resumeSignInfo;
4412
+ st.hash = resumeSignInfo ? resumeSignInfo.hash : "";
4413
+ } else if(signInfo){
4414
+ st.capUsd = signInfo.capUsd;
4415
+ } else if(lastState && lastState.card){
4416
+ st.capUsd = lastState.card.capUsd;
4417
+ }
4418
+ var b = mainButtonFor(st);
4419
+ mainBtn.textContent = b.text;
4420
+ mainBtn.disabled = b.disabled;
4421
+ mainAction = b.action;
4422
+ // the ask box: open on a green plan with changes left, shown but locked while a change is being drafted, closed at 0 left
4423
+ var boxShown = st.boxOpen || (mode === "new" && sessionLive && st.phase === "revising");
4424
+ msgRow.hidden = !boxShown;
4425
+ msgEl.readOnly = !st.boxOpen || !!busy;
4426
+ mainHint.textContent = st.boxOpen ? changesLeftText(st.left) : "";
4427
+ startOverBtn.hidden = !startOverShownFor(st);
4428
+ startOverBtn.disabled = !!st.busy;
4429
+ fitCardBoxes();
4430
+ if(boxShown) fitBox(msgEl);
4431
+ }
4432
+ function renderActions(state){
4433
+ lastState = state;
4434
+ // a newer plan than the one the first Sign click showed (a change came back, or another tab): the first click is void; sign re-checks on the server too
4435
+ if(signInfo && state.hash && state.hash !== signInfo.hash){ signInfo = null; signClickedOnce = false; }
4436
+ // #chat-card-error is POLL-OWNED: it carries only the draft's own sentence (a red plan or a stopped child), written here and
4437
+ // nowhere else. A refused click goes to #chat-action-error, which this function never touches.
4438
+ errEl.textContent = ((state.phase === "red" || state.phase === "stopped") && state.say) ? state.say : "";
4439
+ var progressChanged = renderProgress(stepsFor(state, {model: drafterModel, starting: startId !== null, signClicked: signClickedOnce}));
4440
+ sessionLive = CLIENT_TERMINAL_PHASES.indexOf(state.phase) === -1;
4441
+ refreshStartEnabled();
4442
+ // while the draft is live and the list changed, bring the newest progress line into view.
4443
+ // Never moves keyboard focus, and an unchanged poll tick never scrolls.
4444
+ if(progressChanged && sessionLive && progressRow.lastElementChild){
4445
+ progressRow.lastElementChild.scrollIntoView({block: "nearest"});
4446
+ }
4447
+ }
4448
+
4449
+ // ---- actions ----
4450
+ function stopPoll(){ if(pollTimer){ clearInterval(pollTimer); pollTimer = null; } }
4451
+ function startPoll(){ stopPoll(); pollTimer = setInterval(poll, 2000); }
4452
+ function stopStart(){ if(startTimer){ clearInterval(startTimer); startTimer = null; } startId = null; }
4453
+ // the card's draft is over (abandoned or signed somewhere else, or signed here and its run refused): forget the session, keep
4454
+ // the boxes. Touches neither error line, so a refusal on screen stays on screen.
4455
+ function endSession(){
4456
+ stopPoll();
4457
+ sessionId = null; sessionLive = false; lastState = null; signInfo = null; signClickedOnce = false;
4458
+ threadKey = ""; thread.innerHTML = "";
4459
+ errEl.textContent = "";
4460
+ progressRow.hidden = true; progressRow.innerHTML = "";
4461
+ refreshStartEnabled();
4462
+ }
4463
+ function openNewCard(){
4464
+ thread.innerHTML = ""; threadKey = "";
4465
+ msgEl.value = "";
4466
+ errEl.textContent = "";
4467
+ actionErrEl.textContent = "";
4468
+ clearFieldErrors();
4469
+ stopStart();
4470
+ sessionId = null; sessionLive = false; lastState = null; signInfo = null; signClickedOnce = false; busy = false;
4471
+ stopPoll();
4472
+ progressRow.hidden = true;
4473
+ progressRow.innerHTML = "";
4474
+ refreshStartEnabled();
4475
+ }
4476
+ // back to a fresh empty card: every box, the inputs, the progress list, the ask box
4477
+ function resetCard(){
4478
+ if(mode === "resume"){ resumeCtx = null; setMode(modeBeforeResume === "resume" ? "new" : modeBeforeResume); }
4479
+ ["jf-name", "jf-job", "jf-cap-money", "jf-dest-folder", "jf-inputs"].forEach(function(id){ byId(id).value = ""; });
4480
+ askWaitEl.value = "1h";
4481
+ refreshCapNote();
4482
+ openNewCard();
4483
+ loadFlows(mode === "run");
4484
+ fitCardBoxes();
4485
+ }
4486
+ function chatActionFailed(message){
4487
+ actionErrEl.textContent = message || "The request failed. Nothing was sent.";
4488
+ }
4489
+ function chatActionOk(){
4490
+ actionErrEl.textContent = "";
4491
+ }
4492
+ // a refused POST: field refusals next to their boxes, one sentence in the action line (and any red lines under it)
4493
+ function failFrom(r){
4494
+ var b = r && r.body;
4495
+ var unplaced = (b && Array.isArray(b.refusals)) ? showRefusals(b.refusals) : [];
4496
+ var text = refusalText(r);
4497
+ if(unplaced.length) text += " " + unplaced.join(" ");
4498
+ if(b && Array.isArray(b.reds) && b.reds.length) text += "\n" + b.reds.map(function(x){ return "> " + x; }).join("\n");
4499
+ chatActionFailed(text);
4500
+ }
4501
+ var NETWORK_SAY = "Could not reach the panel. Nothing was sent.";
4502
+
4503
+ function poll(){
4504
+ if(!sessionId) return;
4505
+ var polledId = sessionId;
4506
+ authorGet("/api/author/" + polledId).then(function(j){
4507
+ if(!j || j.ok !== true || polledId !== sessionId) return;
4508
+ if(CLIENT_TERMINAL_PHASES.indexOf(j.phase) !== -1){
4509
+ // abandoned or signed from elsewhere; a start of ours is being watched by pollStart instead
4510
+ if(startId === null) endSession();
4511
+ return;
4512
+ }
4513
+ renderThread(j);
4514
+ renderActions(j);
4515
+ }).catch(function(){ /* transient — next poll tries again */ });
4516
+ }
4517
+
4518
+ // a run start (after a sign, or Run a signed flow): the CLI child may refuse before its run exists, so ask until the start says
4519
+ function beginStart(id){
4520
+ stopStart();
4521
+ startId = id;
4522
+ refusedStartId = null;
4523
+ busy = false;
4524
+ startTimer = setInterval(pollStart, 1000);
4525
+ if(lastState){ renderActions(lastState); } else {
4526
+ renderProgress(stepsFor(null, {model: drafterModel, starting: true, signClicked: false}));
4527
+ refreshStartEnabled();
4528
+ }
4529
+ pollStart();
4530
+ }
4531
+ function pollStart(){
4532
+ var watching = startId;
4533
+ if(!watching) return;
4534
+ authorGet("/api/author/start/" + watching).then(function(j){
4535
+ if(watching !== startId) return;
4536
+ if(!j) return;
4537
+ if(j.ok === true && j.phase === "started"){
4538
+ // the run lives in Runs now; the card goes back to the empty card
4539
+ stopStart();
4540
+ resetCard();
4541
+ document.getElementById("tab-runs").click();
4542
+ reloadLists();
4543
+ return;
4544
+ }
4545
+ if(j.ok === true && j.phase === "refused"){
4546
+ // the CLI's own sentence ("Nothing spent." is in it); it STAYS until the next action
4547
+ var signed = j.kind === "sign";
4548
+ stopStart();
4549
+ window.fwdloopResuming = null; // a refused start leaves the run stopped: Resume is offered again
4550
+ refusedStartId = j.startId;
4551
+ chatActionFailed(signed ? j.say + " The flow is signed; start it from \"Run a signed flow\"." : j.say);
4552
+ if(signed){ endSession(); loadFlows(true); } else { progressRow.hidden = true; progressRow.innerHTML = ""; refreshStartEnabled(); }
4553
+ return;
4554
+ }
4555
+ if(j.ok === false && j.refused === "no-such-start"){
4556
+ stopStart();
4557
+ chatActionFailed("The panel could not find this start. Look in the Runs tab to see whether the run began.");
4558
+ refreshStartEnabled();
4559
+ }
4560
+ }).catch(function(){ /* transient — next tick tries again */ });
4561
+ }
4562
+
4563
+ function doDraft(){
4564
+ clearFieldErrors();
4565
+ chatActionOk();
4566
+ // disabled from the click until the reply; unlocked below only if the draft is refused
4567
+ busy = true;
4568
+ refreshStartEnabled();
4569
+ var body = currentCard();
4570
+ authorPost("/api/author/draft", body).then(function(r){
4571
+ busy = false;
4572
+ var o = chatPostOutcome(r);
4573
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4574
+ sessionId = r.body.draftId;
4575
+ sessionLive = true;
4576
+ signInfo = null; signClickedOnce = false;
4577
+ thread.innerHTML = ""; threadKey = "";
4578
+ renderActions({draftId: sessionId, phase: "drafting", card: {capUsd: body.capUsd}});
4579
+ startPoll();
4580
+ poll();
4581
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4582
+ }
4583
+ function doRun(){
4584
+ clearFieldErrors();
4585
+ chatActionOk();
4586
+ busy = true;
4587
+ refreshStartEnabled();
4588
+ authorPost("/api/author/run", currentRun()).then(function(r){
4589
+ var o = chatPostOutcome(r);
4590
+ if(!o.ok){ busy = false; failFrom(r); refreshStartEnabled(); return; }
4591
+ beginStart(r.body.startId);
4592
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4593
+ }
4594
+ // Run a signed flow with a Destination, Cap $ or ask wait that differs from the flow's (amendment 5 item 3): click 1 asks the server what
4595
+ // is about to be signed (a hash; signs nothing), click 2 is the ONLY call that signs and starts, carrying that hash.
4596
+ function doRunSign(){
4597
+ clearFieldErrors();
4598
+ chatActionOk();
4599
+ busy = true;
4600
+ refreshStartEnabled();
4601
+ if(!runSignInfo){
4602
+ authorPost("/api/author/run-prepare", currentRun()).then(function(r){
4603
+ busy = false;
4604
+ var o = chatPostOutcome(r);
4605
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4606
+ if(r.body.needsSign !== true){ doRun(); return; } // the server sees nothing to sign after all: a plain Run
4607
+ runSignInfo = {hash: r.body.hash};
4608
+ refreshStartEnabled();
4609
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4610
+ return;
4611
+ }
4612
+ var body = currentRun();
4613
+ body.hash = runSignInfo.hash;
4614
+ authorPost("/api/author/run", body).then(function(r){
4615
+ var o = chatPostOutcome(r);
4616
+ runSignInfo = null;
4617
+ if(!o.ok){ busy = false; failFrom(r); refreshStartEnabled(); return; }
4618
+ beginStart(r.body.startId);
4619
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4620
+ }
4621
+ // the Resume form (amendment 4 item 4, "Sign & resume"): the same two clicks; the cap is the only thing in the body besides the run
4622
+ function resumeBody(){ return {flow: resumeCtx.flow, runId: resumeCtx.runId, capUsd: resumeCapEl.value.trim()}; }
4623
+ function doResumeSign(){
4624
+ if(!resumeCtx) return;
4625
+ clearFieldErrors();
4626
+ chatActionOk();
4627
+ busy = true;
4628
+ refreshStartEnabled();
4629
+ if(!resumeSignInfo){
4630
+ authorPost("/api/author/resume-prepare", resumeBody()).then(function(r){
4631
+ busy = false;
4632
+ var o = chatPostOutcome(r);
4633
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4634
+ resumeSignInfo = {hash: r.body.hash};
4635
+ refreshStartEnabled();
4636
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4637
+ return;
4638
+ }
4639
+ var body = resumeBody();
4640
+ body.hash = resumeSignInfo.hash;
4641
+ var resumingKey = resumeCtx.flow + "/" + resumeCtx.runId;
4642
+ authorPost("/api/author/resume", body).then(function(r){
4643
+ var o = chatPostOutcome(r);
4644
+ resumeSignInfo = null;
4645
+ if(!o.ok){ busy = false; failFrom(r); refreshStartEnabled(); return; }
4646
+ window.fwdloopResuming = {key: resumingKey, at: Date.now()};
4647
+ beginStart(r.body.startId);
4648
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4649
+ }
4650
+ // the Run tab's Resume button: read the form's facts from the server (it refuses a run that is not stopped), then show the card in resume mode
4651
+ function openResume(detail){
4652
+ authorGet("/api/author/resume-form?flow=" + encodeURIComponent(detail.flow) + "&runId=" + encodeURIComponent(detail.runId)).then(function(j){
4653
+ document.getElementById("tab-chat").click();
4654
+ if(!j || j.ok !== true){ chatActionFailed((j && j.say) || "This run cannot be resumed."); return; }
4655
+ if(startId !== null || sessionLive){ chatActionFailed("Finish or clear what is on the card first, then Resume."); return; }
4656
+ if(mode !== "resume") modeBeforeResume = mode;
4657
+ resumeCtx = {flow: detail.flow, runId: detail.runId, form: j};
4658
+ chatActionOk();
4659
+ paintJobDim(byId("jf-resume-job"), j.jobLines);
4660
+ byId("jf-resume-dest").textContent = j.values.destination || "no send step";
4661
+ byId("jf-resume-inputs").innerHTML = "";
4662
+ (j.inputs || []).forEach(function(i){ var d = document.createElement("div"); d.className = "ro-line"; d.textContent = i.role + ": " + i.path; byId("jf-resume-inputs").appendChild(d); });
4663
+ byId("jf-resume-waits").textContent = Object.keys(j.values.askWaits || {}).map(function(k){ return "line " + k + ": " + j.values.askWaits[k]; }).join(" \u00b7 ") || "no ask";
4664
+ resumeCapEl.value = String(j.values.capUsd);
4665
+ byId("jf-resume-hint").textContent = "Already spent $" + Number(j.spentUsd).toFixed(4) + ". Same run, same steps, nothing is redrawn; a new cap is signed for this run. Other changes are a new run or a new job.";
4666
+ setMode("resume");
4667
+ }).catch(function(){ document.getElementById("tab-chat").click(); chatActionFailed(NETWORK_SAY); });
4668
+ }
4669
+ window.fwdloopOpenResume = openResume;
4670
+ // the Run tab's Run again button (amendment 7 item 6; bareloop's Reuse workflow): the server reads the run's flow and the run's own values
4671
+ // (any outcome), then the card opens in Run a signed flow with that flow picked and the boxes filled in. A flow the run's preflight
4672
+ // would refuse is refused here with its reason.
4673
+ function openRunAgain(detail){
4674
+ authorGet("/api/author/run-again?flow=" + encodeURIComponent(detail.flow) + "&runId=" + encodeURIComponent(detail.runId)).then(function(j){
4675
+ document.getElementById("tab-chat").click();
4676
+ if(!j || j.ok !== true){ chatActionFailed((j && j.say) || "This run cannot be run again."); return; }
4677
+ if(startId !== null || sessionLive || mode === "resume"){ chatActionFailed("Finish or clear what is on the card first, then Run again."); return; }
4678
+ chatActionOk();
4679
+ againEntry = j.flow; pickedFlow = j.flow.flow; pickedRun = j.pick; pickedLabel = j.flow.flow + " (" + j.pick.runId + ")";
4680
+ runFlowSel.value = pickedLabel;
4681
+ setMode("run");
4682
+ renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4683
+ }).catch(function(){ document.getElementById("tab-chat").click(); chatActionFailed(NETWORK_SAY); });
4684
+ }
4685
+ window.fwdloopRunAgain = openRunAgain;
4686
+ function doSign(){
4687
+ if(!sessionId) return;
4688
+ var id = sessionId;
4689
+ if(!signClickedOnce){
4690
+ // click 1: what is about to be signed (the hash, the cap). Signs nothing.
4691
+ busy = true;
4692
+ refreshStartEnabled();
4693
+ authorPost("/api/author/" + id + "/sign-prepare", {}).then(function(r){
4694
+ busy = false;
4695
+ var o = chatPostOutcome(r);
4696
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4697
+ chatActionOk();
4698
+ signInfo = {hash: r.body.hash, flowName: r.body.flowName, capUsd: r.body.capUsd, runId: r.body.runId};
4699
+ signClickedOnce = true;
4700
+ if(lastState) renderActions(lastState); else refreshStartEnabled();
4701
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4702
+ return;
4703
+ }
4704
+ // click 2: the ONLY call that signs. It carries the hash this page showed; the server signs only if it is still the draft's hash on disk.
4705
+ busy = true;
4706
+ refreshStartEnabled();
4707
+ authorPost("/api/author/" + id + "/sign", {hash: signInfo.hash}).then(function(r){
4708
+ var o = chatPostOutcome(r);
4709
+ if(!o.ok){
4710
+ busy = false;
4711
+ failFrom(r);
4712
+ if(r.body && r.body.signed === true){ endSession(); loadFlows(true); } else { refreshStartEnabled(); }
4713
+ return;
4714
+ }
4715
+ chatActionOk();
4716
+ stopPoll();
4717
+ signClickedOnce = false;
4718
+ beginStart(r.body.startId);
4719
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4720
+ }
4721
+ // amendment 3 item 3: send the note; the server drafts a changed plan beside the old one (the old one stays signable until a new green one exists).
4722
+ // A refused note stays in the box (unsent input is never wiped).
4723
+ function doRevise(){
4724
+ if(!sessionId) return;
4725
+ var id = sessionId;
4726
+ var text = msgEl.value;
4727
+ chatActionOk();
4728
+ busy = true;
4729
+ refreshStartEnabled();
4730
+ authorPost("/api/author/" + id + "/revise", {text: text}).then(function(r){
4731
+ busy = false;
4732
+ var o = chatPostOutcome(r);
4733
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4734
+ msgEl.value = "";
4735
+ signInfo = null; signClickedOnce = false;
4736
+ refreshStartEnabled();
4737
+ poll();
4738
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4739
+ }
4740
+ function doAbandon(){
4741
+ var id = sessionId;
4742
+ busy = true;
4743
+ refreshStartEnabled();
4744
+ authorPost("/api/author/" + id + "/abandon", {}).then(function(r){
4745
+ busy = false;
4746
+ var o = chatPostOutcome(r);
4747
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4748
+ resetCard();
4749
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4750
+ }
4751
+
4752
+ // Re-attach after a page load/refresh or a panel restart: the server reads the newest unsigned draft from its files, so ask it.
4753
+ // If one exists, this tab takes it over as if it had started it: the card filled from the draft's own copy, the poll loop, the
4754
+ // progress list, the readout and the main button. A signed or abandoned draft never comes back (empty card).
4755
+ function attachSession(d){
4756
+ var c = d.card || {};
4757
+ openNewCard();
4758
+ setMode("new");
4759
+ setVal("jf-name", c.flowName); setVal("jf-job", c.job); setVal("jf-cap-money", c.capUsd);
4760
+ refreshCapNote();
4761
+ setVal("jf-dest-folder", typeof c.destination === "string" ? c.destination : ""); setVal("jf-inputs", typeof c.inputs === "string" ? c.inputs : ""); setVal("jf-ask-wait", c.askWait || "1h");
4762
+ sessionId = d.draftId;
4763
+ sessionLive = CLIENT_TERMINAL_PHASES.indexOf(d.phase) === -1;
4764
+ renderThread(d);
4765
+ renderActions(d);
4766
+ startPoll();
4767
+ poll();
4768
+ }
4769
+ function reattachLive(){
4770
+ if(sessionId || sessionLive || startId !== null) return;
4771
+ authorGet("/api/author/live").then(function(j){
4772
+ if(sessionId || sessionLive || startId !== null || !j || j.ok !== true) return;
4773
+ if(j.draft){ attachSession(j.draft); return; }
4774
+ // no draft: the newest start the human has not cleared — still starting (watch it) or refused (show its sentence)
4775
+ var st = j.start;
4776
+ if(!st) return;
4777
+ if(st.phase === "starting"){ beginStart(st.startId); return; }
4778
+ if(st.phase === "refused"){
4779
+ refusedStartId = st.startId;
4780
+ chatActionFailed(st.kind === "sign" ? st.say + " The flow is signed; start it from \"Run a signed flow\"." : st.say);
4781
+ if(st.kind === "sign") loadFlows(true);
4782
+ }
4783
+ }).catch(function(){ /* nothing to attach to — the empty card stays */ });
4784
+ }
4785
+
4786
+ // ---- wiring ----
4787
+ clearBtn.addEventListener("click", function(){
4788
+ if(mode === "resume"){ resumeCtx = null; actionErrEl.textContent = ""; setMode(modeBeforeResume === "resume" ? "new" : modeBeforeResume); return; }
4789
+ if(clearBtn.textContent === "Abandon" && sessionId){ doAbandon(); return; }
4790
+ // a refused start's sentence is dismissed on the server too, or a reload would bring it back
4791
+ if(refusedStartId){ var rid = refusedStartId; refusedStartId = null; authorPost("/api/author/start/" + rid + "/clear", {}).catch(function(){}); }
4792
+ resetCard();
4793
+ });
4794
+ // Start over (amendment 4 item 3): the same draft call as Draft, from the card as it is now; the old draft's files stay (a new draft id)
4795
+ startOverBtn.addEventListener("click", function(){ if(!startOverBtn.disabled) doDraft(); });
4796
+ mainBtn.addEventListener("click", function(){
4797
+ if(mainBtn.disabled) return;
4798
+ if(mainAction === "draft") doDraft();
4799
+ else if(mainAction === "run") doRun();
4800
+ else if(mainAction === "run-sign-prepare" || mainAction === "run-sign") doRunSign();
4801
+ else if(mainAction === "resume-sign-prepare" || mainAction === "resume-sign") doResumeSign();
4802
+ else if(mainAction === "revise") doRevise();
4803
+ else if(mainAction === "sign-prepare" || mainAction === "sign") doSign();
4804
+ });
4805
+ msgEl.addEventListener("input", function(){ fitBox(msgEl); renderMain(); });
4806
+ // Enter sends the note, Shift+Enter is a newline (bareloop's ask box)
4807
+ msgEl.addEventListener("keydown", function(e){
4808
+ if(e.key === "Enter" && !e.shiftKey && mainAction === "revise"){ e.preventDefault(); if(!mainBtn.disabled) doRevise(); }
4809
+ });
4810
+ card.addEventListener("input", function(e){
4811
+ var grp = e.target && e.target.closest ? e.target.closest(".field, .cap-field, .jf-inrow") : null;
4812
+ if(grp) grp.querySelectorAll(".jf-err").forEach(function(x){ x.textContent = ""; });
4813
+ dropFixBoxesBanner();
4814
+ fitCardBoxes();
4815
+ if(e.target && (e.target.id === "jf-cap-money" || e.target.id === "jf-job" || e.target.id === "jf-run-cap" || e.target.id === "jf-resume-cap")) scheduleCapNote();
4816
+ // any edit voids the first Sign click of the Run / Resume form: what is shown must be what is signed
4817
+ runSignInfo = null; resumeSignInfo = null;
4818
+ refreshStartEnabled();
4819
+ });
4820
+ document.querySelectorAll('input[name="jf-mode"]').forEach(function(r){
4821
+ r.addEventListener("change", function(){ if(r.checked) setMode(r.value); });
4822
+ });
4823
+ runFlowSel.addEventListener("input", function(){ rwHl = 0; renderFlowSearch(); });
4824
+ runFlowSel.addEventListener("keydown", function(e){
4825
+ if(e.key === "ArrowDown"){ rwHl = Math.min(rwHl + 1, rwShown.length - 1); renderFlowSearch(); e.preventDefault(); }
4826
+ else if(e.key === "ArrowUp"){ rwHl = Math.max(rwHl - 1, 0); renderFlowSearch(); e.preventDefault(); }
4827
+ else if(e.key === "Enter" && rwShown[rwHl]){ e.preventDefault(); pickFlowChoice(rwShown[rwHl]); }
4828
+ });
4829
+ rwListEl.addEventListener("click", function(e){
4830
+ var li = e.target.closest ? e.target.closest("li") : null;
4831
+ if(li) pickFlowChoice(rwShown[Number(li.getAttribute("data-i"))]);
4832
+ });
4833
+ document.getElementById("rw-change").addEventListener("click", unpickFlow);
4834
+ document.getElementById("rw-change").addEventListener("keydown", function(e){ if(e.key === "Enter" || e.key === " "){ e.preventDefault(); unpickFlow(); } });
4835
+ window.addEventListener("resize", fitCardBoxes);
4836
+ document.getElementById("tab-chat").addEventListener("click", function(){ fitCardBoxes(); reattachLive(); loadFlows(); });
4837
+ // the monthly limit changed in Settings: re-read the note for whatever cap is on the card (no reload; the button follows)
4838
+ document.addEventListener("fwdloop-limit-changed", function(){ refreshCapNote(); });
4839
+
4840
+ loadModel();
4841
+ loadFlows();
4842
+ reattachLive();
4843
+ refreshStartEnabled();
4844
+ })();
4845
+
3228
4846
  // ---- M4d piece 4: Settings. Nothing here is re-rendered by the page's refresh tick: the Settings DOM is
3229
4847
  // painted only when it is opened, a tab is chosen, or a button here is pressed — and a price/limit box the
3230
4848
  // person has typed in ("dirty") is never overwritten by a repaint. No key value ever reaches this page. ----
@@ -3281,10 +4899,9 @@
3281
4899
  function sourceWord(src){
3282
4900
  if(src === "table") return "default";
3283
4901
  if(src === "ceiling") return "highest known rate, the model has no listed price";
3284
- if(src === "default-multiplier") return "default, 0.1 x input";
3285
4902
  return "set here";
3286
4903
  }
3287
- var PRICE_FIELDS = ["inPerM", "cachedInPerM", "outPerM"];
4904
+ var PRICE_FIELDS = ["inPerM", "outPerM"];
3288
4905
  // Name, API shape and Base URL are editable (M4d amendment 1), saved on change one field at a time.
3289
4906
  var PROV_FIELDS = ["name", "shape", "baseUrl"];
3290
4907
  function buildProviderRow(row){
@@ -3455,6 +5072,7 @@
3455
5072
  mlLimit.removeAttribute("data-dirty");
3456
5073
  loadMoney().then(function(){
3457
5074
  setNote(msg, false, r.body.monthlyLimitUsd === null ? "saved — no monthly limit" : "saved — the limit is now $" + r.body.monthlyLimitUsd);
5075
+ document.dispatchEvent(new CustomEvent("fwdloop-limit-changed"));
3458
5076
  });
3459
5077
  } else setNote(msg, true, settingsRefusal(r));
3460
5078
  }, function(){ setNote(msg, true, networkText()); });