@giamme/forge 0.14.0 → 0.15.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 (44) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +2 -1
  5. package/docs/commands.md +301 -7
  6. package/docs/models.md +53 -0
  7. package/package.json +1 -1
  8. package/references/dataset.md +12 -3
  9. package/references/decompose.md +108 -7
  10. package/references/harnesses.md +21 -1
  11. package/references/planning.md +59 -0
  12. package/references/ui.md +39 -1
  13. package/scripts/forge-compare.py +6 -3
  14. package/scripts/forge-config.py +531 -4
  15. package/scripts/forge-dispatch.sh +132 -22
  16. package/scripts/forge-lib-plans.sh +19 -2
  17. package/scripts/forge-lib-review.sh +5 -3
  18. package/scripts/forge-lib-task.sh +119 -0
  19. package/scripts/forge-parallel-options.sh +12 -6
  20. package/scripts/forge-parallel.sh +572 -26
  21. package/scripts/forge-plan-check.py +591 -8
  22. package/scripts/forge-planner.py +480 -0
  23. package/scripts/forge-route.py +72 -23
  24. package/scripts/forge-runtime.py +157 -1
  25. package/scripts/forge-shadow.py +51 -7
  26. package/scripts/forge-solo.sh +81 -7
  27. package/scripts/forge_dataset/cli.py +10 -0
  28. package/scripts/forge_dataset/efforts.py +215 -0
  29. package/scripts/forge_dataset/harvest.py +44 -0
  30. package/scripts/forge_decide/__init__.py +19 -1
  31. package/scripts/forge_decide/builtin_profiles.json +25 -0
  32. package/scripts/forge_decide/cli.py +12 -0
  33. package/scripts/forge_decide/profiles.py +866 -0
  34. package/scripts/forge_decide/resolve.py +38 -6
  35. package/ui/docs/api.md +87 -8
  36. package/ui/forge_ui/control.py +173 -12
  37. package/ui/forge_ui/executions.py +28 -8
  38. package/ui/forge_ui/models.py +60 -1
  39. package/ui/forge_ui/reader.py +21 -1
  40. package/ui/forge_ui/static/leaderboard.js +5 -1
  41. package/ui/forge_ui/static/modelstats.js +25 -1
  42. package/ui/forge_ui/static/panel.js +19 -2
  43. package/ui/forge_ui/static/settings.js +788 -25
  44. package/ui/forge_ui/static/style.css +23 -0
@@ -11,9 +11,12 @@ Levels, lowest to highest; each sets a gate's fields only where it names them:
11
11
  forge_jev.enabled(capability) from jev.json and the FORGE_JEV* variables, and
12
12
  turns a gate `on` when its capability is enabled. It never sets `off`, and a
13
13
  gate with no capability (None) is never turned on there.
14
- 4. profile -- `profile`, else FORGE_DECIDE_PROFILE; looked up in the user file's `profiles`
15
- first, then the repo file's. Sets `gates` and `budget` (`budget.daily_*` only
16
- from a user-file profile).
14
+ 4. profile -- FORGE_DECIDE_PROFILE_JSON when set: the {"name", "gates", "budget"} copy frozen
15
+ when the run was planned, applied as `frozen profile NAME` whatever the live
16
+ files say (set but invalid, empty included, or not of that shape: an error, nothing applied). Else `profile`, else
17
+ FORGE_DECIDE_PROFILE; looked up in the user file's `profiles` first, then the
18
+ repo file's, then the built-in profiles (which set no gate and no budget). Sets
19
+ `gates` and `budget` (`budget.daily_*` only from a user-file profile).
17
20
  5. env -- FORGE_DECIDE_GATE_<NAME>=off|shadow|on (NAME upper-cased, `-` -> `_`). Once a
18
21
  user decide.json exists, the legacy FORGE_JEV_<CAP> variables can only restrict:
19
22
  `off` turns that capability's gates off, and any `on` turns off the gates of
