@giamme/forge 0.16.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 (95) hide show
  1. package/CHANGELOG.md +43 -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 +13 -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/reviews.md +15 -1
  11. package/docs/safety.md +8 -0
  12. package/forge +24 -1
  13. package/package.json +1 -1
  14. package/references/dataset.md +143 -5
  15. package/references/decision-models.md +15 -2
  16. package/references/decompose.md +180 -11
  17. package/references/planning.md +3 -2
  18. package/references/solo.md +2 -1
  19. package/references/ui.md +5 -2
  20. package/scripts/forge-artifact.sh +14 -0
  21. package/scripts/forge-brief.py +132 -0
  22. package/scripts/forge-compare.py +11 -1
  23. package/scripts/forge-config.py +176 -9
  24. package/scripts/forge-contract.py +98 -4
  25. package/scripts/forge-control.py +86 -13
  26. package/scripts/forge-dispatch.sh +14 -10
  27. package/scripts/forge-du.py +167 -0
  28. package/scripts/forge-issues.py +4 -3
  29. package/scripts/forge-ledger.py +3 -1
  30. package/scripts/forge-lib-adopt.sh +8 -1
  31. package/scripts/forge-lib-plans.sh +5 -2
  32. package/scripts/forge-lib-review.sh +29 -1
  33. package/scripts/forge-metrics.sh +29 -3
  34. package/scripts/forge-parallel-options.sh +4 -0
  35. package/scripts/forge-parallel.sh +506 -10
  36. package/scripts/forge-plan-check.py +25 -2
  37. package/scripts/forge-planner.py +20 -6
  38. package/scripts/forge-prompt.py +120 -0
  39. package/scripts/forge-retro.py +115 -0
  40. package/scripts/forge-runs-compact.py +443 -0
  41. package/scripts/forge-runs-rm.py +2 -0
  42. package/scripts/forge-runs.py +18 -3
  43. package/scripts/forge-schedule.py +279 -4
  44. package/scripts/forge-shadow.py +35 -10
  45. package/scripts/forge-solo.sh +2 -0
  46. package/scripts/forge-summarize.py +698 -0
  47. package/scripts/forge-sweep.py +25 -10
  48. package/scripts/forge-ui-options.sh +10 -0
  49. package/scripts/forge_brief/__init__.py +587 -0
  50. package/scripts/forge_brief/answers.py +459 -0
  51. package/scripts/forge_dataset/__init__.py +10 -0
  52. package/scripts/forge_dataset/cli.py +83 -0
  53. package/scripts/forge_dataset/export.py +18 -4
  54. package/scripts/forge_dataset/facts.py +280 -0
  55. package/scripts/forge_dataset/harvest.py +56 -9
  56. package/scripts/forge_dataset/history.py +5 -3
  57. package/scripts/forge_dataset/outcomes.py +206 -58
  58. package/scripts/forge_dataset/pairs.py +174 -0
  59. package/scripts/forge_dataset/risk.py +108 -0
  60. package/scripts/forge_dataset/tiers.py +427 -0
  61. package/scripts/forge_decide/__init__.py +11 -1
  62. package/scripts/forge_decide/cli.py +23 -2
  63. package/scripts/forge_decide/labels.py +30 -6
  64. package/scripts/forge_decide/replay.py +10 -4
  65. package/scripts/forge_locations.py +366 -0
  66. package/scripts/forge_registry.py +19 -0
  67. package/scripts/forge_retro/__init__.py +417 -0
  68. package/scripts/forge_retro/issues.py +1193 -0
  69. package/scripts/forge_retro/report.py +671 -0
  70. package/scripts/forge_side/__init__.py +477 -0
  71. package/scripts/forge_storage.py +515 -0
  72. package/ui/README.md +68 -8
  73. package/ui/docs/api.md +217 -20
  74. package/ui/forge_ui/control.py +92 -11
  75. package/ui/forge_ui/export.py +31 -5
  76. package/ui/forge_ui/findings.py +4 -2
  77. package/ui/forge_ui/links.py +337 -0
  78. package/ui/forge_ui/models.py +57 -4
  79. package/ui/forge_ui/projects.py +4 -1
  80. package/ui/forge_ui/reader.py +732 -34
  81. package/ui/forge_ui/server.py +8 -0
  82. package/ui/forge_ui/static/app.js +92 -5
  83. package/ui/forge_ui/static/briefview.js +302 -0
  84. package/ui/forge_ui/static/checksview.js +6 -2
  85. package/ui/forge_ui/static/controls.js +5 -0
  86. package/ui/forge_ui/static/diffview.js +7 -3
  87. package/ui/forge_ui/static/index.html +3 -0
  88. package/ui/forge_ui/static/panel.js +311 -4
  89. package/ui/forge_ui/static/runmodel.js +13 -1
  90. package/ui/forge_ui/static/storageview.js +271 -0
  91. package/ui/forge_ui/static/style.css +100 -3
  92. package/ui/forge_ui/static/worktreesview.js +3 -3
  93. package/ui/forge_ui/storage.py +136 -0
  94. package/ui/forge_ui/transcripts.py +35 -10
  95. package/ui/forge_ui/worktrees.py +154 -13
