@giamme/forge 0.13.1 → 0.14.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 (47) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -0
  5. package/docs/commands.md +121 -7
  6. package/docs/development.md +3 -0
  7. package/docs/reviews.md +2 -0
  8. package/docs/troubleshooting.md +5 -1
  9. package/forge +28 -1
  10. package/package.json +1 -1
  11. package/references/dataset.md +3 -1
  12. package/references/decompose.md +199 -61
  13. package/references/runtime.md +29 -0
  14. package/references/ui.md +10 -0
  15. package/scripts/forge-compare.py +491 -0
  16. package/scripts/forge-config.py +3 -3
  17. package/scripts/forge-contract.py +34 -8
  18. package/scripts/forge-control.py +105 -13
  19. package/scripts/forge-dispatch.sh +9 -5
  20. package/scripts/forge-jev-options.sh +17 -4
  21. package/scripts/forge-ledger.py +387 -0
  22. package/scripts/forge-lib-plans.sh +11 -2
  23. package/scripts/forge-lib-task.sh +390 -28
  24. package/scripts/forge-parallel-options.sh +20 -4
  25. package/scripts/forge-parallel.sh +116 -12
  26. package/scripts/forge-plan-check.py +68 -3
  27. package/scripts/forge-pr.py +276 -0
  28. package/scripts/forge-route.py +350 -34
  29. package/scripts/forge-runs.py +18 -1
  30. package/scripts/forge-runtime.py +23 -7
  31. package/scripts/forge-schedule.py +303 -46
  32. package/scripts/forge-verify-failed.py +111 -0
  33. package/scripts/forge-watch.py +372 -0
  34. package/scripts/forge_dataset/harvest.py +3 -1
  35. package/scripts/forge_fractal/cli.py +23 -6
  36. package/scripts/forge_infra.py +274 -0
  37. package/scripts/forge_jev/client.py +13 -9
  38. package/ui/docs/api.md +51 -8
  39. package/ui/forge_ui/export.py +6 -2
  40. package/ui/forge_ui/reader.py +172 -6
  41. package/ui/forge_ui/static/app.js +2 -2
  42. package/ui/forge_ui/static/checksview.js +20 -7
  43. package/ui/forge_ui/static/controls.js +6 -3
  44. package/ui/forge_ui/static/panel.js +69 -4
  45. package/ui/forge_ui/static/runmodel.js +30 -4
  46. package/ui/forge_ui/static/scene3d.js +3 -2
  47. package/ui/forge_ui/static/style.css +11 -4
@@ -2,6 +2,7 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import hashlib
5
+ import importlib.util
5
6
  import json
6
7
  import math
7
8
  import os
@@ -609,12 +610,22 @@ def _scheduler(reader):
609
610
  paused = reader.object('infra.paused') if reader.exists('infra.paused') else None
610
611
  for scope in (paused or {}).get('scopes') or []:
611
612
  if isinstance(scope, dict):
