@giamme/forge 0.14.1 → 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 (42) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/SKILL.md +47 -14
  3. package/VERSION +1 -1
  4. package/docs/commands.md +288 -6
  5. package/docs/models.md +53 -0
  6. package/package.json +1 -1
  7. package/references/dataset.md +12 -3
  8. package/references/decompose.md +103 -4
  9. package/references/harnesses.md +17 -0
  10. package/references/planning.md +59 -0
  11. package/references/ui.md +39 -1
  12. package/scripts/forge-compare.py +6 -3
  13. package/scripts/forge-config.py +531 -4
  14. package/scripts/forge-dispatch.sh +56 -2
  15. package/scripts/forge-lib-plans.sh +19 -2
  16. package/scripts/forge-lib-review.sh +5 -3
  17. package/scripts/forge-lib-task.sh +119 -0
  18. package/scripts/forge-parallel-options.sh +12 -6
  19. package/scripts/forge-parallel.sh +565 -21
  20. package/scripts/forge-plan-check.py +591 -8
  21. package/scripts/forge-planner.py +480 -0
  22. package/scripts/forge-runtime.py +86 -0
  23. package/scripts/forge-shadow.py +51 -7
  24. package/scripts/forge-solo.sh +81 -7
  25. package/scripts/forge_dataset/cli.py +10 -0
  26. package/scripts/forge_dataset/efforts.py +215 -0
  27. package/scripts/forge_dataset/harvest.py +44 -0
  28. package/scripts/forge_decide/__init__.py +19 -1
  29. package/scripts/forge_decide/builtin_profiles.json +25 -0
  30. package/scripts/forge_decide/cli.py +12 -0
  31. package/scripts/forge_decide/profiles.py +866 -0
  32. package/scripts/forge_decide/resolve.py +38 -6
  33. package/ui/docs/api.md +87 -8
  34. package/ui/forge_ui/control.py +173 -12
  35. package/ui/forge_ui/executions.py +28 -8
  36. package/ui/forge_ui/models.py +60 -1
  37. package/ui/forge_ui/reader.py +21 -1
  38. package/ui/forge_ui/static/leaderboard.js +5 -1
  39. package/ui/forge_ui/static/modelstats.js +25 -1
  40. package/ui/forge_ui/static/panel.js +19 -2
  41. package/ui/forge_ui/static/settings.js +788 -25
  42. package/ui/forge_ui/static/style.css +23 -0
