@giamme/forge 0.12.1 → 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.
Files changed (107) hide show
  1. package/CHANGELOG.md +55 -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 +7 -3
  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 +759 -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 +17 -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 +455 -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 +38 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge_dataset/cli.py +12 -6
  52. package/scripts/forge_dataset/export.py +55 -45
  53. package/scripts/forge_dataset/harvest.py +33 -5
  54. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  55. package/scripts/forge_decide/__init__.py +141 -0
  56. package/scripts/forge_decide/budget.py +149 -0
  57. package/scripts/forge_decide/cache.py +66 -0
  58. package/scripts/forge_decide/cli.py +953 -0
  59. package/scripts/forge_decide/doctor.py +221 -0
  60. package/scripts/forge_decide/label_addressed.py +75 -0
  61. package/scripts/forge_decide/label_attribution.py +62 -0
  62. package/scripts/forge_decide/label_coverage.py +81 -0
  63. package/scripts/forge_decide/label_message.py +38 -0
  64. package/scripts/forge_decide/label_prompt.py +139 -0
  65. package/scripts/forge_decide/labels.py +328 -0
  66. package/scripts/forge_decide/metrics.py +125 -0
  67. package/scripts/forge_decide/migrate.py +226 -0
  68. package/scripts/forge_decide/providers.py +292 -0
  69. package/scripts/forge_decide/replay.py +350 -0
  70. package/scripts/forge_decide/report.py +382 -0
  71. package/scripts/forge_decide/resolve.py +397 -0
  72. package/scripts/forge_decide/sites.py +377 -0
  73. package/scripts/forge_jev/__init__.py +202 -104
  74. package/scripts/forge_jev/addressed.py +171 -0
  75. package/scripts/forge_jev/attribution.py +198 -0
  76. package/scripts/forge_jev/cli.py +460 -382
  77. package/scripts/forge_jev/client.py +155 -77
  78. package/scripts/forge_jev/coupling.py +19 -87
  79. package/scripts/forge_jev/coverage.py +303 -0
  80. package/scripts/forge_jev/findings.py +219 -0
  81. package/scripts/forge_jev/gates.py +225 -27
  82. package/scripts/forge_jev/memory.py +65 -4
  83. package/scripts/forge_jev/message.py +134 -0
  84. package/scripts/forge_jev/plan_gates.py +294 -0
  85. package/scripts/forge_jev/questions.py +173 -313
  86. package/scripts/forge_jev/verify.py +130 -104
  87. package/ui/README.md +2 -2
  88. package/ui/docs/api.md +60 -32
  89. package/ui/forge_ui/control.py +60 -11
  90. package/ui/forge_ui/export.py +2 -1
  91. package/ui/forge_ui/models.py +1 -0
  92. package/ui/forge_ui/reader.py +87 -14
  93. package/ui/forge_ui/static/app.js +2 -2
  94. package/ui/forge_ui/static/controls.js +20 -13
  95. package/ui/forge_ui/static/panel.js +63 -17
  96. package/ui/forge_ui/static/runmodel.js +23 -1
  97. package/ui/forge_ui/static/scene3d.js +2 -15
  98. package/ui/forge_ui/static/settings.js +336 -41
  99. package/ui/forge_ui/static/style.css +19 -7
  100. package/references/jev.md +0 -865
  101. package/scripts/forge_jev/backtest.py +0 -322
  102. package/scripts/forge_jev/corpus.py +0 -156
  103. package/scripts/forge_jev/features.py +0 -24
  104. package/scripts/forge_jev/predict.py +0 -204
  105. package/scripts/forge_jev/review.py +0 -73
  106. package/scripts/forge_jev/routing.py +0 -271
  107. package/scripts/forge_jev/subset.py +0 -123
