@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
@@ -1,4 +1,13 @@
1
- """Plan-time `files` drift prediction.
1
+ """Plan-time gates: prompt adequacy (site jev-prompt) and `files` drift (site jev-drift).
2
+
3
+ Prompt adequacy is advisory. `score-plan` asks both before `plan` prints its table; drift
4
+ is advisory too unless its gate is `on`, when `score-plan` adds the files drift predicts to
5
+ the task's `files` column in tasks.tsv. Nothing in this module writes there.
6
+
7
+ Prompt adequacy asks whether a reviewer could judge correctness from the task's own
8
+ text. Its `prompt_warn` cutoff was measured on exactly the state `task_state` builds --
9
+ goal, task (id, title, files, deps), prompt, approach, plan_tasks, file_excerpts and
10
+ memory -- so that state must not change shape without re-measuring it.
2
11
 
3
12
  `decompose.md` calls the `files` column "a promise, not a prediction": a task that edits
4
13
  a file it never declared breaks wave disjointness, which is the only thing bounding
@@ -6,23 +15,37 @@ parallelism. Forge already detects this, but afterwards, in `drift.txt` -- by wh
6
15
  the wave has run. Asking at plan time converts a post-mortem into a warning while the
7
16
  plan can still change.
8
17
 
9
- Measured before shipping (see references/jev.md): at the default `gate_warn` of 0.60 this
10
- rubric scored precision 1.000 on one repo and 0.934 on another, over 50 commits. Precision
11
- is the number that matters here -- a warning that fires on files nobody edits teaches
12
- people to ignore every future warning.
18
+ Drift asks about at most CANDIDATE_CAP (25) tracked files, not every one. `candidates`
19
+ ranks them by cheap signals -- named in the task's prompt or approach, a test paired with
20
+ a declared file, committed with a declared file in the last 200 commits, or in a declared
21
+ file's directory -- and keeps the top 25. Each question carries the same ~1 KB rubric, so
22
+ the cap is most of what drift costs. Ranking rather than alphabetical order is what lets
23
+ `tests/` and `ui/` be asked about at all: on this repository the old first-120 cut never
24
+ reached them.
25
+
26
+ Measured before shipping (see references/decision-models.md): at the default `gate_warn` of 0.60 this
27
+ rubric scored precision 1.000 on one repo and 0.934 on another, over 50 commits. That was the
28
+ alphabetical pool, not the ranked one. Precision is the number that matters here -- a warning
29
+ that fires on files nobody edits teaches people to ignore every future warning.
13
30
  """
14
31
  from __future__ import annotations
15
32
 
33
+ import posixpath
34
+ import re
16
35
  import subprocess
36
+ from collections import Counter
17
37
  from pathlib import Path
18
38
 
19
39
  from . import threshold
20
40
  from .client import ask, noul
21
- from .questions import drift_prediction
41
+ from .questions import drift_prediction, prompt_adequacy as prompt_adequacy_question
22
42
 
23
- # One request per task holds this many questions comfortably, and a plan-time gate must
24
- # not turn into the slowest thing in `forge plan`.
25
- CANDIDATE_CAP = 120
43
+ # One request per task, and one Cloudflare chunk: the most questions it holds comfortably.
44
+ # A plan-time gate must not turn into the slowest thing in `forge plan`.
45
+ CANDIDATE_CAP = 25
46
+ # The co-change signal looks this far back, and one file scores at most CO_CHANGE_CAP from it.
47
+ CO_CHANGE_COMMITS = 200
48
+ CO_CHANGE_CAP = 3
26
49
 
27
50
  # Files nobody means when they say "did this task edit something it did not declare".
28
51
  _SKIP_PREFIXES = ('.git/', '.forge/', 'node_modules/', 'vendor/', 'target/', 'dist/',
@@ -36,6 +59,89 @@ _SKIP_NAMES = ('package-lock.json', 'npm-shrinkwrap.json', 'composer.lock',
36
59
  'Gemfile.lock', 'go.sum', 'pnpm-lock.yaml', 'yarn.lock')
37
60
 
38
61
 
62
+ FILE_EXCERPT_CHARS = 600
63
+ MAX_EXCERPT_FILES = 6
64
+ MEMORY_CHARS = 4000
65
+
66
+ # The other tasks in the plan, as sent to the model. Capped because a large plan would
67
+ # otherwise dominate the payload, and truncated per field for the same reason: the model
68
+ # needs their identity and file scope, not their full text.
69
+ MAX_SIBLINGS = 40
70
+ SIBLING_TITLE_CHARS = 120
71
+
72
+
73
+ def _excerpt(repo: Path, files: str) -> dict:
74
+ out = {}
75
+ for rel in (files or '').replace(',', ' ').split():
76
+ if len(out) >= MAX_EXCERPT_FILES:
77
+ break
78
+ path = repo / rel
79
+ if not path.is_file():
80
+ # A file the task will CREATE is normal and informative in itself.
81
+ out[rel] = '(does not exist yet)'
82
+ continue
83
+ try:
84
+ out[rel] = path.read_text(errors='replace')[:FILE_EXCERPT_CHARS]
85
+ except OSError:
86
+ continue
87
+ return out
88
+
89
+
90
+ def _memory(repo: Path) -> str:
91
+ path = repo / '.forge' / 'memory.md'
92
+ try:
93
+ return path.read_text(errors='replace')[:MEMORY_CHARS] if path.is_file() else ''
94
+ except OSError:
95
+ return ''
96
+
97
+
98
+ def _siblings(siblings, task_id: str) -> list[dict]:
99
+ """Compact view of the rest of the plan, excluding the task being asked about."""
100
+ out = []
101
+ for sibling in siblings or []:
102
+ if sibling.get('id') == task_id:
103
+ continue
104
+ out.append(dict(id=sibling.get('id', ''),
105
+ title=str(sibling.get('title', ''))[:SIBLING_TITLE_CHARS],
106
+ files=sibling.get('files', ''),
107
+ deps=sibling.get('deps', '')))
108
+ if len(out) >= MAX_SIBLINGS:
109
+ break
110
+ return out
111
+
112
+
113
+ def task_state(repo, *, goal: str, task_id: str, title: str, files: str, deps: str = '',
114
+ approach: str = '', prompt: str = '', siblings=None) -> dict:
115
+ """The state prompt adequacy is asked against: the one `prompt_warn` was measured on.
116
+
117
+ `prompt` is tasks/<id>/prompt.md, the text the dwarf is dispatched with and the
118
+ reviewer reads. With only a title in state, the honest answer to "could a reviewer
119
+ judge correctness" is no, so a 460-word spec once scored 0.23 and tripped its own
120
+ warning. The planner's declared difficulty is deliberately not sent.
121
+ """
122
+ repo_path = Path(repo)
123
+ return dict(goal=goal, task=dict(id=task_id, title=title, files=files, deps=deps),
124
+ prompt=prompt, approach=approach, plan_tasks=_siblings(siblings, task_id),
125
+ file_excerpts=_excerpt(repo_path, files), memory=_memory(repo_path))
126
+
127
+
128
+ def prompt_adequacy(repo, *, goal: str, task_id: str, title: str, files: str, deps: str = '',
129
+ approach: str = '', prompt: str = '', siblings=None, run_dir=None,
130
+ config: dict | None = None) -> float | None:
131
+ """The probability that a reviewer could judge this task's work from its text.
132
+
133
+ One request, one rubric. None on any failure: a plan that cannot be checked must
134
+ still be a plan.
135
+ """
136
+ state = task_state(repo, goal=goal, task_id=task_id, title=title, files=files, deps=deps,
137
+ approach=approach, prompt=prompt, siblings=siblings)
138
+ result = ask(state, dict(prompt_adequacy=prompt_adequacy_question()), site='jev-prompt',
139
+ run_dir=run_dir, config=config)
140
+ if result is None:
141
+ return None
142
+ return noul(result, 'prompt_adequacy')
143
+
144
+
39
145
  def _tracked(repo: Path) -> list[str]:
40
146
  try:
41
147
  out = subprocess.run(['git', '-C', str(repo), 'ls-files', '-z'],
@@ -47,25 +153,117 @@ def _tracked(repo: Path) -> list[str]:
47
153
  return [name for name in out.stdout.split('\0') if name]
48
154
 
49
155
 
50
- def candidates(repo, declared: str) -> list[str]:
51
- """Tracked files the task does NOT declare, capped.
156
+ def _history(repo: Path) -> list[set[str]]:
157
+ """The files each of the last CO_CHANGE_COMMITS commits touched, one set per commit.
52
158
 
53
- Sorted before truncation so the slice is deterministic: an unstable candidate set
54
- would make the same plan warn differently on two runs.
159
+ Unfiltered on purpose: a `-- <paths>` filter would hide the other files of each commit,
160
+ which are the ones this signal is for. Empty on a git failure or a timeout.
55
161
  """