@@ -30,6 +30,7 @@ import json
30
30
  import math
31
31
  import os
32
32
  import re
33
+ import shlex
33
34
  from pathlib import Path
34
35
  import posixpath
35
36
  import signal
@@ -37,6 +38,7 @@ import stat
37
38
  import subprocess
38
39
  import sys
39
40
  import tempfile
41
+ import threading
40
42
  import time
41
43
 
42
44
  # forge_infra.py sits beside this file; forge-control.py loads this module by path.
@@ -401,6 +403,11 @@ def _pinned(plan: object, name: str) -> bool:
401
403
  # dispatch that died too early left behind.
402
404
  GUARD = str(Path(__file__).resolve().parent / 'forge-guard.py')
403
405
  ROUTE = str(Path(__file__).resolve().parent / 'forge-route.py')
406
+ # FORGE_SUMMARIZE names another script for the same job; tests stand a stub in.
407
+ SUMMARIZE = str(Path(__file__).resolve().parent / 'forge-summarize.py')
408
+ # the dwarf's reply (it ends before the status moves), an attempt ended, a verdict, a retry queued
409
+ SUMMARY_FILES = ('dwarf.last', 'attempts.tsv', 'qa.last', 'retries.used')
410
+ SUMMARY_JOIN = 3.0 # seconds the scheduler's end waits for admission checks to start their summarize
404
411
  HARNESS_ROLES = ('dwarf', 'qa')
405
412
  GUARD_STOP_WAIT = 15.0 # seconds; the guard's own bound is about 3 s plus two ps calls
406
413
 
@@ -456,7 +463,7 @@ def stop_harnesses(plan: object, names: object) -> None:
456
463
 
457
464
 
458
465
  # --- control requests ----------------------------------------------------------------------
459
- # `forge control retry|add` queue one JSON file each in control.requests/, under control.lock and
466
+ # `forge control retry|add|accept` queue one JSON file each in control.requests/, under control.lock and
460
467
  # only while scheduler.live says a scheduler reads them. The scheduler applies or refuses each,
461
468
  # logs one outcome line with the same `request` id, and removes it. live_stop settles whatever
462
469
  # is left after it withdraws liveness, under the same lock, so no request outlives its run.
@@ -507,7 +514,7 @@ def read_request(plan: object, name: str) -> dict | None:
507
514
  request = json.loads(data.decode('utf-8'))
508
515
  except (OSError, ValueError, UnicodeDecodeError):
509
516
  return None
510
- if len(data) > REQUEST_MAX or not isinstance(request, dict) or request.get('verb') not in ('retry', 'add'):
517
+ if len(data) > REQUEST_MAX or not isinstance(request, dict) or request.get('verb') not in ('retry', 'add', 'accept'):
511
518
  return None
512
519
  task, dwarf = request.get('task'), request.get('dwarf')
513
520
  if not isinstance(task, str) or not _task_id_ok(task):
@@ -522,6 +529,9 @@ def read_request(plan: object, name: str) -> dict | None:
522
529
  return None
523
530
  if not isinstance(request.get('approved', False), bool):
524
531
  return None
532
+ actor = request.get('actor')
533
+ if actor is not None and actor not in ('ui', 'cli'):
534
+ return None
525
535
  return request
526
536
 
527
537
 
@@ -586,6 +596,54 @@ def live_stop(plan: object, names: object) -> None:
586
596
  _warn('could not withdraw the live control files: ' + str(error))
587
597
 
588
598
 
