@giamme/forge 0.21.0 → 0.23.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 (165) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +25 -15
  3. package/SKILL.md +137 -216
  4. package/VERSION +1 -1
  5. package/bin/forge.js +104 -0
  6. package/docs/README.md +2 -3
  7. package/docs/add-ons.md +5 -3
  8. package/docs/artifacts.md +17 -2
  9. package/docs/commands.md +85 -63
  10. package/docs/decomposed-runs.md +195 -21
  11. package/docs/development.md +12 -10
  12. package/docs/forge-ui.md +33 -4
  13. package/docs/install.md +127 -6
  14. package/docs/memory.md +6 -1
  15. package/docs/models.md +36 -10
  16. package/docs/reviews.md +50 -29
  17. package/docs/safety.md +27 -2
  18. package/docs/troubleshooting.md +8 -11
  19. package/forge +29 -4
  20. package/forge.cmd +56 -0
  21. package/package.json +6 -3
  22. package/references/dataset.md +10 -9
  23. package/references/decompose-integration.md +337 -0
  24. package/references/decompose-opt-in.md +527 -0
  25. package/references/decompose-recovery.md +569 -0
  26. package/references/decompose-review.md +256 -0
  27. package/references/decompose.md +99 -1606
  28. package/references/findings.md +68 -0
  29. package/references/harnesses.md +7 -12
  30. package/references/memory.md +13 -2
  31. package/references/planning.md +48 -18
  32. package/references/ripwire.md +38 -13
  33. package/references/runtime.md +22 -33
  34. package/references/setup.md +90 -0
  35. package/references/solo.md +13 -42
  36. package/references/ui.md +12 -5
  37. package/registry.tsv +40 -22
  38. package/scripts/forge-artifact.sh +148 -13
  39. package/scripts/forge-compare.py +5 -15
  40. package/scripts/forge-config.py +14 -1
  41. package/scripts/forge-contract.py +216 -53
  42. package/scripts/forge-control.py +781 -51
  43. package/scripts/forge-dispatch.sh +202 -42
  44. package/scripts/forge-du.py +13 -3
  45. package/scripts/forge-guard.py +137 -6
  46. package/scripts/forge-handoff.py +221 -39
  47. package/scripts/forge-install-ripwire.sh +100 -24
  48. package/scripts/forge-install.sh +100 -41
  49. package/scripts/forge-issues.py +6 -4
  50. package/scripts/forge-jev-options.sh +3 -5
  51. package/scripts/forge-lib-adopt.sh +169 -5
  52. package/scripts/forge-lib-attribute.sh +10 -3
  53. package/scripts/forge-lib-decompose.sh +454 -0
  54. package/scripts/forge-lib-env.sh +179 -0
  55. package/scripts/forge-lib-group.sh +9 -6
  56. package/scripts/forge-lib-plans.sh +38 -21
  57. package/scripts/forge-lib-review.sh +28 -8
  58. package/scripts/forge-lib-task.sh +263 -69
  59. package/scripts/forge-lib-verify.sh +59 -10
  60. package/scripts/forge-memory.sh +83 -4
  61. package/scripts/forge-metrics.sh +10 -3
  62. package/scripts/forge-parallel-options.sh +23 -4
  63. package/scripts/forge-parallel.sh +602 -217
  64. package/scripts/forge-plan-check.py +71 -8
  65. package/scripts/forge-planner.py +303 -17
  66. package/scripts/forge-pr.py +9 -1
  67. package/scripts/forge-prompt.py +2 -2
  68. package/scripts/forge-review-links.py +248 -0
  69. package/scripts/forge-ripwire.py +234 -16
  70. package/scripts/forge-route.py +19 -27
  71. package/scripts/forge-runs-rm.py +92 -21
  72. package/scripts/forge-runs.py +46 -5
  73. package/scripts/forge-runtime.py +39 -14
  74. package/scripts/forge-schedule.py +141 -33
  75. package/scripts/forge-setup-stale.py +236 -0
  76. package/scripts/forge-setup.py +804 -0
  77. package/scripts/forge-shadow.py +2 -20
  78. package/scripts/forge-solo-lock.py +46 -0
  79. package/scripts/forge-solo.sh +39 -58
  80. package/scripts/forge-sweep.py +3 -2
  81. package/scripts/forge-ui.py +8 -1
  82. package/scripts/forge-update.sh +8 -3
  83. package/scripts/forge-verify.py +17 -1
  84. package/scripts/forge-version.py +13 -1
  85. package/scripts/forge-watch.py +7 -2
  86. package/scripts/forge-win.sh +156 -0
  87. package/scripts/forge_brief/__init__.py +6 -1
  88. package/scripts/forge_brief/proposals.py +6 -1
  89. package/scripts/forge_dataset/__init__.py +1 -1
  90. package/scripts/forge_dataset/capture.py +0 -34
  91. package/scripts/forge_dataset/checks.py +0 -1
  92. package/scripts/forge_dataset/cli.py +5 -1
  93. package/scripts/forge_dataset/export.py +28 -6
  94. package/scripts/forge_dataset/facts.py +1 -2
  95. package/scripts/forge_dataset/forecast.py +1 -1
  96. package/scripts/forge_dataset/harvest.py +107 -7
  97. package/scripts/forge_dataset/importer.py +3 -2
  98. package/scripts/forge_dataset/pairs.py +3 -3
  99. package/scripts/forge_dataset/reviewers.py +4 -3
  100. package/scripts/forge_dataset/routing.py +6 -3
  101. package/scripts/forge_dataset/tiers.py +1 -1
  102. package/scripts/forge_decide/__init__.py +1 -1
  103. package/scripts/forge_decide/budget.py +12 -7
  104. package/scripts/forge_decide/profiles.py +11 -14
  105. package/scripts/forge_decide/replay.py +9 -4
  106. package/scripts/forge_decompose.py +987 -0
  107. package/scripts/forge_flock.py +17 -2
  108. package/scripts/forge_groups/review.py +6 -1
  109. package/scripts/forge_jev/__init__.py +1 -1
  110. package/scripts/forge_jev/cli.py +10 -1
  111. package/scripts/forge_jev/gates.py +10 -1
  112. package/scripts/forge_jev/verify.py +10 -2
  113. package/scripts/forge_legacy.py +86 -0
  114. package/scripts/forge_memory_home.py +57 -0
  115. package/scripts/forge_models.py +151 -0
  116. package/scripts/forge_posix.py +17 -0
  117. package/scripts/forge_prefs.py +138 -0
  118. package/scripts/forge_proc.py +108 -0
  119. package/scripts/forge_registry.py +2 -2
  120. package/scripts/forge_side/__init__.py +23 -4
  121. package/scripts/forge_storage.py +28 -15
  122. package/ui/README.md +22 -10
  123. package/ui/docs/api.md +121 -99
  124. package/ui/forge_ui/control.py +53 -16
  125. package/ui/forge_ui/export.py +0 -10
  126. package/ui/forge_ui/models.py +15 -2
  127. package/ui/forge_ui/projects.py +4 -1
  128. package/ui/forge_ui/reader.py +462 -60
  129. package/ui/forge_ui/server.py +0 -10
  130. package/ui/forge_ui/static/app.js +28 -9
  131. package/ui/forge_ui/static/checksview.js +12 -3
  132. package/ui/forge_ui/static/controls.js +147 -11
  133. package/ui/forge_ui/static/convo.js +5 -2
  134. package/ui/forge_ui/static/diffview.js +4 -5
  135. package/ui/forge_ui/static/panel.js +180 -77
  136. package/ui/forge_ui/static/projectsview.js +16 -2
  137. package/ui/forge_ui/static/runmodel.js +18 -4
  138. package/ui/forge_ui/static/scene3d.js +52 -31
  139. package/ui/forge_ui/static/settings.js +1 -1
  140. package/ui/forge_ui/static/storageview.js +2 -2
  141. package/ui/forge_ui/static/style.css +23 -6
  142. package/ui/forge_ui/static/worktreesview.js +8 -4
  143. package/ui/forge_ui/transcripts.py +6 -0
  144. package/ui/forge_ui/worktrees.py +13 -1
  145. package/docs/fractal.md +0 -181
  146. package/references/fractal-dashboard.md +0 -21
  147. package/references/fractal.md +0 -307
  148. package/scripts/forge-fractal-dispatch.sh +0 -4
  149. package/scripts/forge-fractal-options.sh +0 -54
  150. package/scripts/forge-fractal.py +0 -6
  151. package/scripts/forge-install-fractal.sh +0 -4
  152. package/scripts/forge_fractal/__init__.py +0 -88
  153. package/scripts/forge_fractal/bridge.py +0 -46
  154. package/scripts/forge_fractal/cli.py +0 -224
  155. package/scripts/forge_fractal/dashboard.css +0 -138
  156. package/scripts/forge_fractal/dashboard.html +0 -41
  157. package/scripts/forge_fractal/dashboard.js +0 -687
  158. package/scripts/forge_fractal/decomposition.py +0 -262
  159. package/scripts/forge_fractal/execution.py +0 -659
  160. package/scripts/forge_fractal/inspection.py +0 -261
  161. package/scripts/forge_fractal/install.py +0 -158
  162. package/scripts/forge_fractal/invocation.py +0 -95
  163. package/scripts/forge_fractal/pipeline.py +0 -125
  164. package/scripts/forge_fractal/selection.py +0 -180
  165. package/ui/forge_ui/fractal.py +0 -582