56
- owned = set((declared or '').replace(',', ' ').split())
57
- found = []
58
- for name in sorted(_tracked(Path(repo))):
59
- if name in owned:
60
- continue
61
- if name.startswith(_SKIP_PREFIXES) or name.endswith(_SKIP_SUFFIXES):
62
- continue
63
- if name.rsplit('/', 1)[-1] in _SKIP_NAMES:
162
+ try:
163
+ out = subprocess.run(['git', '-C', str(repo), '-c', 'core.quotePath=false', 'log',
164
+ '-n', str(CO_CHANGE_COMMITS), '--name-only', '--format=%x00%H'],
165
+ capture_output=True, text=True, timeout=20)
166
+ except (OSError, subprocess.SubprocessError):
167
+ return []
168
+ if out.returncode != 0:
169
+ return []
170
+ # Each commit opens with a NUL, then its hash line, then its file names, one per line.
171
+ return [set(chunk.split('\n')[1:]) - {''} for chunk in out.stdout.split('\0')[1:]]
172
+
173
+
174
+ def _co_changes(repo: Path, declared: set[str]) -> Counter:
175
+ """For each file, how many of the recent commits it shares with a declared file."""
176
+ counts = Counter()
177
+ if not declared:
178
+ return counts
179
+ for files in _history(repo):
180
+ if files & declared:
181
+ counts.update(files - declared)
182
+ return counts
183
+
184
+
185
+ def _stem(name: str) -> str:
186
+ return posixpath.splitext(posixpath.basename(name))[0]
187
+
188
+
189
+ def _test_stem(name: str) -> str | None:
190
+ """The stem a test file pairs by, its name without the test marker; None if not a test."""
191
+ stem = _stem(name)
192
+ if stem.startswith('test_'):
193
+ return stem[len('test_'):] or None
194
+ for suffix in ('_test', '.test', '.spec'):
195
+ if stem.endswith(suffix):
196
+ return stem[:-len(suffix)] or None
197
+ return None
198
+
199
+
200
+ def _paired_stems(declared: list[str]) -> set[str]:
201
+ """The test stems that pair with a declared file: its stem, and that stem minus its
202
+ first segment. So `forge-route.py` pairs with `tests/test_route.py`, whose stem is `route`.
203
+ """
204
+ stems = set()
205
+ for name in declared:
206
+ stem = _stem(name)
207
+ stems.add(stem)
208
+ parts = re.split(r'[-_]', stem, maxsplit=1)
209
+ if len(parts) == 2 and parts[1]:
210
+ stems.add(parts[1])
211
+ return stems
212
+
213
+
214
+ def _named(text: str, name: str) -> bool:
215
+ """Whether `name` appears in `text` as a whole name, not as part of a longer one.
216
+
217
+ `forge` is not named by `forge-route.py`, nor by `forge.py`; it is named by "forge." at
218
+ the end of a sentence.
219
+ """
220
+ pattern = r'(?<![\w.-])' + re.escape(name) + r'(?![\w-]|\.\w)'
221
+ return name in text and re.search(pattern, text) is not None
222
+
223
+
224
+ def _name_score(name: str, text: str) -> int:
225
+ """8 when the full path is named in the text, and 4 more when its basename is."""
226
+ score = 8 if _named(text, name) else 0
227
+ return score + (4 if _named(text, posixpath.basename(name)) else 0)
228
+
229
+
230
+ def _excluded(name: str, declared: set[str]) -> bool:
231
+ """Noise, the declared files themselves, and anything under a declared directory."""
232
+ return (name in declared
233
+ or name.startswith(_SKIP_PREFIXES) or name.endswith(_SKIP_SUFFIXES)
234
+ or name.rsplit('/', 1)[-1] in _SKIP_NAMES
235
+ or any(name.startswith(d.rstrip('/') + '/') for d in declared))
236
+
237
+
238
+ def candidates(repo, declared: str, text: str = '') -> list[str]:
239
+ """Tracked files the task probably touches but does not declare: the best CANDIDATE_CAP.
240
+
241
+ Each file scores on cheap signals, and a file scoring zero is not a candidate:
242
+ its full path named in `text` (+8), and its basename named in `text` (+4) on top;
243
+ a test file paired with a declared file (+3);
244
+ committed with a declared file in the last CO_CHANGE_COMMITS commits (+1 each, up to
245
+ CO_CHANGE_CAP);
246
+ in the same directory as a declared file (+1).
247
+ Ordered by (-score, path), so the same plan always asks the same questions.
248
+ """
249
+ repo = Path(repo)
250
+ named = [token for token in (declared or '').replace(',', ' ').split() if token != '-']
251
+ declared_set = set(named)
252
+ dirs = {posixpath.dirname(name) for name in named}
253
+ stems = _paired_stems(named)
254
+ together = _co_changes(repo, declared_set)
255
+ ranked = []
256
+ for name in _tracked(repo):
257
+ if _excluded(name, declared_set):
64
258
  continue
