@giamme/forge 0.22.0 → 0.23.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 (153) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +19 -12
  3. package/SKILL.md +137 -216
  4. package/VERSION +1 -1
  5. package/docs/README.md +2 -3
  6. package/docs/add-ons.md +5 -3
  7. package/docs/artifacts.md +17 -2
  8. package/docs/commands.md +85 -63
  9. package/docs/decomposed-runs.md +195 -21
  10. package/docs/development.md +11 -9
  11. package/docs/forge-ui.md +33 -4
  12. package/docs/install.md +37 -5
  13. package/docs/memory.md +6 -1
  14. package/docs/models.md +36 -10
  15. package/docs/reviews.md +44 -25
  16. package/docs/safety.md +27 -2
  17. package/docs/troubleshooting.md +7 -10
  18. package/forge +25 -4
  19. package/package.json +2 -1
  20. package/references/dataset.md +10 -9
  21. package/references/decompose-integration.md +337 -0
  22. package/references/decompose-opt-in.md +527 -0
  23. package/references/decompose-recovery.md +569 -0
  24. package/references/decompose-review.md +256 -0
  25. package/references/decompose.md +99 -1606
  26. package/references/findings.md +68 -0
  27. package/references/harnesses.md +7 -12
  28. package/references/memory.md +13 -2
  29. package/references/planning.md +48 -18
  30. package/references/ripwire.md +38 -13
  31. package/references/runtime.md +22 -33
  32. package/references/setup.md +90 -0
  33. package/references/solo.md +13 -42
  34. package/references/ui.md +12 -5
  35. package/registry.tsv +40 -22
  36. package/scripts/forge-artifact.sh +143 -12
  37. package/scripts/forge-compare.py +5 -15
  38. package/scripts/forge-config.py +14 -1
  39. package/scripts/forge-contract.py +216 -53
  40. package/scripts/forge-control.py +777 -54
  41. package/scripts/forge-dispatch.sh +95 -12
  42. package/scripts/forge-du.py +13 -3
  43. package/scripts/forge-handoff.py +221 -39
  44. package/scripts/forge-install-ripwire.sh +100 -24
  45. package/scripts/forge-install.sh +18 -32
  46. package/scripts/forge-issues.py +6 -4
  47. package/scripts/forge-jev-options.sh +3 -5
  48. package/scripts/forge-lib-adopt.sh +169 -5
  49. package/scripts/forge-lib-attribute.sh +10 -3
  50. package/scripts/forge-lib-decompose.sh +454 -0
  51. package/scripts/forge-lib-env.sh +21 -0
  52. package/scripts/forge-lib-group.sh +4 -1
  53. package/scripts/forge-lib-plans.sh +30 -18
  54. package/scripts/forge-lib-review.sh +28 -8
  55. package/scripts/forge-lib-task.sh +225 -56
  56. package/scripts/forge-lib-verify.sh +59 -10
  57. package/scripts/forge-memory.sh +81 -4
  58. package/scripts/forge-metrics.sh +4 -2
  59. package/scripts/forge-parallel-options.sh +23 -4
  60. package/scripts/forge-parallel.sh +447 -175
  61. package/scripts/forge-plan-check.py +71 -8
  62. package/scripts/forge-planner.py +303 -17
  63. package/scripts/forge-pr.py +9 -1
  64. package/scripts/forge-prompt.py +2 -2
  65. package/scripts/forge-review-links.py +248 -0
  66. package/scripts/forge-ripwire.py +234 -16
  67. package/scripts/forge-route.py +19 -27
  68. package/scripts/forge-runs-rm.py +92 -21
  69. package/scripts/forge-runs.py +46 -5
  70. package/scripts/forge-runtime.py +37 -12
  71. package/scripts/forge-schedule.py +124 -33
  72. package/scripts/forge-setup-stale.py +236 -0
  73. package/scripts/forge-setup.py +804 -0
  74. package/scripts/forge-shadow.py +2 -20
  75. package/scripts/forge-solo-lock.py +46 -0
  76. package/scripts/forge-solo.sh +33 -56
  77. package/scripts/forge-sweep.py +2 -1
  78. package/scripts/forge-ui.py +8 -1
  79. package/scripts/forge-update.sh +2 -2
  80. package/scripts/forge-verify.py +16 -1
  81. package/scripts/forge-version.py +13 -1
  82. package/scripts/forge-watch.py +7 -2
  83. package/scripts/forge_dataset/__init__.py +1 -1
  84. package/scripts/forge_dataset/capture.py +0 -34
  85. package/scripts/forge_dataset/checks.py +0 -1
  86. package/scripts/forge_dataset/cli.py +5 -1
  87. package/scripts/forge_dataset/export.py +28 -6
  88. package/scripts/forge_dataset/facts.py +1 -2
  89. package/scripts/forge_dataset/forecast.py +1 -1
  90. package/scripts/forge_dataset/harvest.py +107 -7
  91. package/scripts/forge_dataset/importer.py +3 -2
  92. package/scripts/forge_dataset/pairs.py +3 -3
  93. package/scripts/forge_dataset/reviewers.py +4 -3
  94. package/scripts/forge_dataset/routing.py +6 -3
  95. package/scripts/forge_dataset/tiers.py +1 -1
  96. package/scripts/forge_decide/__init__.py +1 -1
  97. package/scripts/forge_decide/profiles.py +11 -14
  98. package/scripts/forge_decompose.py +987 -0
  99. package/scripts/forge_groups/review.py +6 -1
  100. package/scripts/forge_jev/__init__.py +1 -1
  101. package/scripts/forge_jev/cli.py +10 -1
  102. package/scripts/forge_jev/gates.py +10 -1
  103. package/scripts/forge_jev/verify.py +10 -2
  104. package/scripts/forge_legacy.py +86 -0
  105. package/scripts/forge_memory_home.py +57 -0
  106. package/scripts/forge_models.py +151 -0
  107. package/scripts/forge_prefs.py +138 -0
  108. package/scripts/forge_side/__init__.py +10 -0
  109. package/scripts/forge_storage.py +28 -15
  110. package/ui/README.md +22 -10
  111. package/ui/docs/api.md +121 -99
  112. package/ui/forge_ui/control.py +46 -14
  113. package/ui/forge_ui/export.py +0 -10
  114. package/ui/forge_ui/models.py +15 -2
  115. package/ui/forge_ui/projects.py +4 -1
  116. package/ui/forge_ui/reader.py +456 -59
  117. package/ui/forge_ui/server.py +0 -10
  118. package/ui/forge_ui/static/app.js +28 -9
  119. package/ui/forge_ui/static/checksview.js +12 -3
  120. package/ui/forge_ui/static/controls.js +147 -11
  121. package/ui/forge_ui/static/convo.js +5 -2
  122. package/ui/forge_ui/static/diffview.js +4 -5
  123. package/ui/forge_ui/static/panel.js +180 -77
  124. package/ui/forge_ui/static/projectsview.js +16 -2
  125. package/ui/forge_ui/static/runmodel.js +18 -4
  126. package/ui/forge_ui/static/scene3d.js +29 -29
  127. package/ui/forge_ui/static/settings.js +1 -1
  128. package/ui/forge_ui/static/storageview.js +2 -2
  129. package/ui/forge_ui/static/style.css +23 -6
  130. package/ui/forge_ui/static/worktreesview.js +8 -4
  131. package/ui/forge_ui/transcripts.py +6 -0
  132. package/ui/forge_ui/worktrees.py +13 -1
  133. package/docs/fractal.md +0 -181
  134. package/references/fractal-dashboard.md +0 -21
  135. package/references/fractal.md +0 -307
  136. package/scripts/forge-fractal-dispatch.sh +0 -4
  137. package/scripts/forge-fractal-options.sh +0 -54
  138. package/scripts/forge-fractal.py +0 -6
  139. package/scripts/forge-install-fractal.sh +0 -4
  140. package/scripts/forge_fractal/__init__.py +0 -88
  141. package/scripts/forge_fractal/bridge.py +0 -46
  142. package/scripts/forge_fractal/cli.py +0 -224
  143. package/scripts/forge_fractal/dashboard.css +0 -138
  144. package/scripts/forge_fractal/dashboard.html +0 -41
  145. package/scripts/forge_fractal/dashboard.js +0 -687
  146. package/scripts/forge_fractal/decomposition.py +0 -262
  147. package/scripts/forge_fractal/execution.py +0 -659
  148. package/scripts/forge_fractal/inspection.py +0 -261
  149. package/scripts/forge_fractal/install.py +0 -158
  150. package/scripts/forge_fractal/invocation.py +0 -95
  151. package/scripts/forge_fractal/pipeline.py +0 -125
  152. package/scripts/forge_fractal/selection.py +0 -180
  153. package/ui/forge_ui/fractal.py +0 -582
