@giamme/forge 0.14.1 → 0.16.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 (81) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -1
  5. package/docs/commands.md +302 -9
  6. package/docs/forge-ui.md +14 -0
  7. package/docs/memory.md +22 -0
  8. package/docs/models.md +53 -0
  9. package/docs/reviews.md +7 -0
  10. package/forge +11 -0
  11. package/package.json +1 -1
  12. package/references/dataset.md +16 -4
  13. package/references/decompose.md +154 -9
  14. package/references/harnesses.md +21 -1
  15. package/references/planning.md +59 -0
  16. package/references/solo.md +5 -1
  17. package/references/ui.md +48 -1
  18. package/scripts/forge-artifact.sh +53 -0
  19. package/scripts/forge-compare.py +6 -3
  20. package/scripts/forge-config.py +531 -4
  21. package/scripts/forge-contract.py +55 -8
  22. package/scripts/forge-control.py +0 -2
  23. package/scripts/forge-dispatch.sh +84 -14
  24. package/scripts/forge-fail-first.py +3 -1
  25. package/scripts/forge-guard.py +247 -8
  26. package/scripts/forge-issues.py +12 -0
  27. package/scripts/forge-lib-adopt.sh +260 -0
  28. package/scripts/forge-lib-attribute.sh +10 -2
  29. package/scripts/forge-lib-plans.sh +35 -6
  30. package/scripts/forge-lib-review.sh +13 -5
  31. package/scripts/forge-lib-task.sh +138 -5
  32. package/scripts/forge-memory.sh +41 -4
  33. package/scripts/forge-metrics.sh +7 -0
  34. package/scripts/forge-parallel-options.sh +12 -6
  35. package/scripts/forge-parallel.sh +659 -32
  36. package/scripts/forge-plan-check.py +591 -8
  37. package/scripts/forge-planner.py +480 -0
  38. package/scripts/forge-route.py +16 -2
  39. package/scripts/forge-runs-rm.py +23 -7
  40. package/scripts/forge-runtime.py +111 -2
  41. package/scripts/forge-schedule.py +5 -2
  42. package/scripts/forge-shadow.py +53 -7
  43. package/scripts/forge-solo.sh +87 -7
  44. package/scripts/forge_dataset/cli.py +26 -0
  45. package/scripts/forge_dataset/efforts.py +215 -0
  46. package/scripts/forge_dataset/export.py +1 -0
  47. package/scripts/forge_dataset/harvest.py +55 -0
  48. package/scripts/forge_dataset/history.py +126 -0
  49. package/scripts/forge_dataset/worktrees.py +95 -0
  50. package/scripts/forge_decide/__init__.py +19 -1
  51. package/scripts/forge_decide/builtin_profiles.json +25 -0
  52. package/scripts/forge_decide/cli.py +12 -0
  53. package/scripts/forge_decide/profiles.py +866 -0
  54. package/scripts/forge_decide/resolve.py +38 -6
  55. package/scripts/forge_memory_list.py +153 -0
  56. package/scripts/forge_worktrees.py +88 -0
  57. package/ui/README.md +31 -0
  58. package/ui/docs/api.md +168 -12
  59. package/ui/forge_ui/__init__.py +14 -1
  60. package/ui/forge_ui/__main__.py +1 -1
  61. package/ui/forge_ui/control.py +250 -12
  62. package/ui/forge_ui/executions.py +28 -8
  63. package/ui/forge_ui/findings.py +7 -0
  64. package/ui/forge_ui/models.py +60 -1
  65. package/ui/forge_ui/projects.py +571 -0
  66. package/ui/forge_ui/reader.py +48 -8
  67. package/ui/forge_ui/static/app.js +99 -21
  68. package/ui/forge_ui/static/cloudui.js +6 -2
  69. package/ui/forge_ui/static/convo.js +1 -1
  70. package/ui/forge_ui/static/diffview.js +2 -2
  71. package/ui/forge_ui/static/files.js +1 -1
  72. package/ui/forge_ui/static/index.html +5 -1
  73. package/ui/forge_ui/static/leaderboard.js +5 -1
  74. package/ui/forge_ui/static/modelstats.js +25 -1
  75. package/ui/forge_ui/static/panel.js +47 -4
  76. package/ui/forge_ui/static/projectsview.js +372 -0
  77. package/ui/forge_ui/static/settings.js +924 -29
  78. package/ui/forge_ui/static/style.css +116 -3
  79. package/ui/forge_ui/static/uikit.js +94 -1
  80. package/ui/forge_ui/static/worktreesview.js +250 -0
  81. package/ui/forge_ui/worktrees.py +570 -0