@@ -258,6 +261,28 @@ def _shadowed(repo_gates: dict, repo_budget: dict, user_gates: dict, user_budget
258
261
  return out
259
262
 
260
263
 
264
+ def _frozen_profile(result: dict, text: str, errors: list) -> None:
265
+ """Step 4 from FORGE_DECIDE_PROFILE_JSON, {"name", "gates", "budget"}: nothing applied when
266
+ it is not valid JSON of that shape."""
267
+ try:
268
+ data = json.loads(text)
269
+ except (TypeError, ValueError, RecursionError) as exc:
270
+ errors.append(f'FORGE_DECIDE_PROFILE_JSON: not valid JSON ({exc}); ignored')
271
+ return
272
+ name = data.get('name') if isinstance(data, dict) else None
273
+ if not isinstance(name, str) or not name:
274
+ errors.append('FORGE_DECIDE_PROFILE_JSON: not an object with a name; ignored')
275
+ return
276
+ for key in ('gates', 'budget'):
277
+ if data.get(key) is not None and not isinstance(data[key], dict):
278
+ errors.append(f'FORGE_DECIDE_PROFILE_JSON: {key} is not an object; ignored')
279
+ return
280
+ label = f'frozen profile {name}'
281
+ result['profile'] = name
282
+ _apply(result, _parse_gates(data.get('gates'), label, errors),
283
+ _parse_budget(data.get('budget'), label, errors, RUN_BUDGET + DAILY_BUDGET), 'profile')
284
+
285
+
261
286
  def _resolve(repo, profile, env, flags, errors: list, user_data=None, repo_data=None) -> dict:
262
287
  result = _result(errors)
263
288
 
@@ -301,9 +326,12 @@ def _resolve(repo, profile, env, flags, errors: list, user_data=None, repo_data=
301
326
  _legacy(result, env, errors)
302
327
  result['shadowed'] = _shadowed(repo_gates, repo_budget, user_gates, user_budget)
303
328
 
304
- # 4. profile
329
+ # 4. profile: the copy frozen when the run was planned, else looked up by name
330
+ # (set but empty or invalid still counts as set: an error, and the live profile is not used)
305
331
  name = profile if profile is not None else (env.get('FORGE_DECIDE_PROFILE') or None)
306
- if name is not None:
332
+ if 'FORGE_DECIDE_PROFILE_JSON' in env:
333
+ _frozen_profile(result, env['FORGE_DECIDE_PROFILE_JSON'], errors)
334
+ elif name is not None:
307
335
  found = None
308
336
  for data, label, in_user in ((user_data, user_label, True), (repo_data, repo_label, False)):
309
337
  profiles = data.get('profiles')
@@ -311,7 +339,11 @@ def _resolve(repo, profile, env, flags, errors: list, user_data=None, repo_data=
311
339
  found = (profiles[name], f'{label}: profile {name!r}', in_user)
312
340
  break
313
341
  if found is None:
314
- errors.append(f'profile {name!r} not found; ignored')
342
+ from . import profiles as profile_store
343
+ if name in profile_store.builtin_names():
344
+ result['profile'] = name # a built-in profile sets no gate and no budget
345
+ else:
346
+ errors.append(f'profile {name!r} not found; ignored')
315
347
  elif not isinstance(found[0], dict):
316
348
  errors.append(f'{found[1]} is not an object; ignored')
317
349
  else:
package/ui/docs/api.md CHANGED
@@ -52,6 +52,7 @@ written), and the reader must never raise because of one.
52
52
  | `attribution.json` | the result of `forge-parallel.sh attribute`: `culprit` (a task id or `null`), `base_fails`, `inconclusive` (a reason or `null`), `merges`, `steps`, `verification_runs`, `gate` (`null` without the gate, else `{mode, ranking, tried, outcome}`); returned as `attribution`, see RunDetail |
53
53
  | `max_parallel`, `escalate_after`, `verify_retries` | one integer each |
54
54
  | `qa_threshold` | `P0`..`P3`, the least severe finding that still blocks; `final_qa` the final review's QA spec |
55
+ | `profile.json` | the profile the run froze: `name`, `level` (`user`, `repo` or `builtin`), `body` (the profile object), `shadowed` (levels the winning copy hid), `frozen_at` (UTC, `YYYY-MM-DDTHH:MM:SSZ`), `overridden` (the sorted dotted keys a flag of the run replaced, such as `routing.qa.any`; empty when none). RunDetail returns `settings.profile` `{name, level, overridden}`, `null` when the file is absent, unreadable or not that shape |
55
56
  | `deferrals.txt` | one line per task the wave planner deferred |
56
57
  | `integration.base`, `accepted.integration` | one commit each: where the integration branch started, the revision the run accepted |
57
58
  | `attempts/<role>-<uuid>/` | one *execution* (below) of the run itself: `parallel` (a `run`) or `verification` |
@@ -99,7 +100,7 @@ one of `task dwarf qa solo verification parallel` and `<uuid>` 32 lowercase hex
99
100
 
100
101
  | Path | Format |
101
102
  |---|---|
102
- | `metrics.json` | `role`, `started` (monotonic), `wall_started` (epoch), `phase`, `phase_started` (monotonic), `elapsed_s` (seconds per phase, `total` once done), `exit_code` (`null` while in flight), `harness`, `prompt_bytes`, `input_tokens`, `cached_input_tokens`, `output_tokens`, `infra_class`, `shadow` |
103
+ | `metrics.json` | `role`, `started` (monotonic), `wall_started` (epoch), `phase`, `phase_started` (monotonic), `elapsed_s` (seconds per phase, `total` once done), `exit_code` (`null` while in flight), `harness`, `prompt_bytes`, `input_tokens`, `cached_input_tokens`, `output_tokens`, `infra_class`, `shadow`, `service_tier` (the tier asked), `speed` (`fast`, `standard` or `default`), `speed_reason` (why it was not fast) |
103
104
  | `dataset.json` | may be absent: `parent` (the execution that started this one, e.g. `task-<uuid>`), `trigger`, `attempt_start` and `resume` (task executions) |
104
105
  | `<role>.resolved`, `.prompt`, `.last`, `.timedout`, `.log`, `.clock` | copies made when it finished: the model resolution (`key=value`), the prompt, the final message, the timeout marker, the harness log and its clock |
105
106
 
@@ -134,6 +135,7 @@ raise because of one. Older solo dirs have `verdict` and not `status`.
134
135
  | `attempts/<role>-<uuid>/` | the run's executions: `solo`, `dwarf`, `qa` |
135
136
  | `dwarf.input`, `qa.input`, `qa.gate`, `known_issues.md` | as for a plan task |
136
137
  | `dwarf.last`, `qa.last` | the role's final message. `qa.last` carries `FORGE_VERDICT:` the same way a plan task does |
138
+ | `profile.json` | as for a plan: the profile the run froze. `settings.profile` is `{name, level, overridden}`, or `null` when the file is absent, unreadable or not that shape |
137
139
  | `dwarf.log`, `qa.log` | raw logs. The summary stats them and does not read them, so `updated` moves while a model writes |
138
140
  | `changes.diff`, `existing.diff` | the run's change, and the uncommitted changes the repo already had when it started |
139
141
  | `fractal-selection.json` | as for a plan |
@@ -267,6 +269,8 @@ its last 20,000 behind a leading `…`. Their `truncated` lists the field names
267
269
  | `GET /api/models/reviewers` | `200` the `forge dataset reviewers --json` report (how each reviewer's PASSed work held up); no parameters |
268
270
  | `GET /api/config?run=<key>` | `200` the `forge config show --json` of that run's repository root (see Config) |
269
271
  | `POST /api/config` | set or unset one allowed key (`repo.verify`, `repo.setup`, `repo.verify-subset`, `decide.gate.<gate>`, `decide.gate.<gate>.provider`, `decide.gate.<gate>.model`); `jev.enabled` is gone; authenticated |
272
+ | `GET /api/config/profiles?run=<key>` | `200` every profile of that run's repository, each with its level, shadowed levels, default flag and body (see Profiles) |
273
+ | `POST /api/config/profiles` | create, edit, set, unset, remove or select a profile through `forge config profile`; authenticated |
270
274
  | `GET /api/runs/<key>/export?texts=0\|1&paths=0\|1` | `200` the run as one HTML file (see Export), `Content-Disposition: attachment`, `Content-Security-Policy: default-src 'none'; sandbox`; `404` for an unknown run |
271
275
  | `GET /api/runs/<key>/tasks/<id>/fractal` | `200 TaskFractal` |
272
276
  | `GET /api/runs/<key>/tasks/<id>/fractal/nodes/<node>[/diff]` | `200 FractalNodeDetail`, or with `/diff` a `DiffDetail` of its `candidate.diff`; `<node>` matches `[A-Za-z0-9][A-Za-z0-9_-]{0,100}` |
@@ -388,7 +392,8 @@ Every RunSummary field, plus:
388
392
  "request": "the user's request, verbatim",
389
393
  "settings": {"explore": 0.5, "shadow_rate": 0.5, "shadow_qa": ["opus", "sol:xhigh"], "timeout": 3600,
390
394
  "max_parallel": 2, "qa_threshold": "P2", "escalate_after": 3, "verify_retries": 1,
391
- "final_qa": "opus"},
395
+ "final_qa": "opus",
396
+ "profile": {"name": "balanced", "level": "user", "overridden": ["policy.timeout"]}},
392
397
  "attribution": {"culprit": "page", "base_fails": false, "inconclusive": null, "verification_runs": 4,
393
398
  "gate_outcome": "confirmed"},
394
399
  "verification": {"status": "PASS", "command": "python3 -m unittest", "log_tail": "...",
@@ -429,8 +434,11 @@ Every RunSummary field, plus:
429
434
  list (empty when missing). `max_parallel`, `escalate_after`, `verify_retries` are integers,
430
435
  `final_qa` the first line of their file. `qa_threshold` is the effective level (`P0`..`P3`):
431
436
  a missing file reads `P2` (forge's default) with `qa_threshold_source` `default`; a file reads
432
- with source `set`, and `none` in it reads `P3`. A solo run has no plan settings: every value
433
- is `null`, including `shadow_qa`, except `qa_threshold` and its source, which read the same way.
437
+ with source `set`, and `none` in it reads `P3`. `profile` is `{name, level, overridden}` from
438
+ `profile.json`, the profile the run froze, or `null` when that file is missing, unreadable or
439
+ not a frozen profile (`name` and `level` non-empty strings, `overridden` a list of strings). A solo run
440
+ reads `$RUN/profile.json` the same way and has no other plan settings: every other value is
441
+ `null`, including `shadow_qa`, except `qa_threshold` and its source, which read the same way.
434
442
  - `attribution` is the result of `forge-parallel.sh attribute` from `attribution.json`, or `null` when
435
443
  the file is missing. `culprit` is the merged task's id or `null`; `base_fails` is `true` only when the
436
444
  base verified FAIL; `inconclusive` is the reason the search stopped without a culprit, or `null`;
@@ -699,7 +707,7 @@ the detail is `request.md`.
699
707
  "phases": {"preparation": 1.2, "preflight": 0.4, "model": 590.1, "snapshot": 3.3, "verification": 0.0},
700
708
  "exit_code": 0, "infra_class": null, "timed_out": false,
701
709
  "model": {"spec": "sol:xhigh", "alias": "sol", "harness": "codex", "model": "gpt-sol", "effort": "xhigh",
702
- "clamped": null},
710
+ "clamped": null, "service_tier": "standard", "speed": "fast", "speed_reason": null},
703
711
  "tokens": {"input": 120000, "cached": 90000, "output": 8000}, "prompt_bytes": 45678,
704
712
  "verdict": null, "findings": null}
705
713
  ```
@@ -726,6 +734,13 @@ the detail is `request.md`.
726
734
  - `model`: from the `<role>.resolved` copy (a running execution without one: the owner dir's
727
735
  live `<role>.resolved`); `spec` is `alias[:effort]`, `effort` is `null` for
728
736
  `<harness default>`. `null` for the pipeline roles and when there is no alias.
737
+ `service_tier` is the tier that was asked: `metrics.json`'s `service_tier`, else the
738
+ `<role>.resolved` line `service_tier=` (written only when the dispatch asked for one).
739
+ `speed` is what the log reported (`fast`, `standard` or `default`) and `speed_reason` is why
740
+ it was not fast; both come only from `metrics.json`. Each is a non-empty string with
741
+ surrounding whitespace stripped, or `null` when absent, so a dispatch from before these keys
742
+ is otherwise unchanged. While a dispatch is still running and has no resolved copy of its
743
+ own, `service_tier` falls back to the live `<role>.resolved` and the speed stays unknown.
729
744
  - `tokens` is `null` when all three counts are; `timed_out` is whether `<role>.timedout` exists.
730
745
  - `verdict` and `findings` (FindingsSummary): `qa` only, from its own `qa.last` copy once done.
731
746
  - Executions are ordered by `started` (unknown last), then `id`.
@@ -1117,7 +1132,10 @@ lines follow, a line was cut, or reaching them took more than 64 MB of reading.
1117
1132
  "repo_root": "/x/y",
1118
1133
  "verdict": "FAIL", "findings": FindingsSummary, "duration_s": 270.0, "tokens": {...},
1119
1134
  "agreement": null, "primary_alias": null}],
1120
- "warnings": ["3f9a0c1d2e4b: tasks/x/attempts.tsv line 2: invalid attempt"]}
1135
+ "warnings": ["3f9a0c1d2e4b: tasks/x/attempts.tsv line 2: invalid attempt"],
1136
+ "recommended": {"profile": "balanced",
1137
+ "source": "#86 SWE-bench Pro decomposed runs, 2026-10-28; docs/models.md",
1138
+ "dwarf": {"low": "haiku:xhigh", "medium": "sonnet:medium", "high": "opus:high"}}}
1121
1139
  ```
1122
1140
 
1123
1141
  - `tasks[]`: one per task (`solo` for a solo run). `repo` is the run's `repo` text and `repo_root` its
@@ -1149,6 +1167,13 @@ lines follow, a line was cut, or reaching them took more than 64 MB of reading.
1149
1167
  `task_count`, `counts` or `final_review`, or its `repo_root`, changes (4,096 runs); a run with a `RUNNING` task is
1150
1168
  read again after 120 s. One computation runs at a time. Past 50,000 task rows the next run
1151
1169
  is left out and `truncated` is true. `warnings` (first 500) are prefixed by the run key.
1170
+ - `recommended`: the balanced built-in's first `routing.dwarf` spec of each tier, read from
1171
+ `scripts/forge_decide/builtin_profiles.json` and cached for the life of the process (a later
1172
+ edit of that file is picked up by the next server). `profile` is `"balanced"`. `source` is
1173
+ that profile's `source` when it is a string, otherwise `""`. `dwarf` maps `low`, `medium`
1174
+ and `high` to that tier's first spec; a tier whose pool does not start with one is omitted.
1175
+ The whole value is `null` when the file cannot be read or no tier qualifies. The object
1176
+ above is what the shipped file answers today.
1152
1177
 
1153
1178
  ## Fractal (`forge_ui/fractal.py`)
1154
1179
 
@@ -1354,8 +1379,8 @@ object its stdout holds, when that parses as one.
1354
1379
  | timeout | `504` | `timeout` |
1355
1380
 
1356
1381
  For the controls routes, unknown run keys, solo runs (they have no controls) and runs the
1357
- catalog does not hold are `404 {"error": "not found"}`. The issues, dismiss, delete and config
1358
- routes below accept plan and solo runs alike (`forge issues` and `forge runs rm` take both);
1382
+ catalog does not hold are `404 {"error": "not found"}`. The issues, dismiss, delete, config and
1383
+ profile routes below accept plan and solo runs alike (`forge issues` and `forge runs rm` take both);
1359
1384
  for them only unknown keys and runs the catalog does not hold are `404`. Every write that reaches a route logs
1360
1385
  `forge-ui: control <route> <run key> -> <status>` unless the server runs with `--quiet`.
1361
1386
 
@@ -1481,6 +1506,60 @@ are allowed), not starting with `-`; `repo.verify-subset` must contain `{files}`
1481
1506
  CLI's object (`ok`, `key`, `previous`, `value`). Writes serialize on one server-wide config lock
1482
1507
  (`409 busy`). Unknown run `404`. Timeout 60 s.
1483
1508
 
1509
+ ### `GET /api/config/profiles?run=<key>` and `POST /api/config/profiles`
1510
+
1511
+ The run is resolved as for `/api/config`: the repository is the run's root when that is an
1512
+ existing absolute directory, else the run's own `repo` file, and a missing directory is `409`.
1513
+ An unknown run is `404`. A key that is not 12 hex, or any query parameter other than `run`, is
1514
+ `400` before the CLI runs. `GET` does not take the config lock.
1515
+
1516
+ `GET` runs `config profile list --json --repo <repo>`, then `config profile show <name> --json
1517
+ --repo <repo>` once per row, and answers with the list object with each profile's `body` added.
1518
+ One request is enough for the Settings page. Each row is `{name, level, shadowed, default, body}`:
1519
+
1520
+ - `level` is `user`, `repo` or `builtin` (user hides repo hides builtin).
1521
+ - `shadowed` is the levels that copy hides, in that order, or `[]`.
1522
+ - `default` is whether this profile is the default in effect.
1523
+ - `body` is the winning profile object, the one `show` prints.
1524
+
1525
+ The top-level `default` is `{name, level}` of the default in effect (`default_profile` in the
1526
+ user file, else the repo file), or `{name: null, level: null}` when none is selected. A list or
1527
+ a show that does not print that object, or a row whose name is not a profile name, is `502`.
1528
+ Timeout 60 s per CLI call.
1529
+
1530
+ `POST` takes `{"run": <key>, "action", "level": "user"|"repo", ...}`. `level: "repo"` adds
1531
+ `--repo <repo>` before `--json` and writes `<repo>/.forge/decide.json`; `user` writes the user
1532
+ file and passes no `--repo`. `--json` is always last. The answer is the CLI's `--json` object,
1533
+ `{"ok": true, "name", "level", "body"}` (`rm` returns the removed profile's `name` and
1534
+ `"body": null`; both `name` and `body` are `null` when `use --none` cleared the default).
1535
+ A failure uses the exit mapping above, with `result`
1536
+ set to `{"ok": false, "error"}` when the CLI printed one.
1537
+
1538
+ | `action` | other fields | CLI |
1539
+ |---|---|---|
1540
+ | `create` | `name`, and exactly one of `from` (another profile's name) or `body` (an object) | `config profile create NAME --from OTHER` or `--file -` |
1541
+ | `edit` | `name`, `body` | `config profile edit NAME --file -` |
1542
+ | `set` | `name`, `key`, `value` | `config profile set NAME KEY VALUE` |
1543
+ | `unset` | `name`, `key` | `config profile unset NAME KEY` |
1544
+ | `rm` | `name` | `config profile rm NAME` |
1545
+ | `use` | `name`, or `"none": true` (not both) | `config profile use NAME` or `config profile use --none` |
1546
+
1547
+ A `body` is written to the CLI's stdin as JSON (`--file -`). That text is refused at 64 KiB
1548
+ with `400`; the HTTP body is already capped at 64 KiB (`413`) by the server, and a re-encode
1549
+ can be the larger of the two. This is the one write that passes stdin. Checked before any CLI
1550
+ runs, and a failure there calls nothing: `action` is one of the six; `name` and `from` match
1551
+ `^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$`; `key` matches `^(routing|policy)\.[a-z_.]+$` (the CLI still
1552
+ rejects a key of that shape that is not a real profile key); `value` is a string with no
1553
+ control characters, newline and tab included, and not starting with `-`; `level` is `user` or
1554
+ `repo`; `body` is a JSON object. Any other field is `400`.
1555
+
1556
+ Writes take the same server-wide config lock as `/api/config` (`409 {"error": "busy"}`) and the
1557
+ same token and Origin checks. Timeout 60 s. Exit 2 is `400` (`invalid`). Exit 3 is `409`
1558
+ (`refused`), as for every other write. That includes editing, setting, unsetting or removing a
1559
+ built-in profile (`balanced`, `lite`) that has no copy at the level being written: the detail
1560
+ says it is read-only and names `forge config profile create NAME --from <name>`. The CLI does the validation and the writing, so a profile created here is
1561
+ byte-for-byte the file `forge config profile create` writes.
1562
+
1484
1563
  ## Status vocabulary for the page and the graph
1485
1564
 
1486
1565
  Both the page and the graph mark a task by its status with the CSS class
@@ -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):
@@ -632,6 +791,8 @@ ROUTES = [
632
791
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_file),
633
792
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues/dismiss'), _issues_dismiss),
634
793
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/delete'), _delete),
794
+ ('GET', re.compile(r'/api/config/profiles()'), _config_profiles_get),
795
+ ('POST', re.compile(r'/api/config/profiles()'), _config_profiles_set),
635
796
  ('GET', re.compile(r'/api/config()'), _config_get),
636
797
  ('POST', re.compile(r'/api/config()'), _config_set),
637
798
  ('GET', re.compile(r'/api/models/reviewers()'), _reviewer_outcomes),
@@ -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