@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.
Files changed (117) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +31 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +18 -6
  7. package/docs/commands.md +189 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +34 -4
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +81 -19
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +40 -14
  17. package/references/decision-models.md +759 -0
  18. package/references/decompose.md +197 -28
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/references/ui.md +11 -0
  23. package/scripts/forge-artifact.sh +30 -4
  24. package/scripts/forge-config.py +238 -29
  25. package/scripts/forge-contract.py +127 -58
  26. package/scripts/forge-control.py +40 -9
  27. package/scripts/forge-decide.py +6 -0
  28. package/scripts/forge-dispatch.sh +47 -15
  29. package/scripts/forge-fail-first.py +2 -2
  30. package/scripts/forge-gate-addressed.sh +40 -0
  31. package/scripts/forge-gate-message.sh +64 -0
  32. package/scripts/forge-issues.py +368 -36
  33. package/scripts/forge-jev-options.sh +269 -42
  34. package/scripts/forge-lib-attribute.sh +447 -0
  35. package/scripts/forge-lib-gates.sh +32 -0
  36. package/scripts/forge-lib-plans.sh +17 -6
  37. package/scripts/forge-lib-review.sh +24 -19
  38. package/scripts/forge-lib-task.sh +219 -39
  39. package/scripts/forge-lib-verify.sh +45 -8
  40. package/scripts/forge-memory.sh +3 -3
  41. package/scripts/forge-parallel-options.sh +44 -5
  42. package/scripts/forge-parallel.sh +503 -304
  43. package/scripts/forge-plan-check.py +35 -1
  44. package/scripts/forge-pre-review.py +437 -0
  45. package/scripts/forge-prompt.py +25 -5
  46. package/scripts/forge-route.py +2 -2
  47. package/scripts/forge-runtime.py +55 -1
  48. package/scripts/forge-schedule.py +70 -9
  49. package/scripts/forge-shadow.py +2 -2
  50. package/scripts/forge-solo.sh +41 -10
  51. package/scripts/forge-submodules.py +389 -0
  52. package/scripts/forge-sweep.py +542 -0
  53. package/scripts/forge_dataset/cli.py +12 -6
  54. package/scripts/forge_dataset/export.py +55 -45
  55. package/scripts/forge_dataset/forecast.py +4 -1
  56. package/scripts/forge_dataset/harvest.py +33 -5
  57. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  58. package/scripts/forge_decide/__init__.py +141 -0
  59. package/scripts/forge_decide/budget.py +149 -0
  60. package/scripts/forge_decide/cache.py +66 -0
  61. package/scripts/forge_decide/cli.py +953 -0
  62. package/scripts/forge_decide/doctor.py +221 -0
  63. package/scripts/forge_decide/label_addressed.py +75 -0
  64. package/scripts/forge_decide/label_attribution.py +62 -0
  65. package/scripts/forge_decide/label_coverage.py +81 -0
  66. package/scripts/forge_decide/label_message.py +38 -0
  67. package/scripts/forge_decide/label_prompt.py +139 -0
  68. package/scripts/forge_decide/labels.py +328 -0
  69. package/scripts/forge_decide/metrics.py +125 -0
  70. package/scripts/forge_decide/migrate.py +226 -0
  71. package/scripts/forge_decide/providers.py +292 -0
  72. package/scripts/forge_decide/replay.py +350 -0
  73. package/scripts/forge_decide/report.py +382 -0
  74. package/scripts/forge_decide/resolve.py +397 -0
  75. package/scripts/forge_decide/sites.py +377 -0
  76. package/scripts/forge_jev/__init__.py +202 -104
  77. package/scripts/forge_jev/addressed.py +171 -0
  78. package/scripts/forge_jev/attribution.py +198 -0
  79. package/scripts/forge_jev/cli.py +460 -382
  80. package/scripts/forge_jev/client.py +155 -77
  81. package/scripts/forge_jev/coupling.py +19 -87
  82. package/scripts/forge_jev/coverage.py +303 -0
  83. package/scripts/forge_jev/findings.py +219 -0
  84. package/scripts/forge_jev/gates.py +225 -27
  85. package/scripts/forge_jev/memory.py +65 -4
  86. package/scripts/forge_jev/message.py +134 -0
  87. package/scripts/forge_jev/plan_gates.py +294 -0
  88. package/scripts/forge_jev/questions.py +173 -313
  89. package/scripts/forge_jev/verify.py +130 -104
  90. package/ui/README.md +41 -10
  91. package/ui/docs/api.md +212 -44
  92. package/ui/forge_ui/checks.py +331 -0
  93. package/ui/forge_ui/control.py +60 -11
  94. package/ui/forge_ui/export.py +8 -3
  95. package/ui/forge_ui/models.py +1 -0
  96. package/ui/forge_ui/reader.py +436 -26
  97. package/ui/forge_ui/server.py +13 -0
  98. package/ui/forge_ui/static/app.js +15 -8
  99. package/ui/forge_ui/static/checksview.js +449 -0
  100. package/ui/forge_ui/static/controls.js +20 -13
  101. package/ui/forge_ui/static/convo.js +11 -2
  102. package/ui/forge_ui/static/findingsview.js +6 -4
  103. package/ui/forge_ui/static/index.html +1 -0
  104. package/ui/forge_ui/static/panel.js +105 -17
  105. package/ui/forge_ui/static/runmodel.js +40 -2
  106. package/ui/forge_ui/static/scene3d.js +2 -15
  107. package/ui/forge_ui/static/settings.js +336 -41
  108. package/ui/forge_ui/static/style.css +72 -7
  109. package/ui/forge_ui/transcripts.py +225 -54
  110. package/references/jev.md +0 -865
  111. package/scripts/forge_jev/backtest.py +0 -322
  112. package/scripts/forge_jev/corpus.py +0 -156
  113. package/scripts/forge_jev/features.py +0 -24
  114. package/scripts/forge_jev/predict.py +0 -204
  115. package/scripts/forge_jev/review.py +0 -73
  116. package/scripts/forge_jev/routing.py +0 -271
  117. package/scripts/forge_jev/subset.py +0 -123
