@giamme/forge 0.16.0 → 0.18.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 (95) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +13 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/reviews.md +15 -1
  11. package/docs/safety.md +8 -0
  12. package/forge +24 -1
  13. package/package.json +1 -1
  14. package/references/dataset.md +143 -5
  15. package/references/decision-models.md +15 -2
  16. package/references/decompose.md +180 -11
  17. package/references/planning.md +3 -2
  18. package/references/solo.md +2 -1
  19. package/references/ui.md +5 -2
  20. package/scripts/forge-artifact.sh +14 -0
  21. package/scripts/forge-brief.py +132 -0
  22. package/scripts/forge-compare.py +11 -1
  23. package/scripts/forge-config.py +176 -9
  24. package/scripts/forge-contract.py +98 -4
  25. package/scripts/forge-control.py +86 -13
  26. package/scripts/forge-dispatch.sh +14 -10
  27. package/scripts/forge-du.py +167 -0
  28. package/scripts/forge-issues.py +4 -3
  29. package/scripts/forge-ledger.py +3 -1
  30. package/scripts/forge-lib-adopt.sh +8 -1
  31. package/scripts/forge-lib-plans.sh +5 -2
  32. package/scripts/forge-lib-review.sh +29 -1
  33. package/scripts/forge-metrics.sh +29 -3
  34. package/scripts/forge-parallel-options.sh +4 -0
  35. package/scripts/forge-parallel.sh +506 -10
  36. package/scripts/forge-plan-check.py +25 -2
  37. package/scripts/forge-planner.py +20 -6
  38. package/scripts/forge-prompt.py +120 -0
  39. package/scripts/forge-retro.py +115 -0
  40. package/scripts/forge-runs-compact.py +443 -0
  41. package/scripts/forge-runs-rm.py +2 -0
  42. package/scripts/forge-runs.py +18 -3
  43. package/scripts/forge-schedule.py +279 -4
  44. package/scripts/forge-shadow.py +35 -10
  45. package/scripts/forge-solo.sh +2 -0
  46. package/scripts/forge-summarize.py +698 -0
  47. package/scripts/forge-sweep.py +25 -10
  48. package/scripts/forge-ui-options.sh +10 -0
  49. package/scripts/forge_brief/__init__.py +587 -0
  50. package/scripts/forge_brief/answers.py +459 -0
  51. package/scripts/forge_dataset/__init__.py +10 -0
  52. package/scripts/forge_dataset/cli.py +83 -0
  53. package/scripts/forge_dataset/export.py +18 -4
  54. package/scripts/forge_dataset/facts.py +280 -0
  55. package/scripts/forge_dataset/harvest.py +56 -9
  56. package/scripts/forge_dataset/history.py +5 -3
  57. package/scripts/forge_dataset/outcomes.py +206 -58
  58. package/scripts/forge_dataset/pairs.py +174 -0
  59. package/scripts/forge_dataset/risk.py +108 -0
  60. package/scripts/forge_dataset/tiers.py +427 -0
  61. package/scripts/forge_decide/__init__.py +11 -1
  62. package/scripts/forge_decide/cli.py +23 -2
  63. package/scripts/forge_decide/labels.py +30 -6
  64. package/scripts/forge_decide/replay.py +10 -4
  65. package/scripts/forge_locations.py +366 -0
  66. package/scripts/forge_registry.py +19 -0
  67. package/scripts/forge_retro/__init__.py +417 -0
  68. package/scripts/forge_retro/issues.py +1193 -0
  69. package/scripts/forge_retro/report.py +671 -0
  70. package/scripts/forge_side/__init__.py +477 -0
  71. package/scripts/forge_storage.py +515 -0
  72. package/ui/README.md +68 -8
  73. package/ui/docs/api.md +217 -20
  74. package/ui/forge_ui/control.py +92 -11
  75. package/ui/forge_ui/export.py +31 -5
  76. package/ui/forge_ui/findings.py +4 -2
  77. package/ui/forge_ui/links.py +337 -0
  78. package/ui/forge_ui/models.py +57 -4
  79. package/ui/forge_ui/projects.py +4 -1
  80. package/ui/forge_ui/reader.py +732 -34
  81. package/ui/forge_ui/server.py +8 -0
  82. package/ui/forge_ui/static/app.js +92 -5
  83. package/ui/forge_ui/static/briefview.js +302 -0
  84. package/ui/forge_ui/static/checksview.js +6 -2
  85. package/ui/forge_ui/static/controls.js +5 -0
  86. package/ui/forge_ui/static/diffview.js +7 -3
  87. package/ui/forge_ui/static/index.html +3 -0
  88. package/ui/forge_ui/static/panel.js +311 -4
  89. package/ui/forge_ui/static/runmodel.js +13 -1
  90. package/ui/forge_ui/static/storageview.js +271 -0
  91. package/ui/forge_ui/static/style.css +100 -3
  92. package/ui/forge_ui/static/worktreesview.js +3 -3
  93. package/ui/forge_ui/storage.py +136 -0
  94. package/ui/forge_ui/transcripts.py +35 -10
  95. package/ui/forge_ui/worktrees.py +154 -13