@@ -1,322 +0,0 @@
1
- """Replays git history against Jev to score test-selection and drift-prediction thresholds.
2
-
3
- A commit's test changes are a LOWER BOUND on relevant tests: a human may touch fewer
4
- tests than a change could break, so high recall against this label is necessary, not
5
- sufficient -- it never proves full coverage. Co-change labels also encode one team's
6
- testing habits, so numbers from one repo do not transfer to another without
7
- re-measuring there. Both caveats are repeated in report() so they travel with the numbers.
8
-
9
- Budget discipline: execute=False (the default) makes zero API calls -- it only estimates
10
- how many requests a real run would cost. When execute=True, every request is appended to
11
- a lock-protected ledger under out_dir *before* it is issued, and max_requests is a hard
12
- cap; once hit, remaining records are marked incomplete rather than half-scored. A record
13
- whose Jev calls fail is excluded from metrics entirely -- treating a failed chunk as "not
14
- relevant" would manufacture artificial precision.
15
- """
16
- from __future__ import annotations
17
-
18
- import fcntl
19
- import json
20
- from pathlib import Path
21
- import subprocess
22
- import tempfile
23
- import time
24
-
25
- from . import load_config, threshold, write_json
26
- from .client import ask, noul
27
- from .corpus import VENDOR_PATTERN, commits, is_test
28
- from .questions import drift_prediction, test_relevance
29
-
30
- MAX_QUESTIONS_PER_REQUEST = 100
31
- DRIFT_CANDIDATE_CAP = 200 # capped universe of tracked non-test files considered for drift
32
- DEFAULT_THRESHOLDS = tuple(round(0.05 * i, 2) for i in range(1, 20)) # 0.05 .. 0.95 step 0.05
33
-
34
- LOWER_BOUND_NOTE = ('Test-touch labels are a LOWER BOUND on relevant tests: a human may touch '
35
- 'fewer tests than a change could break. High recall here is necessary, not '
36
- 'sufficient proof of coverage.')
37
- NO_TRANSFER_NOTE = ('Co-change labels encode one team\'s testing habits and repo layout. Numbers '
38
- 'from this repo do not transfer to another repo without re-measuring there.')
39
- # The single most optimistic thing about this whole method, so it travels with every number.
40
- POST_HOC_NOTE = ('Commit messages are written AFTER the work and often name the very files or '
41
- 'behaviour that changed. A Forge task prompt is written before. These scores are '
42
- 'therefore an UPPER BOUND on live performance.')
43
- DRIFT_CAP_NOTE = ('Drift candidates are the parent tree\'s tracked non-test files, sorted and '
44
- 'truncated to the cap -- a commit whose real files fall outside that slice is '
45
- 'scored against a universe that cannot contain them.')
46
-
47
-
48
- def notes(capability: str) -> list[str]:
49
- """Caveats that apply to this capability. Drift's label (the commit's actual file set)
50
- is complete, so the test-selection lower-bound note would be false there."""
51
- if capability == 'drift':
52
- return [POST_HOC_NOTE, NO_TRANSFER_NOTE, DRIFT_CAP_NOTE]
53
- return [LOWER_BOUND_NOTE, POST_HOC_NOTE, NO_TRANSFER_NOTE]
54
-
55
-
56
- def _index_candidates(candidates: list[str]) -> list[tuple[str, str]]:
57
- """Assign stable q<N> ids to candidate paths -- a path itself is not a safe question id."""
58
- return [(f'q{i}', path) for i, path in enumerate(candidates)]
59
-
60
-
61
- def _chunk(pairs: list[tuple[str, str]], size: int = MAX_QUESTIONS_PER_REQUEST):
62
- for i in range(0, len(pairs), size):
63
- yield pairs[i:i + size]
64
-
65
-
66
- def _ledger_append(out_dir: Path, entry: dict) -> None:
67
- path = out_dir / 'requests.jsonl'
68
- path.parent.mkdir(parents=True, exist_ok=True)
69
- with path.open('a') as handle:
70
- fcntl.flock(handle, fcntl.LOCK_EX)
71
- try:
72
- handle.write(json.dumps(entry) + '\n')
73
- handle.flush()
74
- finally:
75
- fcntl.flock(handle, fcntl.LOCK_UN)
76
-
77
-
78
- def _drift_candidates(repo, parent: str, cache: dict[str, list[str]], cap: int = DRIFT_CANDIDATE_CAP) -> list[str]:
79
- """Repo's tracked non-test files at `parent`, capped and sorted for determinism."""
80
- if parent in cache:
81
- return cache[parent]
82
- try:
83
- result = subprocess.run(['git', '-C', str(repo), 'ls-tree', '-r', '--name-only', parent],
84
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
85
- except (OSError, subprocess.TimeoutExpired):
86
- cache[parent] = []
87
- return []
88
- paths = []
89
- if result.returncode == 0:
90
- for line in result.stdout.decode(errors='replace').split('\n'):
91
- if line and not is_test(line) and not VENDOR_PATTERN.search(line):
92
- paths.append(line)
93
- paths = sorted(paths)[:cap]
94
- cache[parent] = paths
95
- return paths
96
-
97
-
98
- def _estimate_requests(n_candidates: int) -> int:
99
- if n_candidates <= 0:
100
- return 0
101
- return -(-n_candidates // MAX_QUESTIONS_PER_REQUEST) # ceil division
102
-
103
-
104
- def _score(sha: str, candidates: list[str], labels: list[str], answers: dict[str, float]) -> dict:
105
- """Package one record's raw probabilities. Threshold selection happens later in sweep()
106
- so re-tuning a threshold never costs another API call. `labels` is not part of the
107
- literal contract example but sweep() cannot compute recall without knowing which
108
- candidate paths are ground truth, so it travels alongside probabilities here."""
109
- return dict(sha=sha, n_candidates=len(candidates), n_labeled=len(labels),
110
- labels=sorted(set(labels)), probabilities=dict(answers), incomplete=False)
111
-
112
-
113
- def score_tests(record: dict, answers: dict[str, float]) -> dict:
114
- """Score one test-selection record's answers against its candidates and test_files label."""
115
- return _score(record['sha'], record['candidates'], record.get('test_files', []), answers)
116
-
117
-
118
- def _evaluate_record(record, *, state, candidates, question_fn, config, out_dir, run_dir,
119
- site, max_requests, request_count) -> tuple[dict, bool]:
120
- """Ask Jev about every candidate for one record, chunked and budget-gated. Returns
121
- (path->probability, incomplete). A failed or budget-skipped chunk marks the whole
122
- record incomplete -- its answered paths are still returned for inspection but the
123
- record is excluded from metrics by the caller."""
124
- pairs = _index_candidates(candidates)
125
- probabilities: dict[str, float] = {}
126
- incomplete = False
127
- for chunk in _chunk(pairs):
128
- if request_count[0] >= max_requests:
129
- incomplete = True
130
- break
131
- questions = {qid: question_fn(path) for qid, path in chunk}
132
- request_count[0] += 1
133
- _ledger_append(out_dir, dict(at=time.time(), sha=record['sha'], site=site,
134
- n_questions=len(questions), request_no=request_count[0]))
135
- result = ask(state, questions, site=site, run_dir=run_dir, config=config)
136
- if result is None:
137
- incomplete = True
138
- break
139
- for qid, path in chunk:
140
- value = noul(result, qid)
141
- if value is not None:
142
- probabilities[path] = value
143
- return probabilities, incomplete
144
-
145
-
146
- def run(repo, *, limit=None, execute=False, max_requests=200, out_dir=None,
147
- capability='tests', config=None) -> dict:
148
- if capability not in ('tests', 'drift'):
149
- raise ValueError("capability must be 'tests' or 'drift'")
150
- config = config or load_config()
151
- out_path = Path(out_dir) if out_dir is not None else Path(tempfile.mkdtemp(prefix='forge-jev-backtest-'))
152
- out_path.mkdir(parents=True, exist_ok=True)
153
-
154
- drift_cache: dict[str, list[str]] = {}
155
- question_fn = test_relevance if capability == 'tests' else drift_prediction
156
- site = 'jev-backtest:' + capability
157
-
158
- n_records = 0
159
- total_candidates = 0
160
- estimated_requests = 0
161
- results: list[dict] = []
162
- request_count = [0]
163
- budget_exhausted = False
164
-
165
- for record in commits(repo, limit=limit):
166
- if capability == 'tests':
167
- candidates = record['candidates']
168
- labels = record['test_files']
169
- else:
170
- candidates = _drift_candidates(repo, record['parent'], drift_cache)
171
- labels = sorted(set(record['all_changed']) & set(candidates))
172
-
173
- n_records += 1
174
- total_candidates += len(candidates)
175
- estimated_requests += _estimate_requests(len(candidates))
176
-
177
- if not execute:
178
- continue
179
-
180
- if budget_exhausted or request_count[0] >= max_requests:
181
- budget_exhausted = True
182
- results.append(_score(record['sha'], candidates, labels, {}) | dict(incomplete=True))
183
- continue
184
-
185
- # Label never enters the request state: only the task text and changed source
186
- # files are sent, never test_files/all_changed.
187
- state = dict(task=(record['subject'] + '\n' + record['body']).strip(),
188
- changed_files=record['source_files'])
189
- probabilities, incomplete = _evaluate_record(
190
- record, state=state, candidates=candidates, question_fn=question_fn, config=config,
191
- out_dir=out_path, run_dir=out_path, site=site, max_requests=max_requests,
192
- request_count=request_count)
193
- if request_count[0] >= max_requests:
194
- budget_exhausted = True
195
- scored = _score(record['sha'], candidates, labels, probabilities)
196
- scored['incomplete'] = incomplete
197
- results.append(scored)
198
-
199
- summary = dict(
200
- capability=capability,
201
- repo=str(repo),
202
- execute=execute,
203
- n_records=n_records,
204
- estimated_requests=estimated_requests,
205
- avg_candidates=(total_candidates / n_records) if n_records else 0.0,
206
- max_requests=max_requests,
207
- max_questions_per_request=MAX_QUESTIONS_PER_REQUEST,
208
- out_dir=str(out_path),
209
- notes=notes(capability),
210
- )
211
- if capability == 'drift':
212
- summary['drift_candidate_cap'] = DRIFT_CANDIDATE_CAP
213
- if execute:
214
- summary['requests_used'] = request_count[0]
215
- summary['n_incomplete'] = sum(1 for r in results if r['incomplete'])
216
- summary['results'] = results
217
- summary['sweep'] = sweep(results)
218
-
219
- write_json(out_path / 'backtest.json', summary)
220
- return summary
221
-
222
-
223
- def sweep(results: list[dict], thresholds=None) -> list[dict]:
224
- """Aggregate scored records across a sweep of thresholds. Incomplete records are
225
- dropped entirely -- an all-failed run must report zero scored records, never
226
- manufactured perfect (or perfectly bad) precision."""
227
- thresholds = list(thresholds) if thresholds is not None else list(DEFAULT_THRESHOLDS)
228
- usable = [r for r in results if not r.get('incomplete')]
229
- n_incomplete = len(results) - len(usable)
230
-
231
- rows = []
232
- for t in thresholds:
233
- total_labeled = 0
234
- total_labeled_selected = 0
235
- total_candidates = 0
236
- total_selected = 0
237
- per_record_recalls = []
238
- full_recall_records = 0
239
- selected_counts = []
240
-
241
- for r in usable:
242
- probs = r['probabilities']
243
- labels = set(r.get('labels', []))
244
- selected = {p for p, v in probs.items() if v is not None and v >= t}
245
- n_labeled = len(labels)
246
- n_labeled_selected = len(labels & selected)
247
-
248
- total_labeled += n_labeled
249
- total_labeled_selected += n_labeled_selected
250
- total_candidates += r['n_candidates']
251
- total_selected += len(selected)
252
- selected_counts.append(len(selected))
253
- if n_labeled:
254
- per_record_recalls.append(n_labeled_selected / n_labeled)
255
- if n_labeled_selected == n_labeled:
256
- full_recall_records += 1
257
-
258
- n_recall_records = len(per_record_recalls)
259
- rows.append(dict(
260
- threshold=t,
261
- micro_recall=(total_labeled_selected / total_labeled) if total_labeled else None,
262
- # Precision is the headline for drift: a warning that fires on files nobody
263
- # edits trains people to ignore it. For test selection it is expected to be
264
- # low by design, since over-selecting only costs runtime.
265
- precision=(total_labeled_selected / total_selected) if total_selected else None,
266
- macro_recall=(sum(per_record_recalls) / n_recall_records) if n_recall_records else None,
267
- reduction=(1 - total_selected / total_candidates) if total_candidates else None,
268
- records_with_full_recall=(full_recall_records / n_recall_records) if n_recall_records else None,
269
- mean_selected=(sum(selected_counts) / len(selected_counts)) if selected_counts else None,
270
- n_records=len(usable),
271
- n_incomplete=n_incomplete,
272
- ))
273
- return rows
274
-
275
-
276
- def _fmt(value, digits=3) -> str:
277
- return 'n/a' if value is None else f'{value:.{digits}f}'
278
-
279
-
280
- def report(summary: dict) -> str:
281
- lines = [f"Jev backtest -- capability={summary.get('capability')} repo={summary.get('repo')}"]
282
- lines += summary.get('notes') or notes(summary.get('capability', 'tests'))
283
- lines.append('')
284
-
285
- if not summary.get('execute'):
286
- lines.append(
287
- f"DRY RUN -- no API calls made. {summary['n_records']} record(s), "
288
- f"avg {summary['avg_candidates']:.1f} candidates/record, "
289
- f"~{summary['estimated_requests']} request(s) estimated at "
290
- f"{summary['max_questions_per_request']} questions/request.")
291
- return '\n'.join(lines)
292
-
293
- sweep_rows = summary.get('sweep', [])
294
- lines.append(f"requests used: {summary.get('requests_used', 0)} "
295
- f"incomplete records: {summary.get('n_incomplete', 0)}")
296
- lines.append(f"{'threshold':>9} | {'micro_recall':>12} | {'macro_recall':>12} | "
297
- f"{'precision':>9} | {'reduction':>9} | {'full_recall':>11} | {'mean_sel':>8}")
298
- best = None
299
- for row in sweep_rows:
300
- micro = row['micro_recall']
301
- lines.append(f"{row['threshold']:>9.2f} | {_fmt(micro):>12} | {_fmt(row['macro_recall']):>12} | "
302
- f"{_fmt(row['precision']):>9} | "
303
- f"{_fmt(row['reduction']):>9} | {_fmt(row['records_with_full_recall']):>11} | "
304
- f"{_fmt(row['mean_selected'], 1):>8}")
305
- if micro is not None and micro >= 0.95:
306
- best = row['threshold'] # ascending order: last hit is the highest qualifying threshold
307
-
308
- # The two capabilities are tuned against opposite errors, so they get different
309
- # headlines: a missed test is a missed regression, while a drift warning on files
310
- # nobody edits is noise that trains people to ignore the warning.
311
- if summary.get('capability') == 'drift':
312
- warn = threshold('gate_warn')
313
- row = min(sweep_rows, key=lambda r: abs(r['threshold'] - warn), default=None)
314
- if row is not None:
315
- lines.append(f"\nDrift headline -- precision at the warn threshold "
316
- f"{row['threshold']:.2f}: {_fmt(row['precision'])} "
317
- f"(recall {_fmt(row['micro_recall'])}).")
318
- elif best is not None:
319
- lines.append(f"\nHighest threshold holding micro recall >= 0.95: {best:.2f}")
320
- else:
321
- lines.append('\nNo threshold in this sweep holds micro recall >= 0.95.')
322
- return '\n'.join(lines)
@@ -1,156 +0,0 @@
1
- """Git-history corpus extractor: labeled (change -> tests touched) examples for Jev calibration."""
2
- from __future__ import annotations
3
-
4
- from collections.abc import Iterator
5
- import re
6
- import subprocess
7
-
8
- # Path segment for tests/, test/, spec/, __tests__/, e2e/, or a filename convention
9
- # (_test., .test., .spec., test_ prefix). Covers the Python and TypeScript repos this runs against.
10
- TEST_PATTERN = re.compile(
11
- r'(?:^|/)(?:tests?|specs?|__tests__|e2e)/'
12
- r'|(?:^|/)test_[^/]*$'
13
- r'|[^/]*(?:_test|\.test|\.spec)\.[^/]+$'
14
- )
15
-
16
- # Generated/vendored/binary paths carry no signal about human test selection.
17
- VENDOR_PATTERN = re.compile(
18
- r'(?:^|/)(?:node_modules|vendor|dist|build|\.next|coverage|__pycache__)/'
19
- r'|\.min\.js$'
20
- r'|(?:^|/)package-lock\.json$'
21
- r'|(?:^|/)yarn\.lock$'
22
- r'|(?:^|/)poetry\.lock$'
23
- r'|\.snap$'
24
- )
25
-
26
- _SEP = '\x1f' # unit separator: safe delimiter for a commit-header line
27
- # \x1e (record separator) LEADS each commit's header, so splitting on it cleanly isolates
28
- # "previous commit's file list" from "next commit's header" -- a trailing separator would
29
- # instead glue this commit's file list to the next commit's header in the same split token.
30
- # Combined with `git log -z`, git NUL-terminates the format text itself (in place of the
31
- # newline it would otherwise emit) before the --name-only listing, and NUL-terminates each
32
- # filename too -- so a multi-line commit body (which freely contains '\n') can never be
33
- # confused with a newline-joined file list. NUL cannot appear in a commit message or path.
34
- _FORMAT = '\x1e' + _SEP.join(('%H', '%P', '%s', '%b'))
35
-
36
-
37
- def is_test(path: str) -> bool:
38
- return bool(TEST_PATTERN.search(path))
39
-
40
-
41
- def _is_vendor(path: str) -> bool:
42
- return bool(VENDOR_PATTERN.search(path))
43
-
44
-
45
- def classify(paths: list[str]) -> tuple[list[str], list[str]]:
46
- """Split into (source, test), dropping vendor paths from both."""
47
- source, test = [], []
48
- for path in paths:
49
- if _is_vendor(path):
50
- continue
51
- (test if is_test(path) else source).append(path)
52
- return source, test
53
-
54
-
55
- def _run(repo, argv: list[str]) -> str:
56
- result = subprocess.run(['git', '-C', str(repo), *argv], stdout=subprocess.PIPE,
57
- stderr=subprocess.PIPE, timeout=120)
58
- if result.returncode:
59
- return ''
60
- return result.stdout.decode(errors='replace')
61
-
62
-
63
- def _parent_tree_tests(repo, parent: str, cache: dict[str, set[str]]) -> set[str]:
64
- """Test files present in the tree AT the parent commit (empty set if parent has none, or lookup fails)."""
65
- if parent in cache:
66
- return cache[parent]
67
- out = _run(repo, ['ls-tree', '-r', '--name-only', parent])
68
- lines = [line for line in out.split('\n') if line]
69
- tests = {line for line in lines if is_test(line) and not _is_vendor(line)}
70
- cache[parent] = tests
71
- return tests
72
-
73
-
74
- def commits(repo, *, limit: int | None = None, max_files: int = 60) -> Iterator[dict]:
75
- """Yield one corpus record per usable commit, newest first."""
76
- log = _run(repo, ['log', '--no-merges', '--name-only', '-z', f'--format={_FORMAT}', 'HEAD'])
77
- if not log:
78
- return
79
-
80
- tree_cache: dict[str, set[str]] = {}
81
- yielded = 0
82
- for block in log.split('\x1e'):
83
- if not block:
84
- continue
85
- header, sep, filelist = block.partition('\x00')
86
- if not sep:
87
- continue
88
- parts = header.split(_SEP)
89
- if len(parts) < 3:
90
- continue
91
- sha, parents, subject = parts[0], parts[1], parts[2]
92
- body = (parts[3].rstrip('\n') if len(parts) > 3 else '')
93
- parent_list = parents.split()
94
- if len(parent_list) != 1:
95
- continue # no parent (root commit) or already excluded by --no-merges; be defensive anyway
96
- parent = parent_list[0]
97
-
98
- changed = [f for f in filelist.lstrip('\n').split('\x00') if f]
99
- if not changed or len(changed) > max_files:
100
- continue
101
-
102
- source_files, test_files = classify(changed)
103
- if not source_files or not test_files:
104
- continue
105
-
106
- candidate_tests = _parent_tree_tests(repo, parent, tree_cache)
107
- if not candidate_tests:
108
- continue
109
-
110
- n_test_created = 0
111
- kept_tests = []
112
- for path in test_files:
113
- if path in candidate_tests:
114
- kept_tests.append(path)
115
- else:
116
- n_test_created += 1
117
- if not kept_tests:
118
- continue
119
-
120
- candidates = sorted(candidate_tests)
121
- record = dict(
122
- repo=str(repo),
123
- sha=sha,
124
- parent=parent,
125
- subject=subject,
126
- body=body,
127
- source_files=source_files,
128
- test_files=sorted(kept_tests),
129
- all_changed=changed,
130
- candidates=candidates,
131
- stats=dict(n_source=len(source_files), n_test=len(kept_tests),
132
- n_candidates=len(candidates), n_test_created=n_test_created),
133
- )
134
- yield record
135
- yielded += 1
136
- if limit is not None and yielded >= limit:
137
- return
138
-
139
-
140
- def stats(records: list[dict]) -> dict:
141
- """Aggregate counts for a dry-run summary."""
142
- n = len(records)
143
- total_source = sum(r['stats']['n_source'] for r in records)
144
- total_test = sum(r['stats']['n_test'] for r in records)
145
- total_candidates = sum(r['stats']['n_candidates'] for r in records)
146
- total_created = sum(r['stats']['n_test_created'] for r in records)
147
- return dict(
148
- n_commits=n,
149
- total_source_files=total_source,
150
- total_test_files=total_test,
151
- total_candidates=total_candidates,
152
- total_test_created=total_created,
153
- avg_candidates=(total_candidates / n) if n else 0.0,
154
- avg_source_per_commit=(total_source / n) if n else 0.0,
155
- avg_test_per_commit=(total_test / n) if n else 0.0,
156
- )
@@ -1,24 +0,0 @@
1
- """Plain numeric features of a task, for a decision model that reads a routing state.
2
-
3
- A task's size is the strongest regime signal in forge's run history: the median prompt of
4
- the newest runs is twice the older ones' and their first-pass rate is half. A model reading
5
- prose and a 40-entry sibling list can only estimate that, so the state spells it out.
6
-
7
- The dataset export adds this block to the routing state it trains on. Hosted Jev's live
8
- request does not carry it (changing that request changes every fixture key), so a local
9
- model wired in later must send the same block, with the exact plan size and decompose
10
- level: the live state caps siblings at 40 and has no level. No I/O here; callers pass values.
11
- """
12
- from __future__ import annotations
13
-
14
-
15
- def _count(value) -> int:
16
- if isinstance(value, (list, tuple)):
17
- return len([v for v in value if v])
18
- return len([w for w in str(value or '').replace(',', ' ').split() if w and w != '-'])
19
-
20
-
21
- def task_size(*, prompt: str, declared_files, plan_tasks: int, deps, decompose_level: str | None) -> dict:
22
- return dict(prompt_chars=len(prompt or ''), declared_files=_count(declared_files),
23
- plan_tasks=int(plan_tasks), deps=_count(deps),
24
- decompose_level=decompose_level if decompose_level in ('low', 'medium', 'high') else None)