@giamme/forge 0.12.1 → 0.13.1

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 (111) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +29 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +12 -6
  7. package/docs/commands.md +179 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +14 -4
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +49 -20
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +39 -13
  17. package/references/decision-models.md +763 -0
  18. package/references/decompose.md +166 -29
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/scripts/forge-artifact.sh +30 -4
  23. package/scripts/forge-config.py +238 -29
  24. package/scripts/forge-contract.py +95 -56
  25. package/scripts/forge-control.py +40 -9
  26. package/scripts/forge-decide.py +6 -0
  27. package/scripts/forge-dispatch.sh +38 -16
  28. package/scripts/forge-fail-first.py +2 -2
  29. package/scripts/forge-gate-addressed.sh +40 -0
  30. package/scripts/forge-gate-message.sh +64 -0
  31. package/scripts/forge-issues.py +321 -33
  32. package/scripts/forge-jev-options.sh +269 -42
  33. package/scripts/forge-lib-attribute.sh +447 -0
  34. package/scripts/forge-lib-gates.sh +32 -0
  35. package/scripts/forge-lib-plans.sh +22 -6
  36. package/scripts/forge-lib-review.sh +22 -17
  37. package/scripts/forge-lib-task.sh +217 -38
  38. package/scripts/forge-lib-verify.sh +45 -8
  39. package/scripts/forge-memory.sh +3 -3
  40. package/scripts/forge-parallel-options.sh +18 -5
  41. package/scripts/forge-parallel.sh +457 -303
  42. package/scripts/forge-plan-check.py +35 -1
  43. package/scripts/forge-pre-review.py +437 -0
  44. package/scripts/forge-prompt.py +25 -5
  45. package/scripts/forge-route.py +2 -2
  46. package/scripts/forge-runtime.py +10 -4
  47. package/scripts/forge-schedule.py +21 -5
  48. package/scripts/forge-shadow.py +2 -2
  49. package/scripts/forge-solo.sh +39 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge-ui-options.sh +25 -0
  52. package/scripts/forge_dataset/cli.py +12 -6
  53. package/scripts/forge_dataset/export.py +140 -84
  54. package/scripts/forge_dataset/harvest.py +33 -5
  55. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  56. package/scripts/forge_decide/__init__.py +141 -0
  57. package/scripts/forge_decide/budget.py +180 -0
  58. package/scripts/forge_decide/cache.py +66 -0
  59. package/scripts/forge_decide/cli.py +953 -0
  60. package/scripts/forge_decide/doctor.py +270 -0
  61. package/scripts/forge_decide/label_addressed.py +75 -0
  62. package/scripts/forge_decide/label_attribution.py +62 -0
  63. package/scripts/forge_decide/label_coverage.py +81 -0
  64. package/scripts/forge_decide/label_message.py +38 -0
  65. package/scripts/forge_decide/label_prompt.py +139 -0
  66. package/scripts/forge_decide/labels.py +328 -0
  67. package/scripts/forge_decide/metrics.py +125 -0
  68. package/scripts/forge_decide/migrate.py +226 -0
  69. package/scripts/forge_decide/providers.py +292 -0
  70. package/scripts/forge_decide/replay.py +350 -0
  71. package/scripts/forge_decide/report.py +382 -0
  72. package/scripts/forge_decide/resolve.py +397 -0
  73. package/scripts/forge_decide/sites.py +377 -0
  74. package/scripts/forge_jev/__init__.py +202 -104
  75. package/scripts/forge_jev/addressed.py +171 -0
  76. package/scripts/forge_jev/attribution.py +198 -0
  77. package/scripts/forge_jev/cli.py +460 -382
  78. package/scripts/forge_jev/client.py +155 -77
  79. package/scripts/forge_jev/coupling.py +19 -87
  80. package/scripts/forge_jev/coverage.py +303 -0
  81. package/scripts/forge_jev/findings.py +219 -0
  82. package/scripts/forge_jev/gates.py +225 -27
  83. package/scripts/forge_jev/memory.py +65 -4
  84. package/scripts/forge_jev/message.py +134 -0
  85. package/scripts/forge_jev/plan_gates.py +294 -0
  86. package/scripts/forge_jev/questions.py +173 -313
  87. package/scripts/forge_jev/verify.py +130 -104
  88. package/ui/README.md +2 -2
  89. package/ui/docs/api.md +92 -39
  90. package/ui/forge_ui/control.py +71 -14
  91. package/ui/forge_ui/export.py +2 -1
  92. package/ui/forge_ui/models.py +17 -16
  93. package/ui/forge_ui/reader.py +132 -21
  94. package/ui/forge_ui/repos.py +428 -0
  95. package/ui/forge_ui/static/app.js +24 -5
  96. package/ui/forge_ui/static/cloudmodel.js +8 -5
  97. package/ui/forge_ui/static/controls.js +20 -13
  98. package/ui/forge_ui/static/modelstats.js +12 -8
  99. package/ui/forge_ui/static/panel.js +63 -17
  100. package/ui/forge_ui/static/runmodel.js +48 -7
  101. package/ui/forge_ui/static/scene3d.js +2 -15
  102. package/ui/forge_ui/static/settings.js +481 -68
  103. package/ui/forge_ui/static/style.css +56 -9
  104. package/references/jev.md +0 -865
  105. package/scripts/forge_jev/backtest.py +0 -322
  106. package/scripts/forge_jev/corpus.py +0 -156
  107. package/scripts/forge_jev/features.py +0 -24
  108. package/scripts/forge_jev/predict.py +0 -204
  109. package/scripts/forge_jev/review.py +0 -73
  110. package/scripts/forge_jev/routing.py +0 -271
  111. package/scripts/forge_jev/subset.py +0 -123