@@ -1,10 +1,11 @@
1
1
  """The write path: routes that call the forge CLI, the one way forge-ui changes anything.
2
2
 
3
3
  The server never writes a run dir, a repo or forge's config itself. A write is one call of
4
- `<forge root>/forge ...` with an argv list, no shell and no stdin, in its own process group, under
5
- a per-run lock; this module holds the route table, the body validation, the call and the mapping
6
- of the CLI's exit code to an HTTP answer. server.py does the authentication and hands each
7
- authenticated POST to `dispatch`.
4
+ `<forge root>/forge ...` with an argv list and no shell, in its own process group, under a lock;
5
+ this module holds the route table, the body validation, the call and the mapping of the CLI's
6
+ exit code to an HTTP answer. server.py does the authentication and hands each authenticated POST
7
+ to `dispatch`. Profile create and edit are the one call that writes a JSON body to the CLI's
8
+ stdin (`--file -`); every other call has no stdin.
8
9
  """
9
10
  from __future__ import annotations
10
11
 
@@ -30,6 +31,12 @@ MAX_LABEL = 50
30
31
  MAX_REASON = 500
31
32
  MAX_CONFIG_VALUE = 4096
32
33
  MAX_DECIDE_VALUE = 256
34
+ # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
35
+ # at 64 KiB by the server; this caps the stdin text itself, which a re-encode can make larger.
36
+ MAX_PROFILE_BODY = 64 * 1024
37
+ _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
38
+ _PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
39
+ _PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
33
40
  FP_RE = re.compile(r'[0-9a-f]{12}')
34
41
  # Mirrored from forge_decide.GATES and MODES. The ui tests do not put scripts/ on the path, so this
35
42
  # module does not import forge_decide; ConfigTests.test_decide_names_match_forge_decide keeps them equal.
@@ -120,21 +127,24 @@ def _signal_group(pgid, sig):
120
127
  pass # already gone
121
128
 
122
129
 
123
- def run_cli(argv, timeout):
130
+ def run_cli(argv, timeout, stdin=None):
124
131
  """Run argv (a list: never a shell) in its own process group and return a CliResult.
125
132
 
126
133
  On timeout the whole group gets SIGTERM, then SIGKILL after TERM_WAIT_S, and the leader is
127
134
  reaped before this returns, so a caller that holds a lock can release it knowing nothing of
128
- the call is still running. The CLI's environment is the server's plus `cli_env`.
135
+ the call is still running. The CLI's environment is the server's plus `cli_env`. `stdin` is
136
+ bytes written to the process and then closed, or None. Only a profile create or edit passes
137
+ any, and only after its size was checked; every other call keeps stdin closed.
129
138
  """
130
139
  env = dict(os.environ, **cli_env) if cli_env else None
131
140
  try:
132
- proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
141
+ proc = subprocess.Popen(argv, stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
142
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
133
143
  start_new_session=True, close_fds=True, env=env)
134
144
  except OSError as exc:
135
145
  return CliResult(error=f'cannot run the forge CLI: {exc.strerror or exc}')
136
146
  try:
137
- out, err = proc.communicate(timeout=timeout)
147
+ out, err = proc.communicate(input=stdin, timeout=timeout)
138
148
  except subprocess.TimeoutExpired:
139
149
  pgid = proc.pid # start_new_session made it the leader of a group of its own
140
150
  _signal_group(pgid, signal.SIGTERM)