599
+ def brief_level(plan: object) -> str:
600
+ """The plan's effective brief level (off, advisory, gated, strict). Off when settings cannot be read:
601
+ a broken brief must never hold a run."""
602
+ try:
603
+ import forge_side
604
+ return str(forge_side.settings(plan)['brief']['level'])
605
+ except Exception:
606
+ return 'off'
607
+
608
+
609
+ def _json_object(path: Path) -> dict | None:
610
+ try:
611
+ value = json.loads(path.read_text(encoding='utf-8'))
612
+ except (OSError, ValueError):
613
+ return None
614
+ return value if isinstance(value, dict) else None
615
+
616
+
617
+ BRIEF_PID_CHECK = 0.5 # seconds a writer liveness answer is reused
618
+
619
+
620
+ def brief_writer_alive(plan: object) -> bool:
621
+ """Whether the brief writer `run` started is still running: brief.pid names a live process.
622
+ The file is removed when the writer ends, so a missing or unreadable one means it is gone."""
623
+ try:
624
+ pid = int((Path(plan) / 'brief.pid').read_text().split()[0])
625
+ if pid <= 0:
626
+ return False
627
+ os.kill(pid, 0)
628
+ except PermissionError:
629
+ return True
630
+ except (OSError, ValueError, IndexError):
631
+ return False
632
+ return True
633
+
634
+
635
+ def brief_unanswered(plan: object, name: str) -> list:
636
+ """The ids of the task's `must_answer` questions that have no entry in brief.answers.json."""
637
+ root = Path(plan) / 'tasks' / name
638
+ brief = _json_object(root / 'brief.json')
639
+ if brief is None or not isinstance(brief.get('questions'), list):
640
+ return []
641
+ answers = _json_object(root / 'brief.answers.json') or {}
642
+ return [q['id'] for q in brief['questions']
643
+ if isinstance(q, dict) and q.get('must_answer') is True
644
+ and isinstance(q.get('id'), str) and q['id'] and q['id'] not in answers]
645
+
646
+
589
647
  def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
590
648
  infra_retries: int = 0, sweep: str | None = None, sweep_max: int = 5,
591
649
  sweep_plausible: bool = False) -> int:
@@ -638,6 +696,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
638
696
  fractal = _fractal_plan(plan)
639
697
  drain_told = False # the drained message was printed for this drain
640
698
  sweep_asked = False # this invocation already asked for the finding sweep
699
+ brief_mode = brief_level(plan) # advisory never waits; strict was settled before the scheduler started
700
+ brief_told = set() # (task, qid or '') whose brief wait was already printed
701
+ brief_waiting = set() # tasks the last dispatch pass held for a brief answer or the brief writer
702
+ brief_alive = [0.0, False] # when the writer was last looked at, and what was seen
641
703
 
642
704
  def status(name: str) -> str:
643
705
  root = plan / 'tasks' / name
@@ -654,6 +716,47 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
654
716
  result = subprocess.run(['/bin/bash', script, '_merge', str(plan), name])
655
717
  if result.returncode and status(name) == 'PASS':
656
718
  mark(name, 'ERROR')
719
+ elif brief_mode != 'off' and status(name) == 'MERGED':
720
+ brief_stale(name)
721
+
722
+ def brief_stale(name: str) -> None:
723
+ """Flag the open questions of the tasks that depend on a merge that touched undeclared files.
724
+ A failure is one warning line and changes nothing else."""
725
+ try:
726
+ result = subprocess.run([sys.executable, str(Path(__file__).resolve().with_name('forge-brief.py')),
727
+ 'stale', str(plan), name], stdin=subprocess.DEVNULL,
728
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, timeout=120)
729
+ failed = result.returncode != 0
730
+ detail = result.stderr.strip().splitlines()[-1:] if failed else []
731
+ except (OSError, subprocess.SubprocessError) as error:
732
+ failed, detail = True, [str(error)]
733
+ if failed:
734
+ _warn('brief: could not flag the dependents of ' + name + ' as possibly stale'
735
+ + (' (' + detail[0] + ')' if detail else ''))
736
+
737
+ def brief_held(name: str) -> bool:
738
+ """Under gated only: the task has a must_answer question nobody answered, or no brief.json yet while
739
+ the writer still runs. Prints one line the first time a question holds it."""
740
+ if brief_mode != 'gated':
741
+ return False
742
+ open_ids = brief_unanswered(plan, name)
743
+ if open_ids:
744
+ if (name, open_ids[0]) not in brief_told:
745
+ brief_told.add((name, open_ids[0]))
746
+ print('forge: ' + name + ' waits for your answer to ' + open_ids[0] + ': forge brief answer '
747
+ + shlex.quote(str(plan)) + ' ' + name + ' ' + open_ids[0] + ' "…"', file=sys.stderr, flush=True)
748
+ return True
749
+ if (plan / 'tasks' / name / 'brief.json').exists():
750
+ return False
751
+ now = time.monotonic()
752
+ if now - brief_alive[0] >= BRIEF_PID_CHECK:
753
+ brief_alive[:] = [now, brief_writer_alive(plan)]
754
+ if not brief_alive[1]:
755
+ return False
756
+ if (name, '') not in brief_told:
757
+ brief_told.add((name, ''))
758
+ print('forge: ' + name + ' waits for its brief questions to be written', file=sys.stderr, flush=True)
759
+ return True
657
760
 