@@ -1,9 +1,10 @@
1
1
  """Stdlib-only decision-model HTTP client; every failure degrades to None, never raises.
2
2
 
3
- Two providers answer the same request shape ({state, model, questions}): TypeSafe's
4
- hosted Jev, and Cloudflare Workers AI's hosted Clef. Which one a call goes to is the
5
- site's (`provider_for`); without a Cloudflare provider configured every site asks
6
- TypeSafe exactly as it always has.
3
+ Two transports answer the same request shape ({state, model, questions}): Jev-compatible
4
+ (TypeSafe's hosted Jev, or a local server speaking its API) and Clef-compatible (Cloudflare
5
+ Workers AI's envelope, hosted or local). Which provider a call goes to is the site's spec
6
+ (forge_decide.providers.spec_for_site); without a decide.json every site asks exactly as it
7
+ always has: TypeSafe, or Cloudflare where jev.json's site map says so.
7
8
  """
8
9
  from __future__ import annotations
9
10
 
@@ -19,8 +20,14 @@ import urllib.error
19
20
  import urllib.request
20
21
  import uuid
21
22
 
22
- from . import (CLOUDFLARE_CONTEXT, CLOUDFLARE_MAX_QUESTIONS, CLOUDFLARE_MODEL, CLOUDFLARE_URL, DEFAULTS,
23
- acting, api_key, cloudflare, load_config, provider_for, redact, secrets, shadow, write_json)
23
+ from . import (CLOUDFLARE_CONTEXT, CLOUDFLARE_MAX_QUESTIONS, CLOUDFLARE_MODEL, _gate, _resolved, acting,
24
+ current_repo, load_config, redact, secrets, shadow, write_json)
25
+
26
+ _SCRIPTS = str(Path(__file__).resolve().parent.parent)
27
+ if _SCRIPTS not in sys.path:
28
+ sys.path.insert(0, _SCRIPTS)
29
+ from forge_decide import SITE_GATE, budget as _budget, cache as _cache, providers as _providers # noqa: E402
30
+ from forge_decide.resolve import resolve as _resolve # noqa: E402
24
31
 
25
32
  _BACKOFFS = (0.2, 0.4, 0.8)
26
33
  _RETRYABLE_CODES = (429, 529)
@@ -46,12 +53,23 @@ def _skip(run_dir: Path | str | None, site: str, reason: str) -> None:
46
53
  pass
47
54
 
48
55
 
49
- def _log(run_dir, site, key, ok, reason, latency_s, model, usage, questions, answers, provider='typesafe') -> None:
56
+ def _gate_fields(site) -> dict:
57
+ """The gate a site answers to and its resolved mode. `shadow` is that mode, or --jev-shadow
58
+ on a gate the legacy level turned on (no user decide.json yet), which acts as it always
59
+ did and is marked shadow as it always was."""
60
+ gate = _gate(site, _resolved())
61
+ mode = gate['mode'] if gate else 'off'
62
+ legacy = mode == 'on' and gate.get('source') == 'legacy' and shadow()
63
+ return dict(gate=SITE_GATE.get(site), mode=mode, shadow=mode == 'shadow' or legacy)
64
+
65
+
66
+ def _log(run_dir, site, key, ok, reason, latency_s, model, usage, questions, answers, provider='typesafe',
67
+ cached=False) -> None:
50
68
  if run_dir is None:
51
69
  return