@@ -144,7 +154,7 @@ def run_cli(argv, timeout):
144
154
  # Children that outlive the leader (or ignore SIGTERM) die here; the leader is reaped by wait().
145
155
  _signal_group(pgid, signal.SIGKILL)
146
156
  proc.wait()
147
- for pipe in (proc.stdout, proc.stderr):
157
+ for pipe in (proc.stdin, proc.stdout, proc.stderr):
148
158
  if pipe:
149
159
  pipe.close()
150
160
  return CliResult(timed_out=True)
@@ -258,11 +268,12 @@ class Context:
258
268
  found = self.server.catalog.locate(self.key)
259
269
  return found[0] if found and found[1] in kinds else None
260
270
 
261
- def call(self, *args, limit=None):
271
+ def call(self, *args, limit=None, stdin=None):
262
272
  """One CLI call, mapped to (status, body); the run's lock is the caller's to hold.
263
273
 
264
- `limit` is the route's timeout; a timeout given to `dispatch` (a test's) replaces it."""
265
- return map_exit(run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S))
274
+ `limit` is the route's timeout; a timeout given to `dispatch` (a test's) replaces it.
275
+ `stdin` is bytes for the one profile write that uses `--file -`, or None."""
276
+ return map_exit(run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin))
266
277
 
267
278
  def locked(self, work):
268
279
  """work() under the run's lock; 409 busy when another write to this run is in flight."""
@@ -612,6 +623,154 @@ def _config_set(ctx):
612
623
  lock.release()
613
624
 
614
625
 