@@ -392,7 +392,12 @@ def _task_lock(plan: Path, task: str):
392
392
  fcntl.flock(fd, fcntl.LOCK_EX)
393
393
  yield
394
394
  finally:
395
- os.close(fd)
395
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases can leave
396
+ # another thread of this process waiting on it for ever.
397
+ try:
398
+ fcntl.flock(fd, fcntl.LOCK_UN)
399
+ finally:
400
+ os.close(fd)
396
401
 
397
402
 
398
403
  def _record(plan: Path, task: str, model: str, level: str, questions, error) -> dict:
@@ -506,7 +506,12 @@ def _proposals_lock(plan):
506
506
  fcntl.flock(fd, fcntl.LOCK_EX)
507
507
  yield
508
508
  finally:
509
- os.close(fd)
509
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases can leave
510
+ # another thread of this process waiting on it for ever.
511
+ try:
512
+ fcntl.flock(fd, fcntl.LOCK_UN)
513
+ finally:
514
+ os.close(fd)
510
515
 
511
516
 
512
517
  @contextlib.contextmanager
@@ -17,7 +17,7 @@ can still be answered from old runs.
17
17
 
18
18
  Capture is fail-open in the same way Jev is. Every entry point swallows its own errors
19
19
  into errors.log, never prints, never raises, and bounds its wait on the database with the
20
- SQLite busy timeout. It uses no signals, because Fractal captures from worker threads.
20
+ SQLite busy timeout. It uses no signals, so a capture may run from any thread.
21
21
  record_strict() is the one exception, for a caller that must know an event is stored (it
22
22
  raises DatasetError instead of returning 0).
23
23
  FORGE_DATASET=off turns it off.
