@giamme/forge 0.17.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 (76) hide show
  1. package/CHANGELOG.md +24 -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 +5 -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/safety.md +8 -0
  11. package/forge +24 -1
  12. package/package.json +1 -1
  13. package/references/dataset.md +19 -0
  14. package/references/decompose.md +134 -1
  15. package/references/solo.md +2 -1
  16. package/references/ui.md +5 -2
  17. package/scripts/forge-artifact.sh +14 -0
  18. package/scripts/forge-brief.py +132 -0
  19. package/scripts/forge-compare.py +11 -1
  20. package/scripts/forge-config.py +176 -9
  21. package/scripts/forge-contract.py +46 -3
  22. package/scripts/forge-control.py +86 -13
  23. package/scripts/forge-dispatch.sh +14 -10
  24. package/scripts/forge-du.py +167 -0
  25. package/scripts/forge-lib-adopt.sh +1 -0
  26. package/scripts/forge-lib-plans.sh +5 -2
  27. package/scripts/forge-lib-review.sh +29 -1
  28. package/scripts/forge-metrics.sh +7 -3
  29. package/scripts/forge-parallel-options.sh +4 -0
  30. package/scripts/forge-parallel.sh +503 -9
  31. package/scripts/forge-prompt.py +120 -0
  32. package/scripts/forge-retro.py +115 -0
  33. package/scripts/forge-runs-compact.py +443 -0
  34. package/scripts/forge-runs-rm.py +2 -0
  35. package/scripts/forge-runs.py +18 -3
  36. package/scripts/forge-schedule.py +279 -4
  37. package/scripts/forge-shadow.py +7 -1
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-summarize.py +698 -0
  40. package/scripts/forge-ui-options.sh +10 -0
  41. package/scripts/forge_brief/__init__.py +587 -0
  42. package/scripts/forge_brief/answers.py +459 -0
  43. package/scripts/forge_dataset/__init__.py +10 -0
  44. package/scripts/forge_dataset/export.py +18 -4
  45. package/scripts/forge_dataset/facts.py +6 -4
  46. package/scripts/forge_dataset/harvest.py +40 -6
  47. package/scripts/forge_dataset/history.py +5 -3
  48. package/scripts/forge_decide/__init__.py +11 -1
  49. package/scripts/forge_locations.py +366 -0
  50. package/scripts/forge_registry.py +19 -0
  51. package/scripts/forge_retro/__init__.py +417 -0
  52. package/scripts/forge_retro/issues.py +1193 -0
  53. package/scripts/forge_retro/report.py +671 -0
  54. package/scripts/forge_side/__init__.py +477 -0
  55. package/scripts/forge_storage.py +515 -0
  56. package/ui/README.md +68 -8
  57. package/ui/docs/api.md +205 -17
  58. package/ui/forge_ui/control.py +92 -11
  59. package/ui/forge_ui/export.py +24 -5
  60. package/ui/forge_ui/links.py +337 -0
  61. package/ui/forge_ui/models.py +57 -4
  62. package/ui/forge_ui/projects.py +4 -1
  63. package/ui/forge_ui/reader.py +661 -30
  64. package/ui/forge_ui/static/app.js +86 -4
  65. package/ui/forge_ui/static/briefview.js +302 -0
  66. package/ui/forge_ui/static/checksview.js +6 -2
  67. package/ui/forge_ui/static/controls.js +5 -0
  68. package/ui/forge_ui/static/index.html +3 -0
  69. package/ui/forge_ui/static/panel.js +268 -2
  70. package/ui/forge_ui/static/runmodel.js +13 -1
  71. package/ui/forge_ui/static/storageview.js +271 -0
  72. package/ui/forge_ui/static/style.css +99 -3
  73. package/ui/forge_ui/static/worktreesview.js +3 -3
  74. package/ui/forge_ui/storage.py +136 -0
  75. package/ui/forge_ui/transcripts.py +35 -10
  76. 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
 
@@ -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())})
@@ -28,8 +28,8 @@ import re
28
28
  import sys
29
29
  from collections import Counter, defaultdict
30
30
 