626
+ def _profile_name(value, label='name'):
627
+ if not isinstance(value, str) or not _PROFILE_NAME.fullmatch(value):
628
+ raise BadBody('%s must be 1-64 letters, digits, ".", "_" or "-", starting with a letter or digit' % label)
629
+ return value
630
+
631
+
632
+ def _profile_key(value):
633
+ if not isinstance(value, str) or not _PROFILE_KEY.fullmatch(value):
634
+ raise BadBody('key must be a routing.* or policy.* name')
635
+ return value
636
+
637
+
638
+ def _profile_value(value):
639
+ # On the CLI's argv, so a leading "-" would be another option. Newline and tab count as
640
+ # control characters here: a profile value is one token, unlike a repo.verify script.
641
+ if not isinstance(value, str) or value.startswith('-') or not _no_control_chars(value):
642
+ raise BadBody('value must be a string with no control characters and not start with "-"')
643
+ return value
644
+
645
+
646
+ def _profile_stdin(value):
647
+ """The bytes `--file -` reads. A re-encode can be larger than the HTTP body, so it is capped on its own."""
648
+ if not isinstance(value, dict):
649
+ raise BadBody('body must be a JSON object')
650
+ try:
651
+ raw = json.dumps(value, allow_nan=False).encode('utf-8')
652
+ except (TypeError, ValueError, RecursionError):
653
+ raise BadBody('body must be a JSON object')
654
+ if len(raw) > MAX_PROFILE_BODY:
655
+ raise BadBody('body is larger than 64 KiB')
656
+ return raw
657
+
658
+
659
+ def validate_profile(body):
660
+ """(level, argv, stdin) for one profile write. BadBody before the CLI runs.
661
+
662
+ argv is the forge arguments through the action, not yet `--repo` or `--json`. stdin is the
663
+ profile object for `--file -`, or None. The CLI still checks that a key is a real profile
664
+ key and that the body validates.
665
+ """
666
+ action = body.get('action')
667
+ if action not in _PROFILE_ACTIONS:
668
+ raise BadBody('action must be one of ' + ', '.join(_PROFILE_ACTIONS))
669
+ level = body.get('level')
670
+ if level not in ('user', 'repo'):
671
+ raise BadBody("level must be 'user' or 'repo'")
672
+ if action == 'create':
673
+ _check_fields(body, ('run', 'action', 'name', 'level', 'from', 'body'))
674
+ name = _profile_name(body.get('name'))
675
+ has_from, has_body = 'from' in body, 'body' in body
676
+ if has_from == has_body:
677
+ raise BadBody('create takes from or body, not both')
678
+ if has_from:
679
+ return level, ['config', 'profile', 'create', name, '--from', _profile_name(body['from'], 'from')], None
680
+ return level, ['config', 'profile', 'create', name, '--file', '-'], _profile_stdin(body['body'])
681
+ if action == 'edit':
682
+ _check_fields(body, ('run', 'action', 'name', 'level', 'body'))
683
+ if 'body' not in body:
684
+ raise BadBody('edit takes a body')
685
+ return level, ['config', 'profile', 'edit', _profile_name(body.get('name')), '--file', '-'], _profile_stdin(body['body'])
686
+ if action == 'set':
687
+ _check_fields(body, ('run', 'action', 'name', 'level', 'key', 'value'))
688
+ if 'key' not in body or 'value' not in body:
689
+ raise BadBody('set takes a key and a value')
690
+ return level, ['config', 'profile', 'set', _profile_name(body.get('name')),
691
+ _profile_key(body.get('key')), _profile_value(body.get('value'))], None
692
+ if action == 'unset':
693
+ _check_fields(body, ('run', 'action', 'name', 'level', 'key'))
694
+ if 'key' not in body:
695
+ raise BadBody('unset takes a key')
696
+ return level, ['config', 'profile', 'unset', _profile_name(body.get('name')), _profile_key(body.get('key'))], None
697
+ if action == 'rm':
698
+ _check_fields(body, ('run', 'action', 'name', 'level'))
699
+ return level, ['config', 'profile', 'rm', _profile_name(body.get('name'))], None
700
+ _check_fields(body, ('run', 'action', 'name', 'level', 'none'))
701
+ if 'none' in body and body['none'] is not True:
702
+ raise BadBody('none must be true')
703
+ if body.get('none') is True:
704
+ if 'name' in body:
705
+ raise BadBody('use takes a name or none, not both')
706
+ return level, ['config', 'profile', 'use', '--none'], None
707
+ if 'name' not in body:
708
+ raise BadBody('use takes a name or none: true')
709
+ return level, ['config', 'profile', 'use', _profile_name(body.get('name'))], None
710
+
711
+
712
+ def _profiles_with_bodies(ctx, repo):
713
+ """The list object, each row carrying the body `show` prints for it."""
714
+ status, obj = ctx.call('config', 'profile', 'list', '--json', '--repo', repo)
715
+ if status != 200:
716
+ return status, obj
717
+ rows = obj.get('profiles')
718
+ if not isinstance(rows, list):
719
+ return 502, {'error': 'bad gateway', 'detail': 'the forge CLI printed no profile list'}
720
+ for row in rows:
721
+ if not isinstance(row, dict):
722
+ return 502, {'error': 'bad gateway', 'detail': 'the forge CLI printed a profile row that is not an object'}
723
+ name = row.get('name')
724
+ if not isinstance(name, str) or not _PROFILE_NAME.fullmatch(name):
725
+ return 502, {'error': 'bad gateway', 'detail': 'the forge CLI printed a profile name that is not usable'}
726
+ show_status, shown = ctx.call('config', 'profile', 'show', name, '--json', '--repo', repo)
727
+ if show_status != 200:
728
+ return show_status, shown
729
+ if not isinstance(shown, dict) or 'body' not in shown:
730
+ return 502, {'error': 'bad gateway', 'detail': 'the forge CLI printed no profile body'}
731
+ row['body'] = shown['body']
732
+ return 200, obj
733
+
734
+
735
+ def _config_profiles_get(ctx):
736
+ ctx.route = 'profiles'
737
+ _name_run(ctx, urllib.parse.parse_qs(ctx.query[:2000]).get('run', [None])[0])
738
+ try:
739
+ params = _query_params(ctx.query, ('run',))
740
+ except BadBody as exc:
741
+ return _invalid(str(exc))
742
+ repo, error = _config_run(ctx, params.get('run'))
743
+ if error:
744
+ return error
745
+ return _profiles_with_bodies(ctx, repo)
746
+
747
+
748
+ def _config_profiles_set(ctx):
749
+ raw = ctx.body if isinstance(ctx.body, dict) else None
750
+ ctx.route = 'profiles'
751
+ _name_run(ctx, raw.get('run') if raw else None)
752
+ try:
753
+ if raw is None:
754
+ raise BadBody('body must be a JSON object')
755
+ level, argv, stdin = validate_profile(raw)
756
+ except BadBody as exc:
757
+ return _invalid(str(exc))
758
+ repo, error = _config_run(ctx, raw.get('run'))
759
+ if error:
760
+ return error
761
+ # User level is the user file: no --repo. Repo level writes <root>/.forge/decide.json.
762
+ if level == 'repo':
763
+ argv += ['--repo', repo]
764
+ argv.append('--json')
765
+ lock = _server_lock(ctx.server, 'config_lock')
766
+ if not lock.acquire(blocking=False):
767
+ return 409, {'error': 'busy'}
768
+ try:
769
+ return ctx.call(*argv, stdin=stdin)
770
+ finally:
771
+ lock.release()
772
+
773
+
615
774
  # (method, path pattern, handler(ctx) -> (status, body)); group 1 of the pattern is the run key