65
- found.append(name)
66
- if len(found) >= CANDIDATE_CAP:
67
- break
68
- return found
259
+ score = (_name_score(name, text)
260
+ + (3 if _test_stem(name) in stems else 0)
261
+ + min(together[name], CO_CHANGE_CAP)
262
+ + (1 if posixpath.dirname(name) in dirs else 0))
263
+ if score:
264
+ ranked.append((-score, name))
265
+ ranked.sort()
266
+ return [name for _score, name in ranked[:CANDIDATE_CAP]]
69
267
 
70
268
 
71
269
  def predict_drift(repo, *, goal: str, task_id: str, title: str, declared: str,
@@ -76,7 +274,7 @@ def predict_drift(repo, *, goal: str, task_id: str, title: str, declared: str,
76
274
  Returns [] when there is nothing to say and None when no judgment could be made, so
77
275
  a caller can tell "no drift predicted" from "Jev did not answer".
78
276
  """
79
- pool = candidates(repo, declared)
277
+ pool = candidates(repo, declared, text=f'{prompt}\n{approach}')
80
278
  if not pool:
81
279
  return []
82
280
  questions = {f'f{i}': drift_prediction(name) for i, name in enumerate(pool)}
@@ -90,7 +288,7 @@ def predict_drift(repo, *, goal: str, task_id: str, title: str, declared: str,
90
288
 
91
289
  # drift_warn reads gate_warn until a model has its own measured value: a cutoff fitted
92
290
  # to one model's probabilities is not a cutoff on another's.
93
- warn_at = threshold('drift_warn', config=config, model=result.get('model'))
291
+ warn_at = threshold('drift_warn', config=config, site='jev-drift', model=result.get('model'))
94
292
  predicted = []
95
293
  for i, name in enumerate(pool):
96
294
  probability = noul(result, f'f{i}')
@@ -11,6 +11,8 @@ capability all leave the model's own category and key exactly as they were.
11
11
  """
12
12
  from __future__ import annotations
13
13
 
14
+ import math
15
+
14
16
  from . import threshold
15
17
  from .client import ask, choice, noul
16
18
  from .questions import memory_category, memory_durable, memory_same_fact
@@ -58,7 +60,7 @@ def curate(*, category: str, text: str, existing=None, run_dir=None,
58
60
  # alike loses one of them permanently, while a duplicate is only untidy -- so the
59
61
  # bar sits on the side of keeping both.
60
62
  if (matched and matched != 'none' and match_confidence is not None
61
- and match_confidence >= threshold('memory_merge', config=config)):
63
+ and match_confidence >= threshold('memory_merge', config=config, site='jev-memory-curate')):
62
64
  out['matched'] = matched
63
65
  out['match_confidence'] = match_confidence
64
66
 
@@ -66,12 +68,12 @@ def curate(*, category: str, text: str, existing=None, run_dir=None,
66
68
  # place it, which is a reason to leave the recorded category alone, not to discard it.
67
69
  if (suggested in CATEGORIES and suggested != category
68
70
  and category_confidence is not None
69
- and category_confidence >= threshold('memory_recategorize', config=config)):
71
+ and category_confidence >= threshold('memory_recategorize', config=config, site='jev-memory-curate')):
70
72
  out['category'] = suggested
71
73
 
72
74
  # The quality gate. Silence is the safe direction: a rejected line still lands in the
73
75
  # ledger in full, so the only thing lost is injection into future prompts.
74
- out['injectable'] = not (durable is not None and durable < threshold('gate_warn', config=config))
76
+ out['injectable'] = not (durable is not None and durable < threshold('gate_warn', config=config, site='jev-memory-curate'))
75
77
 
76
78
  # A line that merged onto an existing entry is exempt, and the two judgments have to
77
79
  # be read together to see why. `rebuild` skips a non-injectable row before it counts
@@ -90,6 +92,65 @@ def curate(*, category: str, text: str, existing=None, run_dir=None,
90
92
  return out
91
93
 
92
94
 
95
+ def _request_model(request) -> str | None:
96
+ """The model a request was measured for: a stored body's or a {model, questions} dict's;
97
+ None for a bare list of ids."""
98
+ model = request.get('model') if isinstance(request, dict) else None
99
+ return model if isinstance(model, str) and model else None
100
+
101
+
102
+ def _number(value) -> float | None:
103
+ """A finite real number, else None. Logged answers are only envelope-checked, so a
104
+ string or a bool in a numeric slot must read as "no answer", not crash the report."""
105
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
106
+ return None
107
+ return float(value) if math.isfinite(value) else None
108
+
109
+
110
+ def _answer(answers, qid: str, kind: str) -> dict | None:
111
+ answer = answers.get(qid) if isinstance(answers, dict) else None
112
+ return answer if isinstance(answer, dict) and answer.get('type') == kind else None
113
+
114
+
115
+ def fired_curate(answers, threshold_value, request=None) -> list[str]:
116
+ """The question ids `curate` acted on, `same` first: what the decision model changed.
117
+
118
+ `same` is a merge (the choice is not `none` and its confidence reaches `memory_merge`).
119
+ `durable` is the durability refusal: the Noul is below `gate_warn` and no merge happened,
120
+ since a merged line is exempt and stays injectable. A category correction is not counted:
121
+ the request does not carry the recorded category, so a correction cannot be told from
122
+ agreement. `threshold_value` is None for this site; both thresholds are resolved here,
123
+ for the request's model when it names one, as `curate` reads them. Malformed answer
124
+ values count as not fired."""
125
+ model = _request_model(request)
126
+ out = []
127
+ same = _answer(answers, 'same', 'choice')
128
+ matched = same.get('choice') if same else None
129
+ confidence = _number(same.get('confidence')) if same else None
130
+ merged = (isinstance(matched, str) and bool(matched) and matched != 'none'
131
+ and confidence is not None
132
+ and confidence >= threshold('memory_merge', site='jev-memory-curate', model=model))
133
+ if merged:
134
+ out.append('same')
135
+ durable = _answer(answers, 'durable', 'noul')
136
+ value = _number(durable.get('noul')) if durable else None
137
+ if (not merged and value is not None
138
+ and value < threshold('gate_warn', site='jev-memory-curate', model=model)):
139
+ out.append('durable')
140
+ return out
141
+
142
+
143
+ def fired_stale(answers, threshold_value, request=None) -> list[str]:
144
+ """['still'] when `still_true` would call the fact stale: its probability is below
145
+ `threshold_value` (`stale_drop`)."""
146
+ still = _answer(answers, 'still', 'noul')
147
+ probability = _number(still.get('noul')) if still else None
148
+ limit = _number(threshold_value)
149
+ if probability is None or limit is None:
150
+ return []
151
+ return ['still'] if probability < limit else []
152
+
153
+
93
154
  # The number of facts a single dispatch is likely to act on. The existing 40-line / 4KB
94
155
  # cap stays the outer bound -- this only narrows within it, and never adds a line.
95
156
  SLICE_KEEP = 8
@@ -128,7 +189,7 @@ def still_true(*, text: str, anchor_path, run_dir=None, config: dict | None = No
128
189
  # keeping a stale one costs a line until someone notices, so the bar sits low enough
129
190
  # that only a confident "this went false" acts.
130
191
  return dict(probability=probability,
131
- stale=probability < threshold('stale_drop', config=config))
192
+ stale=probability < threshold('stale_drop', config=config, site='jev-memory-stale'))
132
193
 
133
194
 
134
195
  def relevant_lines(*, task: str, lines: list, keep: int = SLICE_KEEP,
@@ -0,0 +1,134 @@
1
+ """The dwarf's final message (#44): did the implementer say it did not finish, or ask the user?
2
+
3
+ After every implementer attempt forge pays for a review, whatever `dwarf.last` says. This reads
4
+ that message first, in one request with three questions: `unfinished`, `blocked` and `question`.
5
+ The shell sends an attempt back, without a review, when the implementer says it did not finish
6
+ or was blocked, and stops the task for the user's answer when it asks a question.
7
+
8
+ The gate only ever stops work early: it never accepts anything. It asks nothing when there is no
9
+ message. Run, task and attempt are part of the state, so the request key (and the cache) follow
10
+ them and the same words on a later attempt, or in another run, are asked and recorded again.
11
+
12
+ Prints `<which>TAB<p>` for the first question that fires, in the priority `question`, `blocked`,
13
+ `unfinished`, or `ok TAB <max p>` when none does. Exit 3 is no opinion: the gate is off or in
14
+ shadow, there is no message, or the model did not answer.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from pathlib import Path
19
+
20
+ from . import gate_mode, site_ready, threshold
21
+ from .client import ask, noul
22
+ from .questions import message_blocked, message_question, message_unfinished
23
+
24
+ SITE = 'jev-dwarf-message'
25
+ MESSAGE_CHARS = 6000
26
+ # The order the shell acts in: a question outranks "I could not finish", which outranks it.
27
+ PRIORITY = ('question', 'blocked', 'unfinished')
28
+ THRESHOLD = dict(unfinished='message_warn', blocked='message_warn', question='message_ask')
29
+ # Per kind, the words the plain baseline looks for in the message.
30
+ WORDS = dict(unfinished=('TODO', 'not finished', 'did not finish', 'partially'),
31
+ blocked=('could not', "couldn't", 'unable to', 'blocked'),
32
+ question=('?',))
33
+
34
+
35
+ def _read(path: Path) -> str:
36
+ try:
37
+ return path.read_text(errors='replace')
38
+ except OSError:
39
+ return ''
40
+
41
+
42
+ def _run_id(plan: Path) -> str:
43
+ return _read(plan / 'run_id').strip() or plan.name
44
+
45
+
46
+ def _title(plan: Path, task: str) -> str:
47
+ """The task's title: tasks.tsv column 7."""
48
+ for line in _read(plan / 'tasks.tsv').splitlines():
49
+ cells = line.split('\t')
50
+ if len(cells) >= 7 and not line.startswith('#') and cells[0] == task:
51
+ return cells[6]
52
+ return ''
53
+
54
+
55
+ def _questions() -> dict:
56
+ return dict(unfinished=message_unfinished(), blocked=message_blocked(), question=message_question())
57
+
58
+
59
+ def main(args) -> int:
60
+ if not site_ready(SITE):
61
+ return 3
62
+ plan = Path(args.plan)
63
+ tdir = plan / 'tasks' / args.task
64
+ message = _read(tdir / 'dwarf.last')
65
+ if not message.strip():
66
+ return 3
67
+
68
+ attempt = int(args.attempt)
69
+ state = dict(run=_run_id(plan), task=args.task, attempt=attempt, title=_title(plan, args.task),
70
+ message=message[-MESSAGE_CHARS:])
71
+ result = ask(state, _questions(), site=SITE, run_dir=str(tdir),
72
+ context=dict(task=args.task, attempt=attempt))
73
+ if result is None or gate_mode(SITE) != 'on':
74
+ return 3
75
+
76
+ seen = {}
77
+ for which in PRIORITY:
78
+ probability = noul(result, which)
79
+ if probability is None:
80
+ continue
81
+ seen[which] = probability
82
+ if probability >= threshold(THRESHOLD[which], site=SITE, model=result.get('model')):
83
+ print(f'{which}\t{probability:.3f}')
84
+ return 0
85
+ if not seen:
86
+ return 3
87
+ print(f'ok\t{max(seen.values()):.3f}')
88
+ return 0
89
+
90
+
91
+ # --- measurement: what forge_decide.sites reads for this site --------------------------------
92
+
93
+ def _number(value) -> float | None:
94
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
95
+ return None
96
+ return float(value)
97
+
98
+
99
+ def decisions(body) -> list[str]:
100
+ """The questions of `unfinished`, `blocked` and `question` that the request asked."""
101
+ questions = body.get('questions') if isinstance(body, dict) else None
102
+ asked = set(questions) if isinstance(questions, (dict, list)) else set()
103
+ return [qid for qid in THRESHOLD if qid in asked]
104
+
105
+
106
+ def score(answers, qid, request=None) -> float | None:
107
+ """The Noul of the question."""
108
+ answer = (answers or {}).get(qid)
109
+ if isinstance(answer, dict) and answer.get('type', 'noul') == 'noul':
110
+ return _number(answer.get('noul'))
111
+ return None
112
+
113
+
114
+ def fired(answers, threshold_value=None, request=None) -> list[str]:
115
+ """The questions at or above their own threshold, in the priority order the gate acts in.
116
+
117
+ `threshold_value` is None for this site: two thresholds belong to it, so it resolves
118
+ `message_warn` and `message_ask` itself, for the model the request names. `request` is a stored
119
+ body or a `{model, questions}` dict, or a bare list of question ids (no model)."""
120
+ model = request.get('model') if isinstance(request, dict) else None
121
+ out = []
122
+ for qid in PRIORITY:
123
+ probability = score(answers, qid)
124
+ if probability is not None and probability >= threshold(THRESHOLD[qid], site=SITE, model=model):
125
+ out.append(qid)
126
+ return out
127
+
128
+
129
+ def baseline(body, qid) -> float:
130
+ """1.0 when the message holds one of a few plain words for the kind of question, else 0.0:
131
+ the rule the model's score is measured against."""
132
+ state = body.get('state') if isinstance(body, dict) else None
133
+ message = str(state.get('message') or '') if isinstance(state, dict) else ''
134
+ return 1.0 if any(word in message for word in WORDS.get(qid, ())) else 0.0