31
- from . import connect, dataset_dir
32
- from .export import Runs, Store, _ending_qa, _gate_decision, shadow_pairs
31
+ from . import connect, dataset_dir, is_side_role
32
+ from .export import Runs, Store, _ending_qa, _gate_decision, not_an_attempt, shadow_pairs
33
33
 
34
34
  FACTS = {'reach': ('main', 'realistic', 'unusual'), 'origin': ('new', 'existing'),
35
35
  'evidence': ('ran', 'traced', 'suspected')}
@@ -156,7 +156,9 @@ def report(runs: Runs, repo: str = None) -> dict:
156
156
  by_sev = defaultdict(Counter)
157
157
  for e in runs.store.of('dispatch'):
158
158
  d = e['d']
159
- if d.get('role') not in ('qa', 'qa_shadow') or not mine(e) or not isinstance(d.get('findings'), list):
159
+ role = d.get('role')
160
+ # qa and qa_shadow are reviews. A side dispatch is neither, even when it carries a findings list.
161
+ if role not in ('qa', 'qa_shadow') or is_side_role(role) or not mine(e) or not isinstance(d.get('findings'), list):
160
162
  continue
161
163
  found = [f for f in d['findings'] if isinstance(f, dict)]
162
164
  cov['reviews'] += 1
@@ -194,7 +196,7 @@ def report(runs: Runs, repo: str = None) -> dict:
194
196
 
195
197
  rules = out['rules']
196
198
  for (run, task, role), rows in runs.dispatches.items():
197
- if role != 'qa' or not rows or not mine(rows[0]):
199
+ if not_an_attempt(role) or role != 'qa' or not rows or not mine(rows[0]):
198
200
  continue
199
201
  ended = sorted(_ending_qa(rows).items(), key=lambda item: item[0] or 0)
200
202
  attempts = [n for n, _ in ended]
@@ -25,13 +25,16 @@ from pathlib import Path
25
25
 
26
26
  from . import SCRIPTS, put_blob, put_file, sha256
27
27
 
28
- DISPATCH_ROLES = ('dwarf', 'qa', 'planner')
28
+ DISPATCH_ROLES = ('dwarf', 'qa', 'planner', 'side')
29
+ # The file role stays `side`. Harvest records side_<kind> (see dispatch_event);
30
+ # attempt statistics tell those apart with forge_dataset.is_side_role.
29
31
  PIPELINE_ROLES = ('task', 'solo', 'verification', 'parallel')
30
32
  TASKS_COLS = ('id', 'deps', 'difficulty', 'files', 'dwarf', 'qa', 'title')
31
33
  STRUCTURED = ('codex', 'claude', 'openclaude', 'grok', 'opencode') # as forge-runtime.py's: .last is the message, not the log
32
34
  # Plan files that change what a plan decides, added to its rid only when present (see plan_event).
33
35
  PLAN_RID_LATER = ('decompose_level', 'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session',
34
- 'implementer_session', 'pre_review_tests')
36
+ 'implementer_session', 'pre_review_tests', 'retro_mode', 'brief', 'brief_scope', 'brief_model',
37
+ 'summaries', 'summaries_model')
35
38
 
36
39
  # Files a task or solo execution may write. begin() snapshots their signatures so
37
40
  # finish() can tell this execution's outputs from what an earlier one left behind.
@@ -315,6 +318,13 @@ def locate(root: str | Path, role: str | None = None) -> dict:
315
318
  if p.parent.parent.name == 'shadow' and (p.parent.parent.parent / 'tasks.tsv').exists():
316
319
  # <plan>/shadow/<task>/<attempt>-<k>: a shadow review (forge-shadow.py) of that task.
317
320
  plan, ctx['task'], ctx['scope'], ctx['shadow'] = p.parent.parent.parent, p.parent.name, 'task', True
321
+ elif p.parent.parent.parent.name == 'side' and (p.parent.parent.parent.parent / 'tasks.tsv').exists():
322
+ # <plan>/side/<kind>/<task>/<n>: a side dispatch (brief or summary) of that task.
323
+ # The role is recorded as side_<kind> (see dispatch_event), the way a shadow
324
+ # review is recorded as qa_shadow. n counts dispatches; it is not the attempt.
325
+ kind = p.parent.parent.name
326
+ plan, ctx['task'], ctx['scope'], ctx['side'] = (
327
+ p.parent.parent.parent.parent, p.parent.name, 'task', kind)
318
328
  elif p.parent.name == 'tasks' and (p.parent.parent / 'tasks.tsv').exists():