616
775
  # (the config routes name it in the query or body instead). New routes are added here.
617
776
  def _reviewer_outcomes(ctx):
@@ -625,6 +784,78 @@ def _reviewer_outcomes(ctx):
625
784
  return ctx.call('dataset', 'reviewers', '--json')
626
785
 
627
786
 
787
+ def _project_call(ctx, *args):
788
+ status, body = ctx.call(*args)
789
+ return body if status == 200 else None
790
+
791
+
792
+ def _projects(ctx):
793
+ # The Projects screen (#126): forge_ui/projects.py, which reads run dirs here and the rest through the CLI.
794
+ from forge_ui import projects
795
+ ctx.route = 'projects'
796
+ try:
797
+ _query_params(ctx.query, ())
798
+ except BadBody as exc:
799
+ return _invalid(str(exc))
800
+ return 200, projects.screen(ctx.server).listing(ctx.server.catalog)
801
+
802
+
803
+ def _project(ctx):
804
+ from forge_ui import projects
805
+ ctx.route = 'project'
806
+ try:
807
+ _query_params(ctx.query, ())
808
+ except BadBody as exc:
809
+ return _invalid(str(exc))
810
+ found = projects.screen(ctx.server).detail(ctx.server.catalog, ctx.key)
811
+ return (404, {'error': 'not found'}) if found is None else (200, found)
812
+
813
+
814
+ def _project_findings(ctx):
815
+ from forge_ui import projects
816
+ ctx.route = 'project findings'
817
+ try:
818
+ refresh = _bit(_query_params(ctx.query, ('refresh',)), 'refresh')
819
+ except BadBody as exc:
820
+ return _invalid(str(exc))
821
+ # --offline: no gh call; the listing says which findings are dismissed, filed (as recorded) or swept.
822
+ found = projects.screen(ctx.server).findings(
823
+ ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'),
824
+ lambda path: _project_call(ctx, 'issues', path, '--json', '--offline', '--all-runs', '--include-plausible',
825
+ '--include-dismissed'), refresh=refresh)
826
+ return (404, {'error': 'not found'}) if found is None else (200, found)
827
+
828
+
829
+ def _project_memories(ctx):
830
+ from forge_ui import projects
831
+ ctx.route = 'project memories'
832
+ try:
833
+ refresh = _bit(_query_params(ctx.query, ('refresh',)), 'refresh')
834
+ except BadBody as exc:
835
+ return _invalid(str(exc))
836
+ found = projects.screen(ctx.server).memories(
837
+ ctx.server.catalog, ctx.key, lambda path: _project_call(ctx, 'memory', 'learnings', path, '--json'),
838
+ lambda: _project_call(ctx, 'dataset', 'history', '--json'), refresh=refresh)
839
+ return (404, {'error': 'not found'}) if found is None else (200, found)
840
+
841
+
842
+ def _worktrees(ctx):
843
+ # The Worktrees screen (#125): git and the run dirs, read here, plus the history `forge dataset worktrees`
844
+ # keeps, read through the CLI. Cached per server (worktrees.CACHE_S); ?refresh=1 reads everything again.
845
+ from forge_ui import worktrees
846
+ ctx.route = 'worktrees'
847
+ try:
848
+ params = _query_params(ctx.query, ('refresh',))
849
+ refresh = _bit(params, 'refresh')
850
+ except BadBody as exc:
851
+ return _invalid(str(exc))
852
+
853
+ def history():
854
+ status, body = ctx.call('dataset', 'worktrees', '--json')
855
+ return body if status == 200 else None
856
+ return 200, worktrees.screen(ctx.server).answer(ctx.server.catalog, history, refresh=refresh)
857
+
858
+
628
859
  ROUTES = [
629
860
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
630
861
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
@@ -632,9 +863,16 @@ ROUTES = [
632
863
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_file),
633
864
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues/dismiss'), _issues_dismiss),
634
865
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/delete'), _delete),
866
+ ('GET', re.compile(r'/api/config/profiles()'), _config_profiles_get),
867
+ ('POST', re.compile(r'/api/config/profiles()'), _config_profiles_set),
635
868
  ('GET', re.compile(r'/api/config()'), _config_get),
636
869
  ('POST', re.compile(r'/api/config()'), _config_set),
637
870
  ('GET', re.compile(r'/api/models/reviewers()'), _reviewer_outcomes),
871
+ ('GET', re.compile(r'/api/worktrees()'), _worktrees),
872
+ ('GET', re.compile(r'/api/projects()'), _projects),
873
+ ('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
874
+ ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
875
+ ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/memories'), _project_memories),
638
876
  ]
639
877
 
640
878
 
@@ -55,8 +55,12 @@ _CACHE = _SigCache()
55
55
 
56
56
 
57
57
  class Execution(dict):
58
- """An Execution as the API returns it. `dataset` and `rel` (its dir) stay out of the JSON."""
59
- __slots__ = ('dataset', 'rel')
58
+ """An Execution as the API returns it. `dataset`, `rel` (its dir) and `tier` stay out of the JSON.
59
+
60
+ `tier` is the service-tier triple already parsed from metrics.json, kept for a running
61
+ execution whose `.resolved` still lives only in the owner dir.
62
+ """
63
+ __slots__ = ('dataset', 'rel', 'tier')
60
64
 
61
65
 
62
66
  def inside(root, path) -> bool:
@@ -136,14 +140,27 @@ def spec_of(resolved):
136
140
  return alias
137
141
 
138
142
 
139
- def _model(resolved):
143
+ def _plain(value):
144
+ """A non-empty string, or None. Tier fields are stored that way, and JSON null is absent."""
145
+ if isinstance(value, str):
146
+ value = value.strip()
147
+ return value or None
148
+ return None
149
+
150
+
151
+ def _model(resolved, metrics=None):
140
152
  if not resolved or not resolved.get('alias'):
141
153
  return None
142
154
  effort = resolved.get('effort') or None
155
+ metrics = metrics or {}
156
+ # metrics.json is what finish() recorded. While a dispatch is still running, or on a
157
+ # run from before that record, the asked tier is the resolved line and the speed is unknown.
143
158
  return dict(spec=spec_of(resolved), alias=resolved['alias'], harness=resolved.get('harness') or None,
144
159
  model=resolved.get('model') or None,
145
160
  effort=None if effort == '<harness default>' else effort,
146
- clamped=resolved.get('clamped') or None)
161
+ clamped=resolved.get('clamped') or None,
162
+ service_tier=_plain(metrics.get('service_tier')) or _plain(resolved.get('service_tier')),
163
+ speed=_plain(metrics.get('speed')), speed_reason=_plain(metrics.get('speed_reason')))
147
164
 