@@ -213,40 +213,6 @@ def jev(*, site, key, canonical: bytes, ok, reason, latency, model, usage, quest
213
213
  log_error('jev:' + str(site), error)
214
214
 
215
215
 
216
- def fractal_step(task_dir, node: dict, step_dir, *, phase: str, iteration, rc, cost, resolved) -> None:
217
- """One Fractal step, keyed by its own step uuid.
218
-
219
- node.json is mutable (a retry resets `iteration` to 0), so a step is recorded by
220
- the uuid of the dir it ran in rather than by (node, iteration), which can repeat.
221
- Called from worker threads: no signals, a connection per call.
222
- """
223
- if not enabled():
224
- return
225
- try:
226
- task_dir, step_dir = Path(task_dir), Path(step_dir)
227
- ctx = h.fractal_context(task_dir, create=True)
228
- if location_refused(ctx['repo']):
229
- return
230
- record([h.fractal_step_event(task_dir, node, step_dir, ctx, phase=phase, iteration=iteration, rc=rc,
231
- cost=cost, resolved=resolved)], repo=ctx['repo'], where='fractal_step')
232
- except Exception as error:
233
- log_error('fractal_step', error)
234
-
235
-
236
- def fractal_outcome(task_dir) -> None:
237
- """Every node's final state and the task outcome, once per distinct state."""
238
- if not enabled():
239
- return
240
- try:
241
- task_dir = Path(task_dir)
242
- ctx = h.fractal_context(task_dir, create=True)
243
- if location_refused(ctx['repo']):
244
- return
245
- record(h.fractal_task_events(task_dir, ctx), repo=ctx['repo'], where='fractal_outcome')
246
- except Exception as error:
247
- log_error('fractal_outcome', error)
248
-
249
-
250
216
  def plan_snapshot(plan: str) -> None:
251
217
  """Every routing, decomposition and scheduling decision made before the first dispatch."""
252
218
  if not enabled():
@@ -10,7 +10,6 @@ from __future__ import annotations
10
10
  import json
11
11
  import sqlite3
12
12
  import time
13
- from pathlib import Path
14
13
 
15
14
  from . import dataset_dir
16
15
 
@@ -292,7 +292,7 @@ def parser() -> argparse.ArgumentParser:
292
292
  p = sub.add_parser('import', help='capture run dirs, archives and ledgers that predate live capture')
293
293
  p.add_argument('paths', nargs='*', help='run/plan dirs, dirs to scan, or .tar.gz archives')
294
294
  p.add_argument('--registry', action='store_true', help='every run dir listed in the Jev runs registry')
295
- p.add_argument('--fractal', action='store_true', help='the Fractal state dir')
295
+ p.add_argument('--fractal', action='store_true', help='the state dir of Fractal (removed in forge 0.23): its old runs, to import before deleting it')
296
296
  p.add_argument('--ledger', action='append', default=[], metavar='REPO', help="a repo's .forge/ledger.tsv")
297
297
  p.add_argument('--include-temp', action='store_true', help='also import runs whose repo is a temp dir (test runs)')
298
298
  p.add_argument('--dry-run', action='store_true')
@@ -303,6 +303,7 @@ def parser() -> argparse.ArgumentParser:
303
303
  help='only this slice; repeatable (default: all)')
304
304
  p.add_argument('--limit', type=int, help='at most this many cases per slice, spread across runs')
305
305
  p.add_argument('--seed', type=int, default=7)
306
+ p.add_argument('--include-steered', action='store_true', help='keep attempts a person steered (forge control steer); left out by default')
306
307
  p.set_defaults(func=run_export)
307
308
  p = sub.add_parser('outcomes', help='what happened to integrated work afterwards (read-only git)')
308
309
  p.add_argument('--horizon-days', type=int, default=14, help='how long after integrate to look (default 14)')
@@ -317,11 +318,13 @@ def parser() -> argparse.ArgumentParser:
317
318
  p.add_argument('--repo', help='only this repo')
318
319
  p.add_argument('--since', type=float, metavar='DAYS', help='only tasks first attempted in the last DAYS days')
319
320
  p.add_argument('--json', action='store_true')
321
+ p.add_argument('--include-steered', action='store_true', help='keep attempts a person steered (forge control steer); left out by default')
320
322
  p.set_defaults(func=run_routing)
321
323
  p = sub.add_parser('reviewers', help='how often work each reviewer passed was later reverted or rewritten (advisory)')
322
324
  p.add_argument('--horizon-days', type=int, default=14, help='the outcomes recorded at this horizon (default 14)')
323
325
  p.add_argument('--repo', help='only this repo')
324
326
  p.add_argument('--json', action='store_true')
327
+ p.add_argument('--include-steered', action='store_true', help='keep attempts a person steered (forge control steer); left out by default')
325
328
  p.set_defaults(func=run_reviewers)
326
329
  p = sub.add_parser('facts', help="the reach, origin and evidence reviewers give findings: agreement, and what "
327
330
  "a gate on them would have changed (advisory)")
@@ -332,6 +335,7 @@ def parser() -> argparse.ArgumentParser:
332
335
  'from model and family comparisons and controls (advisory)')
333
336
  p.add_argument('--repo', help='only this repo')
334
337
  p.add_argument('--json', action='store_true')
338
+ p.add_argument('--include-steered', action='store_true', help='keep attempts a person steered (forge control steer); left out by default')
335
339
  p.set_defaults(func=run_pairs)
336
340
  p = sub.add_parser('risk', help="tasks by difficulty and risk together: how often they differ, and how each "
337
341
  "pair fared (advisory)")
@@ -222,10 +222,16 @@ def review_survives() -> dict:
222
222
  # --- indexes ---------------------------------------------------------------------------
223
223
 
224
224
  class Runs:
225
- """Plans, attempts and dispatches of every run, joined by (run, task)."""
225
+ """Plans, attempts and dispatches of every run, joined by (run, task).
226
226
 
227
- def __init__(self, store: Store):
227
+ A task a person steered (`forge control steer`, #134) is its own measure from the first steered
228
+ attempt on: that attempt and every later one (and their dispatches) are left out unless
229
+ `include_steered`. `steered` names those tasks, {(run, task): first steered attempt}, either way.
230
+ """
231
+
232
+ def __init__(self, store: Store, include_steered: bool = False):
228
233
  self.store = store
234
+ self.include_steered = include_steered
229
235
  self.plans = defaultdict(list)
230
236
  for e in store.of('plan'):
231
237
  self.plans[e['run']].append(e)
@@ -237,6 +243,14 @@ class Runs:
237
243
  self.attempts[(e['run'], e['task'])].append(e)
238
244
  for rows in self.attempts.values():
239
245
  rows.sort(key=lambda e: (e['attempt'] or 0, e['d'].get('wall_started') or e['ts']))
246
+ self.steered = {}
247
+ for key, rows in self.attempts.items():
248
+ marked = [e['attempt'] or 0 for e in rows if e['d'].get('steered')]
249
+ if marked:
250
+ self.steered[key] = min(marked)
251
+ if not include_steered:
252
+ for key, first in self.steered.items():
253
+ self.attempts[key] = [e for e in self.attempts[key] if (e['attempt'] or 0) < first]
240
254
  self.dispatches = defaultdict(list)
241
255
  for e in store.of('dispatch'):
242
256
  # A group review names no task. scope group stays out of per-task indexes even
@@ -247,6 +261,11 @@ class Runs:
247
261
  # the attempt ended on, so each list is chronological; a tie keeps store order.
248
262
  for rows in self.dispatches.values():
249
263
  rows.sort(key=lambda e: (e['attempt'] or 0, e['d'].get('wall_started') or e['ts']))
264
+ if not include_steered:
265
+ for (run, task, role), rows in self.dispatches.items():
266
+ first = self.steered.get((run, task))
267
+ if first is not None:
268
+ rows[:] = [e for e in rows if (e['attempt'] or 0) < first]
250
269
  self.accepted = {(e['run'], e['d'].get('task')) for e in store.of('invocation')
251
270
  if e['d'].get('command') == 'accept' and e['d'].get('exit') == 0}
252
271
  self.interrupted = {(e['run'], e['task']) for e in store.of('event')
@@ -255,7 +274,8 @@ class Runs:
255
274
  # What `forge dataset outcomes` saw after integration, per reviewed commit; the
256
275
  # longest horizon observed wins, since it is the stronger observation.
257
276
  self.reviewed = {(e['run'], e['task'], e['attempt']): e['d']['reviewed_commit']
258
- for e in store.of('attempt') if e['d'].get('reviewed_commit')}
277
+ for e in store.of('attempt') if e['d'].get('reviewed_commit')
278
+ and (include_steered or (e['attempt'] or 0) < self.steered.get((e['run'], e['task']), 1 << 30))}
259
279
  self.survival = {}
260
280
  for e in store.of('outcome'):
261
281
  d = e['d']
@@ -1042,10 +1062,11 @@ def _sample(cases: list, limit: int | None, seed: int) -> list:
1042
1062
  return picked
1043
1063
 
1044
1064
 
1045
- def build(db, *, slices=SLICES, limit: int | None = None, seed: int = 7, stats: dict | None = None) -> list:
1065
+ def build(db, *, slices=SLICES, limit: int | None = None, seed: int = 7, stats: dict | None = None,
1066
+ include_steered: bool = False) -> list:
1046
1067
  """Every case of the given slices. `stats`, when given, receives the censored-label counts."""
1047
1068
  store = Store(db)