658
761
  def budget(name: str) -> int:
659
762
  """Automatic retries this task may use. Read at every decision, never cached: the
@@ -1149,10 +1252,45 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1149
1252
  return 'refused', 'tasks/' + name + ' could not be created: ' + str(error)
1150
1253
  tasks[name] = found[0]
1151
1254
  pending.append(name)
1255
+ try:
1256
+ summary_seen[name] = summary_signature(name) # before it runs: its first change must trigger
1257
+ except Exception:
1258
+ pass
1152
1259
  if subprocess.run(['/bin/bash', script, '_waves', str(plan)]).returncode:
1153
1260
  _warn('waves.tsv was not refreshed for ' + name + '; the task still runs')
1154
1261
  return 'applied', None
1155
1262
 
1263
+ def apply_accept(request: dict) -> tuple:
1264
+ """A person's accept of a reviewed task (#138): what `forge-parallel.sh accept` does, run
1265
+ here because this scheduler holds the plan lock it needs. Its dependents start once it merges."""
1266
+ name, reason = request['task'], (request.get('reason') or '').strip()
1267
+ if name not in tasks:
1268
+ return 'refused', 'this run does not know task ' + name
1269
+ if not reason or request.get('approved') is not True:
1270
+ return 'refused', 'an accept needs --reason and --approved'
1271
+ if name in active:
1272
+ return 'refused', 'the task is running'
1273
+ if name in pending:
1274
+ return 'refused', 'the task is already waiting to run'
1275
+ state = status(name)
1276
+ if state not in ('FAIL', 'UNKNOWN', 'NEEDS_DECISION'):
1277
+ return 'refused', ('a ' + state + ' task has no reviewer verdict to override: accept takes a FAIL, '
1278
+ 'UNKNOWN or NEEDS_DECISION task')
1279
+ env = dict(os.environ, FORGE_ACCEPT_ACTOR=request.get('actor') or 'cli')
1280
+ result = subprocess.run(['/bin/bash', script, '_accept', str(plan), name, '--reason', reason, '--approved'],
1281
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env)
1282
+ lines = [line for line in result.stdout.splitlines() if line.strip()]
1283
+ if result.returncode:
1284
+ said = [line[len('forge: '):] for line in lines if line.startswith('forge: ')]
1285
+ return 'refused', (said[-1] if said else 'the accept failed (exit ' + str(result.returncode) + ')')
1286
+ for line in lines:
1287
+ print('forge: ' + line, file=sys.stderr, flush=True)
1288
+ pairs_cache.pop(name, None)
1289
+ refused.pop(name, None)
1290
+ if brief_mode != 'off' and status(name) == 'MERGED':
1291
+ brief_stale(name)
1292
+ return 'applied', None
1293
+
1156
1294
  def is_fix(name: str) -> bool:
1157
1295
  """A finding sweep's fix task."""
1158
1296
  return (plan / 'tasks' / name / 'sweep.json').is_file()
@@ -1195,6 +1333,8 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1195
1333
  outcome, reason = 'refused', 'run is stopping'
1196
1334
  elif request['verb'] == 'retry':
1197
1335
  outcome, reason = apply_retry(request)
1336
+ elif request['verb'] == 'accept':
1337
+ outcome, reason = apply_accept(request)
1198
1338
  else:
1199
1339
  outcome, reason = apply_add(request)
1200
1340
  with _control_lock(plan):
@@ -1236,6 +1376,102 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1236
1376
  if not reaped:
1237
1377
  return
1238
1378
 