148
165
 
149
166
  def _finite(value):
@@ -201,7 +218,9 @@ def _metrics(reader, name, text):
201
218
  phase_started=_finite(wall + (mark - mono)) if None not in (wall, mark, mono) else None,
202
219
  phases=phases, exit_code=exit_code, infra_class=infra if isinstance(infra, str) and infra else None,
203
220
  tokens=tokens if any(value is not None for value in tokens.values()) else None,
204
- prompt_bytes=number('prompt_bytes', obj.get('prompt_bytes'), (int,)), shadow=obj.get('shadow') is True)
221
+ prompt_bytes=number('prompt_bytes', obj.get('prompt_bytes'), (int,)), shadow=obj.get('shadow') is True,
222
+ service_tier=_plain(obj.get('service_tier')), speed=_plain(obj.get('speed')),
223
+ speed_reason=_plain(obj.get('speed_reason')))
205
224
 
206
225
 
207
226
  def _dataset(reader, name, text):
@@ -283,7 +302,7 @@ def scan(reader, rel_dir, owner_live, roles=None):
283
302
  for item in result:
284
303
  if item['role'] in _MODEL_ROLES and item['state'] == 'running' and item['model'] is None:
285
304
  live = parse_resolved(reader.text(posixpath.join(owner, item['role'] + '.resolved')))