@@ -6,6 +6,16 @@
6
6
  the tasks whose prompt.md has no acceptance criteria. Prints nothing when every task is
7
7
  fine. Exit status is always 0.
8
8
 
9
+ forge-plan-check.py gates PLAN
10
+ Prints the decision-model gate block (what drift, forward, prompt and coverage did to this
11
+ plan) from PLAN/plan-gates.json. Prints nothing when no gate recorded anything.
12
+
13
+ forge-plan-check.py sendback PLAN
14
+ Writes PLAN/plan.sendback.md from the items the gates marked in this `plan` call and prints
15
+ it, exiting 4. Prints nothing and exits 0 when nothing was marked.
16
+
17
+ Both of the last two print nothing and exit 0 if forge_jev.plan_gates cannot be imported.
18
+
9
19
  Why these two: in forge's run history (269 first attempts, measured 2026-10-17) the share of
10
20
  first attempts a reviewer passed falls steadily with prompt length (62% under 3K characters,
11
21
  51% at 5-7K, 33% at 7-10K, 23% at 14K and over) and with declared files (68% at 2, 29% at 9
@@ -20,7 +30,7 @@ import sys
20
30
  from pathlib import Path
21
31
 
22
32
  sys.path.insert(0, str(Path(__file__).resolve().parent))
23
- from forge_jev.features import task_size # noqa: E402
33
+ from forge_dataset.states import task_size # noqa: E402
24
34
 
25
35
  LARGE_CHARS = 7000
26
36
  LARGE_FILES = 9
@@ -96,12 +106,36 @@ def size_notes(plan: Path) -> list:
96
106
  return notes
97
107
 
98
108
 
109
+ def plan_gates():
110
+ try:
111
+ from forge_jev import plan_gates as module
112
+ except Exception:
113
+ return None
114
+ return module
115
+
116
+
99
117
  def main(argv=None) -> int:
100
118
  ap = argparse.ArgumentParser(prog='forge-plan-check.py')
101
119
  sub = ap.add_subparsers(dest='command', required=True)
102
120
  p = sub.add_parser('size')
103
121
  p.add_argument('--plan', required=True)
122
+ for name in ('gates', 'sendback'):
123
+ sub.add_parser(name).add_argument('plan')
104
124
  args = ap.parse_args(argv)
125
+ if args.command in ('gates', 'sendback'):
126
+ module = plan_gates()
127
+ if module is None:
128
+ return 0
129
+ try:
130
+ if args.command == 'gates':
131
+ for line in module.marks(args.plan):
132
+ print(line)
133
+ elif module.sendback(args.plan):
134
+ sys.stdout.write((Path(args.plan) / module.SENDBACK_FILE).read_text())
135
+ return 4
136
+ except Exception:
137
+ return 0
138
+ return 0
105
139
  try:
106
140
  notes = size_notes(Path(args.plan))
107
141
  except Exception:
@@ -0,0 +1,437 @@
1
+ #!/usr/bin/env python3
2
+ """Pre-review tests: run only the tests an attempt affects before paying for its review (#85).
3
+
4
+ forge-pre-review.py run --repo <review snapshot> --base <commit> --reviewed <commit>
5
+ --command '<test command with {files} and/or {changed}>'
6
+ --out <prereview.json> --report <prereview.md>
7
+ [--map <.forge/test-map>] [--deps-from <dir>] [--max-files N]
8
+ [--timeout S] [--slots-dir <dir> --slots N] [--log <file>]
9
+ forge-pre-review.py select --repo <dir> --base <commit> --reviewed <commit> [--map <file>]
10
+ [--max-files N]
11
+
12
+ Opt-in (`plan --pre-review-tests`). Never the whole suite. The selection, in order:
13
+
14
+ 1. the test files the change adds or edits;
15
+ 2. for each changed source file, the tests from the first of these that answers:
16
+ `.forge/test-map` (one rule per line: a source glob, then test paths or globs; `-` for
17
+ "no tests"), the naming convention (foo.py -> test_foo.py, foo_test.py, foo.test.js, ...),
18
+ then a reverse lookup (test files that name the changed module);
19
+ 3. with `{changed}` in the command, the changed paths themselves, for a runner that finds
20
+ the related tests on its own (`jest --findRelatedTests {changed}`, `go test`, ...).
21
+
22
+ A change to shared test infrastructure (a conftest, a test helper, a lockfile, a build file),
23
+ more than --max-files selected files, or a run past --timeout makes the check `skipped` (too
24
+ broad): the end-of-run verification is where those belong.
25
+
26
+ The outcome, and the exit code the caller acts on:
27
+
28
+ passed (0) every selected test passed
29
+ flaky (0) the run failed, but every failing file passed when rerun alone
30
+ pre-existing (0) every test that fails here fails on the task base too
31
+ failed (1) a test fails on this attempt and not on the task base (or is new): the
32
+ attempt goes back to the implementer without a review; --report holds
33
+ the failing tests and the end of their output, labelled as forge's
34
+ skipped/error (0) nothing to run, too broad, no command, or the check itself broke
35
+
36
+ stdout is the reviewer's evidence section (empty when there is none); --report is written
37
+ only for `failed`; --log gets one `<epoch> <TAB> <status> <TAB> <seconds>` line per check, which the
38
+ run summary totals. The review snapshot is only read: every run happens in a throwaway export
39
+ made through a private index, so no fingerprint changes. Exit 2 is a usage error.
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import argparse
44
+ import fnmatch
45
+ import importlib.util
46
+ import json
47
+ import os
48
+ from pathlib import Path
49
+ import re
50
+ import shlex
51
+ import shutil
52
+ import subprocess
53
+ import sys
54
+ import tempfile
55
+ import time
56
+
57
+ _SPEC = importlib.util.spec_from_file_location('forge_fail_first', Path(__file__).resolve().parent / 'forge-fail-first.py')
58
+ failfirst = importlib.util.module_from_spec(_SPEC)
59
+ _SPEC.loader.exec_module(failfirst)
60
+
61
+ MAX_FILES = 20
62
+ TIMEOUT_S = 120.0
63
+ SLOTS = 2
64
+ TAIL = 3000
65
+ READ_LIMIT = 1 << 20 # a test file larger than this is not searched by the reverse lookup
66
+
67
+ # A test file by name: what a runner picks up as a test, as opposed to a helper or fixture
68
+ # that lives beside the tests.
69
+ TEST_NAME = re.compile(r'(^|/)test_[^/]*$|(^|/)[^/]*_test\.[^/]+$|(^|/)[^/]*\.(test|spec)\.[^/]+$'
70
+ r'|(^|/)[^/]*_spec\.[^/]+$|(^|/)__tests__/')
71
+ # Shared infrastructure: a change here can break any test, so no selection is honest.
72
+ INFRA_NAMES = {
73
+ 'conftest.py', 'pytest.ini', 'tox.ini', 'setup.cfg', 'setup.py', 'pyproject.toml', 'noxfile.py',
74
+ 'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'npm-shrinkwrap.json', 'bun.lockb',
75
+ 'tsconfig.json', 'babel.config.js', 'Cargo.toml', 'Cargo.lock', 'go.mod', 'go.sum', 'Gemfile',
76
+ 'Gemfile.lock', 'poetry.lock', 'uv.lock', 'Pipfile', 'Pipfile.lock', 'requirements.txt', 'Makefile',
77
+ 'CMakeLists.txt', 'build.gradle', 'build.gradle.kts', 'settings.gradle', 'pom.xml', 'composer.json',
78
+ 'composer.lock', 'Dockerfile',
79
+ }
80
+ INFRA_PATTERNS = ('jest.config.*', 'vitest.config.*', 'karma.conf.*', 'webpack.config.*', 'vite.config.*',
81
+ 'requirements*.txt', '.babelrc*')
82
+
83
+
84
+ def is_test(path: str) -> bool:
85
+ return bool(failfirst.TEST_PATH.search(path)) and bool(TEST_NAME.search(path)) and path.endswith(failfirst.CODE_SUFFIXES)
86
+
87
+
88
+ def is_infra(path: str) -> bool:
89
+ """Shared test infrastructure: a build or lock file, or code under a test directory that is not a test."""
90
+ name = path.rsplit('/', 1)[-1]
91
+ if name in INFRA_NAMES or any(fnmatch.fnmatch(name, pattern) for pattern in INFRA_PATTERNS):
92
+ return True
93
+ return bool(failfirst.TEST_PATH.search(path)) and path.endswith(failfirst.CODE_SUFFIXES) and not is_test(path)
94
+
95
+
96
+ def read_map(path) -> list:
97
+ """[(source glob, [test globs])] from a .forge/test-map; `-` alone means "no tests"."""
98
+ rules = []
99
+ try:
100
+ text = Path(path).read_text(encoding='utf-8', errors='replace') if path else ''
101
+ except OSError:
102
+ return rules
103
+ for line in text.splitlines():
104
+ line = line.split('#', 1)[0].strip()
105
+ if not line:
106
+ continue
107
+ parts = line.split()
108
+ if len(parts) >= 2:
109
+ rules.append((parts[0], [p for p in parts[1:] if p != '-']))
110
+ return rules
111
+
112
+
113
+ def _stems(path: str) -> list:
114
+ """The names a test would use for a source file: its stem, with - and _ both ways; a
115
+ package's __init__ goes by its directory."""
116
+ name = path.rsplit('/', 1)[-1]
117
+ stem = name.split('.', 1)[0]
118
+ if stem in ('__init__', 'index', 'mod', 'lib') and '/' in path:
119
+ stem = path.rsplit('/', 2)[-2]
120
+ out = [stem]
121
+ for variant in (stem.replace('-', '_'), stem.replace('_', '-')):
122
+ if variant not in out:
123
+ out.append(variant)
124
+ return [s for s in out if len(s) >= 3]
125
+
126
+
127
+ def by_convention(path: str, tests: list) -> list:
128
+ names = set()
129
+ for stem in _stems(path):
130
+ names |= {'test_' + stem, stem + '_test', stem + '.test', stem + '.spec', stem + '_spec'}
131
+ found = []
132
+ for test in tests:
133
+ base = test.rsplit('/', 1)[-1]
134
+ for suffix in failfirst.CODE_SUFFIXES:
135
+ if base.endswith(suffix) and base[:-len(suffix)] in names:
136
+ found.append(test)
137
+ break
138
+ return found
139
+
140
+
141
+ def by_reference(path: str, tests: list, root: Path) -> list:
142
+ """Test files that name the changed module (an import, a require, a path in a string)."""
143
+ patterns = [re.compile(r'(?<![\w-])' + re.escape(stem) + r'(?![\w-])') for stem in _stems(path)]
144
+ found = []
145
+ for test in tests:
146
+ file = root / test
147
+ try:
148
+ if file.stat().st_size > READ_LIMIT:
149
+ continue
150
+ text = file.read_text(encoding='utf-8', errors='replace')
151
+ except OSError:
152
+ continue
153
+ if any(p.search(text) for p in patterns):
154
+ found.append(test)
155
+ return found
156
+
157
+
158
+ def tree_files(repo, commit) -> list:
159
+ out = failfirst._git(repo, 'ls-tree', '-r', '-z', '--name-only', commit)
160
+ return [p for p in out.decode('utf-8', 'surrogateescape').split('\0') if p]
161
+
162
+
163
+ def select(repo, base, reviewed, root: Path, map_path=None, max_files=MAX_FILES) -> dict:
164
+ """What to run, and why; `too_broad` set when the check must not run at all."""
165
+ changes = [(s, p) for s, p in failfirst.changed_paths(repo, base, reviewed) if not p.startswith('.forge/')]
166
+ files = tree_files(repo, reviewed)
167
+ tests = [p for p in files if is_test(p)]
168
+ selected, why = [], {}
169
+
170
+ def add(path, reason):
171
+ if path not in why:
172
+ selected.append(path)
173
+ why[path] = reason
174
+
175
+ result = dict(changed=[p for s, p in changes if s != 'D'], selected=selected, why=why, too_broad=None,
176
+ unmatched=[])
177
+ infra = [p for _s, p in changes if is_infra(p)]
178
+ if infra:
179
+ result['too_broad'] = 'the change touches shared test infrastructure: ' + ', '.join(infra[:5])
180
+ return result
181
+ for status, path in changes:
182
+ if status != 'D' and is_test(path):
183
+ add(path, 'changed')
184
+ rules = read_map(map_path)
185
+ present = set(files)
186
+ for status, path in changes:
187
+ if is_test(path) or failfirst.TEST_PATH.search(path) or not path.endswith(failfirst.CODE_SUFFIXES):
188
+ continue # tests are already in; docs, data and fixtures name no tests
189
+ matched = [globs for source, globs in rules if fnmatch.fnmatch(path, source)]
190
+ if matched:
191
+ for globs in matched:
192
+ for pattern in globs:
193
+ for test in sorted(p for p in present if fnmatch.fnmatch(p, pattern)):
194
+ add(test, 'map: ' + path)
195
+ continue
196
+ found = by_convention(path, tests) or by_reference(path, tests, root)
197
+ how = 'convention' if found and found == by_convention(path, tests) else 'reference'
198
+ for test in found:
199
+ add(test, how + ': ' + path)
200
+ if not found:
201
+ result['unmatched'].append(path)
202
+ if len(selected) > max_files:
203
+ result['too_broad'] = '%d test files selected, more than the cap of %d' % (len(selected), max_files)
204
+ return result
205
+
206
+
207
+ # --- running -------------------------------------------------------------------------
208
+ def _fill(command: str, files: list, changed: list) -> str:
209
+ return (command.replace('{files}', ' '.join(shlex.quote(f) for f in files))
210
+ .replace('{changed}', ' '.join(shlex.quote(c) for c in changed)))
211
+
212
+
213
+ class Slot:
214
+ """One of N machine-wide run slots under a directory, so parallel tasks do not run N suites
215
+ at once. A slot whose holder is gone is taken over."""
216
+
217
+ def __init__(self, directory, count):
218
+ self.directory, self.count, self.path = Path(directory) if directory else None, max(1, count), None
219
+
220
+ def __enter__(self):
221
+ if self.directory is None:
222
+ return self
223
+ self.directory.mkdir(parents=True, exist_ok=True)
224
+ while True:
225
+ for n in range(self.count):
226
+ path = self.directory / ('slot-%d' % n)
227
+ try:
228
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
229
+ except FileExistsError:
230
+ try:
231
+ os.kill(int(path.read_text().strip() or 0), 0)
232
+ except (ProcessLookupError, ValueError):
233
+ path.unlink(missing_ok=True) # its holder is gone
234
+ except (OSError, PermissionError):
235
+ pass
236
+ continue
237
+ with os.fdopen(fd, 'w') as handle:
238
+ handle.write(str(os.getpid()))
239
+ self.path = path
240
+ return self
241
+ time.sleep(0.5)
242
+
243
+ def __exit__(self, *exc):
244
+ if self.path:
245
+ self.path.unlink(missing_ok=True)
246
+
247
+
248
+ def evaluate(repo, base, reviewed, command, map_path=None, deps_from=None, max_files=MAX_FILES,
249
+ timeout=TIMEOUT_S, slots_dir=None, slots=SLOTS) -> dict:
250
+ result = dict(version=1, status='skipped', reason=None, command=command, selected=[], why={},
251
+ changed=[], runs=[], failing=[], preexisting=[], flaky=[], started=time.time())
252
+ if '{files}' not in command and '{changed}' not in command:
253
+ result['reason'] = 'no test command: put one with {files} or {changed} in .forge/verify-subset'
254
+ return result
255
+ work = Path(tempfile.mkdtemp(prefix='forge-prereview-'))
256
+ try:
257
+ here = work / 'reviewed'
258
+ failfirst.export(repo, reviewed, here, deps_from=deps_from)
259
+ chosen = select(repo, base, reviewed, here, map_path, max_files)
260
+ result.update(selected=chosen['selected'], why=chosen['why'], changed=chosen['changed'],
261
+ unmatched=chosen['unmatched'])
262
+ if chosen['too_broad']:
263
+ result['reason'] = 'too broad: ' + chosen['too_broad']
264
+ return result
265
+ uses_files = '{files}' in command
266
+ if uses_files and not chosen['selected']:
267
+ result['reason'] = 'no test covers the change'
268
+ return result
269
+ if not uses_files and not chosen['changed']:
270
+ result['reason'] = 'the change has no paths to pass to {changed}'
271
+ return result
272
+ if not uses_files and len(chosen['changed']) > max_files:
273
+ result['reason'] = 'too broad: %d changed paths, more than the cap of %d' % (len(chosen['changed']), max_files)
274
+ return result
275
+ deadline = time.monotonic() + timeout
276
+ with Slot(slots_dir, slots):
277
+ outcome = _run(result, command, chosen, here, work, repo, base, deps_from, deadline)
278
+ result.update(outcome)
279
+ except (OSError, subprocess.SubprocessError) as error:
280
+ result.update(status='error', reason=('the check could not run: %s' % error)[:500])
281
+ finally:
282
+ shutil.rmtree(work, ignore_errors=True)
283
+ result['ended'] = time.time()
284
+ return result
285
+
286
+
287
+ def _run(result, command, chosen, here, work, repo, base, deps_from, deadline) -> dict:
288
+ def left():
289
+ return deadline - time.monotonic()
290
+
291
+ def run(kind, line, cwd, path=None):
292
+ if left() <= 0:
293
+ return None
294
+ done = failfirst.run_one(line, cwd, left())
295
+ done.update(kind=kind, path=path)
296
+ result['runs'].append(done)
297
+ return done
298
+
299
+ uses_files = '{files}' in command
300
+ files, changed = chosen['selected'], chosen['changed']
301
+ first = run('all', _fill(command, files, changed), here)
302
+ if first is None or first['rc'] is None:
303
+ if first is not None and first['tail'] != 'timed out':
304
+ return dict(status='error', reason='the test command could not run: ' + first['tail'][-200:])
305
+ return dict(status='skipped', reason='too broad: the selected tests took longer than %ds' % int(TIMEOUT_S if first is None else first['seconds']))
306
+ if first['rc'] == 0:
307
+ return dict(status='passed')
308
+ # Which files fail on their own: the rest failed only together, or only that once (flaky).
309
+ if uses_files:
310
+ failing = []
311
+ for path in files:
312
+ alone = run('alone', _fill(command, [path], changed), here, path)
313
+ if alone is None:
314
+ return dict(status='skipped', reason='too broad: no time left to rerun the failing tests')
315
+ if alone['rc'] != 0:
316
+ failing.append(path)
317
+ else:
318
+ again = run('again', _fill(command, files, changed), here)
319
+ if again is None:
320
+ return dict(status='skipped', reason='too broad: no time left to rerun the failing tests')
321
+ failing = ['{changed}'] if again['rc'] != 0 else []
322
+ if not failing:
323
+ return dict(status='flaky', flaky=list(files) if uses_files else ['{changed}'])
324
+ # A test that fails on the task base too was red before this attempt: not its fault.
325
+ at_base = set(tree_files(repo, base))
326
+ old = work / 'base'
327
+ failfirst.export(repo, base, old, deps_from=deps_from)
328
+ blamed, preexisting = [], []
329
+ for path in failing:
330
+ if path == '{changed}':
331
+ present = [c for c in changed if c in at_base]
332
+ done = run('base', _fill(command, files, present), old) if present else None
333
+ else:
334
+ done = run('base', _fill(command, [path], changed), old, path) if path in at_base else None
335
+ (preexisting if done is not None and done['rc'] not in (0, None) else blamed).append(path)
336
+ if blamed:
337
+ return dict(status='failed', failing=blamed, preexisting=preexisting)
338
+ return dict(status='pre-existing', preexisting=preexisting)
339
+
340
+
341
+ # --- what people read ------------------------------------------------------------------
342
+ def _tail(result) -> str:
343
+ for run in reversed(result['runs']):
344
+ if run['kind'] in ('alone', 'again', 'all') and run['rc'] not in (0, None):
345
+ return run['tail'][-TAIL:]
346
+ return ''
347
+
348
+
349
+ def report(result) -> str:
350
+ """The retry findings of a `failed` check: what the implementer gets instead of a review."""
351
+ lines = ['Pre-review tests (observed by forge, not by a reviewer): forge ran the tests this attempt',
352
+ 'affects before dispatching a review, and they failed, so no reviewer was asked.',
353
+ 'Command: ' + result['command'],
354
+ 'Failing on this attempt (they pass on the task base, or are new):']
355
+ lines += [' - ' + path for path in result['failing']]
356
+ if result['preexisting']:
357
+ lines += ['Failing on the task base too (not caused by this attempt):']
358
+ lines += [' - ' + path for path in result['preexisting']]
359
+ lines += ['', 'End of the output:', '```', _tail(result).rstrip(), '```', '',
360
+ 'Fix these failures; the review runs once they pass.']
361
+ return '\n'.join(lines) + '\n'
362
+
363
+
364
+ def evidence(result) -> str:
365
+ """What the reviewer reads; empty when nothing ran."""
366
+ status = result['status']
367
+ if status not in ('passed', 'flaky', 'pre-existing'):
368
+ return ''
369
+ ran = result['selected'] or ['(the runner\'s related tests for the changed paths)']
370
+ lines = ['Pre-review tests (observed by forge, not claimed by the implementer): before this review,',
371
+ 'forge ran the tests this change affects on the reviewed tree.',
372
+ 'Command: ' + result['command']]
373
+ if status == 'passed':
374
+ lines.append('All passed: ' + ', '.join(ran))
375
+ elif status == 'flaky':
376
+ lines.append('The run failed once, then every test passed when rerun alone (flaky): ' + ', '.join(ran))
377
+ else:
378
+ lines.append('Some fail, but they fail on the task base too, so this change did not cause them:')
379
+ lines += [' - ' + path for path in result['preexisting']]
380
+ lines.append('Run further tests only where these do not cover the change.')
381
+ return '\n'.join(lines) + '\n'
382
+
383
+
384
+ def main(argv=None) -> int:
385
+ parser = argparse.ArgumentParser(prog='forge-pre-review.py')
386
+ sub = parser.add_subparsers(dest='cmd', required=True)
387
+ for name in ('run', 'select'):
388
+ p = sub.add_parser(name)
389
+ p.add_argument('--repo', required=True)
390
+ p.add_argument('--base', required=True)
391
+ p.add_argument('--reviewed', required=True)
392
+ p.add_argument('--map')
393
+ p.add_argument('--max-files', type=int, default=int(os.environ.get('FORGE_PRE_REVIEW_MAX_FILES') or MAX_FILES))
394
+ if name == 'run':
395
+ p.add_argument('--command', default='')
396
+ p.add_argument('--out', required=True)
397
+ p.add_argument('--report', required=True)
398
+ p.add_argument('--deps-from')
399
+ p.add_argument('--timeout', type=float, default=float(os.environ.get('FORGE_PRE_REVIEW_TIMEOUT') or TIMEOUT_S))
400
+ p.add_argument('--slots-dir')
401
+ p.add_argument('--slots', type=int, default=SLOTS)
402
+ p.add_argument('--log')
403
+ args = parser.parse_args(argv)
404
+ if args.cmd == 'select':
405
+ work = Path(tempfile.mkdtemp(prefix='forge-prereview-'))
406
+ try:
407
+ failfirst.export(args.repo, args.reviewed, work / 'reviewed')
408
+ chosen = select(args.repo, args.base, args.reviewed, work / 'reviewed', args.map, max(1, args.max_files))
409
+ finally:
410
+ shutil.rmtree(work, ignore_errors=True)
411
+ print(json.dumps(chosen, indent=1))
412
+ return 0
413
+ try:
414
+ result = evaluate(args.repo, args.base, args.reviewed, args.command.strip(), args.map, args.deps_from,
415
+ max(1, args.max_files), max(1.0, args.timeout), args.slots_dir, args.slots)
416
+ except Exception as error: # the gate never blocks on its own failure
417
+ result = dict(version=1, status='error', reason=str(error)[:500], command=args.command, selected=[],
418
+ runs=[], failing=[], preexisting=[], flaky=[])
419
+ result['seconds'] = round(sum(r.get('seconds') or 0 for r in result.get('runs', [])), 3)
420
+ try:
421
+ Path(args.out).write_text(json.dumps(result, indent=1) + '\n', encoding='utf-8')
422
+ if result['status'] == 'failed':
423
+ Path(args.report).write_text(report(result), encoding='utf-8')
424
+ except OSError:
425
+ pass
426
+ if args.log:
427
+ try:
428
+ with open(args.log, 'a', encoding='utf-8') as log:
429
+ log.write('%d\t%s\t%.3f\n' % (time.time(), result['status'], result['seconds']))
430
+ except OSError:
431
+ pass
432
+ sys.stdout.write(evidence(result))
433
+ return 1 if result['status'] == 'failed' else 0
434
+
435
+
436
+ if __name__ == '__main__':
437
+ sys.exit(main())
@@ -20,6 +20,17 @@ differ from the last round's. Then review the full task diff below: the changes
20
20
  round are where new problems are most likely."""
21
21
 
22
22
 
23
+ # The dwarf's heading for the retry findings, by where they came from (retry_findings.source).
24
+ # An unknown word reads as a review, as a plan from before the source existed does.
25
+ RETRY_HEADINGS = {
26
+ 'review': 'Your previous attempt was reviewed and rejected',
27
+ 'prereview': "Your previous attempt failed forge's tests before any review",
28
+ 'bounce': 'Your previous attempt left blocking review findings unaddressed',
29
+ 'message': 'Your previous attempt said it did not finish',
30
+ 'answer': 'The user answered your question',
31
+ }
32
+
33
+
23
34
  def read(path: str | None, errors: str = 'strict') -> str:
24
35
  if path and Path(path).is_file():
25
36
  with Path(path).open(newline="", errors=errors) as source:
@@ -33,8 +44,14 @@ def carried(text: str) -> str:
33
44
  return text.replace('```diff', '```text')
34
45
 
35
46
 
36
- def qa_round(findings: str, diff: str | None, span: str | None, stat: str | None, reply: str | None) -> str:
37
- parts = ['## Findings from the previous review round\n' + carried(findings).rstrip('\n') + '\n\n' + QA_ROUND_NOTE]
47
+ def qa_round(findings: str, diff: str | None, span: str | None, stat: str | None, reply: str | None,
48
+ source: str = 'review') -> str:
49
+ if source == 'review':
50
+ head = '## Findings from the previous review round\n'
51
+ else:
52
+ head = ('## forge sent the previous attempt back without a review (' + source
53
+ + '); what it was told:\n')
54
+ parts = [head + carried(findings).rstrip('\n') + '\n\n' + QA_ROUND_NOTE]
38
55
  # A git diff carries raw source bytes, so a file that is not UTF-8 must not abort the prompt.
39
56
  patch = read(diff, 'replace')
40
57
  if patch:
@@ -59,17 +76,19 @@ def context(
59
76
  requirements: str, approach: str | None = None, capsule: str | None = None,
60
77
  retry: str | None = None, goal: str | None = None, memories: tuple[str, ...] = (),
61
78
  role: str = 'dwarf', retry_diff: str | None = None, retry_range: str | None = None,
62
- retry_stat: str | None = None, reply: str | None = None,
79
+ retry_stat: str | None = None, reply: str | None = None, retry_source: str = 'review',
63
80
  ) -> str:
81
+ if retry_source not in RETRY_HEADINGS:
82
+ retry_source = 'review'
64
83
  chunks = []
65
84
  for title, path in [('Ownership and baseline', capsule), ('Overall goal', goal),
66
85
  ('Complete implementation requirements', requirements),
67
86
  ('Intended approach', approach),
68
- ('Your previous attempt was reviewed and rejected', retry)]:
87
+ (RETRY_HEADINGS[retry_source], retry)]:
69
88
  data = read(path) if path and Path(path).is_file() else ''
70
89
  if data:
71
90
  if role == 'qa' and path == retry:
72
- chunks.append(qa_round(data, retry_diff, retry_range, retry_stat, reply).rstrip('\n'))
91
+ chunks.append(qa_round(data, retry_diff, retry_range, retry_stat, reply, retry_source).rstrip('\n'))
73
92
  else:
74
93
  chunks.append('## ' + title + '\n' + data)
75
94
  # Memory injection emits headings and prose around bullet facts. Union only
@@ -97,6 +116,7 @@ if __name__ == '__main__':
97
116
  parser.add_argument('--retry-range')
98
117
  parser.add_argument('--retry-stat')
99
118
  parser.add_argument('--reply')
119
+ parser.add_argument('--retry-source', default='review')
100
120
  args = vars(parser.parse_args())
101
121
  args['memories'] = args.pop('memory')
102
122
  print(context(**args), end='')
@@ -75,8 +75,8 @@ from pathlib import Path
75
75
  TIERS = ('low', 'medium', 'high')
76
76
  SCRIPTS = Path(__file__).resolve().parent
77
77
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
78
- FAILED = ('FAIL', 'TIMEOUT') # a judgment against the spec that ran
79
- NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED') # say nothing about it
78
+ FAILED = ('FAIL', 'TIMEOUT', 'BOUNCED', 'INCOMPLETE') # a judgment against the spec that ran
79
+ NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT') # say nothing about it
80
80
  DEFAULT_ESCALATE_AFTER = 3
81
81
  DEFAULT_EFFORT = 'medium' # forge-dispatch.sh dwarf default
82
82
  LOCK_WAIT = 5.0 # seconds to wait for P/control.lock
@@ -9,6 +9,7 @@ import os
9
9
  from pathlib import Path
10
10
  import re
11
11
  import shutil
12
+ import signal
12
13
  import subprocess
13
14
  import sys
14
15
  import time
@@ -97,6 +98,57 @@ def phase(attempt: str, name: str, rc: str | None = None) -> None:
97
98
  write_json(path, data)
98
99
 
99
100
 
101
+ CLOCK_EVERY_S = 1.0
102
+ CLOCK_STOP_POLL_S = 0.05 # how soon the sampler notices `<out>.stop`
103
+
104
+
105
+ class _ClockStop(Exception):
106
+ pass
107
+
108
+
109
+ def clock(log: str, out: str, every: str | None = None) -> None:
110
+ """When the harness log grew: one `<epoch seconds> <bytes>` line in `out` for each sample that saw a new
111
+ size, the first at the start. codex's and grok's events carry no time of their own, so forge-ui times them
112
+ from this. Runs beside the harness until `<out>.stop` exists (dispatch creates it once the harness exited),
113
+ a TERM, or the dispatch that started it is gone, and ends with one last sample. A stop file, unlike a
114
+ signal, cannot arrive before the sampler is ready: one that starts late still records the log's final
115
+ size (#84). Advisory: nothing reads its exit."""
116
+ def stop(signum: int, frame: object) -> None:
117
+ raise _ClockStop()
118
+
119
+ signal.signal(signal.SIGTERM, stop)
120
+ signal.signal(signal.SIGINT, stop)
121
+ parent, period, last = os.getppid(), float(every) if every else CLOCK_EVERY_S, -1
122
+ stop_file = out + '.stop'
123
+
124
+ def sample() -> None:
125
+ nonlocal last
126
+ # A TERM waits until the line is whole: it is delivered when the mask is lifted.
127
+ signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
128
+ try:
129
+ size = os.stat(log).st_size
130
+ if size != last:
131
+ with open(out, 'a') as stream:
132
+ stream.write('%.3f %d\n' % (time.time(), size))
133
+ last = size
134
+ except OSError:
135
+ pass
136
+ finally:
137
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGTERM})
138
+
139
+ try:
140
+ while os.getppid() == parent and not os.path.exists(stop_file):
141
+ sample()
142
+ deadline = time.monotonic() + period
143
+ while time.monotonic() < deadline and not os.path.exists(stop_file):
144
+ time.sleep(min(CLOCK_STOP_POLL_S, period))
145
+ except _ClockStop:
146
+ pass
147
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
148
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
149
+ sample()
150
+
151
+
100
152
  def token_count(value: object) -> int | None:
101
153
  return value if type(value) is int and value >= 0 else None
102
154
 
@@ -254,7 +306,7 @@ def _finish(attempt: Path, root: Path, role: str, harness: str, rc: str) -> None
254
306
  session_path.unlink(missing_ok=True)
255
307
  if found is not None:
256
308
  session_path.write_text(found + '\n')
257
- for suffix in ('prompt', 'last', 'log', 'resolved', 'cmd', 'timedout', 'infra', 'orphans',
309
+ for suffix in ('prompt', 'last', 'log', 'clock', 'resolved', 'cmd', 'timedout', 'infra', 'orphans',
258
310
  'session', 'continue'):
259
311
  if suffix == 'prompt' and not prompt_ready:
260
312
  continue
@@ -621,6 +673,8 @@ def main() -> None:
621
673
  report(*args)
622
674
  elif command == 'classify':
623
675
  classify_command(*args)
676
+ elif command == 'clock':
677
+ clock(*args)
624
678
  else:
625
679
  raise ValueError('unknown runtime command: ' + command)
626
680
  except (OSError, ValueError, RuntimeError) as error: