@giamme/forge 0.17.0 → 0.18.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 (76) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +5 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/safety.md +8 -0
  11. package/forge +24 -1
  12. package/package.json +1 -1
  13. package/references/dataset.md +19 -0
  14. package/references/decompose.md +134 -1
  15. package/references/solo.md +2 -1
  16. package/references/ui.md +5 -2
  17. package/scripts/forge-artifact.sh +14 -0
  18. package/scripts/forge-brief.py +132 -0
  19. package/scripts/forge-compare.py +11 -1
  20. package/scripts/forge-config.py +176 -9
  21. package/scripts/forge-contract.py +46 -3
  22. package/scripts/forge-control.py +86 -13
  23. package/scripts/forge-dispatch.sh +14 -10
  24. package/scripts/forge-du.py +167 -0
  25. package/scripts/forge-lib-adopt.sh +1 -0
  26. package/scripts/forge-lib-plans.sh +5 -2
  27. package/scripts/forge-lib-review.sh +29 -1
  28. package/scripts/forge-metrics.sh +7 -3
  29. package/scripts/forge-parallel-options.sh +4 -0
  30. package/scripts/forge-parallel.sh +503 -9
  31. package/scripts/forge-prompt.py +120 -0
  32. package/scripts/forge-retro.py +115 -0
  33. package/scripts/forge-runs-compact.py +443 -0
  34. package/scripts/forge-runs-rm.py +2 -0
  35. package/scripts/forge-runs.py +18 -3
  36. package/scripts/forge-schedule.py +279 -4
  37. package/scripts/forge-shadow.py +7 -1
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-summarize.py +698 -0
  40. package/scripts/forge-ui-options.sh +10 -0
  41. package/scripts/forge_brief/__init__.py +587 -0
  42. package/scripts/forge_brief/answers.py +459 -0
  43. package/scripts/forge_dataset/__init__.py +10 -0
  44. package/scripts/forge_dataset/export.py +18 -4
  45. package/scripts/forge_dataset/facts.py +6 -4
  46. package/scripts/forge_dataset/harvest.py +40 -6
  47. package/scripts/forge_dataset/history.py +5 -3
  48. package/scripts/forge_decide/__init__.py +11 -1
  49. package/scripts/forge_locations.py +366 -0
  50. package/scripts/forge_registry.py +19 -0
  51. package/scripts/forge_retro/__init__.py +417 -0
  52. package/scripts/forge_retro/issues.py +1193 -0
  53. package/scripts/forge_retro/report.py +671 -0
  54. package/scripts/forge_side/__init__.py +477 -0
  55. package/scripts/forge_storage.py +515 -0
  56. package/ui/README.md +68 -8
  57. package/ui/docs/api.md +205 -17
  58. package/ui/forge_ui/control.py +92 -11
  59. package/ui/forge_ui/export.py +24 -5
  60. package/ui/forge_ui/links.py +337 -0
  61. package/ui/forge_ui/models.py +57 -4
  62. package/ui/forge_ui/projects.py +4 -1
  63. package/ui/forge_ui/reader.py +661 -30
  64. package/ui/forge_ui/static/app.js +86 -4
  65. package/ui/forge_ui/static/briefview.js +302 -0
  66. package/ui/forge_ui/static/checksview.js +6 -2
  67. package/ui/forge_ui/static/controls.js +5 -0
  68. package/ui/forge_ui/static/index.html +3 -0
  69. package/ui/forge_ui/static/panel.js +268 -2
  70. package/ui/forge_ui/static/runmodel.js +13 -1
  71. package/ui/forge_ui/static/storageview.js +271 -0
  72. package/ui/forge_ui/static/style.css +99 -3
  73. package/ui/forge_ui/static/worktreesview.js +3 -3
  74. package/ui/forge_ui/storage.py +136 -0
  75. package/ui/forge_ui/transcripts.py +35 -10
  76. package/ui/forge_ui/worktrees.py +154 -13
@@ -1,6 +1,8 @@
1
1
  /* forge-ui inspector: what a selected node is, which model owned it, what prompt launched it, how long it
2
2
  took and what its reviewer found. Defines window.ForgePanel.render(host, ctx). All API values enter the
3
3
  DOM as text. Large texts (prompts, reports) come from the lazy endpoints and are fetched once per node.
4
+ A task opens on its header (title, goal, links, and the prompt, approach and acceptance criteria) and
5
+ its attempt trail, then its summary (#133 B), then its brief questions (#135) when it has them, and the chips and the rest.
4
6
  The run's and a task's write controls are controls.js's (ForgeControls); this file only says where they stand. */
5
7
  window.ForgePanel = (() => {
6
8
  'use strict';
@@ -12,6 +14,7 @@ window.ForgePanel = (() => {
12
14
  const STATUSES = new Set(['merged', 'pass', 'running', 'pending', 'fail', 'error', 'infra', 'timeout', 'unknown', 'invalidated', 'blocked',
13
15
  'interrupted', 'nochanges', 'conflict', 'accepted', 'none', 'outdated', 'needs_input', 'needs_decision', 'waiting']);
14
16
  const cache = new Map(); // path → {data, error, at}
17
+ const shownText = new Map(); // task id → which header text is open (prompt, approach, criteria)
15
18
  function el(tag, text, className) {
16
19
  const node = document.createElement(tag);
17
20
  if (text !== undefined) node.textContent = display(text);
@@ -336,6 +339,15 @@ window.ForgePanel = (() => {
336
339
  const line = window.ForgeSettings && window.ForgeSettings.profileRowText && window.ForgeSettings.profileRowText(profile);
337
340
  return line || undefined;
338
341
  }
342
+ // the Retro section (retro mode only): the report's counts on one line, then the report, collapsed like the other long texts.
343
+ // The report is plain text: forge-ui has no Markdown renderer, and run data never goes in as HTML.
344
+ function retroSection(host, run) {
345
+ const line = RM.retroSummary(run.retro);
346
+ if (!line) return;
347
+ const s = section(host, 'Retro');
348
+ muted(s, line);
349
+ if (run.retro.text != null) details(s, 'Report', run.retro.text, 'run-retro');
350
+ }
339
351
  // the run's record: what it was asked, how it was set up, and what verification printed (the header names and counts it)
340
352
  function runRecord(host, ctx) {
341
353
  const run = ctx.run, solo = run.kind === 'solo';
@@ -348,6 +360,7 @@ window.ForgePanel = (() => {
348
360
  ['Verification', chip((run.verification && run.verification.status) || run.verification_status)],
349
361
  ['Command', run.verification && run.verification.command, true]]);
350
362
  details(host, 'Request', display(run.request), 'run-request');
363
+ retroSection(host, run);
351
364
  if (!solo) details(host, 'Waves', list(run.waves).map((ids, i) => `${i + 1}: ${list(ids).join(', ')}`).join('\n') || '—', 'waves');
352
365
  if (run.verification && run.verification.log_tail != null) details(host, 'Verification output', run.verification.log_tail, 'verification-output');
353
366
  }
@@ -431,8 +444,260 @@ window.ForgePanel = (() => {
431
444
  s.append(ul);
432
445
  }
433
446
 
447
+ // Why an attempt ran, in the words the trail shows. Anything else reads as unrecorded.
448
+ const TRAIL_REASONS = {
449
+ first: 'first attempt', review: 'after review findings', prereview: 'after failing tests before review',
450
+ bounce: 'after unaddressed findings', message: 'after an unfinished message', answer: 'after your answer',
451
+ escalation: 'escalated to a stronger model', manual: 'manual retry', unknown: 'reason not recorded',
452
+ };
453
+ function reasonText(reason) {
454
+ return Object.prototype.hasOwnProperty.call(TRAIL_REASONS, reason) ? TRAIL_REASONS[reason] : TRAIL_REASONS.unknown;
455
+ }
456
+ function findingsText(item) {
457
+ const findings = item && item.findings;
458
+ const has = !!findings && typeof findings === 'object' && !Array.isArray(findings);
459
+ const count = has ? (num(findings.confirmed) === null ? 0 : num(findings.confirmed)) : null;
460
+ const worst = item && item.worst ? String(item.worst) : '';
461
+ if (count === null && !worst) return 'no findings';
462
+ const n = count === null ? 0 : count;
463
+ const noun = n === 1 ? 'finding' : 'findings';
464
+ return worst ? `${n} ${noun} (worst ${worst})` : `${n} ${noun}`;
465
+ }
466
+ // `#2 grok:xhigh · FAIL · 3 findings (worst P1) · after review findings`
467
+ function trailLine(item) {
468
+ const row = item || {};
469
+ const attempt = row.attempt == null || row.attempt === '' ? '—' : row.attempt;
470
+ const dwarf = row.dwarf ? String(row.dwarf) : '—';
471
+ const verdict = row.verdict ? String(row.verdict) : '—';
472
+ return `#${attempt} ${dwarf} · ${verdict} · ${findingsText(row)} · ${reasonText(row.reason)}`;
473
+ }
474
+ // A header link: `#123` or `PR #45` when it has a number, the url itself otherwise.
475
+ // Only an http(s) url is opened; anything else is shown as text.
476
+ function linkModel(link) {
477
+ if (!link || typeof link !== 'object') return { label: 'link', href: null };
478
+ const href = typeof link.url === 'string' && /^https?:\/\//i.test(link.url) ? link.url : null;
479
+ let label = 'link';
480
+ if (link.kind === 'pr' && link.number != null) label = `PR #${link.number}`;
481
+ else if (link.number != null) label = `#${link.number}`;
482
+ else if (href) label = href;
483
+ return { label, href };
484
+ }
485
+ function linkChip(item) {
486
+ const model = linkModel(item);
487
+ if (!model.href) return el('span', model.label, 'task-link-text');
488
+ const a = el('a', model.label, 'chip');
489
+ a.href = model.href; a.target = '_blank'; a.rel = 'noopener noreferrer';
490
+ return a;
491
+ }
492
+ const textMissing = v => v == null || v === '';
493
+ // Prompt and approach come from the lazy task detail once it has landed, and from the task until then.
494
+ // Acceptance criteria is header.criteria, already on the task. A missing text disables its button.
495
+ function knownTexts(task, detail) {
496
+ if (detail && detail.data) {
497
+ const t = detail.data.texts || {};
498
+ return { prompt: t.prompt ?? null, approach: t.approach ?? null, settled: true };
499
+ }
500
+ return { prompt: task.prompt ?? null, approach: task.approach ?? null, settled: false };
501
+ }
502
+ function headerActions(header, texts) {
503
+ const h = header || {}, t = texts || {};
504
+ return [
505
+ { key: 'prompt', label: 'Prompt', disabled: textMissing(t.prompt), text: t.prompt ?? null },
506
+ { key: 'approach', label: 'Approach', disabled: textMissing(t.approach), text: t.approach ?? null },
507
+ { key: 'criteria', label: 'Acceptance criteria', disabled: textMissing(h.criteria), text: h.criteria ?? null },
508
+ ];
509
+ }
510
+ function revealBody(key, detail, action) {
511
+ if (key === 'criteria') return action && action.text != null ? String(action.text) : '';
512
+ if (detail && detail.error) {
513
+ const err = detail.error;
514
+ return err.status === 404 ? 'This text is not available from this server.' : `Could not load it: ${err.message || 'error'}`;
515
+ }
516
+ if (!detail || !detail.data) return 'Loading…';
517
+ return action && action.text != null ? String(action.text) : '';
518
+ }
519
+ function taskHeader(host, ctx, task, detail) {
520
+ const header = task.header || {};
521
+ const texts = knownTexts(task, detail);
522
+ const actions = headerActions(header, texts);
523
+ let open = shownText.get(task.id) || null;
524
+ if (open && actions.some(a => a.key === open && a.disabled && texts.settled)) { shownText.delete(task.id); open = null; }
525
+ const box = el('div', undefined, 'task-header');
526
+ const top = el('div', undefined, 'task-header-top');
527
+ top.append(el('h2', header.title || task.title || 'Untitled task'));
528
+ if (header.goal) top.append(el('p', header.goal, 'task-goal'));
529
+ box.append(top);
530
+ const links = list(header.links);
531
+ if (links.length) {
532
+ const row = el('div', undefined, 'chips task-links');
533
+ for (const item of links) row.append(linkChip(item));
534
+ box.append(row);
535
+ }
536
+ const bank = el('div', undefined, 'seg task-texts');
537
+ bank.setAttribute('role', 'group'); bank.setAttribute('aria-label', 'Task text');
538
+ for (const action of actions) {
539
+ const button = el('button', action.label);
540
+ button.type = 'button'; button.dataset.text = action.key; button.disabled = action.disabled;
541
+ button.setAttribute('aria-pressed', open === action.key ? 'true' : 'false');
542
+ button.addEventListener('click', () => {
543
+ shownText.set(task.id, shownText.get(task.id) === action.key ? null : action.key);
544
+ ctx.rerender();
545
+ });
546
+ bank.append(button);
547
+ }
548
+ box.append(bank);
549
+ if (open) {
550
+ const action = actions.find(a => a.key === open);
551
+ const pre = el('pre', revealBody(open, detail, action), 'task-reveal');
552
+ pre.dataset.scroll = `task-${task.id}-header-text`;
553
+ box.append(pre);
554
+ }
555
+ host.append(box);
556
+ }
557
+ // The links to an attempt's executions, one per execution, labelled by role. The trail and a summary's sources share them.
558
+ function executionLinks(ctx, task, ids) {
559
+ const nav = el('span', undefined, 'trail-nav');
560
+ for (const id of list(ids)) {
561
+ const role = String(id).split('-')[0].toLowerCase();
562
+ const target = { kind: 'execution', task: task.id, id: task.id, exec: id, shadow: false };
563
+ nav.append(link(role, ctx.hash(target), () => ctx.onSelect(target)));
564
+ }
565
+ return nav;
566
+ }
567
+ // One line per attempt. Its executions open the same way the Attempts section opens them.
568
+ function attemptTrail(host, ctx, task) {
569
+ const items = list(task.trail);
570
+ if (!items.length) return;
571
+ const ol = el('ol', undefined, 'attempt-trail');
572
+ for (const item of items) {
573
+ const li = el('li', undefined, 'trail-line');
574
+ li.append(el('span', trailLine(item), 'trail-summary'));
575
+ const nav = executionLinks(ctx, task, item && item.executions);
576
+ if (nav.childElementCount) li.append(nav);
577
+ ol.append(li);
578
+ }
579
+ host.append(ol);
580
+ }
581
+
582
+ /* ---------- summaries (#133 B): a task's generated summary, and the switches that turn summaries on or off ---------- */
583
+ // A switch's question, answer and request body are controls.js's (prepare, savedText); the confirm strip and the POST
584
+ // are uikit's. An answer stays on the page for a few seconds, so a poll that draws the section again keeps it in view.
585
+ const ANSWER_MS = 9000;
586
+ const answers = new Map(); // a section's hold key → {res, text, at}
587
+ const ago = (at, now) => window.ForgeControls ? window.ForgeControls.agoText(at, now) : time(at);
588
+ const findingsId = taskId => `task-${taskId}-findings`;
589
+ // A bank of push keys: the value in force is pressed, and pressing the pressed key does nothing.
590
+ function summaryBank(options, current, pick, label) {
591
+ const seg = el('div', undefined, 'seg sum-bank');
592
+ seg.setAttribute('role', 'group'); seg.setAttribute('aria-label', label);
593
+ for (const [value, text] of options) {
594
+ const b = el('button', text); b.type = 'button'; b.dataset.value = value;
595
+ b.setAttribute('aria-pressed', String(value === current));
596
+ b.addEventListener('click', () => { if (b.getAttribute('aria-pressed') !== 'true') pick(value); });
597
+ seg.append(b);
598
+ }
599
+ return seg;
600
+ }
601
+ // Asks, sends and answers one change to a summaries switch (`forge control set summaries`). `slot` takes the question
602
+ // and the answer. `held` is the section that holds a task's switch (null for the run's): it is kept as it is while the
603
+ // question is open or the answer pends, the way controls.js keeps its own sections.
604
+ function changeSummaries(slot, held, runKey, change, done) {
605
+ const C = window.ForgeControls, U = window.ForgeUI, node = held || slot;
606
+ const plan = C.prepare({ kind: 'set', key: 'summaries', input: change.input, task: change.task });
607
+ if (!plan.ok) { U.outcome(slot, { ok: false, status: 400, error: 'invalid', detail: plan.error }); return; }
608
+ if (node.dataset.busy) return;
609
+ node.dataset.editing = '1';
610
+ U.confirmInline(slot, plan.confirm).then(async yes => {
611
+ if (!yes) { if (!slot.querySelector('.ui-confirm')) delete node.dataset.editing; return; } // a newer question took the strip
612
+ node.dataset.busy = '1';
613
+ if (held) held.setAttribute('aria-busy', 'true');
614
+ const res = await U.post(`/api/runs/${encodeURIComponent(runKey)}/controls`, plan.body);
615
+ delete node.dataset.busy; delete node.dataset.editing;
616
+ if (held) held.removeAttribute('aria-busy');
617
+ const text = C.savedText(res.data);
618
+ if (held) answers.set(held.dataset.hold, { res, text, at: Date.now() });
619
+ U.outcome(slot, res, text);
620
+ if (done) done(res);
621
+ });
622
+ }
623
+ // The summary's text as plain text, its model and when it was made, whether the task changed since, the error of a
624
+ // failed try, and where it came from.
625
+ function summaryText(s, ctx, task, sum) {
626
+ s.append(el('p', sum.text, 'sum-text'));
627
+ const by = el('p', undefined, 'muted sum-by');
628
+ by.title = time(sum.generated_at);
629
+ by.append(document.createTextNode('Generated by '), sum.model ? plate(sum.model) : el('span', 'an unrecorded model'),
630
+ document.createTextNode(`, ${ago(sum.generated_at, ctx.now)}`));
631
+ if (sum.stale) by.append(document.createTextNode(' '), chip('Out of date', 'outdated'));
632
+ s.append(by);
633
+ if (sum.error) s.append(el('p', `The last try failed: ${String(sum.error).trim()}`, 'warn sum-error'));
634
+ if (list(sum.sources).length) s.append(sourceList(ctx, task, sum.sources));
635
+ }
636
+ // Where a summary came from: an attempt's executions, as the trail links them; a finding, linked to the review findings
637
+ // section. A source the task no longer has is named, not linked.
638
+ function sourceList(ctx, task, sources) {
639
+ const ul = el('ul', undefined, 'sum-sources');
640
+ for (const src of sources) {
641
+ const li = el('li'), ref = String(src.ref || '');
642
+ if (src.kind === 'attempt') {
643
+ li.append(el('span', `attempt ${ref}`));
644
+ const item = list(task.trail).find(t => t && String(t.attempt) === ref);
645
+ const nav = executionLinks(ctx, task, item && item.executions);
646
+ if (nav.childElementCount) li.append(nav);
647
+ } else {
648
+ const cut = ref.indexOf(':'), attempt = cut > 0 ? ref.slice(0, cut) : null, title = cut > 0 ? ref.slice(cut + 1) : ref;
649
+ const a = el('a', title || 'finding'); a.href = '#' + findingsId(task.id);
650
+ a.addEventListener('click', e => {
651
+ e.preventDefault();
652
+ const node = document.getElementById(findingsId(task.id));
653
+ if (node) node.scrollIntoView({ block: 'nearest' });
654
+ });
655
+ li.append(el('span', 'finding: ', 'muted'), a);
656
+ if (attempt) li.append(el('span', `attempt ${attempt}`, 'muted'));
657
+ }
658
+ ul.append(li);
659
+ }
660
+ return ul;
661
+ }
662
+ // The task's own switch: inherit the run's, or on or off for this task (`forge control set summaries --task`).
663
+ function summaryOverride(s, ctx, task) {
664
+ const key = s.dataset.hold, run = ctx.run, own = task.summaries_override;
665
+ const current = own === 'on' || own === 'off' ? own : 'inherit';
666
+ const runOn = !!run.summaries && run.summaries.mode === 'on';
667
+ // A data-row inside the section's data-hold: controls.js's hold() puts the keyboard back on this key after a redraw.
668
+ const row = el('div', undefined, 'sum-switch'), msgs = el('div', undefined, 'sum-msgs');
669
+ row.dataset.row = 'summary-override';
670
+ const pick = value => changeSummaries(msgs, s, run.key, { input: value, task: task.id }, () => ctx.refresh && ctx.refresh());
671
+ const bank = summaryBank([['inherit', 'Inherit'], ['on', 'On'], ['off', 'Off']], current, pick, 'Summaries for this task');
672
+ row.append(el('p', 'Summaries for this task', 'sum-label'), bank,
673
+ el('p', current === 'inherit' ? `Follows the run: ${runOn ? 'on' : 'off'}.` : `${current === 'on' ? 'On' : 'Off'} for this task, whatever the run sets.`, 'muted sum-note'),
674
+ msgs);
675
+ const answer = answers.get(key);
676
+ if (answer && Date.now() - answer.at < ANSWER_MS && window.ForgeUI) window.ForgeUI.outcome(msgs, answer.res, answer.text, { silent: true });
677
+ return row;
678
+ }
679
+ // The task's summary, after its attempt trail: its text, what it came from, and the switch where this page can change
680
+ // the run. A solo run has none. A task with no summary shows only its switch; where the page cannot write, nothing.
681
+ function summarySection(host, ctx, task) {
682
+ const run = ctx.run, sum = task.summary || null, U = window.ForgeUI;
683
+ if (run.kind === 'solo') return;
684
+ const s = section(host, 'Summary');
685
+ s.classList.add('sum-section');
686
+ s.dataset.hold = `summary:${run.key}:${task.id}`;
687
+ if (sum) summaryText(s, ctx, task, sum); else muted(s, 'No summary yet.');
688
+ const row = summaryOverride(s, ctx, task);
689
+ s.append(row);
690
+ const writable = U && U.controlsEnabled && window.ForgeControls ? U.controlsEnabled() : Promise.resolve(false);
691
+ writable.then(on => { if (!on) { row.remove(); if (!sum) s.remove(); } });
692
+ }
693
+
434
694
  function taskView(host, ctx, task) {
435
695
  const run = ctx.run, now = ctx.now, solo = run.kind === 'solo';
696
+ const detail = lazy(ctx, `/api/runs/${encodeURIComponent(run.key)}/tasks/${encodeURIComponent(task.id)}`, run.updated);
697
+ taskHeader(host, ctx, task, detail);
698
+ attemptTrail(host, ctx, task);
699
+ summarySection(host, ctx, task);
700
+ if (window.ForgeBrief) window.ForgeBrief.taskSection(host, ctx, task);
436
701
  const head = el('div', undefined, 'insp-head');
437
702
  head.append(el('h2', solo ? (task.title || 'Solo run') : `${task.id} · ${task.title || 'Untitled task'}`), el('div', solo ? 'solo task' : `task · wave ${display(task.wave)}`, 'insp-kind'));
438
703
  const chips = el('div', undefined, 'chips');
@@ -521,11 +786,11 @@ window.ForgePanel = (() => {
521
786
 
522
787
  // reviews and their findings
523
788
  const rs = section(host, 'Review findings');
789
+ rs.id = findingsId(task.id); // a summary's finding links here
524
790
  gateLine(rs, task.gate);
525
791
  findingCounts(rs, task.findings);
526
792
  failFirst(rs, task.fail_first);
527
793
  preReview(rs, task.pre_review);
528
- const detail = lazy(ctx, `/api/runs/${encodeURIComponent(run.key)}/tasks/${encodeURIComponent(task.id)}`, run.updated);
529
794
  if (!loading(rs, detail, 'the full findings')) {
530
795
  const reviews = list(detail.data.reviews);
531
796
  if (!reviews.length) muted(rs, 'No review has run yet.');
@@ -858,5 +1123,6 @@ window.ForgePanel = (() => {
858
1123
  if (sel.kind === 'fractal') return fractalNodeView(host, ctx, sel);
859
1124
  return runView(host, ctx);
860
1125
  }
861
- return { render, cache };
1126
+ return { render, cache, trailLine, reasonText, linkModel, headerActions, summaryBank, changeSummaries };
862
1127
  })();
1128
+ if (typeof module === 'object' && module.exports) module.exports = window.ForgePanel;
@@ -914,6 +914,18 @@
914
914
  return s ? { lamp: s[0], text: s[1] } : { lamp: 'pending', text: 'its fix task has not merged' };
915
915
  }
916
916
 
917
+ /* ---------- the retro report (retro.md, retro/notes.jsonl) ---------- */
918
+ // RunDetail.retro → the Retro section's one line, e.g. "5 notes: 3 you can fix, 2 for forge · 4 verified, 1 claimed · 1 blocking".
919
+ // Unsure notes are named only when there are some. Null when the run has no retro record.
920
+ function retroSummary(retro) {
921
+ if (!retro || typeof retro !== 'object') return null;
922
+ const n = key => num(retro[key]) || 0, word = (count, one, many) => `${count} ${count === 1 ? one : many}`;
923
+ if (!n('notes')) return '0 notes';
924
+ const fixable = [`${n('user')} you can fix`, `${n('forge')} for forge`];
925
+ if (n('unsure')) fixable.push(`${n('unsure')} not sure who`);
926
+ return `${word(n('notes'), 'note', 'notes')}: ${fixable.join(', ')} · ${n('verified')} verified, ${n('claimed')} claimed · ${n('blocking')} blocking`;
927
+ }
928
+
917
929
  /* ---------- Fractal: a task's child tasks as a tidy tree (depth across, siblings down) ---------- */
918
930
  // nodes: TaskFractal.nodes (tree order, parent ids); returns {pos: {id: {col, row, depth}}, edges: [[parent, child]], cols, rows}
919
931
  function fractalTree(nodes) {
@@ -942,5 +954,5 @@
942
954
  finalStatus, runReviewStatus, reviewSinceLine, reviewAt, taskStatus, statusText, causeLabel, resetText, taskVerdict, attemptStatus, attemptNote, attemptFailed, isWaiting,
943
955
  attributionLine, taskParts,
944
956
  taskTimes, metricValue, overlap, projectSchedule, execModel, verifyLeds, criticalPath, concurrency, stateAt, timeRange, events, lineage, structureKey, innerKey,
945
- fmtDur, alias, basename, weight, searchIndex, searchRank, statusEvents, fractalTree, sweepLine, sweepState };
957
+ fmtDur, alias, basename, weight, searchIndex, searchRank, statusEvents, fractalTree, sweepLine, sweepState, retroSummary };
946
958
  });
@@ -0,0 +1,271 @@
1
+ /* forge-ui Disk screen (#139): what forge takes on disk in every repository it has runs for (run dirs, worktrees,
2
+ its data home) and the command that takes each part back (window.ForgeStorage, and a CommonJS module under
3
+ node:test). Route #/disk. The same report as `forge du --all`, from the same rules (scripts/forge_storage.py).
4
+ The commands come from the server and are only ever copied: the page runs nothing, so it works with
5
+ --read-only too. Measuring visits every file, so it runs once in the background when the screen opens and
6
+ again on "Measure again"; the page polls only while a measurement runs.
7
+ The pure helpers are tested in ui/tests/js/storageview.test.js.
8
+ ctx = { runHref(path) -> href | null, tablePrefs?(id), saveTablePrefs?(id, prefs) }. */
9
+ (function (root, factory) {
10
+ 'use strict';
11
+ const api = factory(root);
12
+ if (typeof module === 'object' && module.exports) module.exports = api;
13
+ else root.ForgeStorage = api;
14
+ })(typeof self !== 'undefined' ? self : this, function (root) {
15
+ 'use strict';
16
+
17
+ const list = v => Array.isArray(v) ? v : [];
18
+ const POLL_MS = 2000;
19
+
20
+ /* ---------- pure ---------- */
21
+ function humanBytes(n) {
22
+ if (!Number.isFinite(n) || n < 0) return '—';
23
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
24
+ let i = 0, v = n;
25
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
26
+ return (i === 0 ? String(v) : v.toFixed(v < 10 ? 1 : 0)) + ' ' + units[i];
27
+ }
28
+ // One line on the whole: what forge takes and what can go without losing a run.
29
+ function summary(data) {
30
+ const t = (data && data.totals) || {};
31
+ const parts = [`${humanBytes(t.runs || 0)} in ${list(data && data.runs).length} run dirs`,
32
+ `${humanBytes(t.worktrees || 0)} in ${list(data && data.worktrees).length} worktree folders`];
33
+ if (data && data.data_home) parts.push(`${humanBytes(t.data_home || 0)} in the data home`);
34
+ return { total: (t.runs || 0) + (t.worktrees || 0) + (t.data_home || 0), text: parts.join(' · '), reclaimable: t.reclaimable || 0 };
35
+ }
36
+ // The data home's parts, largest first, with what each is for.
37
+ const HOME_LABEL = { dataset: 'dataset (kept: what forge learns from)', blobs: 'dataset blobs (kept)', archive: 'archives of deleted runs (forge runs rm)',
38
+ exports: 'exports (forge dataset export writes them again)', legacy: 'legacy files from older releases', storage: 'storage records', other: 'other' };
39
+ function homeParts(home) {
40
+ const p = (home && home.parts) || {};
41
+ return Object.keys(HOME_LABEL).filter(k => p[k] > 0).map(k => ({ key: k, label: HOME_LABEL[k], bytes: p[k] })).sort((a, b) => b.bytes - a.bytes);
42
+ }
43
+ const repoName = p => typeof p === 'string' && p ? p.replace(/\/+$/, '').split('/').pop() : '—';
44
+ // The chart's parts, in a fixed order that fixes their colours (--disk-1 … --disk-6): a part keeps its colour
45
+ // whatever else is on screen.
46
+ const PARTS = [
47
+ { key: 'snapshots', label: 'review snapshots', note: 'can go: nothing reads them', color: 'var(--disk-1)' },
48
+ { key: 'logs', label: 'logs', note: 'gzipping the log copies takes most of it back', color: 'var(--disk-2)' },
49
+ { key: 'other', label: 'other run files', note: 'prompts, diffs, verdicts: what forge-ui shows', color: 'var(--disk-3)' },
50
+ { key: 'strays', label: "not forge's", note: 'found inside run dirs; forge never removes them', color: 'var(--disk-4)' },
51
+ { key: 'worktrees', label: 'worktrees', note: 'see the Worktrees screen', color: 'var(--disk-5)' },
52
+ { key: 'home', label: 'data home', note: 'the dataset (kept), archives, exports', color: 'var(--disk-6)' },
53
+ ];
54
+ // [{key, label, note, color, bytes, share}] of everything forge takes, in PARTS order; empty parts stay (0 bytes).
55
+ function breakdown(data) {
56
+ const t = (data && data.totals) || {}, runs = list(data && data.runs);
57
+ const sum = f => runs.reduce((n, r) => n + (Number(f(r)) || 0), 0);
58
+ const bytes = { snapshots: sum(r => r.snapshots), logs: sum(r => (r.logs || 0) + (r.gz || 0)), other: sum(r => (r.other || 0) + (r.fractal || 0)),
59
+ strays: sum(r => r.strays), worktrees: t.worktrees || 0, home: (data && data.data_home && data.data_home.bytes) || 0 };
60
+ const total = Object.values(bytes).reduce((a, b) => a + b, 0);
61
+ return PARTS.map(p => ({ ...p, bytes: bytes[p.key], share: total ? bytes[p.key] / total : 0 }));
62
+ }
63
+ // [{repo, name, total, parts: {key: bytes}}] largest first: each repository's run dirs and worktree folders.
64
+ function byRepo(data) {
65
+ const out = new Map();
66
+ const at = repo => {
67
+ const k = repo || '';
68
+ if (!out.has(k)) out.set(k, { repo: repo || null, name: repo ? repoName(repo) : 'unknown repository', total: 0,
69
+ parts: { snapshots: 0, logs: 0, other: 0, strays: 0, worktrees: 0 } });
70
+ return out.get(k);
71
+ };
72
+ const add = (g, key, n) => { n = Number(n) || 0; g.parts[key] += n; g.total += n; };
73
+ for (const r of list(data && data.runs)) {
74
+ const g = at(r.repo);
75
+ add(g, 'snapshots', r.snapshots); add(g, 'logs', (r.logs || 0) + (r.gz || 0)); add(g, 'other', (r.other || 0) + (r.fractal || 0)); add(g, 'strays', r.strays);
76
+ }
77
+ for (const w of list(data && data.worktrees)) add(at(w.repo), 'worktrees', w.bytes);
78
+ return Array.from(out.values()).filter(g => g.total > 0).sort((a, b) => b.total - a.total);
79
+ }
80
+ const pct = x => x >= 0.995 ? '100%' : x >= 0.1 ? Math.round(x * 100) + '%' : x > 0 ? (x * 100 < 1 ? '<1%' : (x * 100).toFixed(0) + '%') : '0%';
81
+
82
+ /* ---------- DOM ---------- */
83
+ function render(host, ctx) {
84
+ const UI = root.ForgeUI;
85
+ const el = (tag, text, cls) => UI.el(tag, text, cls);
86
+ const s = { answer: null, error: null, timer: null, seq: 0 };
87
+
88
+ const head = el('div', undefined, 'wt-head');
89
+ const again = el('button', 'Measure again'); again.type = 'button';
90
+ again.title = 'Visit every file again now; it takes a while on large run dirs';
91
+ again.addEventListener('click', () => load(true));
92
+ const stamp = el('span', '', 'muted wt-stamp');
93
+ head.append(el('h1', 'Disk', 'module-title'), again, stamp);
94
+ const lede = el('p', 'What forge takes on disk in every repository it has runs for, and the command that takes each part back. Review snapshots and log copies can go without losing a run: every run stays viewable here and in the dataset. Commands are only copied: this page runs nothing.', 'muted wt-lede');
95
+ const status = el('p', undefined, 'wt-totals'); status.setAttribute('role', 'status');
96
+ const cmds = el('div', undefined, 'disk-commands');
97
+ const chart = el('section', undefined, 'disk-chart');
98
+ chart.setAttribute('aria-label', 'Where the space goes');
99
+ const tip = el('div', undefined, 'disk-tip'); tip.hidden = true; tip.setAttribute('role', 'tooltip');
100
+ const tableHost = el('div', undefined, 'wt-table');
101
+ const extra = el('section', undefined, 'disk-extra');
102
+ host.replaceChildren(head, lede, status, chart, cmds, tableHost, extra, tip);
103
+
104
+ // one tooltip for every segment: what it is, its size and its share, beside the pointer or the focused segment
105
+ function showTip(seg, x, y) {
106
+ const p = seg._part;
107
+ tip.replaceChildren(el('strong', p.label), el('span', ` ${humanBytes(p.bytes)} · ${pct(p.share)}${seg._of ? ' of ' + seg._of : ''}`), el('span', p.note, 'muted'));
108
+ tip.hidden = false;
109
+ const box = host.getBoundingClientRect(), w = tip.offsetWidth;
110
+ tip.style.left = Math.max(0, Math.min(x - box.left + 12, box.width - w)) + 'px';
111
+ tip.style.top = (y - box.top + 16) + 'px';
112
+ }
113
+ function segment(part, width, of) {
114
+ const seg = el('span', undefined, 'disk-seg');
115
+ seg._part = part; seg._of = of;
116
+ seg.style.flexGrow = String(width); seg.style.background = part.color;
117
+ seg.tabIndex = 0;
118
+ seg.setAttribute('aria-label', `${part.label}: ${humanBytes(part.bytes)}, ${pct(part.share)}${of ? ' of ' + of : ''}`);
119
+ seg.addEventListener('pointermove', e => showTip(seg, e.clientX, e.clientY));
120
+ seg.addEventListener('pointerleave', () => { tip.hidden = true; });
121
+ seg.addEventListener('focus', () => { const r = seg.getBoundingClientRect(); showTip(seg, r.left + r.width / 2, r.bottom - 8); });
122
+ seg.addEventListener('blur', () => { tip.hidden = true; });
123
+ return seg;
124
+ }
125
+ function drawChart(d) {
126
+ const parts = breakdown(d), total = parts.reduce((n, p) => n + p.bytes, 0);
127
+ if (!total) { chart.replaceChildren(); return; }
128
+ const whole = el('div', undefined, 'disk-bar disk-bar-whole');
129
+ for (const p of parts) if (p.bytes > 0) whole.append(segment(p, p.bytes));
130
+ const legend = el('ul', undefined, 'disk-legend');
131
+ for (const p of parts) {
132
+ if (!p.bytes) continue;
133
+ const li = el('li'); const sw = el('i', undefined, 'disk-swatch'); sw.style.background = p.color;
134
+ li.append(sw, el('span', p.label), el('strong', humanBytes(p.bytes)), el('span', pct(p.share), 'muted'));
135
+ li.title = p.note; legend.append(li);
136
+ }
137
+ const repos = byRepo(d).slice(0, 10), top = repos.length ? repos[0].total : 0;
138
+ const rows = el('div', undefined, 'disk-repos');
139
+ for (const g of repos) {
140
+ const row = el('div', undefined, 'disk-repo');
141
+ const name = el('span', g.name, 'disk-repo-name'); if (g.repo) name.title = g.repo;
142
+ const track = el('div', undefined, 'disk-track');
143
+ const bar = el('div', undefined, 'disk-bar'); bar.style.width = (100 * g.total / top) + '%';
144
+ for (const p of parts) {
145
+ const n = g.parts[p.key] || 0;
146
+ if (n > 0) bar.append(segment({ ...p, bytes: n, share: n / g.total }, n, g.name));
147
+ }
148
+ track.append(bar);
149
+ row.append(name, track, el('span', humanBytes(g.total), 'disk-repo-size'));
150
+ rows.append(row);
151
+ }
152
+ const parts2 = [el('h2', 'Where the space goes', 'plate'), whole, legend];
153
+ if (repos.length) parts2.push(el('h2', 'By repository' + (byRepo(d).length > repos.length ? ' (the 10 largest)' : ''), 'plate disk-sub'), rows);
154
+ chart.replaceChildren(...parts2);
155
+ }
156
+
157
+ function copyButton(command) {
158
+ const b = el('button', 'Copy', 'wt-copy'); b.type = 'button';
159
+ b.setAttribute('aria-label', 'Copy: ' + command);
160
+ b.addEventListener('click', async () => {
161
+ try { await navigator.clipboard.writeText(command); b.textContent = 'Copied'; }
162
+ catch (_) { b.textContent = 'Copy failed: select it'; }
163
+ setTimeout(() => { b.textContent = 'Copy'; }, 2500);
164
+ });
165
+ return b;
166
+ }
167
+ function commandBox(c) {
168
+ const box = el('div', undefined, 'wt-cmd');
169
+ const code = el('code', c.command, 'mono'); code.tabIndex = 0; code.title = c.label;
170
+ box.append(code, copyButton(c.command));
171
+ return box;
172
+ }
173
+ const when = t => Number.isFinite(t) ? new Date(t * 1000).toLocaleString() : '—';
174
+ const bytesCell = n => Number.isFinite(n) && n > 0 ? humanBytes(n) : '—';
175
+ const columns = [
176
+ { id: 'run', label: 'Run', value: r => r.run_id, cell: r => {
177
+ const href = ctx.runHref ? ctx.runHref(r.path) : null;
178
+ const n = el(href ? 'a' : 'span', r.run_id, 'mono'); if (href) n.href = href; n.title = r.path; return n; } },
179
+ { id: 'repo', label: 'Repository', value: r => repoName(r.repo), cell: r => { const n = el('span', repoName(r.repo)); if (r.repo) n.title = r.repo; return n; } },
180
+ { id: 'total', label: 'Total', value: r => r.total, cell: r => humanBytes(r.total) },
181
+ { id: 'snapshots', label: 'Snapshots', title: 'review snapshots: nothing reads one once its review ended', value: r => r.snapshots, cell: r => bytesCell(r.snapshots) },
182
+ { id: 'logs', label: 'Logs', value: r => r.logs + r.gz, cell: r => bytesCell(r.logs + r.gz) },
183
+ { id: 'strays', label: "Not forge's", title: 'a dependency install or a .git found inside the run dir: forge never removes these', value: r => r.strays, cell: r => bytesCell(r.strays) },
184
+ { id: 'reclaimable', label: 'Can go', title: 'what forge runs compact --logs would take back (logs estimated)', value: r => r.reclaimable, cell: r => bytesCell(r.reclaimable) },
185
+ { id: 'command', label: 'Command', sortable: false, cls: 'wt-command-col', cell: r => { const box = el('div', undefined, 'wt-cmds'); for (const c of list(r.commands)) box.append(commandBox(c)); return box; } },
186
+ { id: 'updated', label: 'Changed', value: r => r.updated, cell: r => when(r.updated) },
187
+ { id: 'path', label: 'Path', value: r => r.path, cell: r => el('span', r.path, 'mono'), hidden: true },
188
+ ];
189
+ function drawExtra(d) {
190
+ const out = [];
191
+ if (list(d.strays).length) {
192
+ const box = el('div', undefined, 'disk-block');
193
+ box.append(el('h2', "Not forge's, found inside run dirs", 'plate'), el('p', 'forge never removes these. Delete them by hand if nothing needs them.', 'muted'));
194
+ const ul = el('ul', undefined, 'disk-list');
195
+ for (const x of list(d.strays)) { const li = el('li'); li.append(el('strong', humanBytes(x.bytes)), el('span', ' '), el('span', x.path, 'mono')); ul.append(li); }
196
+ box.append(ul); out.push(box);
197
+ }
198
+ const wt = el('div', undefined, 'disk-block');
199
+ wt.append(el('h2', 'Worktrees', 'plate'));
200
+ const line = el('p');
201
+ line.append(el('span', `${humanBytes((d.totals || {}).worktrees || 0)} in ${list(d.worktrees).length} worktree folders. `));
202
+ const a = el('a', 'Open the Worktrees screen'); a.href = '#/worktrees';
203
+ line.append(a, el('span', ' for the state of each one and the command that removes it safely.'));
204
+ wt.append(line);
205
+ if (list(d.worktrees).length) {
206
+ const ul = el('ul', undefined, 'disk-list');
207
+ for (const w of list(d.worktrees).slice(0, 8)) { const li = el('li'); li.append(el('strong', humanBytes(w.bytes)), el('span', ' '), el('span', w.path, 'mono')); ul.append(li); }
208
+ wt.append(ul);
209
+ }
210
+ out.push(wt);
211
+ if (d.data_home) {
212
+ const box = el('div', undefined, 'disk-block');
213
+ box.append(el('h2', 'Data home', 'plate'));
214
+ const p = el('p'); p.append(el('span', humanBytes(d.data_home.bytes) + ' in '), el('span', d.data_home.path, 'mono')); box.append(p);
215
+ const ul = el('ul', undefined, 'disk-list');
216
+ for (const x of homeParts(d.data_home)) { const li = el('li'); li.append(el('strong', humanBytes(x.bytes)), el('span', ' ' + x.label)); ul.append(li); }
217
+ box.append(ul); out.push(box);
218
+ }
219
+ extra.replaceChildren(...out);
220
+ }
221
+ function drawNow() {
222
+ const a = s.answer, d = a && a.data;
223
+ if (s.error) status.replaceChildren(el('span', `Could not read the disk report (${s.error}).`, 'warn'));
224
+ else if (!a) status.replaceChildren(el('span', 'Asking…', 'muted'));
225
+ else if (a.state === 'unavailable' || (a.state === 'error' && !d)) status.replaceChildren(el('span', `Could not measure: ${a.error || 'unknown error'}.`, 'warn'));
226
+ else if (a.state === 'measuring' && !d) {
227
+ const p = a.progress;
228
+ status.replaceChildren(el('span', p && p.of ? `Measuring run dir ${p.done + 1} of ${p.of}… every file is visited, so a large one takes a while.` : 'Measuring… every file is visited, so this takes a while.', 'muted'));
229
+ } else if (d) {
230
+ const sum = summary(d);
231
+ const parts = [el('strong', humanBytes(sum.total)), el('span', ' · ' + sum.text)];
232
+ if (sum.reclaimable) parts.push(el('span', ` · about ${humanBytes(sum.reclaimable)} can go without losing a run`));
233
+ if (a.state === 'measuring') parts.push(el('span', ' · measuring again…', 'muted'));
234
+ if (!d.complete) parts.push(el('span', ' · measuring stopped at its time limit: some sizes are lower bounds', 'muted'));
235
+ status.replaceChildren(...parts);
236
+ }
237
+ if (!d) { chart.replaceChildren(); cmds.replaceChildren(); tableHost.replaceChildren(); extra.replaceChildren(); return; }
238
+ drawChart(d);
239
+ stamp.textContent = 'measured ' + when(d.computed);
240
+ cmds.replaceChildren(...list(d.commands).map(commandBox));
241
+ if (!list(d.runs).length) tableHost.replaceChildren(el('p', 'forge has no registered runs.', 'muted'));
242
+ else {
243
+ tableHost.replaceChildren();
244
+ root.ForgeTable.render(tableHost, { id: 'disk', label: 'Run dirs', columns, rows: list(d.runs), className: 'wt-grid',
245
+ onRow: (_row, tr) => { for (const td of tr.children) if (!td.classList.contains('wt-command-col') && !td.title) td.title = td.textContent; },
246
+ prefs: ctx.tablePrefs ? ctx.tablePrefs('disk') : null, savePrefs: p => ctx.saveTablePrefs && ctx.saveTablePrefs('disk', p) });
247
+ }
248
+ drawExtra(d);
249
+ }
250
+ // A redraw never pulls a command out from under someone selecting or copying it (#115).
251
+ const draw = () => { if (UI.guard) UI.guard(host, drawNow); else drawNow(); };
252
+
253
+ async function load(refresh) {
254
+ const mine = ++s.seq;
255
+ again.disabled = true;
256
+ const res = await UI.get('/api/storage' + (refresh ? '?refresh=1' : ''));
257
+ if (mine !== s.seq) return;
258
+ if (res.ok) { s.answer = res.data; s.error = null; } else s.error = res.detail || res.error || 'no answer';
259
+ again.disabled = !!(s.answer && s.answer.state === 'measuring');
260
+ draw();
261
+ clearTimeout(s.timer);
262
+ if (host.isConnected && s.answer && s.answer.state === 'measuring')
263
+ s.timer = setTimeout(() => { if (host.isConnected) load(false); }, POLL_MS);
264
+ }
265
+ drawNow();
266
+ load(false);
267
+ return { reload: () => load(true) };
268
+ }
269
+
270
+ return { render, humanBytes, summary, homeParts, repoName, HOME_LABEL, PARTS, breakdown, byRepo, pct };
271
+ });