286
- item['model'] = _model(live)
305
+ item['model'] = _model(live, item.tier)
287
306
  if item['role'] == 'qa' and item['state'] == 'done':
288
307
  item['verdict'], item['findings'] = qa_result(reader, item.rel + '/qa.last')
289
308
  return result
@@ -293,9 +312,10 @@ def _build(reader, rel, name, role):
293
312
  metrics_name, dataset_name = rel + '/metrics.json', rel + '/dataset.json'
294
313
  metrics = _cached(reader, metrics_name, 'metrics', lambda text: _metrics(reader, metrics_name, text)) or {}
295
314
  dataset = _cached(reader, dataset_name, 'dataset', lambda text: _dataset(reader, dataset_name, text))
315
+ tier = {key: metrics.get(key) for key in ('service_tier', 'speed', 'speed_reason')}
296
316
  model = timed_out = None
297
317
  if role in _MODEL_ROLES:
298
- model = _model(resolved_of(reader, f'{rel}/{role}.resolved'))
318
+ model = _model(resolved_of(reader, f'{rel}/{role}.resolved'), tier)
299
319
  timed_out = reader.exists(f'{rel}/{role}.timedout')
300
320
  item = Execution(id=name, role=role, parent=None, attempt=None, shadow=bool(metrics.get('shadow')),
301
321
  state=None, started=metrics.get('started'), ended=metrics.get('ended'),
@@ -305,7 +325,7 @@ def _build(reader, rel, name, role):
305
325
  timed_out=bool(timed_out), model=model,
306
326
  tokens=dict(metrics['tokens']) if metrics.get('tokens') else None,
307
327
  prompt_bytes=metrics.get('prompt_bytes'), verdict=None, findings=None)
308
- item.dataset, item.rel = dataset, rel
328
+ item.dataset, item.rel, item.tier = dataset, rel, tier
309
329
  return item
310
330
 
311
331
 
@@ -116,6 +116,13 @@ def listing(text, limit=200):
116
116
  return result
117
117
 
118
118
 
119
+ def tests(text):
120
+ """What the reply says about its tests (forge-contract.py's tests_report), or None."""
121
+ module = _load()
122
+ report = getattr(module, 'tests_report', None)
123
+ return report(text[:_MAX_CHARS]) if report and text else None
124
+
125
+
119
126
  def parse_gate(text):
120
127
  """A qa.gate line: threshold, decision, worst, n_confirmed, n_unlabelled, n_below; None if malformed."""
121
128
  line = next((item for item in (text or '').splitlines() if item.strip()), None)
@@ -10,6 +10,7 @@ from collections import OrderedDict
10
10
  import json