@@ -0,0 +1,459 @@
1
+ """Record brief answers, and flag questions a merge may have made stale (#135).
2
+
3
+ `answer` writes `tasks/<id>/brief.answers.json` as `{qid: {text, actor, t}}` while the
4
+ task is still PENDING and has no `attempts.tsv` row. Once it is past starting, nothing
5
+ about the task changes: the same object goes to `brief.late.json` instead. The command
6
+ prints the `tasks.tsv` row and the `prompt.md` a follow-up needs, then the
7
+ `forge control add` line that queues that row. `add` only takes the plan and a task id
8
+ that is already in `tasks.tsv`, and the prompt is what carries the answer.
9
+
10
+ `stale` runs after a task has merged. When that merge's `changes.diff` (or, if the diff
11
+ is gone, the task's attempt events) names a file outside the task's declared files,
12
+ every open question of a direct dependent that has not started gets `possibly_stale:
13
+ true`. A declared directory covers everything under it, the same rule as `check_drift`:
14
+ `src/routes` covers `src/routes/api.py`.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import importlib.util
19
+ import json
20
+ import shlex
21
+ import sqlite3
22
+ import sys
23
+ import time
24
+ import unicodedata
25
+ from pathlib import Path
26
+
27
+ import forge_brief
28
+
29
+ # Bytes, matching the cap forge-prompt.py uses when it quotes an answer.
30
+ ANSWER_CAP = 4 * 1024
31
+ # Room to strip control characters before the cap, without reading an unbounded file.
32
+ READ_LIMIT = 1024 * 1024
33
+
34
+ _CONTROL = None
35
+
36
+
37
+ class Usage(Exception):
38
+ """The answer text or the actor is not usable. The command exits 2."""
39
+
40
+
41
+ class NoSuchTask(Exception):
42
+ """The task is not in this plan. `valid` is the ids the plan does have."""
43
+
44
+ def __init__(self, task, valid):
45
+ super().__init__(task)
46
+ self.task = task
47
+ self.valid = list(valid)
48
+
49
+
50
+ class NoSuchQuestion(Exception):
51
+ """The task has no question with this id. `valid` is the ids in its brief.json."""
52
+
53
+ def __init__(self, task, qid, valid):
54
+ super().__init__(qid)
55
+ self.task = task
56
+ self.qid = qid
57
+ self.valid = list(valid)
58
+
59
+
60
+ def _control():
61
+ """forge-control.py, loaded once. `audit` is the control.log writer to reuse."""
62
+ global _CONTROL
63
+ if _CONTROL is None:
64
+ path = Path(forge_brief.SCRIPTS) / 'forge-control.py'
65
+ spec = importlib.util.spec_from_file_location('forge_control_cli', path)
66
+ module = importlib.util.module_from_spec(spec)
67
+ spec.loader.exec_module(module)
68
+ _CONTROL = module
69
+ return _CONTROL
70
+
71
+
72
+ def _norm(path) -> str:
73
+ """A repo-relative path, comparable between tasks.tsv and a diff."""
74
+ text = str(path).strip().replace('\\', '/')
75
+ while text.startswith('./'):
76
+ text = text[2:]
77
+ return text
78
+
79
+
80
+ def status_of(plan, task) -> str:
81
+ """The task's status, read the way `task_status` reads it.
82
+
83
+ `tasks/<id>/merged` is MERGED even when `status` still says PASS: the merge
84
+ touches that file and does not rewrite status.
85
+ """
86
+ tdir = forge_brief.task_dir(plan, task)
87
+ if (tdir / 'merged').is_file():
88
+ return 'MERGED'
89
+ try:
90
+ words = (tdir / 'status').read_text(encoding='utf-8', errors='replace').split()
91
+ except OSError:
92
+ return 'PENDING'
93
+ return words[0] if words else 'PENDING'
94
+
95
+
96
+ def _attempt_rows(plan, task) -> bool:
97
+ path = forge_brief.task_dir(plan, task) / 'attempts.tsv'
98
+ try:
99
+ text = path.read_text(encoding='utf-8', errors='replace')
100
+ except OSError:
101
+ return False
102
+ return any(line.strip() and not line.startswith('#') for line in text.splitlines())
103
+
104
+
105
+ def past_start(plan, task) -> bool:
106
+ """Whether an answer can no longer change this task.
107
+
108
+ Past starting when `status` is RUNNING or any finished state (MERGED, FAIL,
109
+ BLOCKED, NEEDS_*, ACCEPTED, and every other status forge writes), or when
110
+ `attempts.tsv` has a row. Only PENDING with no attempt row is still in time.
111
+ """
112
+ if _attempt_rows(plan, task):
113
+ return True
114
+ return status_of(plan, task) != 'PENDING'
115
+
116
+
117
+ def question_ids(plan, task) -> list:
118
+ """Ids of the questions in `brief.json`, in file order. Parked questions are not answers."""
119
+ data = forge_brief._json(forge_brief.task_dir(plan, task) / 'brief.json')
120
+ found = []
121
+ for question in forge_brief._questions(data if isinstance(data, dict) else None):
122
+ qid = question.get('id')
123
+ if isinstance(qid, str) and qid:
124
+ found.append(qid)
125
+ return found
126
+
127
+
128
+ def clean_answer(text) -> str:
129
+ """Drop control characters, then keep the leading 4 KB of what remains."""
130
+ if text is None:
131
+ text = ''
132
+ elif not isinstance(text, str):
133
+ text = str(text)
134
+ kept = ''.join(ch for ch in text if unicodedata.category(ch) != 'Cc')
135
+ try:
136
+ raw = kept.encode('utf-8')
137
+ except UnicodeEncodeError:
138
+ raw = kept.encode('utf-8', errors='ignore')
139
+ kept = raw.decode('utf-8')
140
+ if len(raw) <= ANSWER_CAP:
141
+ return kept
142
+ return raw[:ANSWER_CAP].decode('utf-8', errors='ignore')
143
+
144
+
145
+ def _read_file(file) -> str:
146
+ if file == '-':
147
+ return sys.stdin.read(READ_LIMIT)
148
+ path = Path(file)
149
+ try:
150
+ with path.open('r', encoding='utf-8', errors='replace') as handle:
151
+ return handle.read(READ_LIMIT)
152
+ except OSError as error:
153
+ raise Usage('cannot read %s: %s' % (file, error.strerror or error)) from error
154
+
155
+
156
+ def _actor(value) -> str:
157
+ if value is None:
158
+ return 'cli'
159
+ actor = ''.join(ch for ch in str(value) if unicodedata.category(ch) != 'Cc').strip()
160
+ if not actor or any(ch.isspace() for ch in actor):
161
+ raise Usage('actor must be a single token')
162
+ if len(actor) > 64:
163
+ raise Usage('actor is too long')
164
+ return actor
165
+
166
+
167
+ def _load_map(path) -> dict:
168
+ return forge_brief._entries(forge_brief._json(path))
169
+
170
+
171
+ def _store(path, data: dict) -> None:
172
+ forge_brief.atomic_write(path, forge_brief._dump(data))
173
+
174
+
175
+ def _put(path, qid, record) -> str | None:
176
+ """Replace `qid` and keep every other answer. The previous text, if there was one."""
177
+ current = _load_map(path)
178
+ old = current.get(qid)
179
+ previous = old.get('text') if isinstance(old, dict) and isinstance(old.get('text'), str) else None
180
+ current[qid] = record
181
+ _store(path, current)
182
+ return previous
183
+
184
+
185
+ def _task_token(text) -> str:
186
+ """A tasks.tsv id: no slash, NUL, comma or whitespace, which would split a column or a dep."""
187
+ cleaned = ''.join('-' if ch in '/\0\t\r\n ,' else ch for ch in str(text))
188
+ return cleaned.strip('-')
189
+
190
+
191
+ def _follow_up_id(tasks, task, qid) -> str:
192
+ """An id that is free in tasks.tsv, so the caller can append a row and then `control add` it."""
193
+ taken = {item['id'] for item in tasks}
194
+ base = _task_token('%s-%s' % (task, qid))
195
+ if base in ('', '.', '..'):
196
+ base = _task_token('follow-up-%s' % qid) or 'follow-up'
197
+ candidate = base
198
+ number = 2
199
+ while candidate in taken or candidate in ('', '.', '..'):
200
+ candidate = '%s-%d' % (base, number)
201
+ number += 1
202
+ return candidate
203
+
204
+
205
+ def follow_up_line(plan, follow_id) -> str:
206
+ """`forge control add`: the plan, then the task id. Those are its only positional arguments."""
207
+ return 'forge control add %s %s' % (shlex.quote(str(plan)), shlex.quote(follow_id))
208
+
209
+
210
+ def _one_line(text) -> str:
211
+ return ' '.join(str(text or '').split())
212
+
213
+
214
+ def _question_text(plan, task, qid) -> str:
215
+ data = forge_brief._json(forge_brief.task_dir(plan, task) / 'brief.json')
216
+ for question in forge_brief._questions(data if isinstance(data, dict) else None):
217
+ if question.get('id') == qid:
218
+ text = question.get('text')
219
+ return text if isinstance(text, str) else ''
220
+ return ''
221
+
222
+
223
+ def _follow_row(source, follow_id, qid) -> str:
224
+ """A 7-column tasks.tsv row `check_row` can accept once the prompt exists.
225
+
226
+ Difficulty, files and the two specs are the source task's, so the row stays inside
227
+ the columns that task already used. The new id depends on the source task. The files
228
+ column has to be non-empty; a source row with no files falls back to `.`.
229
+ """
230
+ difficulty = source.get('difficulty')
231
+ if difficulty not in ('low', 'medium', 'high'):
232
+ difficulty = 'low'
233
+ files = str(source.get('files') or '').strip()
234
+ if files in ('', '-'):
235
+ files = '.'
236
+ title = _one_line('Late answer to %s %s' % (source.get('id') or follow_id, qid)) or 'Late answer'
237
+ return '\t'.join((follow_id, source.get('id') or '-', difficulty, files,
238
+ str(source.get('dwarf') or ''), str(source.get('qa') or ''), title))
239
+
240
+
241
+ def late_message(plan, task, follow_id, row, question, answer) -> str:
242
+ """What a late answer prints: the row and the prompt first, then the add command.
243
+
244
+ `forge control add` queues a task that is already a row in tasks.tsv and reads the
245
+ answer from that task's prompt.md. The command line itself has nowhere to put the text.
246
+ """
247
+ prompt = 'tasks/%s/prompt.md' % follow_id
248
+ return (
249
+ 'too late for task %s: the answer does not change this task\n'
250
+ 'Append this row to tasks.tsv and write %s with the question and the answer below. '
251
+ 'The prompt carries the answer. While a scheduler is live, run the command at the end.\n'
252
+ '%s\n'
253
+ 'question: %s\n'
254
+ 'answer: %s\n'
255
+ '%s\n'
256
+ % (task, prompt, row, _one_line(question), answer, follow_up_line(plan, follow_id)))
257
+
258
+
259
+ def _log(plan, actor, task, qid, text, previous, late) -> None:
260
+ """One control.log line in the shape `audit` writes, then the `brief_answer` event."""
261
+ try:
262
+ control = _control()
263
+ except Exception:
264
+ entry = {'at': time.time(), 'actor': actor, 'action': 'answer', 'task': task,
265
+ 'key': qid, 'value': text, 'previous': previous, 'late': bool(late)}
266
+ with (Path(plan) / 'control.log').open('a', encoding='utf-8') as handle:
267
+ handle.write(json.dumps(entry) + '\n')
268
+ else:
269
+ with control.control_lock(str(plan)):
270
+ control.audit(str(plan), actor, 'answer', task, qid, text, previous, late=bool(late))
271
+ _emit(plan, task, qid, actor, late)
272
+
273
+
274
+ def _emit(plan, task, qid, actor, late) -> None:
275
+ """One `brief_answer` dataset event. Fail-open, like every other capture."""
276
+ try:
277
+ from forge_dataset.capture import point
278
+ point('brief_answer', str(plan), str(task), {
279
+ 'task': str(task), 'qid': qid, 'actor': actor, 'late': bool(late)})
280
+ except Exception:
281
+ pass
282
+
283
+
284
+ def answer(plan, task, qid, text=None, actor='cli', file=None) -> dict:
285
+ """Record one answer. Raises `Usage`, `NotAPlan`, `NoSuchTask` or `NoSuchQuestion`.
286
+
287
+ Returns `{task, qid, late, text, message}`. `message` is what the command prints.
288
+ A late answer's message gives the tasks.tsv row and the prompt text, then the
289
+ `forge control add` line that queues that follow-up once a scheduler is live.
290
+ """
291
+ if file is not None and text is not None:
292
+ raise Usage('give the answer as text or --file, not both')
293
+ if file is None and text is None:
294
+ raise Usage('give the answer as text or --file')
295
+ who = _actor(actor)
296
+ cleaned = clean_answer(_read_file(file) if file is not None else text)
297
+ if not cleaned:
298
+ raise Usage('the answer is empty')
299
+ plan = Path(plan)
300
+ tasks = forge_brief.read_tasks(plan)
301
+ ids = [item['id'] for item in tasks]
302
+ if task not in ids:
303
+ raise NoSuchTask(task, ids)
304
+ valid = question_ids(plan, task)
305
+ if qid not in valid:
306
+ raise NoSuchQuestion(task, qid, valid)
307
+ tdir = forge_brief.task_dir(plan, task)
308
+ with forge_brief._task_lock(plan, task):
309
+ # The brief may have been regenerated while this answer waited for the lock.
310
+ if qid not in question_ids(plan, task):
311
+ raise NoSuchQuestion(task, qid, question_ids(plan, task))
312
+ late = past_start(plan, task)
313
+ record = {'text': cleaned, 'actor': who, 't': time.time()}
314
+ target = tdir / ('brief.late.json' if late else 'brief.answers.json')
315
+ previous = _put(target, qid, record)
316
+ _log(plan, who, task, qid, cleaned, previous, late)
317
+ if late:
318
+ source = next(item for item in tasks if item['id'] == task)
319
+ follow = _follow_up_id(tasks, task, qid)
320
+ message = late_message(plan, task, follow, _follow_row(source, follow, qid),
321
+ _question_text(plan, task, qid), cleaned)
322
+ else:
323
+ message = '%s/%s answered\n' % (task, qid)
324
+ return {'task': task, 'qid': qid, 'late': late, 'text': cleaned, 'message': message}
325
+
326
+
327
+ # --- stale -----------------------------------------------------------------------
328
+
329
+ def _declared(files_field) -> set:
330
+ if not files_field or str(files_field).strip() in ('', '-'):
331
+ return set()
332
+ return {_norm(part) for part in str(files_field).split(',') if part.strip() and part.strip() != '-'}
333
+
334
+
335
+ def _covers(declared: str, path: str) -> bool:
336
+ """Whether `check_drift` would treat `path` as inside this declared entry.
337
+
338
+ Exact match, or a declared directory prefix: `src/routes` covers `src/routes/api.py`.
339
+ A trailing slash is the same directory. `src/routes` does not cover `src/routes-extra.py`.
340
+ """
341
+ root = declared.rstrip('/')
342
+ if not root:
343
+ return False
344
+ return path == root or path.startswith(root + '/')
345
+
346
+
347
+ def _undeclared(changed: set, declared: set) -> set:
348
+ """Changed paths that sit outside every declared file and directory."""
349
+ return {path for path in changed if path and not any(_covers(item, path) for item in declared)}
350
+
351
+
352
+ def _diff_files(plan, task) -> set | None:
353
+ """Files in `changes.diff`, or None when that diff is not on disk."""
354
+ path = forge_brief.task_dir(plan, task) / 'changes.diff'
355
+ if not path.is_file():
356
+ return None
357
+ from forge_dataset.harvest import diff_summary
358
+ text = path.read_text(encoding='utf-8', errors='replace')
359
+ summary = diff_summary(text)
360
+ return {_norm(name) for name in summary.get('changed_files') or [] if isinstance(name, str)}
361
+
362
+
363
+ def _dataset_files(plan, task) -> set:
364
+ """`changed_files` of this plan's attempt events for the task, when the diff is gone.
365
+
366
+ Only this run's own events: a plan without a `run_id` reads nothing, so another run's
367
+ attempts (and the store beyond file lists) never reach the brief."""
368
+ repo = forge_brief._text(Path(plan) / 'repo').strip()
369
+ run_id = forge_brief._text(Path(plan) / 'run_id').strip()
370
+ if not repo or not run_id:
371
+ return set()
372
+ try:
373
+ from forge_dataset import dataset_dir, repo_id
374
+ path = dataset_dir() / 'dataset.sqlite'
375
+ if not path.is_file():
376
+ return set()
377
+ # The events table stores repo_id(repo), the same key live capture writes.
378
+ query = 'SELECT data FROM events WHERE kind = ? AND task = ? AND repo = ? AND run_id = ?'
379
+ params = ['attempt', task, repo_id(repo), run_id]
380
+ db = sqlite3.connect(str(path))
381
+ try:
382
+ rows = db.execute(query, params).fetchall()
383
+ finally:
384
+ db.close()
385
+ except Exception:
386
+ return set()
387
+ found = set()
388
+ for (raw,) in rows:
389
+ try:
390
+ data = json.loads(raw)
391
+ except (TypeError, ValueError):
392
+ continue
393
+ files = data.get('changed_files') if isinstance(data, dict) else None
394
+ if isinstance(files, list):
395
+ found.update(_norm(name) for name in files if isinstance(name, str))
396
+ return found
397
+
398
+
399
+ def changed_files(plan, task) -> set:
400
+ """What the merge changed. The diff on disk wins: an earlier attempt may have been reverted."""
401
+ found = _diff_files(plan, task)
402
+ if found is not None:
403
+ return found
404
+ return _dataset_files(plan, task)
405
+
406
+
407
+ def _flag_open(plan, task) -> list:
408
+ """Set `possibly_stale` on this task's open questions. `[(task, qid), ...]` in file order."""
409
+ tdir = forge_brief.task_dir(plan, task)
410
+ path = tdir / 'brief.json'
411
+ if not path.is_file():
412
+ return []
413
+ with forge_brief._task_lock(plan, task):
414
+ if past_start(plan, task):
415
+ return []
416
+ brief = forge_brief._json(path)
417
+ if not isinstance(brief, dict) or not isinstance(brief.get('questions'), list):
418
+ return []
419
+ answered = set(_load_map(tdir / 'brief.answers.json'))
420
+ answered.update(_load_map(tdir / 'brief.late.json'))
421
+ flagged = []
422
+ changed = False
423
+ for question in brief['questions']:
424
+ if not isinstance(question, dict):
425
+ continue
426
+ qid = question.get('id')
427
+ if not isinstance(qid, str) or not qid or qid in answered:
428
+ continue
429
+ flagged.append((task, qid))
430
+ if question.get('possibly_stale') is not True:
431
+ question['possibly_stale'] = True
432
+ changed = True
433
+ if changed:
434
+ forge_brief.atomic_write(path, forge_brief._dump(brief))
435
+ return flagged
436
+
437
+
438
+ def stale(plan, task) -> list:
439
+ """Flag direct dependents' open questions when `task` merged outside its declared files.
440
+
441
+ Returns `[(dependent, qid), ...]` in tasks.tsv order, then question order. An unknown
442
+ task raises `NoSuchTask`. A task that is not merged, or whose changes stay inside its
443
+ declared files and directories, flags nothing.
444
+ """
445
+ plan = Path(plan)
446
+ tasks = forge_brief.read_tasks(plan)
447
+ by_id = {item['id']: item for item in tasks}
448
+ if task not in by_id:
449
+ raise NoSuchTask(task, [item['id'] for item in tasks])
450
+ if status_of(plan, task) != 'MERGED':
451
+ return []
452
+ if not _undeclared(changed_files(plan, task), _declared(by_id[task]['files'])):
453
+ return []
454
+ flagged = []
455
+ for item in tasks:
456
+ if task not in item['deps'] or past_start(plan, item['id']):
457
+ continue
458
+ flagged.extend(_flag_open(plan, item['id']))
459
+ return flagged
@@ -86,6 +86,16 @@ ADDED_COLUMNS = (('code_sha', 'TEXT'), ('forge_rev', 'TEXT'))
86
86
  PROVENANCE = ('forge_version', 'registry_sha', 'code_sha', 'forge_rev')