@@ -0,0 +1,248 @@
1
+ #!/usr/bin/env python3
2
+ """Setup-generated and repo-configured ignored paths linked into review snapshots (#198).
3
+
4
+ Subcommands:
5
+ capture-before CHECKOUT OUT_FILE
6
+ capture-after CHECKOUT BEFORE_FILE [--out PATH] [--dep-dirs "a b ..."]
7
+ plan-extra SOURCE SNAPSHOT [--extra-file PATH] [--dep-dirs "a b ..."]
8
+
9
+ `capture-before` / `capture-after` record non-secret ignored paths created during
10
+ worktree setup (difference of `git status --ignored --porcelain -z` before and after)
11
+ into `<git-dir>/forge-setup-generated` (or `--out`).
12
+ `plan-extra` combines those paths with `<source>/.forge/review-links` (if present) and
13
+ optional `--extra-file`, filters secrets and paths already covered by dependency dirs
14
+ or committed in the snapshot, and prints tab-separated actions for `forge_review_deps`:
15
+ LINK_DIR<TAB><rel>
16
+ LINK_FILE<TAB><rel>
17
+ UNLINKED<TAB><rel>
18
+ Stdlib only. Cross-platform (Windows, macOS, Linux).
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ from pathlib import Path, PurePosixPath
24
+ import subprocess
25
+ import sys
26
+
27
+ DEFAULT_DEP_DIRS = (
28
+ 'node_modules', 'bower_components', '.venv', 'venv', 'vendor',
29
+ '.bundle', 'Pods', 'deps', '_build', '.dart_tool', 'elm-stuff', '.build',
30
+ )
31
+
32
+ _SECRET_EXACT = {
33
+ '.env', '.npmrc', '.pypirc', '.netrc', '.dockercfg', '.htpasswd',
34
+ '.git-credentials', 'credentials.json', 'secrets.json', 'secrets.yaml',
35
+ 'secrets.yml',
36
+ }
37
+ _SECRET_EXTS = (
38
+ '.pem', '.key', '.p12', '.pfx', '.jks', '.keystore', '.kdbx',
39
+ '.asc', '.gpg', '.secret', '.secrets',
40
+ )
41
+ _SECRET_PREFIXES = ('.env.', 'service-account', 'client_secret')
42
+
43
+
44
+ def normalize_rel(raw: str) -> str | None:
45
+ """Normalize a repo-relative path to POSIX form, or None if unsafe/empty."""
46
+ s = raw.replace('\\', '/').strip().rstrip('/')
47
+ while s.startswith('./'):
48
+ s = s[2:]
49
+ if not s or s.startswith('/') or (len(s) >= 2 and s[1] == ':'):
50
+ return None
51
+ parts = [p for p in s.split('/') if p and p != '.']
52
+ if not parts or any(p == '..' for p in parts):
53
+ return None
54
+ if parts[0] in ('.git', '.forge'):
55
+ return None
56
+ return '/'.join(parts)
57
+
58
+
59
+ def is_secret_path(rel: str) -> bool:
60
+ """Return True for filenames that commonly carry credentials or private keys."""
61
+ lower = PurePosixPath(rel).name.lower()
62
+ if lower in _SECRET_EXACT:
63
+ return True
64
+ if lower.startswith('.env.') or lower.endswith('.env'):
65
+ return True
66
+ if any(lower.endswith(ext) for ext in _SECRET_EXTS):
67
+ return True
68
+ if any(lower.startswith(pref) for pref in _SECRET_PREFIXES) and lower.endswith('.json'):
69
+ return True
70
+ return False
71
+
72
+
73
+ def has_dep_dir_component(rel: str, dep_dirs: set[str]) -> bool:
74
+ """Return True if `rel` is a dependency dir or lives inside one."""
75
+ return any(part in dep_dirs for part in rel.split('/'))
76
+
77
+
78
+ def _git_dir(checkout: Path) -> Path | None:
79
+ done = subprocess.run(
80
+ ['git', '-C', str(checkout), 'rev-parse', '--git-dir'],
81
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False,
82
+ )
83
+ if done.returncode != 0:
84
+ return None
85
+ raw = done.stdout.decode('utf-8', 'surrogateescape').strip()
86
+ if not raw:
87
+ return None
88
+ p = Path(raw)
89
+ return p if p.is_absolute() else (checkout / p).resolve()
90
+
91
+
92
+ def _ignored_paths(checkout: Path) -> list[str]:
93
+ done = subprocess.run(
94
+ ['git', '-C', str(checkout), '-c', 'core.quotepath=off',
95
+ 'status', '--ignored', '--porcelain', '-z'],
96
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False,
97
+ )
98
+ if done.returncode != 0:
99
+ return []
100
+ out: list[str] = []
101
+ for rec in done.stdout.split(b'\0'):
102
+ if not rec.startswith(b'!! '):
103
+ continue
104
+ norm = normalize_rel(rec[3:].decode('utf-8', 'surrogateescape'))
105
+ if norm:
106
+ out.append(norm)
107
+ return sorted(set(out))
108
+
109
+
110
+ def _collapse_nested(paths: list[str]) -> list[str]:
111
+ """Drop child paths when an ancestor directory is already in the sorted list."""
112
+ kept: list[str] = []
113
+ for p in sorted(set(paths), key=lambda x: (x.count('/'), x)):
114
+ if any(p == k or p.startswith(k + '/') for k in kept):
115
+ continue
116
+ kept.append(p)
117
+ return sorted(kept)
118
+
119
+
120
+ def cmd_capture_before(checkout: Path, out_file: Path) -> int:
121
+ paths = _ignored_paths(checkout)
122
+ out_file.parent.mkdir(parents=True, exist_ok=True)
123
+ out_file.write_bytes(b'\0'.join(p.encode('utf-8', 'surrogateescape') for p in paths))
124
+ return 0
125
+
126
+
127
+ def cmd_capture_after(checkout: Path, before_file: Path, out_file: Path | None, dep_dirs: set[str]) -> int:
128
+ if before_file.exists():
129
+ raw = before_file.read_bytes()
130
+ before = {p.decode('utf-8', 'surrogateescape') for p in raw.split(b'\0') if p}
131
+ else:
132
+ before = set()
133
+ after = set(_ignored_paths(checkout))
134
+ created = [
135
+ p for p in sorted(after - before)
136
+ if not has_dep_dir_component(p, dep_dirs) and not is_secret_path(p)
137
+ ]
138
+ created = _collapse_nested(created)
139
+ target = out_file
140
+ if target is None:
141
+ gdir = _git_dir(checkout)
142
+ if gdir is None:
143
+ return 0
144
+ target = gdir / 'forge-setup-generated'
145
+ if created:
146
+ target.parent.mkdir(parents=True, exist_ok=True)
147
+ target.write_bytes(('\n'.join(created) + '\n').encode('utf-8', 'surrogateescape'))
148
+ elif target.exists():
149
+ target.unlink()
150
+ return 0
151
+
152
+
153
+ def _read_lines_file(path: Path, dep_dirs: set[str], allow_comments: bool) -> list[str]:
154
+ if not path.is_file():
155
+ return []
156
+ out: list[str] = []
157
+ for line in path.read_text(encoding='utf-8', errors='surrogateescape').splitlines():
158
+ text = line.strip()
159
+ if not text or (allow_comments and text.startswith('#')):
160
+ continue
161
+ norm = normalize_rel(text)
162
+ if norm and not has_dep_dir_component(norm, dep_dirs):
163
+ out.append(norm)
164
+ return out
165
+
166
+
167
+ def cmd_plan_extra(source: Path, snapshot: Path, extra_file: Path | None, dep_dirs: set[str]) -> int:
168
+ candidates: dict[str, str] = {}
169
+ gdir = _git_dir(source)
170
+ if gdir is not None:
171
+ for p in _read_lines_file(gdir / 'forge-setup-generated', dep_dirs, allow_comments=False):
172
+ candidates.setdefault(p, 'setup')
173
+ for p in _read_lines_file(source / '.forge' / 'review-links', dep_dirs, allow_comments=True):
174
+ candidates.setdefault(p, 'config')
175
+ if extra_file is not None:
176
+ for p in _read_lines_file(extra_file, dep_dirs, allow_comments=True):
177
+ candidates.setdefault(p, 'config')
178
+
179
+ if not candidates:
180
+ return 0
181
+
182
+ linked_dirs: list[str] = []
183
+ rows: list[tuple[str, str]] = []
184
+ for rel in sorted(candidates, key=lambda x: (x.count('/'), x)):
185
+ if any(rel == d or rel.startswith(d + '/') for d in linked_dirs):
186
+ continue
187
+ origin = candidates[rel]
188
+ if is_secret_path(rel):
189
+ if origin == 'config':
190
+ rows.append(('UNLINKED', rel))
191
+ continue
192
+ snap_path = snapshot / rel
193
+ if snap_path.exists() or snap_path.is_symlink():
194
+ continue # committed or already linked dependency: keep snapshot's own entry
195
+ src_path = source / rel
196
+ if not (src_path.exists() or src_path.is_symlink()):
197
+ if origin == 'config':
198
+ rows.append(('UNLINKED', rel))
199
+ continue
200
+ parent = snap_path.parent
201
+ if not parent.is_dir():
202
+ rows.append(('UNLINKED', rel))
203
+ continue
204
+ if src_path.is_dir():
205
+ linked_dirs.append(rel)
206
+ rows.append(('LINK_DIR', rel))
207
+ elif src_path.is_file():
208
+ rows.append(('LINK_FILE', rel))
209
+ else:
210
+ rows.append(('UNLINKED', rel))
211
+
212
+ lines = [f'{kind}\t{rel}\n' for kind, rel in sorted(rows, key=lambda item: item[1])]
213
+ sys.stdout.buffer.write(''.join(lines).encode('utf-8', 'surrogateescape'))
214
+ sys.stdout.buffer.flush()
215
+ return 0
216
+
217
+
218
+ def main(argv: list[str] | None = None) -> int:
219
+ parser = argparse.ArgumentParser(prog='forge-review-links.py')
220
+ sub = parser.add_subparsers(dest='cmd', required=True)
221
+
222
+ p_before = sub.add_parser('capture-before')
223
+ p_before.add_argument('checkout', type=Path)
224
+ p_before.add_argument('out_file', type=Path)
225
+
226
+ p_after = sub.add_parser('capture-after')
227
+ p_after.add_argument('checkout', type=Path)
228
+ p_after.add_argument('before_file', type=Path)
229
+ p_after.add_argument('--out', type=Path, default=None)
230
+ p_after.add_argument('--dep-dirs', default='')
231
+
232
+ p_plan = sub.add_parser('plan-extra')
233
+ p_plan.add_argument('source', type=Path)
234
+ p_plan.add_argument('snapshot', type=Path)
235
+ p_plan.add_argument('--extra-file', type=Path, default=None)
236
+ p_plan.add_argument('--dep-dirs', default='')
237
+
238
+ args = parser.parse_args(argv)
239
+ if args.cmd == 'capture-before':
240
+ return cmd_capture_before(args.checkout, args.out_file)
241
+ dep_dirs = set(args.dep_dirs.split()) if args.dep_dirs else set(DEFAULT_DEP_DIRS)
242
+ if args.cmd == 'capture-after':
243
+ return cmd_capture_after(args.checkout, args.before_file, args.out, dep_dirs)
244
+ return cmd_plan_extra(args.source, args.snapshot, args.extra_file, dep_dirs)
245
+
246
+
247
+ if __name__ == '__main__':
248
+ sys.exit(main())
@@ -1,18 +1,33 @@
1
1
  #!/usr/bin/env python3
2
- """Optional, bounded Ripwire preparation. Never consumes model/task stdin."""
2
+ """Optional, bounded Ripwire preparation. Never consumes model/task stdin.
3
+
4
+ --doctor the installed Ripwire, whether forge can use it, and the newest release last seen
5
+ --latest the release tag forge would install on this machine (asks GitHub now)
6
+ --notice what a finished run calls: at most once a day, when a newer Ripwire exists, offer
7
+ the update on the terminal, or print the command when there is none (#170)
8
+ (default) prepare advisory context for one dispatch (--repo, --role, --prompt, --artifacts)
9
+
10
+ forge works with Ripwire 0.6 and later: every flag it passes (`--no-cache`, `--token-budget=`,
11
+ `--exclude=`, `--for=`, `--pr-context=`) exists in 0.6.0. The newest release is read from the GitHub
12
+ releases API (FORGE_RIPWIRE_API replaces https://api.github.com, for tests). Intel Macs stop at
13
+ v0.6.1, the last release upstream built for them. The check is cached for a day in
14
+ ${XDG_STATE_HOME:-~/.local/state}/forge/ripwire-check.json; offline keeps the last known release, and
15
+ FORGE_RIPWIRE=off, FORGE_UPDATE_CHECK=off or CI turn the check and the notice off.
16
+ """
3
17
  import argparse
4
18
  import json
5
19
  import os
6
20
  from pathlib import Path
21
+ import platform
7
22
  import re
8
23
  import selectors
9
24
  import shutil
10
- import signal
11
25
  import subprocess
12
26
  import tempfile
13
27
  import threading
14
28
  import time
15
29
  import sys
30
+ import urllib.request
16
31
 
17
32
  _SCRIPTS = str(Path(__file__).resolve().parent)
18
33
  if _SCRIPTS not in sys.path:
@@ -20,6 +35,124 @@ if _SCRIPTS not in sys.path:
20
35
  import forge_proc # noqa: E402
21
36
 
22
37
 
38
+ REPO = 'redhat-et/ripwire'
39
+ MINIMUM = (0, 6, 0)
40
+ INTEL_MAC_LAST = 'v0.6.1'
41
+ DAY_S = 24 * 3600
42
+ _OFF = ('off', '0', 'false', 'no')
43
+ _VERSION = re.compile(r'(?<![\d.])(\d+)\.(\d+)\.(\d+)(?![\d.])')
44
+
45
+
46
+ def parse_version(text):
47
+ """(major, minor, patch) from `ripwire 0.7.0` or `v0.7.0`, or None."""
48
+ found = _VERSION.search(text or '')
49
+ return tuple(int(x) for x in found.groups()) if found else None
50
+
51
+
52
+ def supported(text):
53
+ version = parse_version(text)
54
+ return version is not None and version >= MINIMUM
55
+
56
+
57
+ def managed_path():
58
+ """Where forge installs Ripwire, and the only binary it ever replaces."""
59
+ return Path.home() / '.local/bin/ripwire'
60
+
61
+
62
+ def check_disabled():
63
+ if os.environ.get('FORGE_RIPWIRE') == 'off':
64
+ return True
65
+ if os.environ.get('FORGE_UPDATE_CHECK', '').strip().lower() in _OFF:
66
+ return True
67
+ try: # `forge setup` answered update_check off
68
+ import forge_prefs
69
+ if forge_prefs.update_check_off():
70
+ return True
71
+ except ImportError:
72
+ pass
73
+ ci = os.environ.get('CI', '').strip().lower()
74
+ return bool(ci) and ci not in _OFF
75
+
76
+
77
+ def state_file():
78
+ base = os.environ.get('XDG_STATE_HOME', '')
79
+ if not os.path.isabs(base):
80
+ base = str(Path.home() / '.local/state')
81
+ return Path(base) / 'forge' / 'ripwire-check.json'
82
+
83
+
84
+ def read_state():
85
+ try:
86
+ data = json.loads(state_file().read_text(encoding='utf-8'))
87
+ except (OSError, ValueError, UnicodeDecodeError):
88
+ return {}
89
+ return data if isinstance(data, dict) else {}
90
+
91
+
92
+ def write_state(data):
93
+ path = state_file()
94
+ try:
95
+ path.parent.mkdir(parents=True, exist_ok=True)
96
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix='.ripwire-check.')
97
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
98
+ json.dump(data, handle)
99
+ os.replace(tmp, path)
100
+ except OSError:
101
+ pass
102
+
103
+
104
+ def intel_mac():
105
+ return platform.system() == 'Darwin' and platform.machine() in ('x86_64', 'amd64')
106
+
107
+
108
+ def latest_tag(timeout=5):
109
+ """The release tag to install here: GitHub's latest, capped at v0.6.1 on an Intel Mac.
110
+ Raises RuntimeError when it cannot be read."""
111
+ api = (os.environ.get('FORGE_RIPWIRE_API') or 'https://api.github.com').rstrip('/')
112
+ request = urllib.request.Request(api + '/repos/%s/releases/latest' % REPO,
113
+ headers={'Accept': 'application/vnd.github+json'})
114
+ try:
115
+ with urllib.request.urlopen(request, timeout=timeout) as reply:
116
+ tag = json.loads(reply.read().decode('utf-8')).get('tag_name')
117
+ except Exception as error: # offline, an HTTP error, a proxy page: no answer
118
+ raise RuntimeError('could not read the latest Ripwire release: %s' % error)
119
+ if not isinstance(tag, str) or parse_version(tag) is None:
120
+ raise RuntimeError('the latest Ripwire release has no usable tag')
121
+ if intel_mac() and parse_version(tag) > parse_version(INTEL_MAC_LAST):
122
+ return INTEL_MAC_LAST
123
+ return tag
124
+
125
+
126
+ def cached_latest(force=False):
127
+ """(latest tag or None, state). Asks GitHub at most once a day unless forced; a failed ask
128
+ keeps the last known tag."""
129
+ state = read_state()
130
+ checked = state.get('checked')
131
+ fresh = isinstance(checked, (int, float)) and 0 <= time.time() - checked < DAY_S
132
+ if fresh and not force:
133
+ return state.get('latest'), state
134
+ try:
135
+ tag = latest_tag()
136
+ except RuntimeError:
137
+ tag = None
138
+ state.update(checked=time.time(), reached=tag is not None)
139
+ if tag:
140
+ state['latest'] = tag
141
+ write_state(state)
142
+ return state.get('latest'), state
143
+
144
+
145
+ def installed_version(binary):
146
+ try:
147
+ return bounded([binary, '--version'], tempfile.gettempdir(), time.monotonic() + 3).strip()
148
+ except (OSError, RuntimeError):
149
+ return None
150
+
151
+
152
+ def update_command():
153
+ return 'forge ripwire update'
154
+
155
+
23
156
  def resolve():
24
157
  binary = shutil.which('ripwire')
25
158
  fallback = Path.home() / '.local/bin/ripwire'
@@ -117,14 +250,15 @@ def prepare(args):
117
250
  raise RuntimeError('native review cannot accept context')
118
251
  binary = resolve()
119
252
  if not binary:
120
- raise RuntimeError('missing; run bash scripts/forge-install-ripwire.sh')
253
+ raise RuntimeError('missing; run forge ripwire install')
121
254
  deadline = started + 30
122
255
  # All subprocesses share one preparation deadline and bounded pipes.
123
256
  with tempfile.TemporaryDirectory(prefix='forge-ripwire-', dir=args.artifacts) as work:
124
257
  version = bounded([binary, '--version'], work, deadline)
125
258
  record['version'] = version.strip()
126
- if not re.search(r'\b0\.4\.0\b', version):
127
- raise RuntimeError('incompatible binary (requires 0.4.0)')
259
+ if not supported(version):
260
+ raise RuntimeError('incompatible binary %s (forge needs Ripwire 0.6 or later: %s)'
261
+ % (version.strip() or '?', update_command()))
128
262
  command = [binary, args.repo, '--no-cache', '--token-budget=4096',
129
263
  '--exclude=.forge', '--exclude=.git/']
130
264
  if args.role == 'qa' and args.baseline:
@@ -153,9 +287,89 @@ def prepare(args):
153
287
  Path(args.artifacts, 'ripwire.json').write_text(json.dumps(record, ensure_ascii=False, indent=2) + '\n')
154
288
 
155
289
 
290
+ def doctor(check):
291
+ if os.environ.get('FORGE_RIPWIRE') == 'off':
292
+ print('ripwire disabled FORGE_RIPWIRE=off')
293
+ return
294
+ binary = resolve()
295
+ if not binary:
296
+ print('ripwire optional missing (forge ripwire install)')
297
+ return
298
+ version = installed_version(binary)
299
+ if version is None:
300
+ print('ripwire unusable %s does not answer --version' % binary)
301
+ return
302
+ latest, state = cached_latest(force=True) if check else (read_state().get('latest'), read_state())
303
+ status = 'optional ' if supported(version) else 'outdated '
304
+ line = 'ripwire %s %s' % (status, version)
305
+ if not supported(version):
306
+ line += ' (forge needs 0.6 or later; Ripwire context is skipped until then)'
307
+ if latest:
308
+ line += '; latest %s' % latest.lstrip('v')
309
+ if parse_version(latest) and parse_version(version) and parse_version(latest) > parse_version(version):
310
+ line += ': %s' % (update_command() if Path(binary) == managed_path().resolve()
311
+ else 'installed outside forge (%s), update it the way you installed it' % binary)
312
+ elif not check:
313
+ line += '; latest not checked yet (forge ripwire status --check)'
314
+ print(line)
315
+
316
+
317
+ def _ask(question):
318
+ """True/False from the controlling terminal, or None when there is none. Never task stdin."""
319
+ try:
320
+ tty = open('/dev/tty', 'r+')
321
+ except OSError:
322
+ return None
323
+ with tty:
324
+ if not tty.isatty():
325
+ return None
326
+ tty.write(question)
327
+ tty.flush()
328
+ reply = tty.readline()
329
+ if not reply:
330
+ return False
331
+ return reply.strip().lower() in ('', 'y', 'yes')
332
+
333
+
334
+ def notice(installer):
335
+ """End of a run: at most once a day, offer a newer Ripwire. Never raises, never fails a run.
336
+ Prints on stdout, like forge-version.py's notice: the runner sends it to its stderr."""
337
+ if check_disabled():
338
+ return
339
+ binary = resolve()
340
+ if not binary:
341
+ return # installing is offered by forge install; a run never asks for it
342
+ version = installed_version(binary)
343
+ state = read_state()
344
+ told = state.get('told')
345
+ if isinstance(told, (int, float)) and 0 <= time.time() - told < DAY_S:
346
+ return
347
+ latest, state = cached_latest()
348
+ if not latest or not version or not parse_version(version) or parse_version(latest) <= parse_version(version):
349
+ return
350
+ state['told'] = time.time()
351
+ write_state(state)
352
+ have, new = version.split()[-1], latest.lstrip('v')
353
+ if Path(binary) != managed_path().resolve():
354
+ print('forge: Ripwire %s is available (you have %s at %s, installed outside forge; update it the way '
355
+ 'you installed it)' % (new, have, binary))
356
+ return
357
+ answer = _ask('Ripwire %s is available (you have %s). Update now? [Y/n] ' % (new, have))
358
+ if answer is None:
359
+ print('forge: Ripwire %s is available (you have %s): %s' % (new, have, update_command()))
360
+ return
361
+ if not answer:
362
+ return
363
+ subprocess.run(['/bin/bash', installer, '--upgrade', '--yes', '--version', latest],
364
+ stdin=subprocess.DEVNULL, stderr=sys.stdout, check=False)
365
+
366
+
156
367
  def main():
157
- parser = argparse.ArgumentParser(description=__doc__)
368
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
158
369
  parser.add_argument('--doctor', action='store_true')
370
+ parser.add_argument('--check', action='store_true', help='with --doctor: ask GitHub for the latest release now')
371
+ parser.add_argument('--latest', action='store_true')
372
+ parser.add_argument('--notice', action='store_true')
159
373
  parser.add_argument('--repo')
160
374
  parser.add_argument('--role')
161
375
  parser.add_argument('--prompt')
@@ -165,18 +379,22 @@ def main():
165
379
  parser.add_argument('--native', default='0')
166
380
  args = parser.parse_args()
167
381
  if args.doctor:
168
- if os.environ.get('FORGE_RIPWIRE') == 'off':
169
- print('ripwire disabled FORGE_RIPWIRE=off')
170
- else:
171
- binary = resolve()
172
- try:
173
- version = bounded([binary, '--version'], tempfile.gettempdir(), time.monotonic() + 3) if binary else 'missing'
174
- print('ripwire optional ' + version.strip())
175
- except (OSError, RuntimeError) as error:
176
- print('ripwire unusable ' + str(error))
382
+ doctor(args.check)
383
+ elif args.latest:
384
+ try:
385
+ print(latest_tag(timeout=10))
386
+ except RuntimeError as error:
387
+ print('forge: ' + str(error), file=sys.stderr)
388
+ return 1
389
+ elif args.notice:
390
+ try:
391
+ notice(str(Path(__file__).resolve().parent / 'forge-install-ripwire.sh'))
392
+ except Exception: # never let the notice change a run's outcome
393
+ pass
177
394
  else:
178
395
  prepare(args)
396
+ return 0
179
397
 
180
398
 
181
399
  if __name__ == '__main__':
182
- main()
400
+ sys.exit(main())
@@ -38,7 +38,7 @@ bias (inverse-propensity weighting needs the probability each choice had).
38
38
  once the streak no longer holds. A pending tasks/<id>/escalation.pin (a human's one-shot
39
39
  choice, applied by prepare_retry) is what `--check` reports as the next model instead
40
40
  (escalation.next = its spec), whatever escalate_after says, unless the next retry is a
41
- QA-only resume or the plan is Fractal (pins never apply there). `--qa-only-next` is
41
+ QA-only resume. `--qa-only-next` is
42
42
  that fact as the caller measured it; without the option, a resume marker or an
43
43
  unreviewed commit is taken as QA-only. Nothing has applied the pin yet, so the policy's
44
44
  own stop and split markers stay as the policy decided them beneath it: they are what
@@ -89,7 +89,7 @@ bias (inverse-propensity weighting needs the probability each choice had).
89
89
 
90
90
  The propensity of the chosen spec is (1-E)*[chosen == SPEC] + E/2. Forge never picks a
91
91
  model the user did not name: both helpers read only the pools `plan` stored in
92
- fractal-routing.json, and "stronger" means only "in a higher tier of those pools" --
92
+ dwarf-routing.json, and "stronger" means only "in a higher tier of those pools" --
93
93
  registry.tsv has no cost or capability column to say more. FORGE_ROUTE_EXPLORE_SEED makes
94
94
  the draws reproducible (tests only). Any failure prints SPEC (explore) or nothing
95
95
  (escalation): neither ever changes a run by breaking.
@@ -118,6 +118,7 @@ SCRIPTS = Path(__file__).resolve().parent
118
118
  if str(SCRIPTS) not in sys.path:
119
119
  sys.path.insert(0, str(SCRIPTS))
120
120
  import forge_flock as fcntl # noqa: E402
121
+ import forge_legacy # noqa: E402
121
122
  import forge_posix # noqa: E402
122
123
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
123
124
  FAILED = ('FAIL', 'TIMEOUT', 'BOUNCED', 'INCOMPLETE') # a judgment against the spec that ran
@@ -176,7 +177,7 @@ def registry_models(path=None) -> dict:
176
177
 
177
178
 
178
179
  def canonical(spec: str, registry: dict) -> str:
179
- """The model a spec runs, so `sol` and `sol:xhigh` count as one model and `gpt-6.1-sol` too."""
180
+ """The model a spec runs, so `sol` and `sol:xhigh` count as one model and `gpt-6.2-sol` too."""
180
181
  parts = str(spec).split(':')
181
182
  alias = parts[0]
182
183
  harness = parts[2] if len(parts) > 2 else None
@@ -190,10 +191,9 @@ def canonical(spec: str, registry: dict) -> str:
190
191
 
191
192
  def model_key(spec: str, registry: dict) -> str:
192
193
  """The model a spec runs, named so that one model reached through two harnesses compares equal
193
- (`gpt-6.1-sol` on codex and `github-copilot/gpt-6.1-sol` on opencode): the id it resolves to, without
194
- its provider prefix and with dots and dashes alike. Two ids are compared, never two aliases, since
195
- one alias may list different models on different harnesses (`gemini` is Flash on antigravity and
196
- Pro on opencode)."""
194
+ (`gpt-6.2-sol` on codex and `github-copilot/gpt-6.2-sol` on opencode): the id it resolves to, without
195
+ its provider prefix and with dots and dashes alike. Two ids are compared, never two aliases: an
196
+ alias names one model on every harness now (#187), but a literal id has no alias at all."""
197
197
  return canonical(spec, registry).rsplit('/', 1)[-1].lower().replace('.', '-')
198
198
 
199
199
 
@@ -442,7 +442,7 @@ def record_running_tier(plan: str, task: str, row: str, control) -> None:
442
442
  return
443
443
  tier = running_tier(Path(plan), task, frm)
444
444
  if tier and source != 'fallback':
445
- tier = escalation_target(source, frm, to, tier, load_pools(Path(plan) / 'fractal-routing.json'),
445
+ tier = escalation_target(source, frm, to, tier, load_pools(forge_legacy.pools_path(plan)),
446
446
  registry_models())
447
447
  if tier:
448
448
  write_running_tier(plan, task, tier, to, control)
@@ -455,7 +455,7 @@ def fallback(args) -> int:
455
455
  current = _dwarf_of(plan, args.task)
456
456
  if not current or current in ('-', 'UNASSIGNED'):
457
457
  return 1
458
- pick = fallback_pick(current, load_pools(plan / 'fractal-routing.json'), registry_models(),
458
+ pick = fallback_pick(current, load_pools(forge_legacy.pools_path(plan)), registry_models(),
459
459
  parse_excluded(args.exclude), running_tier(plan, args.task, current),
460
460
  _row_cell(plan, args.task, 5))
461
461
  if not pick:
@@ -753,16 +753,17 @@ def per_model_setting(plan: Path):
753
753
  def rungs_above(spec: str, plan: Path) -> list:
754
754
  """The specs the policy would move through from `spec`, in order: repeated stronger() until it
755
755
  returns None, then, with the effort step on, repeated _next_effort_spec on the last one. A spec
756
- in none of the pools has none. Stops on a repeat, and at MAX_RUNGS."""
756
+ in none of the pools (every spec of a plan without tier pools) has no stronger model, but still
757
+ has its effort steps when the step is on, as escalation() moves it (#222). Stops on a repeat, and
758
+ at MAX_RUNGS."""
757
759
  if spec in NON_MODEL_DWARFS:
758
760
  return []
759
761
  registry = registry_models()
760
- pools = load_pools(plan / 'fractal-routing.json')
761
- if rank_of(spec, pools, registry) is None:
762
- return []
762
+ pools = load_pools(forge_legacy.pools_path(plan))
763
+ pooled = rank_of(spec, pools, registry) is not None
763
764
  out, seen = [], {spec}
764
765
  current = spec
765
- while len(out) < MAX_RUNGS:
766
+ while pooled and len(out) < MAX_RUNGS:
766
767
  target, _why = stronger(current, pools, registry)
767
768
  if not target or target in seen:
768
769
  break
@@ -846,13 +847,6 @@ def worst_case(plan: Path) -> dict:
846
847
  return {'per_model': limit, 'tasks': tasks, 'total': total, 'capped': capped}
847
848
 
848
849
 
849
- def _fractal(plan: Path) -> bool:
850
- try:
851
- return bool(json.loads((plan / 'fractal-selection.json').read_text()).get('enabled'))
852
- except (OSError, ValueError, AttributeError):
853
- return False
854
-
855
-
856
850
  # --- attempt cap (#69) -------------------------------------------------------------
857
851
  # A task that keeps failing across runs stops for a person. The count and the cap live here, so
858
852
  # the shell (do_task, the retry gate, the run summary), the scheduler and `forge control show`
@@ -1078,7 +1072,7 @@ def _decide(plan: Path, tdir: Path, args, after: int):
1078
1072
  # `--decide retry=N --dwarf <spec>` (#118) is N attempts on that model, whatever the usual patience is.
1079
1073
  if streak < max(after, held_attempts(tdir, current)):
1080
1074
  return MARKERS, (), '', 0
1081
- target, why = stronger(current, load_pools(plan / 'fractal-routing.json'), registry)
1075
+ target, why = stronger(current, load_pools(forge_legacy.pools_path(plan)), registry)
1082
1076
  # Only once no higher tier has a model. A tier-up is still the stronger move.
1083
1077
  if target is None and step:
1084
1078
  target = _next_effort_spec(current)
@@ -1105,16 +1099,14 @@ def escalation(args) -> int:
1105
1099
  _clear(tdir, *MARKERS)
1106
1100
  return 0
1107
1101
  after = _patience(plan)
1108
- fractal = _fractal(plan)
1109
- # Fractal plans freeze their eligible set at selection; a QA-only resume spends no dwarf
1110
- # attempt, so neither is a moment to change the implementer.
1111
- idle = after <= 0 or fractal or (tdir / 'resume').exists()
1102
+ # A QA-only resume spends no dwarf attempt, so it is not a moment to change the implementer.
1103
+ idle = after <= 0 or (tdir / 'resume').exists()
1112
1104
  # A pin is a human's choice and outranks the policy, so `--check` reports it as the next
1113
1105
  # model whatever escalate_after says; prepare_retry applies it and claims the file. The
1114
1106
  # policy is still decided underneath it and its markers kept current. The policy's own
1115
1107
  # idle test above is separate and stays on the raw resume marker.
1116
1108
  qa_only = _qa_next(tdir) if args.qa_only_next is None else args.qa_only_next == 'yes'
1117
- pin = _pin(tdir) if args.check and not fractal and not qa_only else None
1109
+ pin = _pin(tdir) if args.check and not qa_only else None
1118
1110
  clear, writes, shown, rc = (MARKERS if after <= 0 else ()), (), '', 0
1119
1111
  if not idle:
1120
1112
  clear, writes, shown, rc = _decide(plan, tdir, args, after)