11
11
  import math
12
12
  import os
13
+ from pathlib import Path
13
14
  import threading
14
15
  import time
15
16
 
@@ -21,14 +22,72 @@ _MAX_WARNINGS = 500
21
22
  _RUNNING_S = 120
22
23
  _SIZE = 4096
23
24
  _PASS = ('PASS', 'MERGED')
25
+ _TIERS = ('low', 'medium', 'high')
24
26
  _LOCK = threading.Lock()
25
27
  _RUNS = OrderedDict() # realpath -> (signature, computed at, facts)
28
+ # realpath -> the balanced profile's recommendation, or None when that file could not be read.
29
+ # Kept for the process, including a failure: the next server picks up an edited file, not this one.
30
+ _RECOMMENDED = {}
31
+ _REC_LOCK = threading.Lock()
26
32
 
27
33
 
28
34
  def _alias(spec):
29
35
  return (spec.split(':', 1)[0] or None) if isinstance(spec, str) else None
30
36
 
31
37
 
38
+ def _builtin_profiles_path():
39
+ """scripts/forge_decide/builtin_profiles.json, located from this package the way reader._forge_infra finds
40
+ scripts/forge_infra.py. Read as data: forge-ui never imports forge_decide."""
41
+ return Path(__file__).resolve().parents[2] / 'scripts' / 'forge_decide' / 'builtin_profiles.json'
42
+
43
+
44
+ def _first_spec(pool):
45
+ """The first spec of a tier's routing pool, or None when the pool does not start with one."""
46
+ if isinstance(pool, list) and pool and isinstance(pool[0], str) and pool[0]:
47
+ return pool[0]
48
+ return None
49
+
50
+
51
+ def _recommended_from(data):
52
+ """balanced's dwarf per tier: the first spec of each routing.dwarf pool. None when that profile is not there."""
53
+ profiles = data.get('profiles') if isinstance(data, dict) else None
54
+ body = profiles.get('balanced') if isinstance(profiles, dict) else None
55
+ routing = body.get('routing') if isinstance(body, dict) else None
56
+ pools = routing.get('dwarf') if isinstance(routing, dict) else None
57
+ if not isinstance(pools, dict):
58
+ return None
59
+ dwarf = {}
60
+ for tier in _TIERS:
61
+ spec = _first_spec(pools.get(tier))
62
+ if spec:
63
+ dwarf[tier] = spec
64
+ if not dwarf:
65
+ return None
66
+ source = body.get('source')
67
+ return dict(profile='balanced', source=source if isinstance(source, str) else '', dwarf=dwarf)
68
+
69
+
70
+ def _load_recommended(path):
71
+ try:
72
+ data = json.loads(Path(path).read_text(encoding='utf-8'))
73
+ except (OSError, ValueError, RecursionError):
74
+ return None
75
+ return _recommended_from(data)
76
+
77
+
78
+ def recommended():
79
+ """The balanced built-in profile's dwarf per tier, or None when its file cannot be read. Cached per process."""
80
+ path = _builtin_profiles_path()
81
+ try:
82
+ key = os.path.realpath(path)
83
+ except OSError:
84
+ key = os.fspath(path)
85
+ with _REC_LOCK:
86
+ if key not in _RECOMMENDED:
87
+ _RECOMMENDED[key] = _load_recommended(path)
88
+ return _RECOMMENDED[key]
89
+
90
+
32
91
  def _attempt_rows(rd, name):
33
92
  """{n: (status, dwarf spec)} from attempts.tsv, oldest first. Infra-refunded rows spent no
34
93
  attempt; a QA-only resume reuses its number, so the number's last row holds its status."""
@@ -214,4 +273,4 @@ def collect(found):
214
273
  warnings += facts['warnings']
215
274
  count += 1
216
275
  return dict(generated=now, runs=count, truncated=truncated, tasks=tasks, reviews=reviews,
217
- warnings=warnings[:_MAX_WARNINGS])
276
+ warnings=warnings[:_MAX_WARNINGS], recommended=recommended())