87
87
 
88
88
 
89
+ def is_side_role(role) -> bool:
90
+ """True for a harvested side dispatch (`side_brief`, `side_summary`, any `side_*`).
91
+
92
+ The files on disk stay `side.*`; harvest records the kind in the role so attempt
93
+ statistics can leave the dispatch out. A bare `side` is the dispatch role, not one
94
+ of these.
95
+ """
96
+ return isinstance(role, str) and role.startswith('side_')
97
+
98
+
89
99
  def enabled() -> bool:
90
100
  return os.environ.get('FORGE_DATASET', 'on').strip().lower() not in OFF
91
101
 
@@ -6,6 +6,8 @@ silent): event, invocation, plan.
6
6
  from __future__ import annotations
7
7
 
8
8
  import argparse
9
+ import os
10
+ from collections import Counter
9
11
  import json
10
12
  import sys
11
13
  import time
@@ -49,6 +51,35 @@ def _continued_sessions(db) -> dict:
49
51
  return counts
50
52
 
51
53
 
54
+ def _outcomes(db) -> dict:
55
+ """Recorded survival outcomes by status, and what the last harvest that wrote did (#120)."""
56
+ from . import outcomes
57
+ recorded = Counter()
58
+ for (raw,) in db.execute("SELECT data FROM events WHERE kind = 'outcome'"):
59
+ data = json.loads(raw)
60
+ if data.get('name') == 'survival':
61
+ recorded[data.get('status') or 'unknown'] += 1
62
+ return dict(recorded=dict(recorded), last=outcomes.last_harvest())
63
+
64
+
65
+ def _outcomes_line(found) -> str | None:
66
+ recorded, last = found.get('recorded') or {}, found.get('last')
67
+ total = sum(recorded.values())
68
+ line = 'outcomes: %d recorded' % total
69
+ if total:
70
+ line += ' (%s)' % ', '.join('%d %s' % (recorded[k], k.replace('_', ' ')) for k in sorted(recorded))
71
+ if last and isinstance(last.get('at'), (int, float)):
72
+ counts = last.get('counts') or {}
73
+ where = os.path.basename(last['repo']) if last.get('repo') else 'every repo'
74
+ extra = ', '.join('%d %s' % (counts[k], k.replace('_', ' ')) for k in ('not_landed', 'pending', 'deferred', 'git_error')
75
+ if counts.get(k))
76
+ line += '; last harvested %s for %s: %d recorded%s' % (time.strftime('%Y-%m-%d %H:%M', time.localtime(last['at'])),
77
+ where, last.get('recorded') or 0, ', ' + extra if extra else '')
78
+ else:
79
+ line += '; never harvested (`forge dataset outcomes`, or the end of a run)'
80
+ return line
81
+
82
+
52
83
  def status(args) -> int:
53
84
  from . import checks
54
85
  directory = dataset_dir()
@@ -65,6 +96,7 @@ def status(args) -> int:
65
96
  summary['last_event'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last)) if last else None
66
97
  summary['checks'] = checks.run(db, verbose=args.verbose)
67
98
  summary.update(_continued_sessions(db))
99
+ summary['outcomes'] = _outcomes(db)
68
100
  if summary['events'].get('dispatch'):
69
101
  from . import export
70
102
  if db.execute("SELECT 1 FROM events WHERE kind = 'dispatch' AND data LIKE '%qa_shadow%' LIMIT 1").fetchone():
@@ -99,6 +131,10 @@ def status(args) -> int:
99
131
  % (shadow['shadow_reviews'], shadow['pairs'], shadow['agree'], rate))
100
132
  for pair, n in shadow['by_pair'].items():
101
133
  print(' %s: %d of %d agree' % (pair, n['agree'], n['pairs']))
134
+ print(' by effort, model and family: forge dataset pairs')
135
+ line = _outcomes_line(summary.get('outcomes') or {})
136
+ if line:
137
+ print(' ' + line)
102
138
  if summary.get('continued_reviews') or summary.get('failed_continues'):
103
139
  print(' continued reviews: %d' % summary['continued_reviews'])
104
140
  print(' failed continues: %d' % summary['failed_continues'])
@@ -196,6 +232,26 @@ def run_reviewers(args) -> int:
196
232
  return reviewers.main(args)
197
233
 
198
234
 
235
+ def run_facts(args) -> int:
236
+ from . import facts
237
+ return facts.main(args)
238
+
239
+
240
+ def run_pairs(args) -> int:
241
+ from . import pairs
242
+ return pairs.main(args)
243
+
244
+
245
+ def run_risk(args) -> int:
246
+ from . import risk
247
+ return risk.main(args)
248
+
249
+
250
+ def run_tiers(args) -> int:
251
+ from . import tiers
252
+ return tiers.main(args)
253
+
254
+
199
255
  def run_history(args) -> int:
200
256
  from . import history
201
257
  return history.main(args)
@@ -253,6 +309,9 @@ def parser() -> argparse.ArgumentParser:
253
309
  p.add_argument('--repo', help='only this repo')
254
310
  p.add_argument('--include-temp', action='store_true', help='also repos under temp dirs (test runs)')
255
311
  p.add_argument('--dry-run', action='store_true', help='report what would be recorded, write nothing')
312
+ p.add_argument('--deadline', type=float, metavar='SECONDS',
313
+ help='start no new integration after this long; the rest waits for the next harvest')
314
+ p.add_argument('--quiet', action='store_true', help='print nothing (the automatic harvest at the end of a run)')
256
315
  p.set_defaults(func=run_outcomes)