52
70
  entry = dict(at=time.time(), site=site, key=key, ok=ok, reason=reason, latency_s=latency_s,
53
71
  model=model, usage=usage, questions=questions, answers=answers,
54
- acting=acting(), shadow=shadow(), provider=provider)
72
+ acting=acting(), provider=provider, cached=cached, **_gate_fields(site))
55
73
  try:
56
74
  with (Path(run_dir) / 'jev.jsonl').open('a') as handle:
57
75
  handle.write(json.dumps(entry) + '\n')
@@ -62,10 +80,9 @@ def _log(run_dir, site, key, ok, reason, latency_s, model, usage, questions, ans
62
80
  _skip(run_dir, site, reason)
63
81
 
64
82
 
65
- # Not decisions about a real run: replays of recorded answers, the setup key probe, and
66
- # backtests over history. Kept out of the run dataset so it only holds live judgments.
83
+ # Not decisions about a real run: replays of recorded answers and the setup key probe.
84
+ # Kept out of the run dataset so it only holds live judgments.
67
85
  _DATASET_SKIP_SITES = ('setup-probe',)
68
- _DATASET_SKIP_PREFIXES = ('jev-backtest',)
69
86
 
70
87
 
71
88
  def _dataset(site, key, canonical, ok, reason, latency, model, usage, qids, answers, run_dir, extra=None) -> None:
@@ -75,16 +92,17 @@ def _dataset(site, key, canonical, ok, reason, latency, model, usage, qids, answ
75
92
  against another model, or used to train one. The blob's original sha IS that key,
76
93
  so the two records join. Fail-open: never raises, never prints.
77
94
  """
78
- if os.environ.get('FORGE_JEV_FIXTURES') or site in _DATASET_SKIP_SITES or site.startswith(_DATASET_SKIP_PREFIXES):
95
+ if os.environ.get('FORGE_JEV_FIXTURES') or site in _DATASET_SKIP_SITES:
79
96
  return
80
97
  try:
81
98
  scripts = str(Path(__file__).resolve().parent.parent)
82
99
  if scripts not in sys.path:
83
100
  sys.path.insert(0, scripts)
84
101
  from forge_dataset.capture import jev
102
+ fields = _gate_fields(site)
85
103
  jev(site=site, key=key, canonical=canonical, ok=ok, reason=reason, latency=latency, model=model,
86
- usage=usage, questions=qids, answers=answers, run_dir=run_dir, acting=acting(), shadow=shadow(),
87
- extra=extra)
104
+ usage=usage, questions=qids, answers=answers, run_dir=run_dir, acting=acting(),
105
+ shadow=fields.pop('shadow'), extra=dict(extra or {}, **fields))
88
106
  except Exception:
89
107
  pass
90
108
 
@@ -122,15 +140,16 @@ def _tokens(text: str) -> int:
122
140
  return (len(text) + 2) // 3
123
141
 
124
142
 
125
- def chunks(state, questions: dict, model: str) -> list[dict] | None:
143
+ def chunks(state, questions: dict, model: str, context: int | None = None) -> list[dict] | None:
126
144
  """Questions packed into requests Cloudflare will evaluate whole, or None if none fits.
127
145
 
128
146
  Each request carries the full state, at most CLOUDFLARE_MAX_QUESTIONS questions, and
129
- stays under 90% of the model's context, which counts state and questions together.
147
+ stays under 90% of the context limit (`context`, else the model's), which counts state
148
+ and questions together.
130
149
  Past that the service cuts the state silently, so a request that cannot fit even one
131
150
  question is refused here instead of being answered on evidence it never saw.
132
151
  """
133
- budget = int(CLOUDFLARE_CONTEXT.get(model, CLOUDFLARE_CONTEXT[CLOUDFLARE_MODEL]) * 0.9)
152
+ budget = int((context or CLOUDFLARE_CONTEXT.get(model, CLOUDFLARE_CONTEXT[CLOUDFLARE_MODEL])) * 0.9)
134
153
  base = _tokens(_canonical(state).decode())
135
154
  out, current, cost = [], {}, base
136
155
  for qid, question in questions.items():
@@ -164,7 +183,15 @@ def _retry_after(error) -> float | None:
164
183
  return value if math.isfinite(value) and value >= 0 else None
165
184
 
166
185
 
167
- def _cloudflare_post(url: str, body: bytes, token: str, deadline_at: float, hidden: list) -> tuple:
186
+ def _headers(key: str | None) -> dict:
187
+ """A local provider may need no key: then no Authorization header at all."""
188
+ headers = {'Content-Type': 'application/json'}
189
+ if key:
190
+ headers['Authorization'] = 'Bearer ' + key
191
+ return headers
192
+
193
+
194
+ def _cloudflare_post(url: str, body: bytes, token: str | None, deadline_at: float, hidden: list) -> tuple:
168
195
  """One request to Workers AI: (result dict, None) or (None, reason)."""
169
196
  backoffs = iter(_BACKOFFS)
170
197
  reason = 'timeout'
@@ -172,8 +199,7 @@ def _cloudflare_post(url: str, body: bytes, token: str, deadline_at: float, hidd
172
199
  remaining = deadline_at - time.time()
173
200
  if remaining <= 0:
174
201
  return None, reason
175
- request = urllib.request.Request(url, data=body, method='POST', headers={
176
- 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
202
+ request = urllib.request.Request(url, data=body, method='POST', headers=_headers(token))
177
203
  wait = None
178
204
  try:
179
205
  with urllib.request.urlopen(request, timeout=remaining) as response:
@@ -218,11 +244,12 @@ def _cloudflare_post(url: str, body: bytes, token: str, deadline_at: float, hidd
218
244
 
219
245
 
220
246
  def _cloudflare_ask(state, questions: dict, provider: dict, deadline_at: float, hidden: list) -> tuple:
221
- """(result, None, chunk hashes) or (None, reason, chunk hashes); chunks run concurrently."""
222
- parts = chunks(state, questions, provider['model'])
247
+ """(result, None, chunk hashes) or (None, reason, chunk hashes); chunks run concurrently.
248
+ `provider` is a spec: its url is already formatted, its key may be None (local)."""
249
+ parts = chunks(state, questions, provider['model'], provider.get('context'))
223
250
  if parts is None:
224
251
  return None, 'too-large', []
225
- url = (provider.get('url') or CLOUDFLARE_URL).format(account=provider['account_id'], model=provider['model'])
252
+ url = provider['url']
226
253
  bodies = [_canonical(dict(model=provider['model'], state=state, questions=part)) for part in parts]
227
254
  hashes = [hashlib.sha256(body).hexdigest() for body in bodies]
228
255
  results, reasons = [None] * len(bodies), ['timeout'] * len(bodies)
@@ -231,7 +258,7 @@ def _cloudflare_ask(state, questions: dict, provider: dict, deadline_at: float,
231
258
  def work(i):
232
259
  with gate:
233
260
  if time.time() < deadline_at:
234
- results[i], reasons[i] = _cloudflare_post(url, bodies[i], provider['token'], deadline_at, hidden)
261
+ results[i], reasons[i] = _cloudflare_post(url, bodies[i], provider['key'], deadline_at, hidden)
235
262
 
236
263
  if len(bodies) == 1:
237
264
  work(0)
@@ -257,28 +284,98 @@ def _cloudflare_ask(state, questions: dict, provider: dict, deadline_at: float,
257
284
  return dict(answers=answers, usage=usage or None, model=model or provider['model']), None, hashes
258
285
 
259
286
 
287
+ def _transport(spec: dict, state, questions: dict, canonical: bytes, deadline_at: float, hidden: list) -> tuple:
288
+ """The network part of one request to `spec`: (payload, None, chunk hashes) or (None,
289
+ reason, chunk hashes). `canonical` is the Jev body; a Clef spec is sent in chunks, whose
290
+ hashes are a list (None for Jev). A payload always holds an `answers` dict."""
291
+ if not spec['url']:
292
+ return None, 'no-url', None
293
+ hashes = None
294
+ if spec['type'] == 'clef':
295
+ payload, reason, hashes = _cloudflare_ask(state, questions, spec, deadline_at, hidden)
296
+ if payload is None:
297
+ return None, reason, hashes
298
+ else:
299
+ if spec['context'] and _tokens(canonical.decode()) > spec['context'] * 0.9:
300
+ return None, 'too-large', None
301
+ url = spec['url']
302
+ backoffs = iter(_BACKOFFS)
303
+ reason = 'timeout'
304
+ while True:
305
+ remaining = deadline_at - time.time()
306
+ if remaining <= 0:
307
+ return None, reason, None
308
+ request = urllib.request.Request(url, data=canonical, method='POST', headers=_headers(spec['key']))
309
+ try:
310
+ with urllib.request.urlopen(request, timeout=remaining) as response:
311
+ payload = json.loads(response.read().decode())
312
+ break
313
+ except urllib.error.HTTPError as error:
314
+ # Redacted before it is cut, so a key straddling the cut leaves no prefix.
315
+ detail = redact(error.read().decode(errors='replace'), *hidden)[:200]
316
+ reason = f'http-{error.code}: {detail}'
317
+ if error.code not in _RETRYABLE_CODES:
318
+ return None, reason, None
319
+ except urllib.error.URLError as error:
320
+ reason = redact('network: ' + str(error.reason), *hidden)
321
+ except (TimeoutError, ValueError) as error:
322
+ return None, redact('network: ' + str(error), *hidden), None
323
+ delay = next(backoffs, None)
324
+ remaining = deadline_at - time.time()
325
+ if delay is None or remaining <= 0:
326
+ return None, reason, None
327
+ time.sleep(min(delay, remaining))
328
+ if not (isinstance(payload, dict) and isinstance(payload.get('answers'), dict)):
329
+ return None, 'malformed', hashes
330
+ return payload, None, hashes
331
+
332
+
333
+ def send(spec: dict, state, questions: dict, *, deadline_s: float | None = None) -> tuple:
334
+ """One request straight to provider `spec`, model spec['model']: (result, None, usage) or
335
+ (None, reason, None). The transport of ask() (Jev POST or Clef chunks, the context
336
+ limit, retries, validation, redaction) and nothing else: no gate, privacy floor, budget,
337
+ cache, fixtures, jev.jsonl or dataset. For `forge decide replay`, which re-asks stored
338
+ requests on a named provider as deliberate, user-run spend."""
339
+ started = time.time()
340
+ key = spec.get('key')
341
+ if not key and not spec.get('local'):
342
+ return None, 'no-key', None
343
+ try:
344
+ canonical = _canonical(dict(state=state, model=spec['model'], questions=questions))
345
+ except (TypeError, ValueError) as error:
346
+ return None, 'unserializable-state: ' + str(error), None
347
+ budget = deadline_s if deadline_s is not None else spec.get('deadline_s') or _providers.DEFAULT_DEADLINE_S
348
+ hidden = [s for s in secrets() + [key] if s]
349
+ payload, reason, _hashes = _transport(spec, state, questions, canonical, started + budget, hidden)
350
+ if payload is None:
351
+ return None, reason, None
352
+ result = dict(answers=payload['answers'], usage=payload.get('usage'),
353
+ model=payload.get('model', spec['model']), latency_s=time.time() - started)
354
+ return result, None, result['usage']
355
+
356
+
260
357
  def ask(state, questions: dict, *, site: str, run_dir=None, config: dict | None = None,
261
- deadline_s: float | None = None, context: dict | None = None) -> dict | None:
358
+ deadline_s: float | None = None, context: dict | None = None, repo=None) -> dict | None:
262
359
  """One judgment, or None. `context` (task, stage, attempt, assignment) is recorded with
263
- the request in the run dataset, for sites whose run dir does not say which task it is."""
360
+ the request in the run dataset, for sites whose run dir does not say which task it is.
361
+ `repo` is the repo whose .forge/decide.json applies (else FORGE_DECIDE_REPO, else the
362
+ working directory's; a command that knows its repo sets current_repo()): its privacy
363
+ floor skips every request, before fixtures too."""
264
364
  config = config or load_config()
265
- provider = provider_for(site, config)
266
- remote = cloudflare(config) if provider == 'cloudflare' else None
267
- if provider == 'cloudflare':
268
- key = remote['token'] if remote and remote['account_id'] else None
269
- model = remote['model'] if remote else CLOUDFLARE_MODEL
270
- else:
271
- key = api_key(config)
272
- model = config.get('model', DEFAULTS['model'])
365
+ repo = _providers.find_repo(repo or current_repo())
366
+ resolved = _resolve(repo)
367
+ spec = _providers.spec_for_site(site, config=config, repo=repo, resolved=resolved)
368
+ provider, key, model = spec['name'], spec['key'], spec['model']
273
369
  qids = list(questions)
274
370
  started = time.time()
275
371
  extra = dict(context or {}, provider=provider, occurrence=uuid.uuid4().hex)
276
372
 
277
- def done(ok, reason, result, model=None, usage=None, latency=None):
373
+ def done(ok, reason, result, model=None, usage=None, latency=None, cached=False):
278
374
  latency = latency if latency is not None else time.time() - started
279
375
  answers = result['answers'] if result else None
280
- _log(run_dir, site, fixture_key, ok, reason, latency, model, usage, qids, answers, provider)
281
- if canonical is not None:
376
+ _log(run_dir, site, fixture_key, ok, reason, latency, model, usage, qids, answers, provider, cached)
377
+ # A cache hit is not a new judgment: the dataset keeps live ones, as it does for fixtures.
378
+ if canonical is not None and not cached:
282
379
  _dataset(site, fixture_key, canonical, ok, reason, latency, model, usage, qids, answers, run_dir,
283
380
  extra)
284
381
  return result
@@ -293,7 +390,17 @@ def ask(state, questions: dict, *, site: str, run_dir=None, config: dict | None
293
390
  return done(False, 'unserializable-state: ' + str(error), None)
294
391
  fixture_key = hashlib.sha256(canonical).hexdigest()
295
392
 
296
- if not key:
393
+ # `repo` is already looked up: no second git call once the deadline is running.
394
+ if repo is not None and _providers.privacy_floor(repo):
395
+ return done(False, 'privacy', None)
396
+ hit = _cache.get(run_dir, fixture_key, spec)
397
+ if hit:
398
+ result = dict(answers=hit['answers'], usage=hit.get('usage'), model=hit.get('model') or model)
399
+ return done(True, None, result, model=result['model'], usage=dict(input_tokens=0, output_tokens=0),
400
+ latency=0.0, cached=True)
401
+ if _budget.check(resolved.get('budget'), run_dir=run_dir):
402
+ return done(False, _budget.SKIP, None)
403
+ if not key and not spec['local']:
297
404
  return done(False, 'no-key', None)
298
405
 
299
406
  fixtures_dir = os.environ.get('FORGE_JEV_FIXTURES')
@@ -312,45 +419,13 @@ def ask(state, questions: dict, *, site: str, run_dir=None, config: dict | None
312
419
  model=payload.get('model', model), latency_s=0.0, site=site)
313
420
  return done(True, None, result, model=result['model'], usage=result['usage'], latency=0.0)
314
421
 
315
- budget = deadline_s if deadline_s is not None else config.get('deadline_s', DEFAULTS['deadline_s'])
316
- deadline_at = started + budget
317
- hidden = secrets(config)
318
- if provider == 'cloudflare':
319
- payload, reason, extra['chunks'] = _cloudflare_ask(state, questions, remote, deadline_at, hidden)
320
- if payload is None:
321
- return done(False, reason, None)
322
- else:
323
- url = config.get('endpoint', DEFAULTS['endpoint'])
324
- backoffs = iter(_BACKOFFS)
325
- reason = 'timeout'
326
- while True:
327
- remaining = deadline_at - time.time()
328
- if remaining <= 0:
329
- return done(False, reason, None)
330
- request = urllib.request.Request(url, data=canonical, method='POST', headers={
331
- 'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
332
- try:
333
- with urllib.request.urlopen(request, timeout=remaining) as response:
334
- payload = json.loads(response.read().decode())
335
- break
336
- except urllib.error.HTTPError as error:
337
- # Redacted before it is cut, so a key straddling the cut leaves no prefix.
338
- detail = redact(error.read().decode(errors='replace'), key)[:200]
339
- reason = f'http-{error.code}: {detail}'
340
- if error.code not in _RETRYABLE_CODES:
341
- return done(False, reason, None)
342
- except urllib.error.URLError as error:
343
- reason = redact('network: ' + str(error.reason), key)
344
- except (TimeoutError, ValueError) as error:
345
- return done(False, redact('network: ' + str(error), key), None)
346
- delay = next(backoffs, None)
347
- remaining = deadline_at - time.time()
348
- if delay is None or remaining <= 0:
349
- return done(False, reason, None)
350
- time.sleep(min(delay, remaining))
351
-
352
- if not (isinstance(payload, dict) and isinstance(payload.get('answers'), dict)):
353
- return done(False, 'malformed', None)
422
+ budget = deadline_s if deadline_s is not None else spec['deadline_s']
423
+ hidden = [s for s in secrets(config) + [key] if s]
424
+ payload, reason, hashes = _transport(spec, state, questions, canonical, started + budget, hidden)
425
+ if hashes is not None:
426
+ extra['chunks'] = hashes
427
+ if payload is None:
428
+ return done(False, reason, None)
354
429
 
355
430
  record_dir = os.environ.get('FORGE_JEV_RECORD')
356
431
  if record_dir:
@@ -362,6 +437,8 @@ def ask(state, questions: dict, *, site: str, run_dir=None, config: dict | None
362
437
  latency = time.time() - started
363
438
  result = dict(answers=payload['answers'], usage=payload.get('usage'),
364
439
  model=payload.get('model', model), latency_s=latency, site=site)
440
+ _budget.charge(spec, result['usage'], run_dir=run_dir)
441
+ _cache.put(run_dir, fixture_key, spec, site, result['model'], result['answers'], result['usage'])
365
442
  return done(True, None, result, model=result['model'], usage=result['usage'], latency=latency)
366
443
 
367
444
 
@@ -407,6 +484,7 @@ def score(result, qid: str) -> tuple[float | None, float]:
407
484
  return (answer.get('score'), answer.get('confidence', 0.0))
408
485
 
409
486
 
487
+
410
488
  def normalized(result, qid: str) -> float | None:
411
489
  answer = (result or {}).get('answers', {}).get(qid) if result else None
412
490
  if not answer or answer.get('type') != 'score':
@@ -1,14 +1,14 @@
1
- """Plan-time semantic wave coupling.
1
+ """Plan-time forward-dependency check.
2
2
 
3
- `compute_waves` bounds parallelism structurally: two tasks share a wave only when their
4
- declared `files` are disjoint. Disjointness is blind to the conflict where task A changes
5
- an interface task B consumes -- both diffs pass review against their own baseline, and the
6
- merge is broken (see questions.wave_coupling). This asks about every pair `compute_waves`
7
- would actually run concurrently, before the wave runs, so the warning still lands while the
8
- plan can change.
3
+ `compute_waves` orders tasks by their declared `deps` and `files`. It cannot see that an
4
+ earlier-wave task is written against an interface a later-wave task builds (see
5
+ questions.forward_dependency). This asks about the cross-wave pairs nothing declares, before
6
+ the waves run, so the warning still lands while the plan can change.
9
7
 
10
- Nothing here writes to tasks.tsv or waves.tsv. Scoring is advisory and silent in shadow
11
- mode, exactly like routing.py and gates.py.
8
+ Nothing here writes to tasks.tsv or waves.tsv: scoring is advisory and silent in shadow mode,
9
+ the same way the other plan-time gates are. When the gate is `on`, `cmd_coupling` (cli.py)
10
+ turns each warned pair into a dependency through plan_gates.add_dep; the waves are recomputed
11
+ by the caller. The same-wave rubric is gone.
12
12
  """
13
13
  from __future__ import annotations
14
14
 
@@ -16,12 +16,7 @@ from pathlib import Path
16
16
 
17
17
  from . import threshold
18
18
  from .client import ask, noul
19
- from .questions import forward_dependency, wave_coupling
20
-
21
- # A wave of 12 tasks is 66 pairs; a plan-time gate must not become the slowest thing in
22
- # `forge plan`. Sorted before truncation (see pairs()) so the same plan always produces
23
- # the same capped set.
24
- MAX_PAIRS = 60
19
+ from .questions import forward_dependency
25
20
 
26
21
  # How many pairs a plan may warn about, however many clear the threshold.
27
22
  #
@@ -38,9 +33,9 @@ MAX_PAIRS = 60
38
33
  MAX_WARNINGS = 3
39
34
 
40
35
 
41
- # Cross-wave pairs get their own budget rather than sharing MAX_PAIRS: a plan with one
42
- # big first wave would otherwise spend the whole allowance inside it and never ask the
43
- # ordering question at all, which is the one that shipped a defect.
36
+ # A plan-time gate must not become the slowest thing in `forge plan`, so the number of
37
+ # cross-wave pairs asked about is capped. forward_pairs sorts before truncating so the
38
+ # same plan always produces the same capped set.
44
39
  MAX_FORWARD_PAIRS = 40
45
40
 
46
41
  PROMPT_CHARS = 2500
@@ -97,22 +92,6 @@ def parse_waves(plan: Path) -> dict[str, list[str]]:
97
92
  return waves
98
93
 
99
94
 
100
- def pairs(tasks: dict, waves: dict) -> list[tuple[str, str]]:
101
- """Every same-wave task pair with both ids known, capped at MAX_PAIRS.
102
-
103
- Sorted before truncation, same reasoning as gates.candidates: an unstable slice would
104
- make the same plan warn about a different subset of pairs on two runs.
105
- """
106
- found = []
107
- for ids in waves.values():
108
- ordered = sorted(i for i in ids if i in tasks)
109
- for i, first in enumerate(ordered):
110
- for second in ordered[i + 1:]:
111
- found.append((first, second))
112
- found.sort()
113
- return found[:MAX_PAIRS]
114
-
115
-
116
95
  def _wave_order(waves: dict) -> dict[str, int]:
117
96
  """Task id -> wave position. Waves are numbered as strings in waves.tsv; sort them
118
97
  numerically where possible so '10' follows '9' rather than '1'."""
@@ -132,8 +111,7 @@ def _wave_order(waves: dict) -> dict[str, int]:
132
111
  def forward_pairs(tasks: dict, waves: dict) -> list[tuple[str, str]]:
133
112
  """Ordered (earlier, later) pairs across waves that nothing forces to be safe.
134
113
 
135
- `pairs()` only looks inside a wave, so "task A is written against an interface task B
136
- builds later" was structurally outside this gate's reach -- and that is what shipped:
114
+ "Task A is written against an interface task B builds later" is what shipped:
137
115
  jevscope's `readme` ran in wave 1 documenting the CLI that wave 2 built, passed its
138
116
  own review, and described an interface nobody ever wrote.
139
117
 
@@ -162,8 +140,10 @@ def forward_pairs(tasks: dict, waves: dict) -> list[tuple[str, str]]:
162
140
  def forward_dependencies(repo, *, tasks, waves, run_dir=None, config: dict | None = None):
163
141
  """Earlier-wave tasks Jev thinks were written against work that lands later.
164
142
 
165
- Same contract as coupled_pairs: [(earlier, later, probability), ...] highest first,
166
- [] for "nothing to say", None for "no judgment could be made".
143
+ `tasks` is a list of dicts with id/title/files/difficulty; `waves` maps a wave number
144
+ to the list of task ids placed in it -- the same shapes `compute_waves` produces.
145
+ Returns [(earlier, later, probability), ...] highest first, [] for "nothing to say",
146
+ None for "no judgment could be made".
167
147
  """
168
148
  by_id = {t['id']: t for t in tasks if isinstance(t, dict) and t.get('id')}
169
149
  candidates = forward_pairs(by_id, waves)
@@ -185,7 +165,7 @@ def forward_dependencies(repo, *, tasks, waves, run_dir=None, config: dict | Non
185
165
  if result is None:
186
166
  return None
187
167
 
188
- warn_at = threshold('forward_warn', config=config)
168
+ warn_at = threshold('forward_warn', config=config, site='jev-forward')
189
169
  found = []
190
170
  for i, (earlier, later) in enumerate(candidates):
191
171
  probability = noul(result, f'f{i}')
@@ -194,51 +174,3 @@ def forward_dependencies(repo, *, tasks, waves, run_dir=None, config: dict | Non
194
174
  found.sort(key=lambda row: (-row[2], row[0], row[1]))
195
175
  return found[:MAX_WARNINGS]
196
176
 
197
-
198
- def coupled_pairs(repo, *, tasks, waves, run_dir=None, config: dict | None = None):
199
- """Same-wave task pairs Jev thinks would still conflict once merged.
200
-
201
- `tasks` is a list of dicts with id/title/files/difficulty; `waves` maps a wave number
202
- to the list of task ids placed in it -- the same shapes `compute_waves` produces.
203
- Returns [(id_a, id_b, probability), ...] at or above threshold('gate_warn'), highest
204
- probability first. Returns [] when there is nothing to warn about and None when no
205
- judgment could be made, so a caller can tell "no coupling found" from "Jev did not
206
- answer".
207
- """
208
- by_id = {t['id']: t for t in tasks if isinstance(t, dict) and t.get('id')}
209
- candidate_pairs = pairs(by_id, waves)
210
- if not candidate_pairs:
211
- return []
212
-
213
- questions = {}
214
- for i, (first, second) in enumerate(candidate_pairs):
215
- first_desc = f"{first} ({by_id[first]['title']}) files: {by_id[first]['files']}"
216
- second_desc = f"{second} ({by_id[second]['title']}) files: {by_id[second]['files']}"
217
- questions[f'p{i}'] = wave_coupling(first_desc, second_desc)
218
-
219
- # No file CONTENTS in state -- the rubric asks about interfaces between tasks, not
220
- # implementations, and sending diffs nobody wrote yet would only add noise and cost.
221
- # The task's requirements are a different thing, and they are where an interface
222
- # dependency is actually written down. Without them this rubric had no signal at all:
223
- # measured over 11 pairs with known outcomes, the two that produced a defect that
224
- # really shipped scored LOWEST of everything, below pairs that were unrelated. With
225
- # them, 4 of the 5 coupled pairs rank above every independent one.
226
- #
227
- # Only the tasks appearing in a candidate pair are sent, not the whole plan.
228
- involved = sorted({task_id for pair in candidate_pairs for task_id in pair})
229
- state = dict(tasks=[dict(id=by_id[i]['id'], title=by_id[i]['title'],
230
- files=by_id[i]['files'],
231
- requirements=by_id[i].get('prompt', ''))
232
- for i in involved])
233
- result = ask(state, questions, site='jev-coupling', run_dir=run_dir, config=config)
234
- if result is None:
235
- return None
236
-
237
- warn_at = threshold('coupling_warn', config=config)
238
- found = []
239
- for i, (first, second) in enumerate(candidate_pairs):
240
- probability = noul(result, f'p{i}')
241
- if probability is not None and probability >= warn_at:
242
- found.append((first, second, round(probability, 3)))
243
- found.sort(key=lambda item: item[2], reverse=True)
244
- return found[:MAX_WARNINGS]