1048
- runs = Runs(store)
1069
+ runs = Runs(store, include_steered=include_steered)
1049
1070
  builders = dict(routing=lambda: routing_cases(runs), retry=lambda: retry_cases(runs),
1050
1071
  review=lambda: review_cases(runs),
1051
1072
  drift=lambda: drift_cases(runs, seed), citation=lambda: citation_cases(runs, seed),
@@ -1106,7 +1127,8 @@ def main(args) -> int:
1106
1127
  db = connect()
1107
1128
  try:
1108
1129
  stats = {}
1109
- cases = build(db, slices=args.slices or SLICES, limit=args.limit, seed=args.seed, stats=stats)
1130
+ cases = build(db, slices=args.slices or SLICES, limit=args.limit, seed=args.seed, stats=stats,
1131
+ include_steered=getattr(args, 'include_steered', False))
1110
1132
  finally:
1111
1133
  db.close()
1112
1134
  if args.out:
@@ -25,11 +25,10 @@ from __future__ import annotations
25
25
  import json
26
26
  import os
27
27
  import re
28
- import sys
29
28
  from collections import Counter, defaultdict
30
29
 
31
30
  from . import connect, dataset_dir, is_side_role
32
- from .export import Runs, Store, _ending_qa, _gate_decision, not_an_attempt, shadow_pairs
31
+ from .export import Runs, Store, _ending_qa, not_an_attempt, shadow_pairs
33
32
 
34
33
  FACTS = {'reach': ('main', 'realistic', 'unusual'), 'origin': ('new', 'existing'),
35
34
  'evidence': ('ran', 'traced', 'suspected')}
@@ -31,7 +31,7 @@ import time
31
31
  from collections import defaultdict
32
32
  from pathlib import Path
33
33
 
34
- from . import SKILL, connect, dataset_dir, record
34
+ from . import connect, dataset_dir, record
35
35
  from .export import Runs, Store
36
36
  from .names import registry_models # noqa: F401 (forge-route, forge-compare and efforts import it from here)
37
37
  from .routing import tasks as routing_tasks, wilson
@@ -24,6 +24,8 @@ import time
24
24
  from pathlib import Path
25
25
 
26
26
  from . import SCRIPTS, put_blob, put_file, sha256
27
+ import forge_decompose # noqa: E402 (scripts/ is on sys.path once the package is imported)
28
+ import forge_legacy # noqa: E402
27
29
 
28
30
  DISPATCH_ROLES = ('dwarf', 'qa', 'planner', 'side')
29
31
  # The file role stays `side`. Harvest records side_<kind> (see dispatch_event);
@@ -300,8 +302,9 @@ def locate(root: str | Path, role: str | None = None) -> dict:
300
302
  """Which run, mode and task a dispatch or pipeline root belongs to, from the path alone.
301
303
 
302
304
  Env vars cannot carry this reliably (the orchestrator dispatches the planner by hand,
303
- Fractal steps run under tmux, and the importer has no env at all), so live capture
304
- and import both derive it from where forge put the files.
305
+ and the importer has no env at all), so live capture and import both derive it from
306
+ where forge put the files. The steps/nodes shape is an old record: a run made with
307
+ Fractal, which forge 0.23 removed and the importer still reads.
305
308
  """
306
309
  p = Path(root).resolve()
307
310
  parts = p.parts
@@ -727,6 +730,26 @@ def requirement_blob(tdir: Path, stem: str):
727
730
  return put_file(tdir / (stem + '.md'), 'prompt')
728
731
 
729
732
 
733
+ def steered_of(tdir: Path, attempt) -> tuple[list, str | None]:
734
+ """The messages `forge control steer` gave this attempt (#134), as `{actor, at, sha256, chars, mode}`,
735
+ and their texts joined for the blob. An attempt nobody steered has `[]`. mode is `queued` (given with the
736
+ prompt) or `live` (sent while the implementer ran, #252)."""
737
+ if attempt is None:
738
+ return [], None
739
+ found, texts = [], []
740
+ for line in (text(tdir / ('steered.%d.jsonl' % attempt)) or '').splitlines():
741
+ try:
742
+ entry = json.loads(line)
743
+ except ValueError:
744
+ continue
745
+ if not isinstance(entry, dict) or not isinstance(entry.get('text'), str):
746
+ continue
747
+ found.append(dict(actor=entry.get('actor'), at=entry.get('at'), sha256=entry.get('sha256'),
748
+ chars=entry.get('chars'), mode='live' if entry.get('mode') == 'live' else 'queued'))
749
+ texts.append(entry['text'])
750
+ return found, ('\n\n---\n\n'.join(texts) if texts else None)
751
+
752
+
730
753
  def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') -> dict:
731
754
  before = prov.get('files')
732
755
  made = lambda name: produced(tdir, before, name)
@@ -738,6 +761,7 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
738
761
  row = tasks_rows(plan / 'tasks.tsv').get(tdir.name, {})
739
762
  diff = text(tdir / 'changes.diff') if made('changes.diff') else None
740
763
  gate = first_line(tdir / 'qa.gate') if made('qa.gate') else None
764
+ steered, steer_text = steered_of(tdir, end)
741
765
  data = dict(
742
766
  status=status, exit=as_int(rc), attempt_start=prov.get('attempt_start'), attempt_end=end,
743
767
  trigger=prov.get('trigger'), **flags,
@@ -752,6 +776,7 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
752
776
  retry_source=first_line(tdir / 'retry_findings.source'),
753
777
  identical_retry=bool(diff) and made('changes.prev.diff') and diff == text(tdir / 'changes.prev.diff'),
754
778
  prompt_changed=attempt_prompt_changed(status),
779
+ steered=steered,
755
780
  produced=sorted(n for n in WATCHED if made(n)),
756
781
  carried=sorted(n for n in WATCHED if (tdir / n).exists() and not made(n)),
757
782
  children=children(tdir, attempt.name),
@@ -771,6 +796,7 @@ def task_event(attempt: Path, tdir: Path, rc, prov: dict, src: str = 'live') ->
771
796
  review_triage_jev=put_file(tdir / 'qa.jev.json') if made('qa.jev.json') else None,
772
797
  routing_jev=put_file(tdir / 'jev.json'),
773
798
  prompt=requirement_blob(tdir, 'prompt'), approach=requirement_blob(tdir, 'approach'),
799
+ steer=put_blob(steer_text, 'message') if steer_text else None,
774
800
  )
775
801
  data['blobs'] = refs
776
802
  return dict(rid=attempt.name, kind='attempt', ts=prov.get('wall_ended') or time.time(), src=src,
@@ -886,7 +912,7 @@ def run_end_event(attempt: Path, plan: Path, rc, prov: dict, src: str = 'live')
886
912
  repo = first_line(plan / 'repo')
887
913
  data = dict(exit=as_int(rc), results=results,
888
914
  accepted_integration=first_line(plan / 'accepted.integration'),
889
- blobs=blobs(memory=put_file(Path(repo) / '.forge' / 'memory.md') if repo else None))
915
+ blobs=blobs(memory=put_file(_memory_md(repo)) if repo else None))
890
916
  return dict(rid=attempt.name, kind='run_end', ts=prov.get('wall_ended') or time.time(), src=src,
891
917
  run=prov.get('run'), run_id=prov.get('run_id'), mode='parallel', parent=prov.get('parent'),
892
918
  inv=prov.get('inv'), data=data)
@@ -928,6 +954,49 @@ def decision_snapshot(repo: str, rows: dict, head: str | None) -> dict | None:
928
954
  return excerpts
929
955
 
930
956
 
957
+ def decomposition_of(plan: Path) -> tuple:
958
+ """(parent, decomposition, chain) of a plan, each None when the plan has no such record (#153).
959
+
960
+ parent: for the sub-plan of a split task (`<plan>/tasks/<id>/sub`), the run and the task it holds the
961
+ subtasks of: {run, run_id, task, level, root, start, by, reason}. `level` is how deep its tasks are
962
+ (1 for the subtasks of a plan's own task), `root` the run at the top of the tree.
963
+ decomposition: {limits, frozen, nodes: {task: {decision, reason, by, children, limit}}}, the decision
964
+ recorded for each task of this plan: atomic, split or bounded.
965
+ chain: {stage, first, previous, later}: where a plan made by `next` stands in its goal, and how many
966
+ stages its planner proposed after it."""
967
+ plan = Path(plan)
968
+ parent = None
969
+ if plan.name == 'sub' and plan.parent.parent.name == 'tasks' and (plan.parents[2] / 'tasks.tsv').exists():
970
+ link = read_json(plan / 'parent.json')
971
+ if isinstance(link, dict):
972
+ above, level, root = plan.parents[2], 1, plan.parents[2]
973
+ while root.name == 'sub' and root.parent.parent.name == 'tasks' and (root.parents[2] / 'tasks.tsv').exists() \
974
+ and level < 16:
975
+ root, level = root.parents[2], level + 1
976
+ parent = dict(run=run_uid(above, create=False), run_id=first_line(above / 'run_id') or above.name,
977
+ task=plan.parent.name, level=level, root=run_uid(root, create=False),
978
+ start=link.get('start'), by=link.get('by'), reason=link.get('reason'))
979
+ decomposition = None
980
+ record = read_json(plan / 'decomposition.json')
981
+ if isinstance(record, dict):
982
+ nodes = {}
983
+ for task, node in (record.get('nodes') or {}).items() if isinstance(record.get('nodes'), dict) else ():
984
+ if isinstance(node, dict):
985
+ used = node.get('limits_used') if isinstance(node.get('limits_used'), dict) else {}
986
+ nodes[task] = dict(decision=node.get('decision'), reason=node.get('reason'), by=node.get('by'),
987
+ children=used.get('children'), limit=used.get('limit'))
988
+ # The limits in force are the root plan's, each default where it set none.
989
+ decomposition = dict(limits=forge_decompose.limits(plan), frozen=forge_decompose.is_frozen(plan), nodes=nodes)
990
+ chain = None
991
+ link, later = read_json(plan / 'chain.json'), read_json(plan / 'later.json')
992
+ stages = later.get('later') if isinstance(later, dict) and isinstance(later.get('later'), list) else []
993
+ if isinstance(link, dict) or stages:
994
+ link = link if isinstance(link, dict) else {}
995
+ chain = dict(stage=link.get('stage'), first=link.get('first'), previous=link.get('previous'),
996
+ later=[s.get('title') for s in stages if isinstance(s, dict)])
997
+ return parent, decomposition, chain
998
+
999
+
931
1000
  def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True, head: str | None = None) -> dict:
932
1001
  rows = tasks_rows(plan / 'tasks.tsv')
933
1002
  declared_path = plan / 'tasks.declared.tsv'
@@ -986,6 +1055,15 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
986
1055
  later['collapsed'] = collapsed_record
987
1056
  if plan_gate is not None:
988
1057
  later['plan_gate'] = plan_gate
1058
+ # The decisions about the plan's tasks (#153), hashed without their times: a task split after the
1059
+ # plan was first recorded is a new revision of the plan, and reading the same file again is not.
1060
+ parent, decomposition, chain = decomposition_of(plan)
1061
+ if parent is not None:
1062
+ later['parent'] = [parent['run'], parent['task']]
1063
+ if decomposition is not None:
1064
+ later['decomposition'] = [decomposition['limits'], decomposition['nodes']]
1065
+ if chain is not None:
1066
+ later['chain'] = chain
989
1067
  inputs = json.dumps([text(plan / 'goal.txt'), text(plan / 'tasks.tsv'), text(declared_path),
990
1068
  {t: [r['prompt'], r['approach']] for t, r in per_task.items()}] + ([later] if later else []),
991
1069
  sort_keys=True, default=str)
@@ -997,8 +1075,7 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
997
1075
  planner=first_line(plan / 'planner'), author='planner' if list(plan.glob('attempts/planner-*')) else 'orchestrator',
998
1076
  planner_dispatches=sorted(p.name for p in plan.glob('attempts/planner-*')),
999
1077
  head=head, tasks=per_task, waves=waves, deferrals=(text(plan / 'deferrals.txt') or '').splitlines(),
1000
- pools=read_json(plan / 'fractal-routing.json'), jev_selection=read_json(plan / 'jev-selection.json'),
1001
- fractal_selection=read_json(plan / 'fractal-selection.json'),
1078
+ pools=read_json(forge_legacy.pools_path(plan)), jev_selection=read_json(plan / 'jev-selection.json'),
1002
1079
  jev_coupling=read_json(plan / 'jev-coupling.json'),
1003
1080
  options=dict({name: first_line(plan / name) for name in ('verify_retries', 'timeout', 'final_qa',
1004
1081
  'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session', 'reviewer_session_rate',
@@ -1012,8 +1089,13 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
1012
1089
  jev_routing=put_file(plan / 'jev-routing.tsv'),
1013
1090
  snapshot=put_blob(json.dumps(snapshot_excerpts, sort_keys=True), 'request') if snapshot_excerpts else None,
1014
1091
  inventory=put_blob(listing, 'request') if listing else None,
1015
- memory=put_file(Path(repo) / '.forge' / 'memory.md') if repo else None),
1092
+ memory=put_file(_memory_md(repo)) if repo else None),
1016
1093
  )
1094
+ # An old record only: a plan made before forge 0.23 says whether it ran under Fractal, and the
1095
+ # routing analysis leaves such a run out. A plan without the file gets no such key.
1096
+ old_selection = read_json(plan / forge_legacy.OLD_SELECTION)
1097
+ if old_selection is not None:
1098
+ data['fractal_selection'] = old_selection
1017
1099
  if plan_gates is not None:
1018
1100
  data['plan_gates'] = plan_gates
1019
1101
  if plan_shape is not None:
@@ -1032,6 +1114,13 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
1032
1114
  data['collapsed_from'] = origin
1033
1115
  if plan_gate is not None:
1034
1116
  data['plan_gate'] = plan_gate
1117
+ # Recursive decomposition (#153). Absent on a plan with no such record, so an older plan keeps its shape.
1118
+ if parent is not None:
1119
+ data['parent'] = parent
1120
+ if decomposition is not None:
1121
+ data['decomposition'] = decomposition
1122
+ if chain is not None:
1123
+ data['chain'] = chain
1035
1124
  # Who started the plan: `auto` for forge-parallel.sh auto. Absent for a plan built by hand.
1036
1125
  orchestrator = first_line(plan / 'orchestrator')
1037
1126
  if orchestrator:
@@ -1041,7 +1130,9 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
1041
1130
  inv=prov.get('inv'), data=data)
1042
1131
 
1043
1132
 
1044
- # --- Fractal ------------------------------------------------------------------------------
1133
+ # --- old records: runs made with Fractal ----------------------------------------------------
1134
+ # forge 0.23 removed Fractal (#154). Nothing writes these live any more; the importer still reads
1135
+ # what such a run left on disk, so its history is not lost when its state directory is deleted.
1045
1136
 
1046
1137
  def fractal_context(task_dir: Path, create: bool) -> dict:
1047
1138
  request = read_json(task_dir / 'request.json') or {}
@@ -1090,3 +1181,12 @@ def fractal_task_events(task_dir: Path, ctx: dict, src: str = 'live') -> list:
1090
1181
  blobs=blobs(diff=put_file(task_dir / 'changes.diff', 'diff'),
1091
1182
  qa=put_file(task_dir / 'qa.last', 'message')))))
1092
1183
  return events
1184
+
1185
+
1186
+ def _memory_md(repo) -> Path:
1187
+ """repo's .forge/memory.md, in the main checkout when repo is a linked worktree (#159)."""
1188
+ try:
1189
+ import forge_memory_home
1190
+ except ImportError:
1191
+ return Path(repo) / '.forge' / 'memory.md'
1192
+ return forge_memory_home.memory_file(repo)
@@ -27,7 +27,7 @@ import time
27
27
  from pathlib import Path
28
28
  from types import SimpleNamespace
29
29
 