257
316
  p = sub.add_parser('routing', help='pass rate and runtime per tier and model, and what the --explore draws say')
258
317
  p.add_argument('--repo', help='only this repo')
@@ -264,6 +323,30 @@ def parser() -> argparse.ArgumentParser:
264
323
  p.add_argument('--repo', help='only this repo')
265
324
  p.add_argument('--json', action='store_true')
266
325
  p.set_defaults(func=run_reviewers)
326
+ p = sub.add_parser('facts', help="the reach, origin and evidence reviewers give findings: agreement, and what "
327
+ "a gate on them would have changed (advisory)")
328
+ p.add_argument('--repo', help='only this repo')
329
+ p.add_argument('--json', action='store_true')
330
+ p.set_defaults(func=run_facts)
331
+ p = sub.add_parser('pairs', help='two reviewers of one attempt, per pair of settings: effort within one model apart '
332
+ 'from model and family comparisons and controls (advisory)')
333
+ p.add_argument('--repo', help='only this repo')
334
+ p.add_argument('--json', action='store_true')
335
+ p.set_defaults(func=run_pairs)
336
+ p = sub.add_parser('risk', help="tasks by difficulty and risk together: how often they differ, and how each "
337
+ "pair fared (advisory)")
338
+ p.add_argument('--repo', help='only this repo')
339
+ p.add_argument('--json', action='store_true')
340
+ p.set_defaults(func=run_risk)
341
+ p = sub.add_parser('tiers', help="what explains results inside each difficulty tier: plan-time facts held out by "
342
+ "run and adjusted for the implementer, and blind-rating agreement (advisory)")
343
+ p.add_argument('--repo', help='only this repo')
344
+ p.add_argument('--tier', choices=('low', 'medium', 'high'), help='only this tier')
345
+ p.add_argument('--sample', type=int, metavar='N', help='write N past prompts for blind rating into --out')
346
+ p.add_argument('--out', help='an empty directory for --sample')
347
+ p.add_argument('--blind', metavar='DIR', help='agreement of DIR/ratings.tsv with the recorded tiers')
348
+ p.add_argument('--json', action='store_true')
349
+ p.set_defaults(func=run_tiers)
267
350
  p = sub.add_parser('history', help="every review's findings and every learning, for forge-ui's Projects screen")