612
- result['pauses'].append({key: scope.get(key) for key in
613
- ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')})
613
+ pause = {key: scope.get(key) for key in
614
+ ('scope', 'class', 'harness', 'model', 'tasks', 'cycle', 'until', 'exhausted')}
615
+ # the keys forge added later: an older scope has none, so they read as false and null
616
+ hint, reset_at = scope.get('hint'), scope.get('reset_at')
617
+ numeric = isinstance(reset_at, (int, float)) and not isinstance(reset_at, bool)
618
+ pause.update(needs_you=scope.get('needs_you') is True, hint=hint if isinstance(hint, str) else None,
619
+ reset_at=reset_at if numeric else None)
620
+ result['pauses'].append(pause)
614
621
  return result
615
622
 
616
623
 
624
+ # Not NEEDS_INPUT or NEEDS_DECISION: those wait for the user, so a task that depends on one waits rather than stops.
617
625
  _STOPPED = ('FAIL', 'BLOCKED', 'INFRA', 'INTERRUPTED', 'TIMEOUT', 'ERROR', 'CONFLICT', 'NOCHANGES', 'INVALIDATED', 'UNKNOWN')
626
+ _DETAIL_CAP = 400 # characters of an infra stop's detail, a short text
627
+ _ATTEMPT_CAP = 8 # a plan without a max_attempts file
628
+ _LEDGER_KEEP = 50 # the newest ledger rows a task keeps
618
629
 
619
630
 
620
631
  def _escalation_stop(reader, ident):
@@ -629,6 +640,150 @@ def _escalation_stop(reader, ident):
629
640
  split=reader.cap(split, f'tasks/{ident}/split.suggested', 600) or None)
630
641
 
631
642
 
643
+ def _number_or_none(value):
644
+ """A key=value number (reset_at, retry_after): None when missing, empty or not finite."""
645
+ try:
646
+ result = float(value)
647
+ except (TypeError, ValueError):
648
+ return None
649
+ return result if math.isfinite(result) else None
650
+
651
+
652
+ _INFRA_TABLE = Path(__file__).resolve().parents[2] / 'scripts' / 'forge_infra.py'
653
+ _INFRA_STATE = {}
654
+
655
+
656
+ def _forge_infra():
657
+ """forge's table of infrastructure causes (scripts/forge_infra.py), loaded once and read-only; None when it
658
+ cannot be, which leaves needs_you false and hint null."""
659
+ if 'module' not in _INFRA_STATE:
660
+ try:
661
+ spec = importlib.util.spec_from_file_location(
662
+ 'forge_infra_for_ui', _INFRA_TABLE, loader=findings._ReadOnlyLoader('forge_infra_for_ui', str(_INFRA_TABLE)))
663
+ module = importlib.util.module_from_spec(spec)
664
+ spec.loader.exec_module(module)
665
+ _INFRA_STATE['module'] = module if callable(getattr(module, 'stop_of', None)) else None
666
+ except Exception:
667
+ _INFRA_STATE['module'] = None
668
+ return _INFRA_STATE['module']
669
+
670
+
671
+ def _infra(reader, prefix, status, ident):
672
+ """task['infra']: the stop record of an INFRA task (infra.txt, key=value lines); None for any other status.
673
+ needs_you and hint are forge's own answer (forge_infra.stop_of): the pause that names the task, live
674
+ (infra.paused) or the one the run ended with (infra.last), else what the cause asks for with no peer."""
675
+ if status != 'INFRA':
676
+ return None
677
+ fields = executions.parse_resolved(reader.text(prefix + '/infra.txt'))
678
+ record = dict(cause=fields.get('class') or None, stage=fields.get('stage') or None,
679
+ harness=fields.get('harness') or None, model=fields.get('model') or None,
680
+ reset_at=_number_or_none(fields.get('reset_at')), retry_after=_number_or_none(fields.get('retry_after')),
681
+ detail=reader.cap(fields.get('detail') or None, prefix + '/infra_detail', _DETAIL_CAP),
682
+ needs_you=False, hint=None)
683
+ module = _forge_infra()
684
+ if module is not None:
685
+ try:
686
+ scopes = module.parse_pauses(reader.text('infra.paused')) or module.parse_pauses(reader.text('infra.last'))
687
+ judged = module.stop_of(ident, fields, scopes, time.time())
688
+ record.update(needs_you=judged.get('needs_you') is True,
689
+ hint=judged.get('hint') if isinstance(judged.get('hint'), str) else None)
690
+ except Exception:
691
+ pass
692
+ return record
693
+
694
+
695
+ def _lateral(reader, name):
696
+ """task['lateral']: the moves of a stopped dispatch to another model of its tier (lateral.tsv), read as escalations are."""
697
+ result = []
698
+ for label, row in reader.rows(name, 6):
699
+ try:
700
+ at, attempt = float(row[0]), int(row[1])
701
+ if not math.isfinite(at):
702
+ raise ValueError()
703
+ except (ValueError, OverflowError):
704
+ reader.warn(label, 'invalid epoch or attempt')
705
+ continue
706
+ result.append(dict(at=at, attempt=attempt, role=row[2], cause=row[5], **{'from': row[3], 'to': row[4]}))
707
+ return result
708
+
709
+
710
+ def _ledger(reader, name):
711
+ """task['ledger']: one row per review (ledger.tsv), the newest _LEDGER_KEEP. `-` is None; the counts are ints."""
712
+ result = []
713
+ for label, row in reader.rows(name, 11):
714
+ try:
715
+ at, attempt = float(row[0]), int(row[1])
716
+ if not math.isfinite(at):
717
+ raise ValueError()
718
+ confirmed, new, carried, diff_bytes = (int(cell) for cell in row[6:10])
719
+ delta = _nullable(row[10])
720
+ delta = None if delta is None else int(delta)
721
+ except (ValueError, OverflowError):
722
+ reader.warn(label, 'invalid epoch, attempt or count')
723
+ continue
724
+ result.append(dict(at=at, attempt=attempt, review=row[2], verdict=row[3], gate=_nullable(row[4]),
725
+ worst=_nullable(row[5]), confirmed=confirmed, new=new, carried=carried,
726
+ diff_bytes=diff_bytes, delta_bytes=delta))
727
+ if len(result) > _LEDGER_KEEP:
728
+ reader.truncated.append(name)
729
+ del result[:-_LEDGER_KEEP]
730
+ return result
731
+
732
+
733
+ def _decision(reader, prefix, status):
734
+ """task['decision'] of a NEEDS_DECISION task: `reasons` from decision.md's first line, `text` the markdown after it."""
735
+ if status != 'NEEDS_DECISION':
736
+ return None
737
+ text = reader.text(prefix + '/decision.md')
738
+ first, _, rest = (text or '').partition('\n')
739
+ match = re.fullmatch(r'\s*reasons:(.*)', first)
740
+ if text is not None and match is None:
741
+ reader.warn(prefix + '/decision.md', 'no reasons line')
742
+ body = rest if match else text
743
+ return dict(reasons=_list(match.group(1)) if match else [],
744
+ text=None if body is None else reader.cap(body, prefix + '/decision'))
745
+
746
+
747
+ def _decisions(reader, name):
748
+ """task['decisions']: one human decision per row of decisions.tsv (epoch, attempt, choice, reason)."""
749
+ result = []
750
+ for label, row in reader.rows(name, 3):
751
+ try:
752
+ at, attempt = float(row[0]), int(row[1])
753
+ if not math.isfinite(at):
754
+ raise ValueError()
755
+ except (ValueError, OverflowError):
756
+ reader.warn(label, 'invalid epoch or attempt')
757
+ continue
758
+ result.append(dict(at=at, attempt=attempt, choice=row[2], reason=_nullable('\t'.join(row[3:]))))
759
+ return result
760
+
761
+
762
+ def _max_attempts(reader):
763
+ """The plan's max_attempts: a whole number, 0 for no cap; 8 without the file or when it is not a whole number."""
764
+ value = reader.number('max_attempts', int)
765
+ if value is not None and value < 0:
766
+ reader.warn('max_attempts', 'negative')
767
+ value = None
768
+ return _ATTEMPT_CAP if value is None else value
769
+
770
+
771
+ def _grant(choice):
772
+ """The N of a retry=N choice, however many digits it has; 0 for any other choice."""
773
+ match = re.fullmatch(r'retry=([0-9]+)', choice)
774
+ try:
775
+ return int(match.group(1)) if match else 0
776
+ except ValueError: # more digits than Python reads as an int: a reader must not raise over one bad row
777
+ return 0
778
+
779
+
780
+ def _attempt_cap(max_attempts, decisions):
781
+ """A task's attempt cap: max_attempts plus the N of each retry=N decision. None when max_attempts is 0 (no cap)."""
782
+ if max_attempts == 0:
783
+ return None
784
+ return max_attempts + sum(_grant(item['choice']) for item in decisions)
785
+
786
+
632
787
  def _waiting(reader, tasks, scheduler):
633
788
  """Task.waiting: why a task that is not running is not, as far as the run dir tells.
634
789
 
@@ -672,7 +827,7 @@ def _waiting(reader, tasks, scheduler):
672
827
  task['waiting'] = dict(kind='next')
673
828
 
674
829
 
675
- def _task_detail(reader, task, run_id, waves, branches):
830
+ def _task_detail(reader, task, run_id, waves, branches, max_attempts):
676
831
  """Fill in a plan task; returns every execution it read (its own and its shadows')."""
677
832
  ident = task['id']
678
833
  prefix = f'tasks/{ident}'
@@ -684,6 +839,7 @@ def _task_detail(reader, task, run_id, waves, branches):
684
839
  except (OSError, ValueError):
685
840
  pass
686
841
  task['attempts'], task['attempt'] = _attempt_state(reader, prefix)
842
+ task['attempts_total'] = sum(item['status'] != 'INFRA' for item in task['attempts'])
687
843
  task['escalations'] = _history(reader, prefix + '/escalations.tsv', True)
688
844
  qa = reader.text(prefix + '/qa.last')
689
845
  task['verdict'] = _verdict(qa)
@@ -696,6 +852,13 @@ def _task_detail(reader, task, run_id, waves, branches):
696
852
  task[field] = reader.cap(reader.text(prefix + '/' + filename), prefix + '/' + field)
697
853
  # the implementer's question for the user, when the task stopped NEEDS_INPUT
698
854
  task['needs_input'] = reader.cap(reader.text(prefix + '/needs_input.md'), prefix + '/needs_input')
855
+ # the stop records: why an INFRA dispatch stopped, the lateral moves, the review ledger, and a NEEDS_DECISION's question
856
+ task['infra'] = _infra(reader, prefix, task['status'], task['id'])
857
+ task['lateral'] = _lateral(reader, prefix + '/lateral.tsv')
858
+ task['ledger'] = _ledger(reader, prefix + '/ledger.tsv')
859
+ task['decision'] = _decision(reader, prefix, task['status'])
860
+ task['decisions'] = _decisions(reader, prefix + '/decisions.tsv')
861
+ task['attempt_cap'] = _attempt_cap(max_attempts, task['decisions'])
699
862
  task['route'] = []
700
863
  for n, line in enumerate((reader.text(prefix + '/route.jsonl') or '').splitlines(), 1):
701
864
  if line.strip():
@@ -797,7 +960,7 @@ def _sweep(reader, tasks):
797
960
  # files without touching the run dir, so they are stat'd for `updated` only.
798
961
  # Read only for their mtimes, so the run's `updated` stamp moves when a control changes.
799
962
  # control.requests is a directory: its mtime moves when a request is queued or settled.
800
- _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused',
963
+ _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused', 'infra.last',
801
964
  'infra_backoff', 'escalate_effort', 'control.requests')
802
965
  _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next')
803
966
 
@@ -1293,7 +1456,9 @@ def _solo_detail(reader, source):
1293
1456
  accepted=False, accepted_attempt=None, accepted_over=None,
1294
1457
  explored=False, route=[], shadow=[],
1295
1458
  prompt=reader.cap(reader.text('prompt.md'), 'tasks/solo/prompt'), approach=None,
1296
- retry_findings=None, needs_input=None, qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
1459
+ retry_findings=None, needs_input=None, infra=None, lateral=[], ledger=[], decision=None, decisions=[],
1460
+ attempts_total=sum(item['status'] != 'INFRA' for item in attempts), attempt_cap=None,
1461
+ qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
1297
1462
  dwarf_tail=reader.cap(reader.text('dwarf.last'), 'tasks/solo/dwarf_tail', 4000, True),
1298
1463
  executions=execs, merged_at=None, findings=executions.summary_of(qa),
1299
1464
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
@@ -1368,9 +1533,10 @@ def detail(path, source='plan') -> dict:
1368
1533
  waves, wave_map = _waves(reader)
1369
1534
  result['waves'] = [waves.get(n, []) for n in range(1, max(waves, default=0) + 1)]
1370
1535
  branches = {row[0]: _nullable(row[2]) for _, row in reader.rows('results.tsv', 3)}
1536
+ max_attempts = _max_attempts(reader)
1371
1537
  pool = []
1372
1538
  for task in tasks:
1373
- pool += _task_detail(reader, task, result['run_id'], wave_map, branches)
1539
+ pool += _task_detail(reader, task, result['run_id'], wave_map, branches, max_attempts)
1374
1540
  for name in _RUN_CONTROLS:
1375
1541
  reader.stat(name)
1376
1542
  result['scheduler'] = _scheduler(reader)
@@ -106,7 +106,7 @@ window.ForgeApp = (() => {
106
106
  function link(text, key, sel) { const a = el('a', text); a.href = hashFor(key, sel); return a; }
107
107
 
108
108
  const statuses = new Set(['merged', 'pass', 'running', 'pending', 'fail', 'error', 'infra',
109
- 'timeout', 'unknown', 'invalidated', 'blocked', 'interrupted', 'nochanges', 'conflict', 'accepted', 'outdated', 'needs_input']);
109
+ 'timeout', 'unknown', 'invalidated', 'blocked', 'interrupted', 'nochanges', 'conflict', 'accepted', 'outdated', 'needs_input', 'needs_decision']);
110
110
  function chip(value, cls) {
111
111
  const status = String(cls || value || 'unknown').toLowerCase();
112
112
  return el('span', value || '—', 'chip st-' + (statuses.has(status) ? status : 'unknown'));
@@ -778,7 +778,7 @@ window.ForgeApp = (() => {
778
778
  { id: 'title', label: 'Title', value: t => t.title },
779
779
  { id: 'difficulty', label: 'Difficulty', value: t => DIFF_RANK[t.difficulty] ?? null, cell: t => display(t.difficulty) },
780
780
  { id: 'wave', label: 'Wave', value: t => Number.isFinite(Number(t.wave)) && t.wave !== null && t.wave !== '' ? Number(t.wave) : null, cell: t => display(t.wave) },
781
- { id: 'status', label: 'Status', value: t => RM.taskStatus(t), cell: t => chip(RM.taskStatus(t)) },
781
+ { id: 'status', label: 'Status', value: t => RM.taskStatus(t), cell: t => chip(RM.statusText(t), RM.taskStatus(t)) },
782
782
  ...(window.ForgeChecks ? [{ id: 'now', label: 'Now', title: 'What a running task is doing, or why one that is not running waits',
783
783
  value: t => window.ForgeChecks.nowRank(t), cell: t => window.ForgeChecks.cell(t, now(), { hash: s => hashFor(run.key, s) }) }] : []),
784
784
  { id: 'dwarf', label: 'Dwarf', value: t => t.dwarf, cell: t => window.ForgeIcons.modelPlate(t.dwarf) },
@@ -19,6 +19,7 @@
19
19
  })(typeof self !== 'undefined' ? self : this, function (root) {
20
20
  'use strict';
21
21
 
22
+ const RM = typeof module === 'object' && module.exports ? require('./runmodel.js') : root.ForgeRunModel;
22
23
  const QUIET_WARN_S = 300; // a log quiet past this is flagged, as the verification view flags its own
23
24
  const ENV_EVERY_S = 15; // a running run's environment problems are read again at most this often
24
25
  const list = v => Array.isArray(v) ? v : [];
@@ -68,8 +69,9 @@
68
69
  if (scope.startsWith('harness:')) return `harness ${w.harness || scope.slice(8)}`;
69
70
  return scope || 'its model';
70
71
  }
71
- // Why a task waits: {kind, text, tasks: [{id, stopped}], until, exhausted, split}, or null
72
- function waitingModel(w) {
72
+ // Why a task waits: {kind, text, tasks: [{id, stopped}], until, exhausted, split}, or null. A pause also has
73
+ // reset (its reset time, from now) and needs (`needs you: <hint>` when the user must act), each null when unknown.
74
+ function waitingModel(w, now) {
73
75
  if (!w || typeof w !== 'object') return null;
74
76
  const ids = v => list(v).map(String);
75
77
  const out = { kind: w.kind, tasks: [], until: null, exhausted: false, split: null };
@@ -83,8 +85,11 @@
83
85
  if (w.kind === 'stopping') return { ...out, text: w.mode === 'now' ? 'the run is stopping now' : 'the run stops once its running tasks end' };
84
86
  if (w.kind === 'next') return { ...out, text: "starts at the scheduler's next turn" };
85
87
  if (w.kind === 'infra') {
86
- return { ...out, text: `paused: ${scopeText(w)}${w.class ? ' · ' + String(w.class).replace(/_/g, ' ') : ''}`,
87
- until: w.exhausted === true ? null : num(w.until), exhausted: w.exhausted === true };
88
+ const cause = RM.causeLabel(w.class);
89
+ const needs = w.needs_you === true ? (typeof w.hint === 'string' && w.hint ? `needs you: ${w.hint}` : 'needs you') : null;
90
+ return { ...out, text: `paused: ${scopeText(w)}${cause ? ' · ' + cause : ''}`,
91
+ until: w.exhausted === true ? null : num(w.until), exhausted: w.exhausted === true,
92
+ reset: RM.resetText(w.reset_at, now), needs };
88
93
  }
89
94
  if (w.kind === 'escalation') {
90
95
  return { ...out, text: `stopped by the retry policy${num(w.attempts) !== null ? ` after ${plural(w.attempts, 'attempt')}` : ''}${w.model ? ' on ' + w.model : ''}`,
@@ -196,6 +201,11 @@
196
201
  if (t.stopped) parent.append(el('span', ' (stopped)', 'warn'));
197
202
  });
198
203
  }
204
+ // a pause's reset time after its line, then `needs you: <hint>` on a line of its own in the warn style
205
+ function pauseNotes(parent, w) {
206
+ if (w.reset) parent.append(document.createTextNode(' · ' + w.reset));
207
+ if (w.needs) parent.append(el('span', w.needs, 'warn pause-needs'));
208
+ }
199
209
  // Brings the times under `root` up to `now` (epoch seconds) between redraws.
200
210
  function tick(rootNode, now) {
201
211
  if (!rootNode || !rootNode.querySelectorAll || num(now) === null) return;
@@ -216,19 +226,20 @@
216
226
  box.append(quietNode(m.quietSince, now));
217
227
  return box;
218
228
  }
219
- const w = waitingModel(task && task.waiting);
229
+ const w = waitingModel(task && task.waiting, now);
220
230
  if (!w) { box.append(el('span', '—', 'muted')); return box; }
221
231
  box.classList.add('now-waiting');
222
232
  box.append(el('span', w.text + (w.tasks.length ? ' ' : ''), 'now-why'));
223
233
  taskLinks(box, ctx, w.tasks);
224
234
  if (w.until !== null) box.append(untilNode(w.until, now));
235
+ pauseNotes(box, w);
225
236
  if (w.exhausted) box.append(el('span', 'waits used up', 'warn'));
226
237
  return box;
227
238
  }
228
239
 
229
240
  // The task inspector's Now section: what it does, or why it waits
230
241
  function nowSection(host, ctx, task) {
231
- const m = nowModel(task), w = m ? null : waitingModel(task.waiting);
242
+ const m = nowModel(task), w = m ? null : waitingModel(task.waiting, ctx.now);
232
243
  if (!m && !w) return;
233
244
  const s = section(host, 'Now', 'now-section');
234
245
  const box = el('div', undefined, 'vfy-live now-live');
@@ -267,6 +278,7 @@
267
278
  p.append(el('span', w.text + (w.tasks.length ? ' ' : '')));
268
279
  taskLinks(p, ctx, w.tasks);
269
280
  if (w.until !== null) p.append(document.createTextNode(' · '), untilNode(w.until, ctx.now));
281
+ pauseNotes(p, w);
270
282
  if (w.exhausted) p.append(el('span', ' · its waits are used up', 'warn'));
271
283
  box.append(p);
272
284
  if (w.split) {
@@ -390,9 +402,10 @@
390
402
  const dl = el('dl', undefined, 'fields');
391
403
  for (const [label, value] of rows) { dl.append(el('dt', label), el('dd', value)); }
392
404
  for (const p of list(run.scheduler.pauses)) {
393
- const w = waitingModel({ ...p, kind: 'infra' });
405
+ const w = waitingModel({ ...p, kind: 'infra' }, now);
394
406
  const dd = el('dd', w.text);
395
407
  if (w.until !== null) dd.append(document.createTextNode(' · '), untilNode(w.until, now));
408
+ pauseNotes(dd, w);
396
409
  if (w.exhausted) dd.append(el('span', ' · its waits are used up', 'warn'));
397
410
  dl.append(el('dt', 'Paused'), dd);
398
411
  }
@@ -32,7 +32,10 @@
32
32
  };
33
33
  const BACKOFF_FORMS = 'exp:<base>[,<cap>], linear:<start>,<step>[,<cap>] or list:<a>,<b>,… (seconds)';
34
34
  // A task status after which "Retry now" applies (or the policy stopped it).
35
- const RETRYABLE = ['FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED']; // scripts/forge-schedule.py RETRYABLE; NEEDS_INPUT is in neither list
35
+ const RETRYABLE = ['FAIL', 'UNKNOWN', 'TIMEOUT', 'ERROR', 'INTERRUPTED', 'BLOCKED', 'INVALIDATED']; // scripts/forge-schedule.py RETRYABLE
36
+ // A task waiting for the user is not retried from forge-ui. NEEDS_INPUT needs an answer (retry --answer);
37
+ // NEEDS_DECISION is resumed with the CLI commands the decision text lists.
38
+ const WAITING = new Set(['NEEDS_INPUT', 'NEEDS_DECISION']);
36
39
 
37
40
  const obj = v => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
38
41
  const num = v => typeof v === 'number' && Number.isFinite(v) ? v : null;
@@ -216,10 +219,10 @@
216
219
  }
217
220
  const requestText = st => st.state === 'refused' ? `refused${st.reason ? ': ' + st.reason : ''}` : st.state;
218
221
  // Whether "Retry now" shows for a task: live only, after it ended without passing or once the policy stopped it.
219
- // Never for a task waiting for an answer: forge refuses a retry without one (retry --answer).
222
+ // Never while it waits for the user: an answer is retry --answer, a decision is the CLI commands in the decision text.
220
223
  const canRetry = (controls, id) => {
221
224
  const c = obj(controls), v = taskValues(c, id);
222
- return c.live === true && v.known && v.status !== 'MERGED' && v.status !== 'NEEDS_INPUT' && (RETRYABLE.includes(v.status) || v.stop);
225
+ return c.live === true && v.known && v.status !== 'MERGED' && !WAITING.has(v.status) && (RETRYABLE.includes(v.status) || v.stop);
223
226
  };
224
227
  // A task's controls with the effective value of each: an override wins, else the run's value is inherited.
225
228
  function taskValues(controls, id) {
@@ -10,7 +10,7 @@ window.ForgePanel = (() => {
10
10
  const num = v => typeof v === 'number' && Number.isFinite(v) ? v : null;
11
11
  const display = v => v === null || v === undefined || v === '' ? '—' : typeof v === 'object' ? JSON.stringify(v, null, 2) : String(v);
12
12
  const STATUSES = new Set(['merged', 'pass', 'running', 'pending', 'fail', 'error', 'infra', 'timeout', 'unknown', 'invalidated', 'blocked',
13
- 'interrupted', 'nochanges', 'conflict', 'accepted', 'none', 'outdated', 'needs_input', 'waiting']);
13
+ 'interrupted', 'nochanges', 'conflict', 'accepted', 'none', 'outdated', 'needs_input', 'needs_decision', 'waiting']);
14
14
  const cache = new Map(); // path → {data, error, at}
15
15
  function el(tag, text, className) {
16
16
  const node = document.createElement(tag);
@@ -89,6 +89,17 @@ window.ForgePanel = (() => {
89
89
  // A task that stopped NEEDS_INPUT: the question it asked, and the command that answers it. forge-ui shows the
90
90
  // command and never runs it; only the user's answer, passed to retry, resumes the task.
91
91
  const shellWord = s => /^[\w@%+=:,./-]+$/.test(s) ? s : "'" + String(s).replace(/'/g, "'\\''") + "'";
92
+ // An INFRA task: why its dispatch stopped (the cause, the stage, the model it ran on), when its limit resets, and
93
+ // whether the user must act: the reader's answer from forge's cause table (after the run too), else a live
94
+ // scope pause that names the task in its `tasks`
95
+ function infraSection(host, ctx, task) {
96
+ const s = section(host, 'Stopped on infrastructure'), inf = task.infra || {};
97
+ fields(s, [['Cause', RM.causeLabel(inf.cause)], ['Stage', inf.stage], ['Harness', inf.harness, true], ['Model', inf.model, true],
98
+ ['Reset', RM.resetText(inf.reset_at, ctx.now) || undefined]]);
99
+ const pause = list(ctx.run.scheduler && ctx.run.scheduler.pauses).find(p => list(p.tasks).includes(task.id)) || {};
100
+ const hint = inf.hint || pause.hint;
101
+ if (inf.needs_you === true || pause.needs_you === true) s.append(el('p', 'needs you' + (hint ? `: ${hint}` : ''), 'warn'));
102
+ }
92
103
  function waitingSection(host, ctx, task) {
93
104
  const s = section(host, 'Waiting for you');
94
105
  muted(s, 'This task stopped for an answer only you can give. Nothing retries it until you answer.');
@@ -105,6 +116,53 @@ window.ForgePanel = (() => {
105
116
  line.append(el('pre', text, 'cmd'), copy);
106
117
  s.append(line);
107
118
  }
119
+ // A task that stopped NEEDS_DECISION: why the retry policy stopped it, its attempts against the cap, the ledger of its
120
+ // reviews, and the decision text, which holds the commands to run. forge-ui shows the commands and never runs them.
121
+ const REASON_WORDS = { converging: 'reviews are not converging', split: 'no stronger model left', cap: 'attempt cap reached' };
122
+ // `attempts 9 of 8 allowed`, or `attempts 9` with no cap; null for a task that has made no attempt
123
+ function attemptsText(task) {
124
+ const n = num(task.attempts_total), cap = num(task.attempt_cap);
125
+ if (!n) return null;
126
+ return cap === null ? `attempts ${n}` : `attempts ${n} of ${cap} allowed`;
127
+ }
128
+ function decisionSection(host, ctx, task) {
129
+ const d = task.decision || {};
130
+ const reasons = list(d.reasons).map(r => Object.prototype.hasOwnProperty.call(REASON_WORDS, r) ? REASON_WORDS[r] : r);
131
+ const s = el('section', undefined, 'insp-section');
132
+ s.append(el('h3', reasons.length ? reasons.join(', ') : 'waiting for a decision', 'decision-reasons'));
133
+ host.append(s);
134
+ muted(s, 'This task stopped for a decision only you can make. Nothing retries it until you run one of the commands below.');
135
+ const attempts = attemptsText(task);
136
+ if (attempts) s.append(el('p', attempts));
137
+ ledgerTable(s, list(task.ledger));
138
+ s.append(el('pre', d.text != null ? d.text : `The decision is not recorded: tasks/${task.id}/decision.md is missing.`));
139
+ }
140
+ // The review ledger as a small table, one row per review. A FAIL verdict or a `fail` gate reads as failed: a gate fail
141
+ // over a PASS verdict keeps the reviewer's word and turns the chip red, with the gate's decision on hover.
142
+ function ledgerTable(parent, rows) {
143
+ if (!rows.length) { muted(parent, 'No review is recorded for this task yet.'); return; }
144
+ const word = v => String(v || '').toLowerCase();
145
+ const wrap = el('div', undefined, 'ledger-wrap'), table = el('table', undefined, 'ledger');
146
+ const findings = el('th', 'Findings'); findings.title = 'confirmed findings';
147
+ const thead = el('thead'), head = el('tr');
148
+ head.append(el('th', 'Attempt'), el('th', 'Verdict'), findings, el('th', 'New'), el('th', 'Worst'));
149
+ thead.append(head);
150
+ const tbody = el('tbody');
151
+ for (const r of rows) {
152
+ const failed = word(r.verdict) === 'fail' || word(r.gate) === 'fail';
153
+ const verdict = el('td'), worst = el('td');
154
+ const v = chip(r.verdict, failed ? 'fail' : word(r.verdict) === 'pass' ? 'pass' : 'unknown');
155
+ if (word(r.gate) === 'fail' && word(r.verdict) !== 'fail') v.title = 'forge gate: FAIL' + (r.verdict ? ` (reviewer said ${r.verdict})` : '');
156
+ verdict.append(v);
157
+ worst.append(r.worst ? sevChip(r.worst, r.worst) : document.createTextNode('—'));
158
+ const tr = el('tr', undefined, failed ? 'failed' : undefined);
159
+ tr.append(el('td', r.attempt, 'num'), verdict, el('td', r.confirmed, 'num'), el('td', r.new, 'num'), worst);
160
+ tbody.append(tr);
161
+ }
162
+ table.append(thead, tbody);
163
+ wrap.append(table);
164
+ parent.append(wrap);
165
+ }
108
166
  // An attempt's chip. A failed attempt is red whatever its words; a send-back says what forge did in its title.
109
167
  function attemptChip(word) {
110
168
  const c = chip(word, RM.attemptFailed(word) ? 'fail' : undefined), note = RM.attemptNote(word);
@@ -355,7 +413,7 @@ window.ForgePanel = (() => {
355
413
  const chips = el('div', undefined, 'chips');
356
414
  if (RM.taskStatus(task) === 'ACCEPTED') chips.append(acceptedChip(task));
357
415
  else {
358
- chips.append(chip(RM.taskStatus(task)));
416
+ chips.append(RM.taskStatus(task) === 'INFRA' ? chip(RM.statusText(task), 'infra') : chip(RM.taskStatus(task)));
359
417
  if (task.accepted === true) chips.append(acceptedChip(task));
360
418
  else if (task.verdict) chips.append(chip('review ' + task.verdict, task.verdict.toLowerCase()));
361
419
  }
@@ -363,20 +421,27 @@ window.ForgePanel = (() => {
363
421
  head.append(chips);
364
422
  const dl = diffLink(ctx, solo ? 'View the diff →' : 'View its diff, findings pinned to their lines →', { kind: 'task', task: task.id, source: 'current' }); if (dl) head.append(dl);
365
423
  host.append(head);
366
- if (RM.isWaiting(task.status)) waitingSection(host, ctx, task);
424
+ if (task.status === 'NEEDS_DECISION') decisionSection(host, ctx, task);
425
+ else if (RM.isWaiting(task.status)) waitingSection(host, ctx, task);
426
+ if (RM.taskStatus(task) === 'INFRA') infraSection(host, ctx, task);
367
427
  if (!solo) fields(host, [['Difficulty', task.difficulty], ['Depends on', depLinks(task.deps, ctx)], ['Files', list(task.files).join('\n') || '—', true], ['Branch', task.branch, true]]);
368
428
  if (C) C.nowSection(host, ctx, task);
369
429
  sweepSection(host, ctx, task);
370
430
 
371
431
  // the models: who owned it, how it was routed, what it was escalated to
372
432
  const ms = section(host, 'Models');
373
- fields(ms, [['Dwarf', plate(task.dwarf)], ['Reviewer', plate(task.qa)], ['Attempt', task.attempt]]);
433
+ const attempts = attemptsText(task);
434
+ fields(ms, [['Dwarf', plate(task.dwarf)], ['Reviewer', plate(task.qa)], attempts ? ['Attempts', attempts] : ['Attempt', task.attempt]]);
374
435
  const route = list(task.route).slice(-1)[0];
375
436
  if (route) fields(ms, [['Routed', `${display(route.chosen)} from ${list(route.candidates).join(', ') || '—'}${route.explored ? ` (exploratory, p=${display(route.propensity)})` : ''}`, true], ['Tier · ε', `${display(route.tier)} · ${display(route.epsilon)}`]]);
376
437
  for (const e of list(task.escalations)) {
377
438
  const line = el('p', `Escalated after attempt ${display(e.attempt)}: ${display(e.from)} → ${display(e.to)} at ${time(e.at)} `, 'muted');
378
439
  line.append(sourcePlate(e.source)); ms.append(line);
379
440
  }
441
+ for (const m of list(task.lateral)) {
442
+ const cause = RM.causeLabel(m.cause);
443
+ ms.append(el('p', `moved sideways: ${display(m.role)} ${display(m.from)} → ${display(m.to)}${cause ? ` (${cause})` : ''} · attempt ${display(m.attempt)} · ${time(m.at)}`, 'muted'));
444
+ }
380
445
  controlsSection(host, ctx, task);
381
446
 
382
447
  // timings
@@ -15,8 +15,8 @@
15
15
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
16
16
  const DONE = new Set(['MERGED', 'PASS', 'NOCHANGES']);
17
17
  const BAD = new Set(['FAIL', 'ERROR', 'CONFLICT', 'INFRA', 'TIMEOUT', 'INVALIDATED', 'INTERRUPTED', 'UNKNOWN', 'BLOCKED']);
18
- // NEEDS_INPUT: stopped for an answer only the user can give. Neither DONE nor BAD, so never a failure.
19
- const WAITING = new Set(['NEEDS_INPUT']);
18
+ // NEEDS_INPUT (an answer) and NEEDS_DECISION (a choice): stopped for the user. Neither DONE nor BAD, so never a failure.
19
+ const WAITING = new Set(['NEEDS_INPUT', 'NEEDS_DECISION']);
20
20
  const isWaiting = status => WAITING.has(status);
21
21
  const WEIGHT = { low: 1, medium: 2, high: 3 };
22
22
  const weight = t => WEIGHT[String(t && t.difficulty || '').toLowerCase()] || 2;
@@ -203,7 +203,7 @@
203
203
  if (statuses.some(s => s === 'RUNNING')) return 'RUNNING';
204
204
  if (statuses.every(s => s === 'MERGED')) return 'MERGED';
205
205
  if (statuses.some(s => s === 'PENDING' || s === 'PASS')) return 'PENDING';
206
- // only answers are missing: the integration waits for the user, not for a fix
206
+ // only the user is missing (an answer or a decision): the integration waits, not for a fix
207
207
  if (statuses.some(isWaiting) && statuses.every(s => s === 'MERGED' || isWaiting(s))) return 'WAITING';
208
208
  return 'BLOCKED';
209
209
  }
@@ -231,6 +231,31 @@
231
231
  if (t.status === 'MERGED' && t.accepted === true) return 'ACCEPTED';
232
232
  return t.status || 'PENDING';
233
233
  }
234
+ // An infrastructure stop's cause as a short label, shared by the task table, the panel and the checks view.
235
+ // A cause the page does not know (an older run's `quota`) is shown as it was written; no cause is null.
236
+ const CAUSE_LABELS = { capacity: 'at capacity', rate_limit: 'rate limited', usage_limit: 'usage limit', budget: 'out of budget',
237
+ auth: 'login needed', network: 'network down', provider_down: 'provider down', empty: 'empty answer', cancelled: 'cancelled' };
238
+ const causeLabel = cause => cause ? (Object.prototype.hasOwnProperty.call(CAUSE_LABELS, cause) ? CAUSE_LABELS[cause] : String(cause)) : null;
239
+ // The status word, with an INFRA task's cause after it (`INFRA · usage limit`); plain `INFRA` when no cause was recorded.
240
+ function statusText(t) {
241
+ const status = taskStatus(t), label = status === 'INFRA' ? causeLabel(t.infra && t.infra.cause) : null;
242
+ return label ? `INFRA · ${label}` : status;
243
+ }
244
+ const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
245
+ const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
246
+ // When a limit resets, in local time: `resets 14:05` today, `resets Fri 09:00` within the next six days, else
247
+ // `resets Nov 3 09:00`. Null without a reset (epoch seconds, or null) or without now to compare it with.
248
+ function resetText(epoch, now) {
249
+ const at = num(epoch), t = num(now);
250
+ if (at === null || t === null) return null;
251
+ const when = new Date(at * 1000), today = new Date(t * 1000);
252
+ if (Number.isNaN(when.getTime()) || Number.isNaN(today.getTime())) return null;
253
+ const clock = `${String(when.getHours()).padStart(2, '0')}:${String(when.getMinutes()).padStart(2, '0')}`;
254
+ const days = Math.round((new Date(when.getFullYear(), when.getMonth(), when.getDate()) - new Date(today.getFullYear(), today.getMonth(), today.getDate())) / 86400000);
255
+ if (days === 0) return `resets ${clock}`;
256
+ if (days > 0 && days < 7) return `resets ${DAY_NAMES[when.getDay()]} ${clock}`;
257
+ return `resets ${MONTH_NAMES[when.getMonth()]} ${when.getDate()} ${clock}`;
258
+ }
234
259
  // Verdict column and the 2D graph's tick or cross. text is the words, status the lamp class,
235
260
  // mark the cross (FAIL) or tick (PASS). An acceptance names FAIL or UNKNOWN and never invents a FAIL,
236
261
  // and it draws no mark: the graph must not put a red cross on a task a human accepted.
@@ -850,6 +875,7 @@
850
875
  }
851
876
 
852
877
  /* ---------- notifications: what changed between two polls of the run list ---------- */
878
+ // Waiting statuses are absent: a task that stops for the user (NEEDS_INPUT, NEEDS_DECISION) is not a failure.
853
879
  const FAILING = new Set(['FAIL', 'ERROR', 'CONFLICT', 'TIMEOUT', 'INVALIDATED', 'INTERRUPTED', 'BLOCKED']);
854
880
  // prev, next: RunSummary lists (prev null on the first poll, which is only a baseline). A run that has not
855
881
  // changed for two hours (stale: its process died) never fires.
@@ -913,7 +939,7 @@
913
939
  }
914
940
 
915
941
  return { liveNow, runState, execStatus, matchRun, filterOptions, atlasModel, repoKey, repoLabel, compareRepo, columns, planModel, finishState,
916
- finalStatus, runReviewStatus, reviewSinceLine, reviewAt, taskStatus, taskVerdict, attemptStatus, attemptNote, attemptFailed, isWaiting,
942
+ finalStatus, runReviewStatus, reviewSinceLine, reviewAt, taskStatus, statusText, causeLabel, resetText, taskVerdict, attemptStatus, attemptNote, attemptFailed, isWaiting,
917
943
  attributionLine, taskParts,
918
944
  taskTimes, metricValue, overlap, projectSchedule, execModel, verifyLeds, criticalPath, concurrency, stateAt, timeRange, events, lineage, structureKey, innerKey,
919
945
  fmtDur, alias, basename, weight, searchIndex, searchRank, statusEvents, fractalTree, sweepLine, sweepState };
@@ -167,7 +167,8 @@ export async function createStage(host, cb = {}) {
167
167
  const parts = [r.kind === 'solo' ? (Object.keys(c)[0] || 'solo') : `${merged}/${total} done`];
168
168
  if (running) parts.push(`${running} running`);
169
169
  if (bad) parts.push(`${bad} failed`);
170
- if (c.NEEDS_INPUT) parts.push(`${c.NEEDS_INPUT} waiting for you`); // not in the failed count: it waits for an answer
170
+ const waiting = (c.NEEDS_INPUT || 0) + (c.NEEDS_DECISION || 0);
171
+ if (waiting) parts.push(`${waiting} waiting for you`); // not in the failed count: each waits for the user
171
172
  const reviewStatus = RM.runReviewStatus(r);
172
173
  if (reviewStatus) parts.push(`review ${reviewStatus}`);
173
174
  else if (r.verification_status) parts.push(`verify ${r.verification_status}`);
@@ -1248,7 +1249,7 @@ export async function createStage(host, cb = {}) {
1248
1249
  const lamps = { title: 'Lamps', rows: [
1249
1250
  { sw: { lamp: 'st-merged' }, label: 'merged · passed · accepted' }, { sw: { lamp: 'st-running' }, label: 'running · interrupted' },
1250
1251
  { sw: { lamp: 'st-fail' }, label: 'failed · conflict · infra · timeout' }, { sw: { lamp: 'st-pending' }, label: 'pending, not started' },
1251
- { sw: { lamp: 'st-outdated' }, label: 'outdated review' }, { sw: { lamp: 'st-needs_input' }, label: 'waiting for you' },
1252
+ { sw: { lamp: 'st-outdated' }, label: 'outdated review' }, { sw: { lamp: 'st-needs_input' }, label: 'waiting for you' }, // NEEDS_INPUT and NEEDS_DECISION share this lamp
1252
1253
  { sw: { route: true }, label: st.view === 'atlas' ? 'chosen run' : 'chosen task' + (L.route ? ' and its route' : '') }] };
1253
1254
  if (st.view === 'atlas') {
1254
1255
  out.push({ title: 'Map', rows: [], note: 'Each block is a run, each district a repository. The lamps on a block are its tasks; the block stands taller the more tasks it has.' }, lamps);