30
- from . import (BUSY_TIMEOUT_S, DatasetError, config_runs_dir, connect, data_home, dataset_dir, enabled,
30
+ from . import (BUSY_TIMEOUT_S, DatasetError, config_runs_dir, connect, dataset_dir, enabled,
31
31
  location_refused, put_blob, put_file, record, record_strict, repo_id, sha256, watch_blob_failures)
32
32
  from . import harvest as h
33
33
  from . import capture
@@ -70,6 +70,7 @@ def walk_plans(top: Path, onerror=None) -> list[Path]:
70
70
 
71
71
 
72
72
  def walk_fractal_tasks(top: Path, onerror=None) -> list[Path]:
73
+ """Task dirs of a run made with Fractal (removed in forge 0.23): old records, still imported."""
73
74
  found = []
74
75
  for directory, subdirs, files in os.walk(top, onerror=onerror):
75
76
  subdirs[:] = [d for d in subdirs if d not in SKIP_DIRS and not d.startswith('review-')
@@ -478,7 +479,7 @@ def _manifest(directory: Path) -> dict:
478
479
 
479
480
 
480
481
  def _member(member, path):
481
- # Links are never run data (Fractal's archive carries a venv full of absolute ones),
482
+ # Links are never run data (an old Fractal archive carries a venv full of absolute ones),
482
483
  # and skipping them means nothing extracted can point outside the temp dir.
483
484
  if member.issym() or member.islnk():
484
485
  return None
@@ -134,13 +134,13 @@ def report(runs: Runs, repo: str = None) -> dict:
134
134
  by_kind={k: sum(r['pairs'] for r in out if r['kind'] == k) for k in KINDS}, comparisons=out)
135
135
 
136
136
 
137
- def load(repo: str = None) -> dict:
137
+ def load(repo: str = None, include_steered: bool = False) -> dict:
138
138
  # Reading must not create a store: a fresh machine gets an empty report.
139
139
  if not (dataset_dir() / 'dataset.sqlite').exists():
140
140
  return dict(min_pairs=MIN_PAIRS, line_window=LINE_WINDOW, pairs=0, by_kind={k: 0 for k in KINDS}, comparisons=[])
141
141
  db = connect()
142
142
  try:
143
- runs = Runs(Store(db))
143
+ runs = Runs(Store(db), include_steered=include_steered)
144
144
  finally:
145
145
  db.close()
146
146
  return report(runs, repo=repo)
@@ -151,7 +151,7 @@ HEADINGS = dict(effort='effort, within one model', model='another model, one fam
151
151
 
152
152
 
153
153
  def main(args) -> int:
154
- rep = load(os.path.realpath(args.repo) if args.repo else None)
154
+ rep = load(os.path.realpath(args.repo) if args.repo else None, include_steered=getattr(args, 'include_steered', False))
155
155
  if args.json:
156
156
  print(json.dumps(rep, indent=2, sort_keys=True))
157
157
  return 0
@@ -100,13 +100,13 @@ def report(runs: Runs, *, horizon_days: int = HORIZON_DAYS, repo: str = None) ->
100
100
  return out
101
101
 
102
102
 
103
- def load(horizon_days: int = HORIZON_DAYS, repo: str = None) -> dict:
103
+ def load(horizon_days: int = HORIZON_DAYS, repo: str = None, include_steered: bool = False) -> dict:
104
104
  # Reading must not create a store: a fresh machine (or forge-ui asking) gets an empty report.
105
105
  if not (dataset_dir() / 'dataset.sqlite').exists():
106
106
  return _empty(horizon_days)
107
107
  db = connect()
108
108
  try:
109
- runs = Runs(Store(db))
109
+ runs = Runs(Store(db), include_steered=include_steered)
110
110
  finally:
111
111
  db.close()
112
112
  return report(runs, horizon_days=horizon_days, repo=repo)
@@ -120,7 +120,8 @@ def main(args) -> int:
120
120
  if args.horizon_days < 1:
121
121
  print('forge dataset reviewers: --horizon-days must be at least 1', file=sys.stderr)
122
122
  return 2
123
- rep = load(args.horizon_days, os.path.realpath(args.repo) if args.repo else None)
123
+ rep = load(args.horizon_days, os.path.realpath(args.repo) if args.repo else None,
124
+ include_steered=getattr(args, 'include_steered', False))
124
125
  if args.json:
125
126
  print(json.dumps(rep, indent=2, sort_keys=True))
126
127
  return 0
@@ -3,10 +3,10 @@
3
3
  Two tables, kept apart because they answer different questions:
4
4
 
5
5
  - **Observational**: every task's first attempt, by declared tier and the model and effort
6
- that ran it (resolved, so `sol` and `gpt-6.1-sol:medium:codex` are one row). First-pass rate
6
+ that ran it (resolved, so `sol` and `gpt-6.2-sol:medium:codex` are one row). First-pass rate
7
7
  (Wilson 95%), the share that passed review at some attempt (or that a human accepted),
8
8
  unfinished tasks, attempts per task and the implementer's runtime. Routing chose who ran what, so a model sent the hard tasks looks
9
- worse here than it is. Fractal runs are left out: their dispatches have their own identities
9
+ worse here than it is. Runs made with Fractal (removed in forge 0.23) are left out: their dispatches have their own identities
10
10
  and their runtime would be missing.
11
11
  - **Randomized**: the `plan --explore` draws (forge-route.py), one row per (tier, default,
12
12
  alternative) pair, since round-robin pools make the pair differ between rows and a spec has
@@ -93,6 +93,9 @@ def tasks(runs: Runs, *, repo=None, since=None) -> list:
93
93
  rows[tid] = row
94
94
  decisions[tid].extend(row.get('route') or [])
95
95
  for tid, row in rows.items():
96
+ # A steered task (#134) is left out whole: its later attempts and its outcome carry a person's nudge.
97
+ if (run, tid) in runs.steered and not runs.include_steered:
98
+ continue
96
99
  events = runs.attempts.get((run, tid), [])
97
100
  attempts = _attempts(runs, run, tid, events)
98
101
  first = attempts[0] if attempts else None
@@ -241,7 +244,7 @@ def _pct(x):
241
244
  def main(args) -> int:
242
245
  db = connect()
243
246
  try:
244
- runs = Runs(Store(db))
247
+ runs = Runs(Store(db), include_steered=getattr(args, 'include_steered', False))
245
248
  finally:
246
249
  db.close()
247
250
  repo = os.path.realpath(args.repo) if args.repo else None
@@ -5,7 +5,7 @@ very differently. This report looks inside each tier with only what the dataset
5
5
  nothing in a run.
6
6
 
7
7
  Population: the tasks `forge dataset routing` counts, whose first attempt says something about the
8
- implementer (fractal runs left out). Each task is described by:
8
+ implementer (old Fractal runs left out). Each task is described by:
9
9
 
10
10
  plan time known before dispatch, so a rule could route on it: declared files, dependencies, wave,
11
11
  the size of the task's prompt (KB)
@@ -18,7 +18,7 @@ File schema, the same at both levels (unknown keys are kept and ignored):
18
18
  "profiles": {"<name>": {
19
19
  "routing": {"dwarf": {"any"|"low"|"medium"|"high": [spec, ...]},
20
20
  "qa": {"any"|"low"|"medium"|"high": [spec, ...]},
21
- "planner": spec, "fractal_planner": spec, "final_reviewer": spec,
21
+ "planner": spec, "final_reviewer": spec,
22
22
  "escalate_after": int >= 0, "escalate_effort": bool},
23
23
  "policy": {"qa_threshold": "P0"|"P1"|"P2"|"P3"|"none", "retry_failed": int >= 0,
24
24
  "infra_retries": int >= 0, "verify_retries": int >= 0, "timeout": int >= 0,
@@ -119,15 +119,20 @@ def _add(path: Path, tokens: int, usd: float) -> None:
119
119
  path.parent.mkdir(parents=True, exist_ok=True)
120
120
  with open(f'{path}.lock', 'a') as lock:
121
121
  fcntl.flock(lock, fcntl.LOCK_EX)
122
- total = _read(path)
123
- total['tokens'] += tokens
124
- total['usd'] = _sum_usd(total['usd'], usd)
125
- tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
126
122
  try:
127
- tmp.write_text(json.dumps(total))
128
- os.replace(tmp, path)
123
+ total = _read(path)
124
+ total['tokens'] += tokens
125
+ total['usd'] = _sum_usd(total['usd'], usd)
126
+ tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
127
+ try:
128
+ tmp.write_text(json.dumps(total))
129
+ os.replace(tmp, path)
130
+ finally:
131
+ tmp.unlink(missing_ok=True)
129
132
  finally:
130
- tmp.unlink(missing_ok=True)
133
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases
134
+ # can leave another thread of this process waiting on it for ever.
135
+ fcntl.flock(lock, fcntl.LOCK_UN)
131
136
  except Exception: # fail-open: a charge that cannot be recorded is dropped
132
137
  pass
133
138