1379
+ summary_seen = {} # task -> what the scheduler last saw of it (status, attempt trail, verdict, retries)
1380
+ summary_due = set() # tasks that changed and wait for a summarize
1381
+ summary_procs = {} # task -> its detached forge-summarize.py, polled only to reap it
1382
+ summary_starters = {} # task -> the thread that is checking admission and starting one
1383
+ summary_checks = {} # task -> (that thread's abandon flag, the pid it waits for)
1384
+ summary_warned = [] # a failure to start one is reported once
1385
+
1386
+ def summary_signature(name: str) -> tuple:
1387
+ root = plan / 'tasks' / name
1388
+ parts = [status(name)]
1389
+ for file in SUMMARY_FILES:
1390
+ try:
1391
+ found = os.stat(root / file)
1392
+ parts.append((found.st_size, found.st_mtime_ns))
1393
+ except OSError:
1394
+ parts.append(None)
1395
+ return tuple(parts)
1396
+
1397
+ def summary_spawn(name: str, after: int | None) -> None:
1398
+ """Start the detached summarize of one task, in its own session. With after (a pid), it begins once
1399
+ that process is gone: the run is ending and the earlier summarize of this task still holds its lock."""
1400
+ command = [sys.executable, os.environ.get('FORGE_SUMMARIZE') or SUMMARIZE, str(plan), '--task', name]
1401
+ if after is not None:
1402
+ command = ['/bin/sh', '-c', 'while kill -0 "$0" 2>/dev/null; do sleep 1; done; exec "$@"',
1403
+ str(after)] + command
1404
+ out = open(plan / 'summaries.out', 'ab')
1405
+ try:
1406
+ process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out,
1407
+ start_new_session=True)
1408
+ finally:
1409
+ out.close()
1410
+ summary_procs[name] = process
1411
+
1412
+ def summary_run(name: str, after: int | None, abandoned: threading.Event) -> None:
1413
+ """Thread body: forge_side.allowed() takes a blocking lock, so it never runs on the scheduler's
1414
+ loop. An abandoned check (the scheduler is ending and handed the task on) starts nothing."""
1415
+ try:
1416
+ import forge_side
1417
+ if not forge_side.allowed('summary', plan, name)[0] or abandoned.is_set():
1418
+ return
1419
+ summary_spawn(name, after)
1420
+ except Exception as error: # a summary is never worth the run
1421
+ if not summary_warned:
1422
+ summary_warned.append(error)
1423
+ _warn('summaries not started: ' + str(error))
1424
+
1425
+ def summaries_on_change(final: bool = False) -> None:
1426
+ """Start a detached `forge-summarize.py <plan> --task <id>` for every task whose status, dwarf reply,
1427
+ attempt trail, verdict or retry count changed since the last look: once per change, never on a timer,
1428
+ one at a time per task, and only where forge_side.allowed() says summaries are on. The first look at a
1429
+ task only remembers it. Nothing here can change a task or the run, or wait for one."""
1430
+ try:
1431
+ for name in list(summary_procs):
1432
+ if summary_procs[name].poll() is not None:
1433
+ del summary_procs[name]
1434
+ for name in list(summary_starters):
1435
+ if not summary_starters[name].is_alive():
1436
+ del summary_starters[name]
1437
+ for name in tasks:
1438
+ signature = summary_signature(name)
1439
+ if name in summary_seen and summary_seen[name] != signature:
1440
+ summary_due.add(name)
1441
+ summary_seen[name] = signature
1442
+ deadline = time.monotonic() + SUMMARY_JOIN
1443
+ if final: # let the admission checks that are under way finish, for a bounded time
1444
+ for starter in list(summary_starters.values()):
1445
+ starter.join(max(0.0, deadline - time.monotonic()))
1446
+ for name in sorted(summary_due):
1447
+ starter = summary_starters.get(name)
1448
+ running = summary_procs.get(name)
1449
+ running = running if running is not None and running.poll() is None else None
1450
+ if (starter is not None and starter.is_alive()) or (running is not None and not final):
1451
+ continue # still summarising: the change waits for it to end
1452
+ summary_due.discard(name)
1453
+ after = running.pid if running else None
1454
+ abandoned = threading.Event()
1455
+ thread = threading.Thread(target=summary_run, args=(name, after, abandoned), daemon=True)
1456
+ summary_starters[name] = thread
1457
+ summary_checks[name] = (abandoned, after)
1458
+ thread.start()
1459
+ if final:
1460
+ for starter in list(summary_starters.values()):
1461
+ starter.join(max(0.0, deadline - time.monotonic()))
1462
+ # A check still blocked at the deadline (the side lock is held) was past the switch tests,
1463
+ # which never block: summaries are on. The thread dies with the scheduler, so the detached
1464
+ # summarize takes it over and makes the whole admission check itself.
1465
+ for name, starter in list(summary_starters.items()):
1466
+ if starter.is_alive():
1467
+ abandoned, after = summary_checks[name]
1468
+ abandoned.set()
1469
+ summary_spawn(name, after)
1470
+ except Exception as error: # a summary is never worth the run
1471
+ if not summary_warned:
1472
+ summary_warned.append(error)
1473
+ _warn('summaries not started: ' + str(error))
1474
+
1239
1475
  def stop(signum: int, frame: object) -> None:
1240
1476
  nonlocal interrupted
1241
1477
  interrupted = True
@@ -1244,6 +1480,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1244
1480
  signal.signal(signal.SIGINT, stop)
1245
1481
  try:
1246
1482
  live_start(plan, tasks, retry_failed, infra_retries)
1483
+ summaries_on_change()
1247
1484
  # Failures require an explicit retry unless this run asked for automatic ones.
1248
1485
  # Saved PASS results use the same fingerprint checks without paying for
1249
1486
  # implementation or QA again; an INFRA stop is not a failure of the work, so it
@@ -1276,6 +1513,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1276
1513
  interrupted = True
1277
1514
  graceful = graceful or mode == 'graceful'
1278
1515
  reap_exited(ended)
1516
+ summaries_on_change()
1279
1517
  if interrupted:
1280
1518
  break
1281
1519
  draining = drained(plan)
@@ -1331,12 +1569,17 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1331
1569
  handle_requests()
1332
1570
  cap = live_capacity(plan, capacity)
1333
1571
  draining = drained(plan) # again: the infrastructure wait above can last minutes
1572
+ brief_waiting.clear()
1334
1573
  for name in pending[:]:
1335
1574
  if paused or len(active) >= cap or interrupted or graceful or draining:
1336
1575
  break
1337
1576
  deps = [d for d in tasks[name][1].split(',') if d and d != '-']
1338
1577
  if any(status(dep) != 'MERGED' for dep in deps):
1339
1578
  continue
1579
+ if brief_held(name):
1580
+ # A wait, not a stop: the rest of the plan runs, and the run does not end while it lasts.
1581
+ brief_waiting.add(name)
1582
+ continue
1340
1583
  if any(overlap(tasks[name][3], tasks[other][3]) for other in active):
1341
1584
  continue
1342
1585
  if pauses and scope_held(name):
@@ -1376,7 +1619,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1376
1619
  drain_told = True
1377
1620
  print('forge: drained — ' + str(len(pending)) + ' task(s) waiting; forge control resume '
1378
1621
  + str(plan) + ' continues', file=sys.stderr, flush=True)
1379
- elif not active and not waiting_scopes():
1622
+ elif not active and not waiting_scopes() and not brief_waiting:
1380
1623
  if paused or held or any(live_pause(pause) for pause in pauses.values()):
1381
1624
  # Infrastructure stop: leave everything not yet run PENDING. Marking it
1382
1625
  # BLOCKED would turn "the provider was down" into a recorded failure.
@@ -1437,6 +1680,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1437
1680
  mark(name, 'INTERRUPTED')
1438
1681
  except OSError as error:
1439
1682
  _warn('could not mark ' + name + ' INTERRUPTED: ' + str(error))
1683
+ summaries_on_change(final=True) # the last merges and stops; the children outlive the scheduler
1440
1684
  if interrupted or (graceful and not all(status(name) == 'MERGED' for name in tasks)):
1441
1685
  return 130
1442
1686
  if paused or any(live_pause(pause) for pause in pauses.values()) \
@@ -1446,6 +1690,31 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
1446
1690
  return 0 if all(status(name) == 'MERGED' for name in tasks if not is_fix(name)) else 5
1447
1691
 
1448
1692
 