268
351
  p.add_argument('--json', action='store_true')
269
352
  p.set_defaults(func=run_history)
@@ -32,7 +32,7 @@ import time
32
32
  from collections import Counter, defaultdict
33
33
  from pathlib import Path
34
34
 
35
- from . import SKILL, connect, data_home, read_blob
35
+ from . import SKILL, connect, data_home, is_side_role, read_blob
36
36
  from .harvest import review_completeness
37
37
  from .states import assemble, retry, siblings, task_size
38
38
 
@@ -586,6 +586,17 @@ def _ending_qa(rows) -> dict:
586
586
  return ending
587
587
 
588
588
 
589
+ def not_an_attempt(role) -> bool:
590
+ """A shadow review or a side dispatch: in the run's tokens, not in its attempt statistics.
591
+
592
+ `qa_shadow` is the second reviewer. A harvested side call is `side_<kind>`
593
+ (`is_side_role`); the dir on disk, and a side dispatch harvested outside
594
+ `side/<kind>/`, keeps the role `side`. None of these is the review of record.
595
+ Shadow agreement still reads `qa_shadow`. This does not drop a side dispatch's tokens.
596
+ """
597
+ return role == 'qa_shadow' or role == 'side' or is_side_role(role)
598
+
599
+
589
600
  def _qa_rows(runs: Runs):
