@giamme/forge 0.12.0 → 0.13.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.
- package/CHANGELOG.md +77 -0
- package/README.md +1 -1
- package/SKILL.md +31 -12
- package/VERSION +1 -1
- package/docs/add-ons.md +11 -6
- package/docs/artifacts.md +18 -6
- package/docs/commands.md +189 -17
- package/docs/decomposed-runs.md +13 -5
- package/docs/forge-ui.md +34 -4
- package/docs/memory.md +2 -1
- package/docs/models.md +4 -2
- package/docs/reviews.md +81 -19
- package/docs/troubleshooting.md +3 -1
- package/forge +17 -1
- package/package.json +1 -1
- package/references/dataset.md +40 -14
- package/references/decision-models.md +759 -0
- package/references/decompose.md +197 -28
- package/references/harnesses.md +10 -3
- package/references/planning.md +8 -0
- package/references/solo.md +13 -3
- package/references/ui.md +11 -0
- package/scripts/forge-artifact.sh +30 -4
- package/scripts/forge-config.py +238 -29
- package/scripts/forge-contract.py +127 -58
- package/scripts/forge-control.py +40 -9
- package/scripts/forge-decide.py +6 -0
- package/scripts/forge-dispatch.sh +47 -15
- package/scripts/forge-fail-first.py +2 -2
- package/scripts/forge-gate-addressed.sh +40 -0
- package/scripts/forge-gate-message.sh +64 -0
- package/scripts/forge-issues.py +368 -36
- package/scripts/forge-jev-options.sh +269 -42
- package/scripts/forge-lib-attribute.sh +447 -0
- package/scripts/forge-lib-gates.sh +32 -0
- package/scripts/forge-lib-plans.sh +17 -6
- package/scripts/forge-lib-review.sh +24 -19
- package/scripts/forge-lib-task.sh +219 -39
- package/scripts/forge-lib-verify.sh +45 -8
- package/scripts/forge-memory.sh +3 -3
- package/scripts/forge-parallel-options.sh +44 -5
- package/scripts/forge-parallel.sh +503 -304
- package/scripts/forge-plan-check.py +35 -1
- package/scripts/forge-pre-review.py +437 -0
- package/scripts/forge-prompt.py +25 -5
- package/scripts/forge-route.py +2 -2
- package/scripts/forge-runtime.py +55 -1
- package/scripts/forge-schedule.py +70 -9
- package/scripts/forge-shadow.py +2 -2
- package/scripts/forge-solo.sh +41 -10
- package/scripts/forge-submodules.py +389 -0
- package/scripts/forge-sweep.py +542 -0
- package/scripts/forge_dataset/cli.py +12 -6
- package/scripts/forge_dataset/export.py +55 -45
- package/scripts/forge_dataset/forecast.py +4 -1
- package/scripts/forge_dataset/harvest.py +33 -5
- package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
- package/scripts/forge_decide/__init__.py +141 -0
- package/scripts/forge_decide/budget.py +149 -0
- package/scripts/forge_decide/cache.py +66 -0
- package/scripts/forge_decide/cli.py +953 -0
- package/scripts/forge_decide/doctor.py +221 -0
- package/scripts/forge_decide/label_addressed.py +75 -0
- package/scripts/forge_decide/label_attribution.py +62 -0
- package/scripts/forge_decide/label_coverage.py +81 -0
- package/scripts/forge_decide/label_message.py +38 -0
- package/scripts/forge_decide/label_prompt.py +139 -0
- package/scripts/forge_decide/labels.py +328 -0
- package/scripts/forge_decide/metrics.py +125 -0
- package/scripts/forge_decide/migrate.py +226 -0
- package/scripts/forge_decide/providers.py +292 -0
- package/scripts/forge_decide/replay.py +350 -0
- package/scripts/forge_decide/report.py +382 -0
- package/scripts/forge_decide/resolve.py +397 -0
- package/scripts/forge_decide/sites.py +377 -0
- package/scripts/forge_jev/__init__.py +202 -104
- package/scripts/forge_jev/addressed.py +171 -0
- package/scripts/forge_jev/attribution.py +198 -0
- package/scripts/forge_jev/cli.py +460 -382
- package/scripts/forge_jev/client.py +155 -77
- package/scripts/forge_jev/coupling.py +19 -87
- package/scripts/forge_jev/coverage.py +303 -0
- package/scripts/forge_jev/findings.py +219 -0
- package/scripts/forge_jev/gates.py +225 -27
- package/scripts/forge_jev/memory.py +65 -4
- package/scripts/forge_jev/message.py +134 -0
- package/scripts/forge_jev/plan_gates.py +294 -0
- package/scripts/forge_jev/questions.py +173 -313
- package/scripts/forge_jev/verify.py +130 -104
- package/ui/README.md +41 -10
- package/ui/docs/api.md +212 -44
- package/ui/forge_ui/checks.py +331 -0
- package/ui/forge_ui/control.py +60 -11
- package/ui/forge_ui/export.py +8 -3
- package/ui/forge_ui/models.py +1 -0
- package/ui/forge_ui/reader.py +436 -26
- package/ui/forge_ui/server.py +13 -0
- package/ui/forge_ui/static/app.js +15 -8
- package/ui/forge_ui/static/checksview.js +449 -0
- package/ui/forge_ui/static/controls.js +20 -13
- package/ui/forge_ui/static/convo.js +11 -2
- package/ui/forge_ui/static/findingsview.js +6 -4
- package/ui/forge_ui/static/index.html +1 -0
- package/ui/forge_ui/static/panel.js +105 -17
- package/ui/forge_ui/static/runmodel.js +40 -2
- package/ui/forge_ui/static/scene3d.js +2 -15
- package/ui/forge_ui/static/settings.js +336 -41
- package/ui/forge_ui/static/style.css +72 -7
- package/ui/forge_ui/transcripts.py +225 -54
- package/references/jev.md +0 -865
- package/scripts/forge_jev/backtest.py +0 -322
- package/scripts/forge_jev/corpus.py +0 -156
- package/scripts/forge_jev/features.py +0 -24
- package/scripts/forge_jev/predict.py +0 -204
- package/scripts/forge_jev/review.py +0 -73
- package/scripts/forge_jev/routing.py +0 -271
- package/scripts/forge_jev/subset.py +0 -123
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Which transport a decision-model site's request takes, and whether it may be sent at all.
|
|
2
|
+
|
|
3
|
+
spec_for_site(site, *, config=None, repo=None, resolved=None) -> dict
|
|
4
|
+
spec_for_provider(name, model=None, *, config=None) -> dict | None
|
|
5
|
+
identity(site, entry=None, *, config=None, repo=None, resolved=None, providers=None, env=None) -> (provider, model)
|
|
6
|
+
privacy_floor(repo=None) -> bool
|
|
7
|
+
|
|
8
|
+
A spec is {name, type: 'jev'|'clef', url, model, key, context, price_usd_per_mtok, local,
|
|
9
|
+
deadline_s}. Two transports, each hosted or local: `jev` is TypeSafe's request shape, `clef`
|
|
10
|
+
Cloudflare's envelope with chunking. A local provider may have no key, and then no
|
|
11
|
+
Authorization header is sent. `context` is the declared context limit in tokens; a request
|
|
12
|
+
over 90% of it is refused (`too-large`), never truncated.
|
|
13
|
+
|
|
14
|
+
When decide.json does not configure the site's gate, the spec is exactly what forge_jev's
|
|
15
|
+
client used before decide.json existed (the legacy branch): TypeSafe from jev.json, or
|
|
16
|
+
Cloudflare when the jev.json site map or FORGE_JEV_PROVIDER says so.
|
|
17
|
+
|
|
18
|
+
Never raises on a bad config file; a key is never logged or returned anywhere but `key`.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import math
|
|
23
|
+
import os
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
import re
|
|
26
|
+
import subprocess
|
|
27
|
+
|
|
28
|
+
from . import SITE_GATE, config_dir, load_repo, load_user
|
|
29
|
+
|
|
30
|
+
DEFAULT_DEADLINE_S = 5.0
|
|
31
|
+
_NAME = re.compile(r'^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$')
|
|
32
|
+
_ENV_NAME = re.compile(r'^[A-Z_][A-Z0-9_]*$')
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def find_repo(repo=None):
|
|
36
|
+
"""`repo`, else FORGE_DECIDE_REPO, else the git top level of the working directory;
|
|
37
|
+
None when there is none."""
|
|
38
|
+
if repo:
|
|
39
|
+
return repo
|
|
40
|
+
env = os.environ.get('FORGE_DECIDE_REPO')
|
|
41
|
+
if env:
|
|
42
|
+
return env
|
|
43
|
+
try:
|
|
44
|
+
out = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True, text=True,
|
|
45
|
+
timeout=5)
|
|
46
|
+
except (OSError, subprocess.SubprocessError):
|
|
47
|
+
return None
|
|
48
|
+
top = out.stdout.strip() if out.returncode == 0 else ''
|
|
49
|
+
return top or None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def privacy_floor(repo=None) -> bool:
|
|
53
|
+
"""The repo's .forge/decide.json says "privacy": "never-send". No repo, no floor."""
|
|
54
|
+
repo = find_repo(repo)
|
|
55
|
+
if repo is None:
|
|
56
|
+
return False
|
|
57
|
+
data, _ = load_repo(repo)
|
|
58
|
+
return data.get('privacy') == 'never-send'
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _assignment(line: str, key_env: str | None, single: bool) -> tuple[str, str] | None:
|
|
62
|
+
"""(NAME, value) for a NAME=value line, None for a raw token. Base64 keeps `=` for its
|
|
63
|
+
trailing padding only, so a value starting with `=` (`YWJjZGVmZw==`) is a raw token. An
|
|
64
|
+
empty value (`YWJjZGU=`, `QUJDREU=`) is a raw token too when it is the file's only line,
|
|
65
|
+
unless the name is key_env's; beside other lines, a CAPS name is an empty assignment."""
|
|
66
|
+
match = _NAME.match(line)
|
|
67
|
+
if not match:
|
|
68
|
+
return None
|
|
69
|
+
name, value = match.group(1), match.group(2).strip()
|
|
70
|
+
if value.startswith('='):
|
|
71
|
+
return None
|
|
72
|
+
if not value and (name != key_env if single else not _ENV_NAME.match(name)):
|
|
73
|
+
return None
|
|
74
|
+
return name, value.strip('"').strip("'")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _read_key_file(path: str, key_env: str | None) -> str | None:
|
|
78
|
+
"""A raw token, or the value of one NAME=value line. A file of several such lines (a
|
|
79
|
+
cloudflare.env with the account id beside the token) gives key_env's line, else the
|
|
80
|
+
line whose name ends in _TOKEN or _KEY."""
|
|
81
|
+
# A path that cannot be read gives no key: `~user` with no such user raises RuntimeError, a
|
|
82
|
+
# NUL byte ValueError (as does undecodable text), and ask() must still reach its skips.
|
|
83
|
+
try:
|
|
84
|
+
full = Path(path).expanduser()
|
|
85
|
+
if not full.is_absolute():
|
|
86
|
+
full = config_dir() / full
|
|
87
|
+
text = full.read_text()
|
|
88
|
+
except (OSError, RuntimeError, ValueError):
|
|
89
|
+
return None
|
|
90
|
+
lines = [line.strip() for line in text.splitlines()
|
|
91
|
+
if line.strip() and not line.strip().startswith('#')]
|
|
92
|
+
if not lines:
|
|
93
|
+
return None
|
|
94
|
+
pairs = [_assignment(line, key_env, len(lines) == 1) for line in lines]
|
|
95
|
+
if not all(pairs):
|
|
96
|
+
return lines[0] if len(lines) == 1 else None
|
|
97
|
+
values = dict(pairs)
|
|
98
|
+
if key_env and values.get(key_env):
|
|
99
|
+
return values[key_env]
|
|
100
|
+
if len(values) == 1:
|
|
101
|
+
return next(iter(values.values())) or None
|
|
102
|
+
for name, value in values.items():
|
|
103
|
+
if value and (name.endswith('_TOKEN') or name.endswith('_KEY')):
|
|
104
|
+
return value
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _key(entry: dict) -> str | None:
|
|
109
|
+
"""key_env's variable, else key_file's contents: the first non-empty one."""
|
|
110
|
+
key_env = entry.get('key_env') if isinstance(entry.get('key_env'), str) else None
|
|
111
|
+
if key_env and os.environ.get(key_env):
|
|
112
|
+
return os.environ[key_env]
|
|
113
|
+
key_file = entry.get('key_file')
|
|
114
|
+
if isinstance(key_file, str) and key_file:
|
|
115
|
+
return _read_key_file(key_file, key_env)
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _positive(value) -> float | None:
|
|
120
|
+
"""A finite number above zero, else None: JSON's 1e309, NaN or an integer too big for a
|
|
121
|
+
float must not reach int() or crash ask()."""
|
|
122
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
123
|
+
return None
|
|
124
|
+
try:
|
|
125
|
+
if not math.isfinite(value) or value <= 0:
|
|
126
|
+
return None
|
|
127
|
+
except OverflowError:
|
|
128
|
+
return None
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _user_providers() -> dict:
|
|
133
|
+
user, _ = load_user()
|
|
134
|
+
entries = user.get('providers') if isinstance(user, dict) else None
|
|
135
|
+
return entries if isinstance(entries, dict) else {}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _kind(entry: dict) -> str:
|
|
139
|
+
return entry.get('type') if entry.get('type') in ('jev', 'clef') else 'jev'
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _entry_model(entry: dict, model: str | None) -> str:
|
|
143
|
+
"""`model`, else the provider entry's own model, else its transport's default."""
|
|
144
|
+
import forge_jev
|
|
145
|
+
default_model = forge_jev.CLOUDFLARE_MODEL if _kind(entry) == 'clef' else forge_jev.MODEL
|
|
146
|
+
return model or (entry.get('model') if isinstance(entry.get('model'), str) else None) or default_model
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _from_entry(name: str, entry: dict, model: str | None, config: dict) -> dict:
|
|
150
|
+
"""The spec of the user decide.json provider `name`, asking `model` (else the entry's
|
|
151
|
+
own model, else its transport's default)."""
|
|
152
|
+
import forge_jev
|
|
153
|
+
kind = _kind(entry)
|
|
154
|
+
model = _entry_model(entry, model)
|
|
155
|
+
url = entry.get('url') if isinstance(entry.get('url'), str) and entry.get('url') else None
|
|
156
|
+
# Only hosted TypeSafe has a default address: a local provider without one is `no-url`,
|
|
157
|
+
# never the hosted service unauthenticated.
|
|
158
|
+
if url is None and kind == 'jev' and entry.get('local') is not True:
|
|
159
|
+
url = forge_jev.ENDPOINT
|
|
160
|
+
if url is not None and '{model}' in url:
|
|
161
|
+
url = url.replace('{model}', model)
|
|
162
|
+
context = _positive(entry.get('context'))
|
|
163
|
+
context = int(context) if context else None
|
|
164
|
+
if context is None and kind == 'clef':
|
|
165
|
+
context = forge_jev.CLOUDFLARE_CONTEXT.get(model)
|
|
166
|
+
deadline = _positive(entry.get('deadline_s')) or _positive(config.get('deadline_s')) or DEFAULT_DEADLINE_S
|
|
167
|
+
return dict(name=name, type=kind, url=url, model=model, key=_key(entry), context=context,
|
|
168
|
+
price_usd_per_mtok=_positive(entry.get('price_usd_per_mtok')),
|
|
169
|
+
local=entry.get('local') is True, deadline_s=float(deadline))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _provider_entry(gate: dict, providers: dict | None = None) -> tuple[str, dict] | None:
|
|
173
|
+
"""(name, user provider entry) of the provider `gate` names, or None when it names none
|
|
174
|
+
the user decide.json (or `providers`, standing in for its `providers`) has: such a gate
|
|
175
|
+
takes the legacy route."""
|
|
176
|
+
name = gate.get('provider')
|
|
177
|
+
if not name:
|
|
178
|
+
return None
|
|
179
|
+
entry = (_user_providers() if providers is None else providers).get(name)
|
|
180
|
+
return (name, entry) if isinstance(entry, dict) else None
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _configured(site: str, config: dict, resolved: dict) -> dict | None:
|
|
184
|
+
"""The spec decide.json gives `site`, or None when it does not configure it."""
|
|
185
|
+
gate = (resolved.get('gates') or {}).get(SITE_GATE.get(site)) or {}
|
|
186
|
+
found = _provider_entry(gate)
|
|
187
|
+
if found is None:
|
|
188
|
+
return None
|
|
189
|
+
return _from_entry(found[0], found[1], gate.get('model'), config)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _cloudflare_model(remote: dict | None) -> str:
|
|
193
|
+
"""jev.json's Cloudflare model; `remote` is forge_jev.cloudflare(config)."""
|
|
194
|
+
import forge_jev
|
|
195
|
+
return remote['model'] if remote else forge_jev.CLOUDFLARE_MODEL
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _typesafe_model(config: dict) -> str:
|
|
199
|
+
import forge_jev
|
|
200
|
+
return config.get('model', forge_jev.DEFAULTS['model'])
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _cloudflare(config: dict, model: str | None = None) -> dict:
|
|
204
|
+
"""The legacy Cloudflare transport of jev.json, asking `model` (else jev.json's)."""
|
|
205
|
+
import forge_jev
|
|
206
|
+
deadline = config.get('deadline_s', forge_jev.DEFAULTS['deadline_s'])
|
|
207
|
+
remote = forge_jev.cloudflare(config)
|
|
208
|
+
model = model or _cloudflare_model(remote)
|
|
209
|
+
url = (remote.get('url') if remote else None) or forge_jev.CLOUDFLARE_URL
|
|
210
|
+
key = remote['token'] if remote and remote['account_id'] else None
|
|
211
|
+
if remote and remote['account_id']:
|
|
212
|
+
url = url.format(account=remote['account_id'], model=model)
|
|
213
|
+
return dict(name='cloudflare', type='clef', url=url, model=model, key=key,
|
|
214
|
+
context=forge_jev.CLOUDFLARE_CONTEXT.get(model), price_usd_per_mtok=None,
|
|
215
|
+
local=False, deadline_s=deadline)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _typesafe(config: dict, model: str | None = None) -> dict:
|
|
219
|
+
"""The legacy hosted TypeSafe transport of jev.json, asking `model` (else jev.json's)."""
|
|
220
|
+
import forge_jev
|
|
221
|
+
deadline = config.get('deadline_s', forge_jev.DEFAULTS['deadline_s'])
|
|
222
|
+
return dict(name='typesafe', type='jev', url=config.get('endpoint', forge_jev.DEFAULTS['endpoint']),
|
|
223
|
+
model=model or _typesafe_model(config), key=forge_jev.api_key(config),
|
|
224
|
+
context=None, price_usd_per_mtok=None, local=False, deadline_s=deadline)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
LEGACY = {'typesafe': _typesafe, 'cloudflare': _cloudflare}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _legacy(site: str, config: dict) -> dict:
|
|
231
|
+
"""What forge_jev.client.ask asked before decide.json: TypeSafe, or Cloudflare by site map."""
|
|
232
|
+
import forge_jev
|
|
233
|
+
return LEGACY[forge_jev.provider_for(site, config)](config)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def provider_names() -> list[str]:
|
|
237
|
+
"""The names spec_for_provider knows: the user decide.json providers, then the legacy ones."""
|
|
238
|
+
return sorted(_user_providers()) + [name for name in LEGACY if name not in _user_providers()]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def spec_for_provider(name: str, model: str | None = None, *, config: dict | None = None) -> dict | None:
|
|
242
|
+
"""The transport of provider `name` asking `model`, whatever any gate says: a provider of
|
|
243
|
+
the user decide.json, else the legacy `typesafe`/`cloudflare` transport of jev.json; None
|
|
244
|
+
for an unknown name. The legacy cloudflare url may raise KeyError on a stray brace."""
|
|
245
|
+
entry = _user_providers().get(name)
|
|
246
|
+
if isinstance(entry, dict):
|
|
247
|
+
import forge_jev
|
|
248
|
+
return _from_entry(name, entry, model, config or forge_jev.load_config())
|
|
249
|
+
if name in LEGACY:
|
|
250
|
+
import forge_jev
|
|
251
|
+
return LEGACY[name](config or forge_jev.load_config(), model)
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def spec_for_site(site: str, *, config: dict | None = None, repo=None, resolved: dict | None = None) -> dict:
|
|
256
|
+
"""The transport for one request to `site`. `config` is the legacy jev.json config
|
|
257
|
+
(forge_jev.load_config() when not given), `resolved` is resolve(repo)."""
|
|
258
|
+
import forge_jev
|
|
259
|
+
config = config or forge_jev.load_config()
|
|
260
|
+
if resolved is None:
|
|
261
|
+
from .resolve import resolve
|
|
262
|
+
resolved = resolve(find_repo(repo))
|
|
263
|
+
return _configured(site, config, resolved) or _legacy(site, config)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def identity(site: str, entry: dict | None = None, *, config: dict | None = None, repo=None,
|
|
267
|
+
resolved: dict | None = None, providers: dict | None = None, env=None) -> tuple[str, str]:
|
|
268
|
+
"""(provider, model) that spec_for_site would use for `site`, with `entry` (a gate entry:
|
|
269
|
+
{provider, model}) in place of the resolved gate when given. A provider of the user
|
|
270
|
+
decide.json asks the entry's model, else its own; without one, the legacy typesafe or
|
|
271
|
+
cloudflare transport asks its jev.json model. Builds no spec: no key is read and no
|
|
272
|
+
url formatted, so it does not raise on a stray brace. `providers` stands in for the user
|
|
273
|
+
decide.json's providers (a decide.json about to be written). `env` stands in for
|
|
274
|
+
os.environ in the legacy choice (FORGE_CLEF, FORGE_JEV_PROVIDER): a check of what is
|
|
275
|
+
written passes an empty one, since this shell's overrides do not outlive it."""
|
|
276
|
+
import forge_jev
|
|
277
|
+
config = config or forge_jev.load_config()
|
|
278
|
+
if entry is None:
|
|
279
|
+
if resolved is None:
|
|
280
|
+
from .resolve import resolve
|
|
281
|
+
resolved = resolve(find_repo(repo))
|
|
282
|
+
entry = (resolved.get('gates') or {}).get(SITE_GATE.get(site)) or {}
|
|
283
|
+
elif SITE_GATE.get(site) is None:
|
|
284
|
+
entry = {} # spec_for_site routes only gate sites to decide providers
|
|
285
|
+
found = _provider_entry(entry, providers)
|
|
286
|
+
if found is not None:
|
|
287
|
+
model = entry.get('model') if isinstance(entry.get('model'), str) else None
|
|
288
|
+
return found[0], _entry_model(found[1], model)
|
|
289
|
+
name = forge_jev.provider_for(site, config, env)
|
|
290
|
+
if name == 'cloudflare':
|
|
291
|
+
return name, _cloudflare_model(forge_jev.cloudflare(config))
|
|
292
|
+
return name, _typesafe_model(config)
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""`forge decide replay`: re-ask a site's stored live requests on one provider and model, and
|
|
2
|
+
judge the answers against the free labels and the site's cheap baseline (GitHub #37).
|
|
3
|
+
|
|
4
|
+
plan(site, provider, model, spec, *, runs=None) -> Plan which requests, what is answered
|
|
5
|
+
estimate(plan) -> dict the dry run's count, tokens, cost
|
|
6
|
+
send_all(plan, *, workers=3) -> dict ask every unanswered request
|
|
7
|
+
evaluate(plan, *, seed=7, margin=0.02) -> dict AUCs, interval, precision, promotes
|
|
8
|
+
record(gate, result) / recorded(gate, provider, model) the result the configuration reads
|
|
9
|
+
|
|
10
|
+
Answers are appended to state_dir()/replay/<site>/<provider>/<model>.jsonl, one line per
|
|
11
|
+
attempt ({key, answers, usage, at} or {key, reason, at}); a key already answered there is not
|
|
12
|
+
sent again, so a replay resumes. A failed key is asked again by the next --send.
|
|
13
|
+
|
|
14
|
+
Requests go through forge_jev.client.send: never the budget, the cache, jev.jsonl or the
|
|
15
|
+
dataset. Replays are deliberate, user-run spend. The privacy floor is read per request, from
|
|
16
|
+
the repo the store recorded for it, not from the working directory.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
import fcntl
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
from urllib.parse import quote
|
|
29
|
+
|
|
30
|
+
from . import _save, providers, state_dir
|
|
31
|
+
from . import labels, metrics, sites
|
|
32
|
+
|
|
33
|
+
VERSION = 1
|
|
34
|
+
# A replay is not waiting on a dispatch: a short live deadline would only lose answers.
|
|
35
|
+
MIN_DEADLINE_S = 30.0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Plan:
|
|
40
|
+
site: str
|
|
41
|
+
provider: str
|
|
42
|
+
model: str
|
|
43
|
+
spec: dict
|
|
44
|
+
rows: list # labels.collect rows that may be sent
|
|
45
|
+
usage: dict # key -> the stored live usage, when the store has it
|
|
46
|
+
skipped_privacy: int = 0
|
|
47
|
+
answered: dict = field(default_factory=dict) # key -> answers already in the replay file
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _part(name: str) -> str:
|
|
51
|
+
"""A path component: a Clef model is `@cf/meta/...`, which must not open directories."""
|
|
52
|
+
return quote(name, safe='') or '_'
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def answers_path(site: str, provider: str, model: str) -> Path:
|
|
56
|
+
return state_dir() / 'replay' / _part(site) / _part(provider) / (_part(model) + '.jsonl')
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def record_path(gate: str) -> Path:
|
|
60
|
+
return state_dir() / 'replays' / (_part(gate) + '.json')
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _private_dir(path: Path) -> None:
|
|
64
|
+
"""`path` and its missing parents, each created 0700."""
|
|
65
|
+
missing = []
|
|
66
|
+
while not path.exists():
|
|
67
|
+
missing.append(path)
|
|
68
|
+
path = path.parent
|
|
69
|
+
for directory in reversed(missing):
|
|
70
|
+
directory.mkdir(exist_ok=True)
|
|
71
|
+
directory.chmod(0o700)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def answered(path: Path) -> dict:
|
|
75
|
+
"""{key: answers} of the replay file; a later answer of a key wins, failures do not count."""
|
|
76
|
+
out = {}
|
|
77
|
+
try:
|
|
78
|
+
lines = path.read_text().splitlines()
|
|
79
|
+
except OSError:
|
|
80
|
+
return out
|
|
81
|
+
for line in lines:
|
|
82
|
+
try:
|
|
83
|
+
entry = json.loads(line)
|
|
84
|
+
except ValueError:
|
|
85
|
+
continue # a line cut by an interrupted write
|
|
86
|
+
if isinstance(entry, dict) and entry.get('key') and isinstance(entry.get('answers'), dict):
|
|
87
|
+
out[entry['key']] = entry['answers']
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _newest_runs(events, n: int) -> set:
|
|
92
|
+
"""The n dataset runs whose first stored request is newest."""
|
|
93
|
+
first = {}
|
|
94
|
+
for event in events:
|
|
95
|
+
first[event['run']] = min(first.get(event['run'], event['ts']), event['ts'])
|
|
96
|
+
return set(sorted(first, key=lambda run: (first[run], str(run)), reverse=True)[:n])
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def plan(site: str, provider: str, model: str, spec: dict, *, runs: int | None = None, store=None) -> Plan:
|
|
100
|
+
"""The labelled live requests of `site` (newest `runs` dataset runs only, when given), less
|
|
101
|
+
those whose own repo has the privacy floor, and which of them the replay file answers."""
|
|
102
|
+
store = store if store is not None else labels._open_store()
|
|
103
|
+
rows, usage, skipped = [], {}, 0
|
|
104
|
+
if store is not None:
|
|
105
|
+
stored = labels.requests(store, site)
|
|
106
|
+
usage = {event['d'].get('key'): event['d'].get('usage') for event, _body in stored}
|
|
107
|
+
keep = _newest_runs([event for event, _body in stored], runs) if runs else None
|
|
108
|
+
floors = {}
|
|
109
|
+
for row in labels.collect(site, store=store, runs=keep):
|
|
110
|
+
path = store.repo_paths.get(row['repo'])
|
|
111
|
+
# No recorded path, no floor: privacy_floor(None) would read the working directory's.
|
|
112
|
+
if path not in floors:
|
|
113
|
+
floors[path] = bool(path) and providers.privacy_floor(path)
|
|
114
|
+
if floors[path]:
|
|
115
|
+
skipped += 1
|
|
116
|
+
continue
|
|
117
|
+
rows.append(row)
|
|
118
|
+
found = answered(answers_path(site, provider, model))
|
|
119
|
+
return Plan(site=site, provider=provider, model=model, spec=spec, rows=rows, usage=usage,
|
|
120
|
+
skipped_privacy=skipped, answered={row['key']: found[row['key']] for row in rows if row['key'] in found})
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _input_tokens(plan_: Plan, row: dict) -> int:
|
|
124
|
+
usage = plan_.usage.get(row['key'])
|
|
125
|
+
value = usage.get('input_tokens') if isinstance(usage, dict) else None
|
|
126
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
|
|
127
|
+
return int(value)
|
|
128
|
+
return len(json.dumps(row['body'], sort_keys=True, separators=(',', ':'))) // 4
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def pending(plan_: Plan) -> list:
|
|
132
|
+
return [row for row in plan_.rows if row['key'] not in plan_.answered]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def estimate(plan_: Plan) -> dict:
|
|
136
|
+
"""What --send would send: requests, answered, to send, input tokens, cost (None unpriced)."""
|
|
137
|
+
todo = pending(plan_)
|
|
138
|
+
tokens = sum(_input_tokens(plan_, row) for row in todo)
|
|
139
|
+
price = plan_.spec.get('price_usd_per_mtok')
|
|
140
|
+
return dict(site=plan_.site, provider=plan_.provider, model=plan_.model, requests=len(plan_.rows),
|
|
141
|
+
answered=len(plan_.answered), to_send=len(todo), skipped_privacy=plan_.skipped_privacy,
|
|
142
|
+
input_tokens=tokens, cost_usd=None if price is None else tokens * price / 1e6)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _cut(path: Path) -> bool:
|
|
146
|
+
"""Whether `path` ends inside a line."""
|
|
147
|
+
try:
|
|
148
|
+
with open(path, 'rb') as handle:
|
|
149
|
+
handle.seek(0, os.SEEK_END)
|
|
150
|
+
if not handle.tell():
|
|
151
|
+
return False
|
|
152
|
+
handle.seek(-1, os.SEEK_END)
|
|
153
|
+
return handle.read(1) != b'\n'
|
|
154
|
+
except OSError:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def send_all(plan_: Plan, *, workers: int = 3, send=None) -> dict:
|
|
159
|
+
"""Ask every unanswered request on the plan's spec, `workers` at a time, appending one line
|
|
160
|
+
per answer or failure. {sent, answered, failed: {reason: count}}; plan_.answered grows."""
|
|
161
|
+
if send is None:
|
|
162
|
+
from forge_jev import client
|
|
163
|
+
send = client.send
|
|
164
|
+
path = answers_path(plan_.site, plan_.provider, plan_.model)
|
|
165
|
+
_private_dir(path.parent)
|
|
166
|
+
lock = threading.Lock()
|
|
167
|
+
failed = {}
|
|
168
|
+
deadline = max(float(plan_.spec.get('deadline_s') or 0.0), MIN_DEADLINE_S)
|
|
169
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
170
|
+
os.chmod(path, 0o600)
|
|
171
|
+
if _cut(path):
|
|
172
|
+
os.write(fd, b'\n') # end a line cut by an interrupted write, so the next answer stays whole
|
|
173
|
+
|
|
174
|
+
def one(row):
|
|
175
|
+
body = row['body']
|
|
176
|
+
result, reason, usage = send(plan_.spec, body.get('state'), body.get('questions') or {}, deadline_s=deadline)
|
|
177
|
+
if result is not None:
|
|
178
|
+
entry = dict(key=row['key'], answers=result['answers'], usage=usage, at=time.time())
|
|
179
|
+
else:
|
|
180
|
+
entry = dict(key=row['key'], reason=reason or 'no answer', at=time.time())
|
|
181
|
+
with lock:
|
|
182
|
+
os.write(fd, (json.dumps(entry) + '\n').encode())
|
|
183
|
+
if result is not None:
|
|
184
|
+
plan_.answered[row['key']] = result['answers']
|
|
185
|
+
else:
|
|
186
|
+
failed[entry['reason']] = failed.get(entry['reason'], 0) + 1
|
|
187
|
+
|
|
188
|
+
todo = pending(plan_)
|
|
189
|
+
try:
|
|
190
|
+
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
|
|
191
|
+
list(pool.map(one, todo))
|
|
192
|
+
finally:
|
|
193
|
+
os.close(fd)
|
|
194
|
+
return dict(sent=len(todo), answered=len(todo) - sum(failed.values()), failed=failed)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def rows(plan_: Plan) -> list:
|
|
198
|
+
"""One row per labelled decision of an answered request."""
|
|
199
|
+
record = sites.site(plan_.site)
|
|
200
|
+
out = []
|
|
201
|
+
for row in plan_.rows:
|
|
202
|
+
answers = plan_.answered.get(row['key'])
|
|
203
|
+
if answers is None:
|
|
204
|
+
continue
|
|
205
|
+
for qid, label in row['labels'].items():
|
|
206
|
+
replay = record.score(answers, qid, row['body'])
|
|
207
|
+
out.append(dict(run=row['run'], ts=row['ts'], key=row['key'], qid=qid, label=bool(label),
|
|
208
|
+
replay=None if replay is None else float(replay),
|
|
209
|
+
baseline=float(record.baseline(row['body'], qid)),
|
|
210
|
+
live=row['live'].get(qid), live_model=row.get('model')))
|
|
211
|
+
return out
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _promotes(judged, interval, *, margin, floor, threshold):
|
|
215
|
+
"""metrics.promotes, judged on `interval` (paired_bootstrap at --seed) instead of the
|
|
216
|
+
default seed's, so the recorded verdict and the reported interval always agree."""
|
|
217
|
+
labelled = [row for row in judged if row.get('label') is not None]
|
|
218
|
+
runs = {row['run'] for row in labelled}
|
|
219
|
+
if len(labelled) < metrics.MIN_DECISIONS or len(runs) < metrics.MIN_RUNS:
|
|
220
|
+
return metrics.promotes(labelled) # its count reasons; it fails before any bootstrap
|
|
221
|
+
if interval is None:
|
|
222
|
+
return False, 'the replay and the baseline cannot be compared (a class is missing or too few resamples)'
|
|
223
|
+
if not interval[0] > -margin:
|
|
224
|
+
return False, (f'replay is worse than the cheap baseline: AUC difference lower bound '
|
|
225
|
+
f'{interval[0]:.3f} is not above -{margin}')
|
|
226
|
+
if floor is not None:
|
|
227
|
+
if threshold is None:
|
|
228
|
+
return False, 'the precision floor needs a threshold'
|
|
229
|
+
got = metrics.precision_at([(row['replay'], row['label']) for row in labelled
|
|
230
|
+
if row.get('replay') is not None], threshold)['precision']
|
|
231
|
+
if got is None:
|
|
232
|
+
return False, f'the replay flags nothing at {threshold}, so precision cannot reach {floor}'
|
|
233
|
+
if got < floor:
|
|
234
|
+
return False, f'precision {got:.3f} at {threshold} is below the floor {floor}'
|
|
235
|
+
return True, 'passes'
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def evaluate(plan_: Plan, *, seed: int = 7, margin: float = 0.02) -> dict:
|
|
239
|
+
"""The replay judged on the newer half of the runs, against the baseline and the live answers.
|
|
240
|
+
|
|
241
|
+
The threshold is the one the score is compared with: an inverted site (sites.Site.invert)
|
|
242
|
+
flags a score at or above 1 - threshold; `threshold_name` stays the config name."""
|
|
243
|
+
import forge_jev
|
|
244
|
+
record = sites.site(plan_.site)
|
|
245
|
+
_calibrate, judged = metrics.split(rows(plan_))
|
|
246
|
+
live = {}
|
|
247
|
+
for row in judged:
|
|
248
|
+
if row['live'] is not None:
|
|
249
|
+
live.setdefault(row['live_model'] or '-', []).append((row['live'], row['label']))
|
|
250
|
+
threshold = (forge_jev.threshold(record.threshold, site=plan_.site, model=plan_.model)
|
|
251
|
+
if record.threshold else None)
|
|
252
|
+
if threshold is not None and record.invert:
|
|
253
|
+
threshold = 1.0 - threshold
|
|
254
|
+
answered_pairs = [(r['replay'], r['label']) for r in judged if r['replay'] is not None]
|
|
255
|
+
precision = (metrics.precision_at(answered_pairs, threshold) if threshold is not None
|
|
256
|
+
else dict(precision=None, recall=None, flagged=None))
|
|
257
|
+
interval = metrics.paired_bootstrap(judged, metrics._difference, seed=seed) if judged else None
|
|
258
|
+
passes, reason = _promotes(judged, interval, margin=margin, floor=record.floor, threshold=threshold)
|
|
259
|
+
return dict(at=time.time(), site=plan_.site, gate=record.gate, provider=plan_.provider, model=plan_.model,
|
|
260
|
+
passes=passes, reason=reason,
|
|
261
|
+
judged=dict(decisions=len(judged), runs=len({r['run'] for r in judged}),
|
|
262
|
+
positives=sum(r['label'] for r in judged)),
|
|
263
|
+
auc=dict(replay=metrics.auc(answered_pairs),
|
|
264
|
+
baseline=metrics.auc([(r['baseline'], r['label']) for r in judged]),
|
|
265
|
+
live={model: metrics.auc(pairs) for model, pairs in sorted(live.items())}),
|
|
266
|
+
diff=dict(value=metrics._difference(judged), ci=list(interval) if interval else None),
|
|
267
|
+
threshold=threshold, threshold_name=record.threshold, precision=precision['precision'],
|
|
268
|
+
recall=precision['recall'], flagged=precision['flagged'], floor=record.floor,
|
|
269
|
+
seed=seed, margin=margin, skipped_privacy=plan_.skipped_privacy,
|
|
270
|
+
requests=len(plan_.rows), answered=len(plan_.answered))
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
_RECORDED = ('at', 'site', 'provider', 'model', 'passes', 'reason', 'judged', 'auc', 'diff', 'threshold',
|
|
274
|
+
'precision', 'floor', 'seed', 'margin', 'threshold_name', 'recall', 'flagged')
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _load(path: Path) -> dict:
|
|
278
|
+
try:
|
|
279
|
+
data = json.loads(path.read_text())
|
|
280
|
+
except (OSError, ValueError):
|
|
281
|
+
return {}
|
|
282
|
+
return data if isinstance(data, dict) else {}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def record(gate: str, result: dict) -> Path:
|
|
286
|
+
"""Store `result` under results["<provider>/<model>"] of replays/<gate>.json (0600, atomic).
|
|
287
|
+
|
|
288
|
+
The read-modify-write holds flock on a sibling .lock, so two replays of one gate cannot each
|
|
289
|
+
save a snapshot that drops the other's entry."""
|
|
290
|
+
path = record_path(gate)
|
|
291
|
+
_private_dir(path.parent)
|
|
292
|
+
with open(f'{path}.lock', 'a') as lock:
|
|
293
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
294
|
+
data = _load(path)
|
|
295
|
+
results = data.get('results') if isinstance(data.get('results'), dict) else {}
|
|
296
|
+
results['%s/%s' % (result['provider'], result['model'])] = {k: result[k] for k in _RECORDED if k in result}
|
|
297
|
+
_save(path, dict(data, version=VERSION, results=results), 0o600)
|
|
298
|
+
return path
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def recorded(gate: str, provider: str, model: str) -> dict | None:
|
|
302
|
+
"""The recorded replay of `gate` on provider/model, or None."""
|
|
303
|
+
results = _load(record_path(gate)).get('results')
|
|
304
|
+
entry = results.get('%s/%s' % (provider, model)) if isinstance(results, dict) else None
|
|
305
|
+
return entry if isinstance(entry, dict) else None
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _number(value, digits=3) -> str:
|
|
309
|
+
return '-' if value is None else f'{value:.{digits}f}'
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def render_estimate(data: dict) -> str:
|
|
313
|
+
cost = '-' if data['cost_usd'] is None else f"${data['cost_usd']:.4f}"
|
|
314
|
+
return '\n'.join([
|
|
315
|
+
f"replay {data['site']} on {data['provider']}/{data['model']} (dry run: nothing sent; --send asks)",
|
|
316
|
+
f" requests {data['requests']}",
|
|
317
|
+
f" answered {data['answered']}",
|
|
318
|
+
f" to send {data['to_send']}",
|
|
319
|
+
f" privacy floor {data['skipped_privacy']} skipped",
|
|
320
|
+
f" input tokens ~{data['input_tokens']}",
|
|
321
|
+
f" cost {cost}",
|
|
322
|
+
])
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def render(result: dict) -> str:
|
|
326
|
+
judged = result['judged']
|
|
327
|
+
ci = result['diff']['ci']
|
|
328
|
+
lines = [
|
|
329
|
+
f"replay {result['site']} on {result['provider']}/{result['model']}: "
|
|
330
|
+
f"{result['answered']}/{result['requests']} requests answered, {result['skipped_privacy']} skipped "
|
|
331
|
+
f"(privacy floor)",
|
|
332
|
+
f"judged half: {judged['decisions']} decisions, {judged['positives']} positive, {judged['runs']} runs",
|
|
333
|
+
'',
|
|
334
|
+
f" {'scorer':<28} {'AUC':>6}",
|
|
335
|
+
f" {'replay ' + result['model']:<28} {_number(result['auc']['replay']):>6}",
|
|
336
|
+
f" {'baseline':<28} {_number(result['auc']['baseline']):>6}",
|
|
337
|
+
]
|
|
338
|
+
for model, value in result['auc']['live'].items():
|
|
339
|
+
lines.append(f" {'live ' + model:<28} {_number(value):>6}")
|
|
340
|
+
lines += [
|
|
341
|
+
'',
|
|
342
|
+
f" replay - baseline {_number(result['diff']['value'])} 95% CI "
|
|
343
|
+
+ ('-' if ci is None else f'[{ci[0]:.3f}, {ci[1]:.3f}]') + f" (margin {result['margin']})",
|
|
344
|
+
]
|
|
345
|
+
if result['threshold'] is not None:
|
|
346
|
+
lines.append(f" at {result['threshold_name']} {result['threshold']}: precision "
|
|
347
|
+
f"{_number(result['precision'])}, recall {_number(result['recall'])}, "
|
|
348
|
+
f"{result['flagged']} flagged (floor {_number(result['floor'], 2)})")
|
|
349
|
+
lines += ['', ('PASSES: ' if result['passes'] else 'does not pass: ') + result['reason']]
|
|
350
|
+
return '\n'.join(lines)
|