319
329
  plan, ctx['task'], ctx['scope'] = p.parent.parent, p.name, 'task'
320
330
  elif p.name.startswith('final-review-') and (p.parent / 'tasks.tsv').exists():
@@ -423,6 +433,20 @@ def session_record(attempt: Path, role: str, metrics: dict) -> tuple[str | None,
423
433
  return recorded, 'continued' if kv(path).get('mode') == 'continued' else 'failed'
424
434
 
425
435
 
436
+ def side_kind(root: Path, role: str, prov: dict | None = None) -> str | None:
437
+ """The kind of a side dispatch (`brief`, `summary`), or None when this is not one.
438
+
439
+ The files stay `side.*`. The kind lives in the directory `<plan>/side/<kind>/...`
440
+ and, when a caller already knows it, in prov['side'].
441
+ """
442
+ if role != 'side':
443
+ return None
444
+ recorded = (prov or {}).get('side')
445
+ if isinstance(recorded, str) and recorded and '/' not in recorded and recorded not in ('.', '..'):
446
+ return recorded
447
+ return locate(root, role).get('side')
448
+
449
+
426
450
  def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov: dict, src: str = 'live') -> dict:
427
451
  metrics = read_json(attempt / 'metrics.json') or {}
428
452
  resolved = kv(attempt / (role + '.resolved'))
@@ -437,10 +461,19 @@ def dispatch_event(attempt: Path, root: Path, role: str, harness: str, rc, prov:
437
461
  verdict = verdict_of(message) if message is not None else None
438
462
  found, parsed = parse_review(message) if role == 'qa' else ([], True)
439
463
  shadow = prov.get('shadow')
464
+ kind = side_kind(root, role, prov)
465
+ # A shadow review keeps the qa files and contract but is never a task's review, so it
466
+ # gets its own role: nothing that reads qa dispatches mistakes it for the one that decided.
467
+ # A side dispatch keeps the side files and is recorded as side_<kind>, so attempt
468
+ # statistics can leave it out (forge_dataset.is_side_role).
469
+ if kind:
470
+ recorded_role = 'side_' + kind
471
+ elif shadow and role == 'qa':
472
+ recorded_role = 'qa_shadow'
473
+ else:
474
+ recorded_role = role
440
475
  data = dict(
441
- # A shadow review keeps the qa files and contract but is never a task's review, so it
442
- # gets its own role: nothing that reads qa dispatches mistakes it for the one that decided.
443
- role='qa_shadow' if shadow and role == 'qa' else role, alias=resolved.get('alias'), harness=harness, model=resolved.get('model'),
476
+ role=recorded_role, alias=resolved.get('alias'), harness=harness, model=resolved.get('model'),
444
477
  effort=None if not effort or effort.startswith('<') else effort,
445
478
  # metrics.json is the record finish() wrote. A run from before that record falls
446
479
  # back to the resolved line, which exists only when a tier was asked.
@@ -774,7 +807,8 @@ def plan_event(plan: Path, prov: dict, src: str = 'live', inventory: bool = True
774
807
  jev_coupling=read_json(plan / 'jev-coupling.json'),
775
808
  options=dict({name: first_line(plan / name) for name in ('verify_retries', 'timeout', 'final_qa',
776
809
  'shadow_qa', 'shadow_rate', 'explore', 'reviewer_session',
777
- 'implementer_session')
810
+ 'implementer_session', 'retro_mode', 'brief', 'brief_scope',
811
+ 'brief_model', 'summaries', 'summaries_model')
778
812
  if (plan / name).exists()}, qa_threshold=threshold, qa_threshold_source=threshold_source),
779
813
  flags=sorted(name for name in ('no_memory', 'no_ripwire', 'yolo_dwarf', 'yolo_qa', 'pre_review_tests')
780
814
  if (plan / name).exists()),