@@ -0,0 +1,866 @@
1
+ """Named profiles: where they are kept, how they are chosen, checked and captured.
2
+
3
+ A profile is a named bundle of a run's model routing, policies, decision-model gates and
4
+ budget (the schema is in forge_decide's docstring). Profiles live in three places, and for
5
+ one name the first of these wins: the user file, the repo file, the built-in profiles
6
+ (builtin_profiles.json, read-only). Standard library only; importing this reads no file.
7
+
8
+ available(repo=None) -> {name: {"level", "body", "shadowed"}}
9
+ errors(repo=None) -> why a profile or a file was skipped
10
+ default_name(repo=None) -> (name, level) | (None, None)
11
+ select(repo=None, name=None, none=False) -> {"name", "level", "body", "shadowed"} | None
12
+ validate(body, providers) -> [reason, ...] (empty: valid)
13
+ check_spec(spec) -> reason | None
14
+ from_plan(plan_dir) -> a profile body captured from a plan dir
15
+ frozen_decide(text) -> the value of FORGE_DECIDE_PROFILE_JSON, or None
16
+
17
+ The shell reads and freezes a profile through the entry point at the end of this file
18
+ (`python3 -m forge_decide.profiles <command>`, with scripts/ on PYTHONPATH):
19
+
20
+ freeze PLAN --repo R [--profile N | --no-profile] [--given KEY]... `plan`: freeze, apply
21
+ solo RUN --repo R [--profile N | --no-profile] [--given TOKEN]... forge-solo.sh: the same
22
+ decide FILE | line FILE | value FILE KEY... read a frozen profile.json
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import datetime
28
+ import json
29
+ import math
30
+ import os
31
+ from pathlib import Path
32
+ import re
33
+ import subprocess
34
+ import sys
35
+ import tempfile
36
+ import unicodedata
37
+
38
+ from . import GATES, MODES, load_repo, load_user
39
+
40
+ LEVELS = ('user', 'repo', 'builtin')
41
+ TIERS = ('any', 'low', 'medium', 'high')
42
+ POOLS = ('dwarf', 'qa')
43
+ ROUTING_SPECS = ('planner', 'fractal_planner', 'final_reviewer')
44
+ ROUTING_KEYS = POOLS + ROUTING_SPECS + ('escalate_after', 'escalate_effort')
45
+ THRESHOLDS = ('P0', 'P1', 'P2', 'P3', 'none')
46
+ FAST_ROLES = ('dwarf', 'qa', 'planner', 'review')
47
+ POLICY_INTS = ('retry_failed', 'infra_retries', 'verify_retries', 'timeout')
48
+ POLICY_KEYS = ('qa_threshold', 'explore', 'shadow_qa', 'shadow_rate', 'fast') + POLICY_INTS
49
+ BUDGET_KEYS = ('run_tokens', 'run_usd', 'daily_tokens', 'daily_usd')
50
+
51
+ BUILTIN_PATH = Path(__file__).with_name('builtin_profiles.json')
52
+ DISPATCH = Path(__file__).resolve().parents[1] / 'forge-dispatch.sh'
53
+
54
+
55
+ class ProfileError(Exception):
56
+ """A profile that is asked for does not exist."""
57
+
58
+
59
+ # --- the store --------------------------------------------------------------------------
60
+
61
+ def _builtin() -> tuple[dict, str | None]:
62
+ try:
63
+ data = json.loads(BUILTIN_PATH.read_text())
64
+ except (OSError, ValueError, RecursionError) as exc:
65
+ return {}, f'{BUILTIN_PATH}: {exc}'
66
+ profiles = data.get('profiles') if isinstance(data, dict) else None
67
+ if not isinstance(profiles, dict):
68
+ return {}, f'{BUILTIN_PATH}: no profiles object'
69
+ return profiles, None
70
+
71
+
72
+ def builtin_names() -> tuple:
73
+ return tuple(_builtin()[0])
74
+
75
+
76
+ def _collect(repo) -> tuple[dict, list]:
77
+ found: dict = {} # name -> [(level, body)] in precedence order
78
+ errs: list = []
79
+ sources = [('user', *load_user())]
80
+ if repo is not None:
81
+ sources.append(('repo', *load_repo(repo)))
82
+ builtin, error = _builtin()
83
+ sources.append(('builtin', builtin, error))
84
+ for level, data, error in sources:
85
+ if error:
86
+ errs.append(error)
87
+ profiles = data if level == 'builtin' else data.get('profiles')
88
+ if profiles is None:
89
+ continue
90
+ if not isinstance(profiles, dict):
91
+ errs.append(f'{level} file: profiles is not an object; ignored')
92
+ continue
93
+ for name, body in profiles.items():
94
+ if not isinstance(body, dict):
95
+ errs.append(f'{level} profile {name!r} is not an object; skipped')
96
+ continue
97
+ found.setdefault(name, []).append((level, body))
98
+ out = {}
99
+ for name, entries in found.items():
100
+ level, body = entries[0]
101
+ out[name] = dict(level=level, body=body, shadowed=[lv for lv, _ in entries[1:]])
102
+ return out, errs
103
+
104
+
105
+ def available(repo=None) -> dict:
106
+ """name -> {"level": "user"|"repo"|"builtin", "body", "shadowed": [levels it hides]}."""
107
+ return _collect(repo)[0]
108
+
109
+
110
+ def errors(repo=None) -> list:
111
+ """Why a profile or a file was skipped by available(): one string each."""
112
+ return _collect(repo)[1]
113
+
114
+
115
+ def default_name(repo=None) -> tuple:
116
+ """(name, level): the user file's default_profile, else the repo file's."""
117
+ sources = [('user', load_user()[0])]
118
+ if repo is not None:
119
+ sources.append(('repo', load_repo(repo)[0]))
120
+ for level, data in sources:
121
+ name = data.get('default_profile')
122
+ if isinstance(name, str) and name:
123
+ return name, level
124
+ return None, None
125
+
126
+
127
+ def select(repo=None, name=None, none=False) -> dict | None:
128
+ """The profile a run uses: `name`, else the default; None when `none` or no default."""
129
+ if none:
130
+ return None
131
+ profiles = available(repo)
132
+ default_level = None
133
+ if name is None:
134
+ name, default_level = default_name(repo)
135
+ if name is None:
136
+ return None
137
+ if name not in profiles:
138
+ hint = ''
139
+ if default_level:
140
+ option = ' --repo DIR' if default_level == 'repo' else ''
141
+ hint = (f'; it is the {default_level} default_profile: clear it with forge config profile use'
142
+ f' --none{option}, or pass --no-profile or --profile NAME')
143
+ raise ProfileError(f'profile {name!r} not found (known: {", ".join(sorted(profiles))}){hint}')
144
+ return dict(name=name, **profiles[name])
145
+
146
+
147
+ # --- validation -------------------------------------------------------------------------
148
+
149
+ _SPEC_CACHE: dict = {}
150
+
151
+
152
+ def check_spec(spec) -> str | None:
153
+ """None when `spec` (alias[:effort[:harness]]) names a pairing forge can run, else why not."""
154
+ if not isinstance(spec, str) or not spec:
155
+ return f'{spec!r} is not a spec (a non-empty string)'
156
+ if any(c == ',' or c.isspace() or unicodedata.category(c).startswith('C') for c in spec):
157
+ return f'{spec!r} has whitespace, a comma or a control character'
158
+ parts = spec.split(':')
159
+ if len(parts) > 3 or not all(parts) or spec.startswith('-'):
160
+ return f'{spec!r} is not alias[:effort[:harness]]'
161
+ key = (spec, os.environ.get('FORGE_REGISTRY', ''))
162
+ if key not in _SPEC_CACHE:
163
+ _SPEC_CACHE[key] = _check_pairing(spec, parts)
164
+ return _SPEC_CACHE[key]
165
+
166
+
167
+ def _check_pairing(spec: str, parts: list) -> str | None:
168
+ try:
169
+ done = subprocess.run(['bash', str(DISPATCH), 'efforts', '--spec', spec],
170
+ capture_output=True, text=True, timeout=60)
171
+ except (OSError, subprocess.SubprocessError) as exc:
172
+ return f'{spec!r} could not be checked: {exc}'
173
+ if done.returncode != 0:
174
+ reason = (done.stderr.strip().splitlines() or ['refused'])[-1]
175
+ return f'{spec!r}: {reason.removeprefix("forge: ")}'
176
+ ladder = done.stdout.split()
177
+ if len(parts) > 1 and ladder and parts[1] not in ladder:
178
+ return f'{spec!r}: effort {parts[1]!r} is not accepted here (accepted: {", ".join(ladder)})'
179
+ return None
180
+
181
+
182
+ def _count(value, low=0, high=None) -> bool:
183
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
184
+ return False
185
+ if isinstance(value, float) and not math.isfinite(value):
186
+ return False
187
+ return value >= low and (high is None or value <= high)
188
+
189
+
190
+ def _spec(value, key: str, out: list) -> None:
191
+ reason = check_spec(value)
192
+ if reason:
193
+ out.append(f'{key}: {reason}')
194
+
195
+
196
+ def _spec_list(value, key: str, out: list) -> None:
197
+ if not isinstance(value, list) or not value:
198
+ out.append(f'{key}: not a non-empty list of specs')
199
+ return
200
+ for item in value:
201
+ _spec(item, key, out)
202
+
203
+
204
+ def _validate_routing(routing, out: list) -> None:
205
+ if not isinstance(routing, dict):
206
+ out.append('routing: not an object')
207
+ return
208
+ for key, value in routing.items():
209
+ path = f'routing.{key}'
210
+ if key not in ROUTING_KEYS:
211
+ out.append(f'{path}: unknown key (known: {", ".join(ROUTING_KEYS)})')
212
+ elif key in POOLS:
213
+ if not isinstance(value, dict):
214
+ out.append(f'{path}: not an object')
215
+ continue
216
+ for tier, specs in value.items():
217
+ if tier not in TIERS:
218
+ out.append(f'{path}.{tier}: unknown tier (known: {", ".join(TIERS)})')
219
+ else:
220
+ _spec_list(specs, f'{path}.{tier}', out)
221
+ elif key in ROUTING_SPECS:
222
+ _spec(value, path, out)
223
+ elif key == 'escalate_after':
224
+ if not _count(value) or not isinstance(value, int):
225
+ out.append(f'{path}: not an integer >= 0')
226
+ elif not isinstance(value, bool):
227
+ out.append(f'{path}: not true or false')
228
+
229
+
230
+ def _validate_policy(policy, out: list) -> None:
231
+ if not isinstance(policy, dict):
232
+ out.append('policy: not an object')
233
+ return
234
+ for key, value in policy.items():
235
+ path = f'policy.{key}'
236
+ if key not in POLICY_KEYS:
237
+ out.append(f'{path}: unknown key (known: {", ".join(POLICY_KEYS)})')
238
+ elif key == 'qa_threshold':
239
+ if value not in THRESHOLDS:
240
+ out.append(f'{path}: {value!r} is not one of {", ".join(THRESHOLDS)}')
241
+ elif key in POLICY_INTS:
242
+ if not isinstance(value, int) or not _count(value):
243
+ out.append(f'{path}: not an integer >= 0')
244
+ elif key == 'explore':
245
+ if not _count(value, 0, 0.5):
246
+ out.append(f'{path}: not a number in [0, 0.5]')
247
+ elif key == 'shadow_rate':
248
+ if not _count(value, 0, 1):
249
+ out.append(f'{path}: not a number in [0, 1]')
250
+ elif key == 'shadow_qa':
251
+ _spec_list(value, path, out)
252
+ elif key == 'fast':
253
+ if not isinstance(value, list) or any(role not in FAST_ROLES for role in value):
254
+ out.append(f'{path}: not a list of roles from {", ".join(FAST_ROLES)}')
255
+
256
+
257
+ def _validate_gates(gates, providers, out: list) -> None:
258
+ if not isinstance(gates, dict):
259
+ out.append('gates: not an object')
260
+ return
261
+ known = providers if isinstance(providers, dict) else {}
262
+ for name, value in gates.items():
263
+ path = f'gates.{name}'
264
+ if name not in GATES:
265
+ out.append(f'{path}: unknown gate')
266
+ continue
267
+ if isinstance(value, str):
268
+ value = dict(mode=value)
269
+ if not isinstance(value, dict):
270
+ out.append(f'{path}: not a mode or an object')
271
+ continue
272
+ mode = value.get('mode')
273
+ if mode is not None and mode not in MODES:
274
+ out.append(f'{path}.mode: {mode!r} is not one of {", ".join(MODES)}')
275
+ for field in ('provider', 'model', 'thresholds_model'):
276
+ field_value = value.get(field)
277
+ if field_value is None:
278
+ continue
279
+ if not isinstance(field_value, str):
280
+ out.append(f'{path}.{field}: not a string')
281
+ elif field == 'provider' and field_value not in known:
282
+ out.append(f'{path}.provider: {field_value!r} is not a provider of the user file '
283
+ f'(known: {", ".join(sorted(known)) or "none"})')
284
+ if value.get('force') is not None and not isinstance(value['force'], bool):
285
+ out.append(f'{path}.force: not true or false')
286
+ thresholds = value.get('thresholds')
287
+ if thresholds is not None:
288
+ if not isinstance(thresholds, dict):
289
+ out.append(f'{path}.thresholds: not an object')
290
+ else:
291
+ for key, number in thresholds.items():
292
+ if not _threshold_ok(number):
293
+ out.append(f'{path}.thresholds.{key}: not a number')
294
+
295
+
296
+ def _threshold_ok(value) -> bool:
297
+ """A threshold as resolution reads it: a number that fits a float."""
298
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
299
+ return False
300
+ try:
301
+ return math.isfinite(float(value))
302
+ except OverflowError:
303
+ return False
304
+
305
+
306
+ def validate(body, providers) -> list:
307
+ """One reason per problem, each naming its key; [] when `body` is a valid profile.
308
+ `providers` is the user file's providers object, which the gates' providers come from."""
309
+ if not isinstance(body, dict):
310
+ return ['profile: not an object']
311
+ out: list = []
312
+ if 'routing' in body:
313
+ _validate_routing(body['routing'], out)
314
+ if 'policy' in body:
315
+ _validate_policy(body['policy'], out)
316
+ if 'gates' in body:
317
+ _validate_gates(body['gates'], providers, out)
318
+ if 'budget' in body:
319
+ budget = body['budget']
320
+ if not isinstance(budget, dict):
321
+ out.append('budget: not an object')
322
+ else:
323
+ for key, value in budget.items():
324
+ if key in BUDGET_KEYS and value is not None and not _count(value):
325
+ out.append(f'budget.{key}: not a number >= 0')
326
+ return out
327
+
328
+
329
+ # --- capture from a plan dir ------------------------------------------------------------
330
+
331
+ def _text(plan: Path, name: str):
332
+ try:
333
+ return (plan / name).read_text().strip()
334
+ except (OSError, UnicodeDecodeError):
335
+ return None
336
+
337
+
338
+ def _first_line(plan: Path, name: str):
339
+ text = _text(plan, name)
340
+ return (text.splitlines()[0].strip() or None) if text else None
341
+
342
+
343
+ def _pool(plan: Path, name: str) -> dict:
344
+ text = _text(plan, name)
345
+ try:
346
+ data = json.loads(text) if text else {}
347
+ except (ValueError, RecursionError):
348
+ return {}
349
+ if not isinstance(data, dict):
350
+ return {}
351
+ out = {}
352
+ for tier in TIERS:
353
+ specs = data.get(tier)
354
+ if isinstance(specs, list):
355
+ specs = [s for s in specs if isinstance(s, str) and s]
356
+ if specs:
357
+ out[tier] = specs
358
+ return out
359
+
360
+
361
+ def _number(text, kind):
362
+ try:
363
+ return kind(text) if text is not None else None
364
+ except ValueError:
365
+ return None
366
+
367
+
368
+ def from_plan(plan_dir) -> dict:
369
+ """A profile body (routing and policy) from the files of a plan dir; only the keys that
370
+ have a source. A frozen profile.json supplies the policy values no file gives."""
371
+ plan = Path(plan_dir)
372
+ routing: dict = {}
373
+ policy: dict = {}
374
+ for key, name in (('dwarf', 'fractal-routing.json'), ('qa', 'qa-routing.json')):
375
+ pool = _pool(plan, name)
376
+ if pool:
377
+ routing[key] = pool
378
+ for key, name in (('planner', 'planner'), ('final_reviewer', 'final_qa')):
379
+ value = _first_line(plan, name)
380
+ if value:
381
+ routing[key] = value
382
+ value = _number(_text(plan, 'escalate_after'), int)
383
+ if value is not None:
384
+ routing['escalate_after'] = value
385
+ text = _text(plan, 'escalate_effort')
386
+ if text is not None:
387
+ routing['escalate_effort'] = 'on' in text.split()
388
+ value = _first_line(plan, 'qa_threshold')
389
+ if value:
390
+ policy['qa_threshold'] = value
391
+ for key in ('timeout', 'verify_retries'):
392
+ value = _number(_text(plan, key), int)
393
+ if value is not None:
394
+ policy[key] = value
395
+ value = _number(_text(plan, 'explore'), float)
396
+ if value is not None:
397
+ policy['explore'] = value
398
+ text = _text(plan, 'shadow_qa')
399
+ specs = [s for s in re.split(r'[,\s]+', text or '') if s]
400
+ if specs:
401
+ policy['shadow_qa'] = specs
402
+ value = _number(_text(plan, 'shadow_rate'), float)
403
+ if value is not None:
404
+ policy['shadow_rate'] = value
405
+ text = _text(plan, 'fast')
406
+ roles = [line.strip() for line in (text or '').splitlines() if line.strip()]
407
+ if roles:
408
+ policy['fast'] = roles
409
+ frozen = _text(plan, 'profile.json')
410
+ try:
411
+ frozen = json.loads(frozen) if frozen else None
412
+ except (ValueError, RecursionError):
413
+ frozen = None
414
+ frozen_policy = (frozen.get('body') or {}).get('policy') if isinstance(frozen, dict) \
415
+ and isinstance(frozen.get('body'), dict) else None
416
+ if isinstance(frozen_policy, dict):
417
+ for key in ('retry_failed', 'infra_retries'):
418
+ if key not in policy and key in frozen_policy:
419
+ policy[key] = frozen_policy[key]
420
+ body: dict = {}
421
+ if routing:
422
+ body['routing'] = routing
423
+ if policy:
424
+ body['policy'] = policy
425
+ return body
426
+
427
+
428
+ def frozen_decide(profile_json_text) -> str | None:
429
+ """The value for FORGE_DECIDE_PROFILE_JSON from a frozen profile.json, or None when its
430
+ body has neither gates nor budget (or the text is not a frozen profile)."""
431
+ try:
432
+ data = json.loads(profile_json_text)
433
+ except (TypeError, ValueError, RecursionError):
434
+ return None
435
+ if not isinstance(data, dict) or not isinstance(data.get('body'), dict):
436
+ return None
437
+ body = data['body']
438
+ gates, budget = body.get('gates'), body.get('budget')
439
+ gates = gates if isinstance(gates, dict) and gates else None
440
+ budget = budget if isinstance(budget, dict) and budget else None
441
+ if gates is None and budget is None:
442
+ return None
443
+ if data.get('level') != 'user' and budget:
444
+ # daily budgets count only in the user file, wherever the copy is applied
445
+ budget = {k: v for k, v in budget.items() if k not in ('daily_tokens', 'daily_usd')} or None
446
+ name = data.get('name')
447
+ return json.dumps(dict(name=name if isinstance(name, str) else '', gates=gates or {},
448
+ budget=budget or {}))
449
+
450
+
451
+ # --- a profile in a run: choose, check, freeze, apply -------------------------------------
452
+ # `plan` and forge-solo.sh pick a profile (a flag, the plan's own frozen copy, or the default),
453
+ # keep it as <dir>/profile.json, and turn its values into what their flags would have set.
454
+
455
+ FROZEN = 'profile.json'
456
+ # Files an escalation policy leaves in the task dirs; turning the policy off removes them.
457
+ ESCALATION_MARKERS = ('escalation.stop', 'split.suggested', 'escalation.next')
458
+ SOLO_FAST_ROLES = ('dwarf', 'qa')
459
+ SOLO_POOL_TOKENS = ('dwarf-low', 'dwarf-medium', 'dwarf-high')
460
+
461
+
462
+ def flat(body) -> dict:
463
+ """The routing and policy keys a profile sets, dotted: routing.dwarf.high, policy.timeout."""
464
+ out: dict = {}
465
+ if not isinstance(body, dict):
466
+ return out
467
+ routing, policy = body.get('routing'), body.get('policy')
468
+ for key, value in (routing.items() if isinstance(routing, dict) else ()):
469
+ if key in POOLS and isinstance(value, dict):
470
+ for tier, specs in value.items():
471
+ out[f'routing.{key}.{tier}'] = specs
472
+ else:
473
+ out[f'routing.{key}'] = value
474
+ for key, value in (policy.items() if isinstance(policy, dict) else ()):
475
+ out[f'policy.{key}'] = value
476
+ return out
477
+
478
+
479
+ def table_line(record, overridden=None) -> str:
480
+ """`profile: NAME (LEVEL[, shadows LEVEL]) — flags override: KEY, KEY` for the approval table."""
481
+ if not isinstance(record, dict) or not isinstance(record.get('name'), str):
482
+ return ''
483
+ where = str(record.get('level') or '?')
484
+ shadowed = [lv for lv in (record.get('shadowed') or []) if isinstance(lv, str)]
485
+ if shadowed:
486
+ where += ', shadows ' + ', '.join(shadowed)
487
+ line = f'profile: {record["name"]} ({where})'
488
+ keys = record.get('overridden') if overridden is None else overridden
489
+ keys = [k for k in (keys or []) if isinstance(k, str)]
490
+ if keys:
491
+ line += ' \u2014 flags override: ' + ', '.join(keys)
492
+ return line
493
+
494
+
495
+ def _load_frozen(path) -> dict | None:
496
+ try:
497
+ data = json.loads(Path(path).read_text())
498
+ except (OSError, UnicodeDecodeError, ValueError, RecursionError):
499
+ return None
500
+ return data if isinstance(data, dict) and isinstance(data.get('body'), dict) else None
501
+
502
+
503
+ def _write_atomic(path: Path, text: str) -> None:
504
+ """A temp file in the same directory, then a rename."""
505
+ fd, temporary = tempfile.mkstemp(prefix=path.name + '.', dir=str(path.parent))
506
+ try:
507
+ with os.fdopen(fd, 'w') as handle:
508
+ handle.write(text)
509
+ os.chmod(temporary, 0o644)
510
+ os.replace(temporary, path)
511
+ except BaseException:
512
+ try:
513
+ os.unlink(temporary)
514
+ except OSError:
515
+ pass
516
+ raise
517
+
518
+
519
+ def _providers() -> dict:
520
+ providers = load_user()[0].get('providers')
521
+ return providers if isinstance(providers, dict) else {}
522
+
523
+
524
+ def _choose(repo, name, none, frozen_path: Path, prefer_frozen: bool, validate_it: bool = True):
525
+ """(action, record): 'none' (nothing to do), 'remove' (--no-profile), 'keep' (the frozen
526
+ copy stays; record is it) or 'new' (record is a freshly selected, valid profile).
527
+ Raises ProfileError for an unknown or invalid profile."""
528
+ if none:
529
+ return 'remove', None
530
+ kept = _load_frozen(frozen_path) if (name is None or prefer_frozen) else None
531
+ if kept is not None:
532
+ return 'keep', kept
533
+ if name is None and frozen_path.exists() and not prefer_frozen:
534
+ return 'keep', {} # a frozen copy that cannot be read is still the plan's, kept as it is
535
+ chosen = select(repo, name)
536
+ if chosen is None:
537
+ return 'none', None
538
+ reasons = validate(chosen['body'], _providers()) if validate_it else []
539
+ if reasons:
540
+ raise ProfileError(f'profile {chosen["name"]!r} is not valid:\n'
541
+ + '\n'.join(f' - {reason}' for reason in reasons))
542
+ return 'new', chosen
543
+
544
+
545
+ def _record(chosen: dict, given) -> dict:
546
+ keys = flat(chosen['body'])
547
+ return dict(name=chosen['name'], level=chosen['level'], body=chosen['body'],
548
+ shadowed=list(chosen.get('shadowed') or []),
549
+ frozen_at=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
550
+ overridden=sorted(k for k in set(given) if k in keys))
551
+
552
+
553
+ def _list(value) -> str:
554
+ return ','.join(value) if isinstance(value, list) else str(value)
555
+
556
+
557
+ def _share(value) -> str:
558
+ """0.1 -> 0.1, 1.0 -> 1, 0.0 -> 0: the shapes the --explore and --shadow-rate flags accept."""
559
+ return ('%.10f' % float(value)).rstrip('0').rstrip('.') or '0'
560
+
561
+
562
+ def _fast_roles(roles, allowed) -> str:
563
+ kept = [role for role in FAST_ROLES if role in roles and role in allowed]
564
+ return ','.join(kept) if kept else 'none'
565
+
566
+
567
+ def _apply_plan_files(plan: Path, keys: dict) -> None:
568
+ """The profile values `plan` has no variable for, written as their flags write them."""
569
+ def put(name, text):
570
+ (plan / name).write_text(text)
571
+
572
+ def markers():
573
+ for task in plan.glob('tasks/*'):
574
+ for marker in ESCALATION_MARKERS:
575
+ try:
576
+ (task / marker).unlink()
577
+ except OSError:
578
+ pass
579
+ if 'routing.final_reviewer' in keys:
580
+ put('final_qa', keys['routing.final_reviewer'])
581
+ if 'routing.escalate_after' in keys:
582
+ put('escalate_after', str(keys['routing.escalate_after']))
583
+ if keys['routing.escalate_after'] == 0:
584
+ markers()
585
+ if 'routing.escalate_effort' in keys:
586
+ if keys['routing.escalate_effort']:
587
+ put('escalate_effort', 'on\n')
588
+ markers()
589
+ else:
590
+ try:
591
+ (plan / 'escalate_effort').unlink()
592
+ except OSError:
593
+ pass
594
+ if 'policy.qa_threshold' in keys:
595
+ put('qa_threshold', str(keys['policy.qa_threshold']))
596
+ for key in ('timeout', 'verify_retries'):
597
+ if f'policy.{key}' in keys:
598
+ put(key, str(keys[f'policy.{key}']))
599
+
600
+
601
+ ROUTED = 'routed.json'
602
+ _BLANK = {'dwarf': ('', '-', 'UNASSIGNED'), 'qa': ('', '-')}
603
+
604
+
605
+ def _rows(path: Path) -> dict:
606
+ """{task id: fields} of a task table; {} when it cannot be read."""
607
+ try:
608
+ lines = path.read_text().split('\n')
609
+ except (OSError, UnicodeDecodeError):
610
+ return {}
611
+ rows = {}
612
+ for line in lines:
613
+ fields = line.split('\t')
614
+ if not line.startswith('#') and len(fields) >= 7:
615
+ rows[fields[0]] = fields
616
+ return rows
617
+
618
+
619
+ def _load_routed(plan: Path) -> dict:
620
+ try:
621
+ data = json.loads((plan / ROUTED).read_text())
622
+ except (OSError, UnicodeDecodeError, ValueError, RecursionError):
623
+ data = None
624
+ data = data if isinstance(data, dict) else {}
625
+ return {pool: {k: v for k, v in (data.get(pool) or {}).items() if isinstance(k, str) and isinstance(v, str)}
626
+ if isinstance(data.get(pool), dict) else {} for pool in ('dwarf', 'qa')}
627
+
628
+
629
+ def record_routed(plan: Path) -> None:
630
+ """Remember which dwarf and qa cells routing wrote into the task table (`plan` calls this once it
631
+ has resolved the table): a cell that was blank in tasks.declared.tsv, the table as this call
632
+ found it, and now holds a spec. A cell an earlier call recorded stays recorded while it still holds
633
+ what routing wrote, so a model put there by hand is never mistaken for a routed one."""
634
+ declared, current, before = _rows(plan / 'tasks.declared.tsv'), _rows(plan / 'tasks.tsv'), _load_routed(plan)
635
+ after = {'dwarf': {}, 'qa': {}}
636
+ for task, fields in current.items():
637
+ for column, pool in ((4, 'dwarf'), (5, 'qa')):
638
+ value = fields[column]
639
+ if value in _BLANK[pool]:
640
+ continue
641
+ was = declared.get(task)
642
+ if was is not None and was[column] in _BLANK[pool]:
643
+ after[pool][task] = value
644
+ elif before[pool].get(task) == value:
645
+ after[pool][task] = value
646
+ _write_atomic(plan / ROUTED, json.dumps(after, indent=2) + '\n')
647
+
648
+
649
+ def _release_routed(plan: Path, routed) -> None:
650
+ """A profile chosen again replaces the routing the plan was resolved with: a task model that routing
651
+ itself wrote (routed.json) goes back to unassigned, when the new pools (`routed`: the routing keys of
652
+ the new profile and of this call's flags) can resolve that row, and the table then does it. A model
653
+ written into a row by hand, a row the new pools say nothing about, and a task that merged stay."""
654
+ written = _load_routed(plan)
655
+ if not any(written.values()):
656
+ return
657
+ table = plan / 'tasks.tsv'
658
+ try:
659
+ lines = table.read_text().split('\n')
660
+ except (OSError, UnicodeDecodeError):
661
+ return
662
+ changed = False
663
+ for number, line in enumerate(lines):
664
+ fields = line.split('\t')
665
+ if line.startswith('#') or len(fields) < 7:
666
+ continue
667
+ try:
668
+ merged = (plan / 'tasks' / fields[0] / 'status').read_text().strip() == 'MERGED'
669
+ except (OSError, UnicodeDecodeError):
670
+ merged = False
671
+ if merged:
672
+ continue
673
+ for column, pool in ((4, 'dwarf'), (5, 'qa')):
674
+ if written[pool].get(fields[0]) == fields[column] and (
675
+ f'routing.{pool}.{fields[2]}' in routed or f'routing.{pool}.any' in routed):
676
+ fields[column] = '-'
677
+ changed = True
678
+ lines[number] = '\t'.join(fields)
679
+ if changed:
680
+ _write_atomic(table, '\n'.join(lines))
681
+
682
+
683
+ def freeze_plan(plan: Path, repo, name, none, given, check_only=False, validate_it=True) -> list:
684
+ """Select, freeze and apply a profile for `plan`; returns `key<TAB>value` lines for the shell
685
+ (the values of its variables: pools, planner, shadow review, exploration, fast roles)."""
686
+ frozen_path = plan / FROZEN
687
+ action, chosen = _choose(repo, name, none, frozen_path, False, validate_it)
688
+ if check_only:
689
+ return []
690
+ if action == 'remove':
691
+ # routed.json stays: the models a profile routed stay in the table, and a profile chosen later
692
+ # must still tell them from a model written by hand.
693
+ try:
694
+ frozen_path.unlink()
695
+ except OSError:
696
+ pass
697
+ return []
698
+ body = chosen.get('body') if isinstance(chosen, dict) else None
699
+ # A plain --dwarf or --qa is that role's pool for every tier, so it replaces the profile's tier
700
+ # pools of the role too: plan reads a tier pool before the `any` one. A tier flag beside it still
701
+ # names its tier alone.
702
+ given = set(given)
703
+ for pool in POOLS:
704
+ if f'routing.{pool}.any' in given:
705
+ given.update(k for k in flat(body) if k.startswith(f'routing.{pool}.'))
706
+ if action == 'keep':
707
+ # The kept profile's pools, for the rows still unassigned: a plan that stopped before routing
708
+ # (a send-back) has none resolved yet. A row with a model keeps it, and nothing is written.
709
+ # A pool a flag replaced, now or when the profile was frozen, stays replaced.
710
+ if isinstance(chosen.get('overridden'), list):
711
+ given |= set(chosen['overridden'])
712
+ return [f'{key}\t{_list(value)}' for key, value in flat(body).items()
713
+ if key.startswith(('routing.dwarf.', 'routing.qa.')) and key not in given]
714
+ if action != 'new':
715
+ return []
716
+ record = _record(chosen, given)
717
+ keys = {k: v for k, v in flat(chosen['body']).items() if k not in record['overridden']}
718
+ out = []
719
+ for key, value in keys.items():
720
+ if key.startswith(('routing.dwarf.', 'routing.qa.')) or key in (
721
+ 'routing.planner', 'policy.shadow_qa'):
722
+ out.append(f'{key}\t{_list(value)}')
723
+ elif key in ('policy.shadow_rate', 'policy.explore'):
724
+ out.append(f'{key}\t{_share(value)}')
725
+ elif key == 'policy.fast':
726
+ out.append(f'{key}\t{_fast_roles(value, FAST_ROLES)}')
727
+ _release_routed(plan, set(keys) | set(given))
728
+ _apply_plan_files(plan, keys)
729
+ _write_atomic(frozen_path, json.dumps(record, indent=2) + '\n')
730
+ return out
731
+
732
+
733
+ SOLO_GIVEN = {'dwarf': None, 'qa': None, 'qa_threshold': 'policy.qa_threshold',
734
+ 'timeout': 'policy.timeout', 'fast': 'policy.fast',
735
+ 'fractal-planner': 'routing.fractal_planner',
736
+ 'dwarf-low': 'routing.dwarf.low', 'dwarf-medium': 'routing.dwarf.medium',
737
+ 'dwarf-high': 'routing.dwarf.high'}
738
+
739
+
740
+ def _first(body, pool):
741
+ """The first spec of `pool` (dwarf or qa) at the medium tier, else the any tier."""
742
+ pools = flat(body)
743
+ for tier in ('medium', 'any'):
744
+ specs = pools.get(f'routing.{pool}.{tier}')
745
+ if isinstance(specs, list) and specs:
746
+ return f'routing.{pool}.{tier}', specs[0]
747
+ return None, None
748
+
749
+
750
+ def solo_profile(run: Path, repo, name, none, given, use_frozen, write, validate_it=True) -> list:
751
+ """The solo run's values from a profile, as `key<TAB>value` lines; writes the frozen copy
752
+ when `write`. Keys: dwarf, qa, qa_threshold, timeout, fast, pool.<tier>, fractal_planner, line."""
753
+ frozen_path = run / FROZEN
754
+ action, chosen = _choose(repo, name, none, frozen_path, use_frozen, validate_it)
755
+ if action == 'remove':
756
+ if write:
757
+ try:
758
+ frozen_path.unlink()
759
+ except OSError:
760
+ pass
761
+ return []
762
+ if action == 'none' or not chosen:
763
+ return []
764
+ body = chosen['body']
765
+ keys = flat(body)
766
+ overridden = []
767
+ for token in given:
768
+ if token in ('dwarf', 'qa'):
769
+ key, _ = _first(body, token)
770
+ overridden.append(key)
771
+ else:
772
+ overridden.append(SOLO_GIVEN.get(token))
773
+ overridden = sorted(k for k in set(overridden) if k in keys)
774
+ record = chosen if action == 'keep' else _record(chosen, overridden)
775
+ shown = dict(record, overridden=overridden)
776
+ out = []
777
+ for token in ('dwarf', 'qa'):
778
+ if token not in given:
779
+ _, spec = _first(body, token)
780
+ if spec:
781
+ out.append(f'{token}\t{spec}')
782
+ if 'qa_threshold' not in given and 'policy.qa_threshold' in keys:
783
+ out.append(f'qa_threshold\t{keys["policy.qa_threshold"]}')
784
+ if 'timeout' not in given and 'policy.timeout' in keys:
785
+ out.append(f'timeout\t{keys["policy.timeout"]}')
786
+ if 'fast' not in given and isinstance(keys.get('policy.fast'), list):
787
+ out.append(f'fast\t{_fast_roles(keys["policy.fast"], SOLO_FAST_ROLES)}')
788
+ for tier in ('low', 'medium', 'high'):
789
+ specs = keys.get(f'routing.dwarf.{tier}')
790
+ if f'dwarf-{tier}' not in given and isinstance(specs, list) and specs:
791
+ out.append(f'pool.{tier}\t{_list(specs)}')
792
+ planner = keys.get('routing.fractal_planner')
793
+ if 'fractal-planner' not in given and isinstance(planner, str) and planner:
794
+ out.append(f'fractal_planner\t{planner}')
795
+ out.append(f'line\t{table_line(shown)}')
796
+ out.append(f'decide\t{frozen_decide(json.dumps(record)) or ""}')
797
+ if write and action == 'new':
798
+ _write_atomic(frozen_path, json.dumps(record, indent=2) + '\n')
799
+ return out
800
+
801
+
802
+ # --- command line -----------------------------------------------------------------------
803
+
804
+ def _command_line() -> argparse.ArgumentParser:
805
+ parser = argparse.ArgumentParser(prog='python3 -m forge_decide.profiles')
806
+ commands = parser.add_subparsers(dest='command', required=True)
807
+ for name in ('freeze', 'solo'):
808
+ sub = commands.add_parser(name)
809
+ sub.add_argument('directory')
810
+ sub.add_argument('--repo', default=None)
811
+ sub.add_argument('--profile', default=None)
812
+ sub.add_argument('--no-profile', action='store_true')
813
+ sub.add_argument('--given', action='append', default=[])
814
+ sub.add_argument('--no-validate', action='store_true')
815
+ if name == 'freeze':
816
+ sub.add_argument('--check-only', action='store_true')
817
+ else:
818
+ sub.add_argument('--use-frozen', action='store_true')
819
+ sub.add_argument('--write', action='store_true')
820
+ commands.add_parser('routed').add_argument('directory')
821
+ commands.add_parser('decide').add_argument('file')
822
+ commands.add_parser('line').add_argument('file')
823
+ value = commands.add_parser('value')
824
+ value.add_argument('file')
825
+ value.add_argument('keys', nargs='+')
826
+ return parser
827
+
828
+
829
+ def main(argv=None) -> int:
830
+ args = _command_line().parse_args(argv)
831
+ if args.command in ('decide', 'line', 'value'):
832
+ text = Path(args.file).read_text() if Path(args.file).is_file() else ''
833
+ if args.command == 'decide':
834
+ print(frozen_decide(text) or '')
835
+ elif args.command == 'line':
836
+ print(table_line(_load_frozen(args.file)))
837
+ else:
838
+ values = flat((_load_frozen(args.file) or {}).get('body'))
839
+ for key in args.keys:
840
+ if key in values:
841
+ print(f'{key}\t{values[key]}')
842
+ return 0
843
+ if args.command == 'routed':
844
+ record_routed(Path(args.directory))
845
+ return 0
846
+ if args.profile is not None and args.no_profile:
847
+ print('forge: --profile and --no-profile are mutually exclusive', file=sys.stderr)
848
+ return 2
849
+ repo = args.repo or None
850
+ try:
851
+ if args.command == 'freeze':
852
+ lines = freeze_plan(Path(args.directory), repo, args.profile, args.no_profile, args.given,
853
+ args.check_only, not args.no_validate)
854
+ else:
855
+ lines = solo_profile(Path(args.directory), repo, args.profile, args.no_profile, args.given,
856
+ args.use_frozen, args.write, not args.no_validate)
857
+ except ProfileError as exc:
858
+ print(f'forge: {exc}', file=sys.stderr)
859
+ return 2
860
+ for line in lines:
861
+ print(line)
862
+ return 0
863
+
864
+
865
+ if __name__ == '__main__':
866
+ sys.exit(main())