1693
+ HOLDER = 'schedule.holder' # the forge command holding schedule.lock: written by each one that takes it
1694
+
1695
+
1696
+ def lock_refusal(plan: Path, command: str) -> str:
1697
+ """What a command the plan lock refuses says (#138): who holds the lock, and what to do instead."""
1698
+ holder = _json_object(plan / HOLDER) or {}
1699
+ pid, held_by, since = holder.get('pid'), holder.get('command'), holder.get('at')
1700
+ who = 'another forge command'
1701
+ if isinstance(held_by, str) and held_by.isidentifier() and type(pid) is int:
1702
+ who = 'forge-parallel.sh ' + held_by + ' (pid ' + str(pid) + ')'
1703
+ if isinstance(since, (int, float)):
1704
+ try:
1705
+ who += ', since ' + time.strftime('%H:%M', time.localtime(since))
1706
+ except (ValueError, OverflowError, OSError):
1707
+ pass
1708
+ text = 'forge: ' + command + ': the plan ' + str(plan) + ' is locked by ' + who + '.'
1709
+ if held_by == 'run' or (plan / 'scheduler.live').exists():
1710
+ live = ('forge control accept ' + str(plan) + ' <task> --reason TEXT --approved'
1711
+ if command == 'accept' else 'forge control (retry, accept, add, set, drain, stop)')
1712
+ text += ' A run is live: change it with ' + live + ', or wait for the run to end.'
1713
+ else:
1714
+ text += ' Wait for it to finish, then run forge-parallel.sh ' + command + ' again.'
1715
+ return text
1716
+
1717
+
1449
1718
  def main() -> None:
1450
1719
  try:
1451
1720
  if sys.argv[1] == 'backoff-check':
@@ -1461,8 +1730,14 @@ def main() -> None:
1461
1730
  # The shell inherits the lock for its entire operation, including
1462
1731
  # preflight, setup, scheduling, verification and cleanup.
1463
1732
  lock = open(Path(plan) / 'schedule.lock', 'a')
1464
- fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
1733
+ try:
1734
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
1735
+ except BlockingIOError:
1736
+ print(lock_refusal(Path(plan), command), file=sys.stderr)
1737
+ sys.exit(3)
1465
1738
  os.set_inheritable(lock.fileno(), True)
1739
+ # Who holds it, for the next command the lock refuses. exec keeps this pid.
1740
+ _write_atomic(plan, json.dumps(dict(pid=os.getpid(), command=command, at=time.time())) + '\n', HOLDER)
1466
1741
  env = dict(os.environ, FORGE_PLAN_LOCK=plan)
1467
1742
  os.execve('/bin/bash', ['/bin/bash', script, command, plan, *args], env)
1468
1743
  parser = argparse.ArgumentParser(prog='forge-schedule.py')
@@ -27,11 +27,14 @@ Guarantees, because the task waits for this process before it writes any status:
27
27
  timeout, error, invalid (the reviewer changed its snapshot), overtime, stopped, orphaned.
28
28
  Only a `done` review counts as a second opinion.
29
29
  Forge never picks a model: the reviewer is one the user listed, preferring a different
30
- model family from the primary reviewer's, so two reviewers do not share one blind spot.
30
+ model family from the primary reviewer's, so two reviewers do not share one blind spot. A listed
31
+ spec that resolves to the primary's own harness, model and effort is picked last, as a `control`:
32
+ it measures a reviewer's noise, not what another effort or model buys (#121).
31
33
  """
32
34
  from __future__ import annotations
33
35
 
34
36
  import argparse
37
+ import functools
35
38
  import hashlib
36
39
  import json
37
40
  import os
@@ -115,8 +118,9 @@ def family(model: str) -> str:
115
118
  return m
116
119
 
117
120
 
118
- def resolved_model(spec: str) -> str | None:
119
- """The model a qa dispatch of `spec` would use, by dispatch's own dry run."""
121
+ @functools.lru_cache(maxsize=None)
122
+ def resolution(spec: str) -> tuple | None:
123
+ """(harness, model, effort) a qa dispatch of `spec` would use, by dispatch's own dry run; None when it fails."""
120
124
  with tempfile.TemporaryDirectory(prefix='forge-shadow-resolve-') as tmp:
121
125
  prompt = Path(tmp) / 'input'
122
126
  prompt.write_text('Offline resolution')
@@ -127,7 +131,9 @@ def resolved_model(spec: str) -> str | None:
127
131
  except (OSError, subprocess.SubprocessError):
128
132
  return None
129
133
  fields = dict(line.split('=', 1) for line in out.stdout.splitlines() if '=' in line)
130
- return fields.get('model') or None
134
+ if not fields.get('model'):
135
+ return None
136
+ return fields.get('harness') or None, fields['model'], fields.get('effort') or None
131
137
 