590
601
  """Every independent QA dispatch with a verdict, with the diff it was shown and its task text.
591
602
 
@@ -610,7 +621,8 @@ def _qa_rows(runs: Runs):
610
621
  word, _, conf = text.strip().partition('\t')
611
622
  effort[(run, task, e['attempt'])] = (word, _float(conf))
612
623
  for (run, task, role), rows in runs.dispatches.items():
613
- if role != 'qa':
624
+ # The review of record only. A shadow pair is selected below; a side dispatch is not a row.
625
+ if not_an_attempt(role) or role != 'qa':
614
626
  continue
615
627
  ending = _ending_qa(rows)
616
628
  for index, e in enumerate(rows):
@@ -672,7 +684,8 @@ def shadow_pairs(runs: Runs) -> dict:
672
684
  ended[(e['run'], e['task'], _int(e['d'].get('attempt')))] = e['d'].get('status')
673
685
  out = {}
674
686
  for (run, task, role), rows in runs.dispatches.items():
675
- if role != 'qa_shadow':
687
+ # Selects the shadow reviewer. A side role is not `qa_shadow`, so it is not a pair.
688
+ if role != 'qa_shadow' or is_side_role(role):
676
689
  continue
677
690
  for shadow in rows:
678
691
  n = shadow['attempt']
@@ -700,7 +713,8 @@ def agreement(runs: Runs) -> dict:
700
713
  key = '%s vs %s' % (primary['d'].get('model'), shadow['d'].get('model'))
701
714
  by_pair[key][0] += 1
702
715
  by_pair[key][1] += primary['d']['verdict'] == shadow['d']['verdict']
703
- shadows = sum(len(rows) for (_, _, role), rows in runs.dispatches.items() if role == 'qa_shadow')
716
+ shadows = sum(len(rows) for (_, _, role), rows in runs.dispatches.items()
717
+ if role == 'qa_shadow' and not is_side_role(role))
704
718
  agree = sum(a for _, a in by_pair.values())
705
719
  return dict(shadow_reviews=shadows, pairs=len(pairs), agree=agree,
706
720
  by_pair={k: dict(pairs=n, agree=a) for k, (n, a) in sorted(by_pair.items())})