132
138
 
133
139
  def candidates(plan: Path) -> list:
@@ -140,14 +146,27 @@ def candidates(plan: Path) -> list:
140
146
 
141
147
 
142
148
  def pick(listed: list, primary: str) -> tuple[str | None, str | None]:
143
- """(spec, why): the first listed spec of another family than the primary's, else the first."""
149
+ """(spec, why): the first listed spec of another family than the primary's (`other_family`); else the
150
+ first one of its family that does not resolve to the primary's own harness, model and effort
151
+ (`same_model` when only the effort or harness differs, `same_family` for another model); else the
152
+ first listed, labelled `control` (#121). A control reviews the diff with the primary's own settings,
153
+ so it measures noise and never counts as an effort comparison. A spec that does not resolve is
154
+ compared by its text."""
144
155
  if not listed:
145
156
  return None, None
146
- mine = family(resolved_model(primary) or primary)
147
- for spec in listed:
148
- if family(resolved_model(spec) or spec) != mine:
157
+ me = resolution(primary)
158
+ mine = family(me[1] if me else primary)
159
+ resolved = [(spec, resolution(spec)) for spec in listed]
160
+ for spec, found in resolved:
161
+ if family(found[1] if found else spec) != mine:
149
162
  return spec, 'other_family'
150
- return listed[0], 'same_family'
163
+ for spec, found in resolved:
164
+ if me and found:
165
+ if found != me:
166
+ return spec, 'same_model' if found[1] == me[1] else 'same_family'
167
+ elif spec.strip().lower() != primary.strip().lower():
168
+ return spec, 'same_family'
169
+ return listed[0], 'control'
151
170
 
152
171
 
153
172
  def fresh_dir(base: Path, attempt: str) -> Path:
@@ -214,7 +233,7 @@ def run(args) -> int:
214
233
  signal.signal(signal.SIGTERM, _stop)
215
234
  plan = Path(args.plan)
216
235
  parent = os.getppid()
217
- status, out, spec, why = 'skipped', None, None, None
236
+ status, out, spec, why, review = 'skipped', None, None, None, None
218
237
  try:
219
238
  if os.environ.get('FORGE_FRACTAL_RUN') or not sampled(plan, args.task, args.attempt, rate_of(plan)):
220
239
  return 0
@@ -256,6 +275,12 @@ def run(args) -> int:
256
275
  if out is not None:
257
276
  write(out / 'shadow.error', '%s: %s\n' % (type(error).__name__, error))
258
277
  finally:
278
+ # The verdict is read and the snapshot checked: nothing uses the snapshot again (#139).
279
+ if review is not None:
280
+ try:
281
+ bash('forge_drop_snapshot', str(review))
282
+ except Exception: # a leftover snapshot never costs the shadow its status
283
+ pass
259
284
  if out is not None:
260
285
  write(out / 'shadow.status', status + '\n')
261
286
  dataset_event(out, args.task, dict(status=status, attempt=args.attempt, reviewed=args.reviewed,
@@ -277,6 +277,7 @@ fi
277
277
  [ "$DRY" = 1 ] || forge_repo_identity "$REPO" "$RUN"
278
278
  # Every real run, --ui or not: forge-ui's view of this repo's runs reads the registry.
279
279
  [ "$DRY" = 1 ] || forge_ui_register "$RUN"
280
+ [ "$DRY" = 1 ] || forge_storage_check "$RUN" "$REPO"
280
281
  # Recorded before any dispatch: forge-ui opens this dir immediately, and a re-run
281
282
  # that dies early must not keep showing the previous invocation's verdict.
282
283
  if [ "$DRY" != 1 ]; then
@@ -361,6 +362,7 @@ if [ ! -s "$RUN/changes.diff" ]; then
361
362
  fi
362
363
 
363
364
  REVIEW="$RUN/review-$(date +%s)-$$"
365
+ FORGE_REVIEW_SNAPSHOT="$REVIEW" # forge_metric_begin's EXIT trap removes it, whatever the outcome (#139)
364
366
  forge_review_snapshot "$REPO" "$START" "$END" "$REVIEW" || die "cannot create review snapshot" 3
365
367
  forge_review_deps "$REPO" "$REVIEW" "$RUN/review.deps"
366
368
  SOURCE_FP="$(forge_fingerprint "$REPO")" || exit 3