@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,587 @@
1
+ """Brief mode: each task's open questions, asked before the task starts (#135).
2
+
3
+ `write` makes one read-only `side` dispatch of kind `brief` per task and stores the reply:
4
+
5
+ - `tasks/<id>/brief.json`: `{questions: [{id, text, why, options, default, scope: "task",
6
+ must_answer}], model, generated_at}`. `must_answer` survives only under the `gated` level.
7
+ - `tasks/<id>/brief.parked.json`: the same shape for questions whose scope is `wave` or
8
+ `plan`. Only task scope acts in this issue, so wider scopes are parked whatever
9
+ `brief_scope` says.
10
+
11
+ A broken writer never holds a task: a reply that is not valid JSON, or has the wrong
12
+ shape, is retried once, and a second failure (or a failed dispatch) stores
13
+ `{"questions": [], "error": "<reason>"}` as `brief.json`.
14
+
15
+ `show` lists every question with its state: `open`, `answered` (`brief.answers.json`),
16
+ `late` (`brief.late.json`) or `possibly_stale` (a flag in brief.json).
17
+
18
+ `answer` and `stale` (answers.py) write those. An answer given before the task starts
19
+ goes to `brief.answers.json`; one given after goes to `brief.late.json` and does not
20
+ change the task. `stale` sets `possibly_stale` on the open questions of tasks that
21
+ depend on a merge which changed files outside the ones it declared.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import concurrent.futures
26
+ import contextlib
27
+ import fcntl
28
+ import json
29
+ import os
30
+ from pathlib import Path
31
+ import shutil
32
+ import sys
33
+ import tempfile
34
+ import threading
35
+ import time
36
+
37
+ SCRIPTS = Path(__file__).resolve().parent.parent
38
+ if str(SCRIPTS) not in sys.path:
39
+ sys.path.insert(0, str(SCRIPTS))
40
+
41
+ import forge_side # noqa: E402
42
+
43
+ MAX_QUESTIONS = 3
44
+ DEP_PROMPT_LIMIT = 4096
45
+ SCOPES = ('task', 'wave', 'plan')
46
+ DEFAULT_JOBS = 4
47
+
48
+ REMINDER = (
49
+ 'Your last reply was not usable: %s.\n'
50
+ 'Reply again with the JSON object only, in exactly the format above: no prose, no code fence.\n'
51
+ 'If there is nothing to ask, reply {"questions": []}.\n')
52
+
53
+
54
+ class NotAPlan(Exception):
55
+ """The plan dir is missing or has no tasks.tsv. The command exits 3."""
56
+
57
+
58
+ class BriefOff(Exception):
59
+ """Brief mode is off for this plan. `reason` is why. The command exits 3."""
60
+
61
+ def __init__(self, reason: str):
62
+ super().__init__(reason)
63
+ self.reason = reason
64
+
65
+
66
+ class UnknownTask(Exception):
67
+ """`--task` names a task the plan does not have. The command exits 2."""
68
+
69
+
70
+ # --- plan reading ----------------------------------------------------------------
71
+
72
+ def _text(path: Path) -> str:
73
+ try:
74
+ return Path(path).read_text(encoding='utf-8', errors='replace')
75
+ except OSError:
76
+ return ''
77
+
78
+
79
+ def _json(path: Path):
80
+ try:
81
+ return json.loads(Path(path).read_text(encoding='utf-8'))
82
+ except (OSError, UnicodeError, ValueError):
83
+ return None
84
+
85
+
86
+ def task_dir(plan, task) -> Path:
87
+ return Path(plan) / 'tasks' / str(task)
88
+
89
+
90
+ def read_tasks(plan) -> list:
91
+ """The `tasks.tsv` rows, in file order: `{id, deps, difficulty, files, dwarf, qa, title, row}`."""
92
+ path = Path(plan) / 'tasks.tsv'
93
+ if not path.is_file():
94
+ raise NotAPlan(str(plan))
95
+ tasks = []
96
+ for line in _text(path).splitlines():
97
+ if not line.strip() or line.startswith('#'):
98
+ continue
99
+ cols = line.split('\t')
100
+ cols += [''] * (7 - len(cols))
101
+ deps = [dep for dep in cols[1].split(',') if dep and dep != '-']
102
+ tasks.append({'id': cols[0], 'deps': deps, 'difficulty': cols[2], 'files': cols[3],
103
+ 'dwarf': cols[4], 'qa': cols[5], 'title': '\t'.join(cols[6:]).strip(),
104
+ 'row': line})
105
+ return tasks
106
+
107
+
108
+ def _waves(plan) -> dict:
109
+ found = {}
110
+ for line in _text(Path(plan) / 'waves.tsv').splitlines():
111
+ cols = line.split('\t')
112
+ if len(cols) >= 2 and cols[0].strip().isdigit():
113
+ found.setdefault(cols[1].strip(), int(cols[0]))
114
+ return found
115
+
116
+
117
+ def ordered(plan, tasks: list) -> list:
118
+ """Earliest projected start first: wave order from waves.tsv, then tasks.tsv order."""
119
+ waves = _waves(plan)
120
+ last = max(waves.values(), default=0) + 1
121
+ ranked = sorted(enumerate(tasks), key=lambda item: (waves.get(item[1]['id'], last), item[0]))
122
+ return [task for _, task in ranked]
123
+
124
+
125
+ # --- storage ---------------------------------------------------------------------
126
+
127
+ def atomic_write(path: Path, text: str) -> None:
128
+ path = Path(path)
129
+ path.parent.mkdir(parents=True, exist_ok=True)
130
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
131
+ try:
132
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle:
133
+ handle.write(text)
134
+ os.replace(tmp, path)
135
+ except BaseException:
136
+ try:
137
+ os.unlink(tmp)
138
+ except OSError:
139
+ pass
140
+ raise
141
+
142
+
143
+ def _dump(value) -> str:
144
+ return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
145
+
146
+
147
+ def _now() -> str:
148
+ return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
149
+
150
+
151
+ # --- the prompt and the reply ----------------------------------------------------
152
+
153
+ def build_prompt(plan, task: dict, tasks: list, repo: str) -> str:
154
+ plan = Path(plan)
155
+ tdir = task_dir(plan, task['id'])
156
+ by_id = {item['id']: item for item in tasks}
157
+ parts = [
158
+ 'You are preparing the open questions for ONE task of a multi-task coding run, '
159
+ 'before an implementer starts it.\n'
160
+ 'Read the task below. The repository is at %s: you may read it and you must not '
161
+ 'write to it.\n' % repo,
162
+ '## The task: %s\n' % task['id'],
163
+ '### prompt.md\n\n%s\n' % _text(tdir / 'prompt.md').strip(),
164
+ ]
165
+ approach = _text(tdir / 'approach.md').strip()
166
+ if approach:
167
+ parts.append('### approach.md\n\n%s\n' % approach)
168
+ parts.append('### Its tasks.tsv row\n\n(id, deps, difficulty, files, dwarf, qa, title)\n\n%s\n' % task['row'])
169
+ parts.append('### All tasks in this run\n\n%s\n' % '\n'.join(
170
+ '- %s: %s' % (item['id'], item['title'] or '(no title)') for item in tasks))
171
+ deps = [by_id[dep] for dep in task['deps'] if dep in by_id]
172
+ if deps:
173
+ parts.append('### Its dependencies\' prompts (each capped at 4 KB)\n')
174
+ for dep in deps:
175
+ parts.append('#### %s\n\n%s\n' % (
176
+ dep['id'], forge_side.cap(_text(task_dir(plan, dep['id']) / 'prompt.md').strip(),
177
+ DEP_PROMPT_LIMIT)))
178
+ parts.append(
179
+ '## What to ask\n\n'
180
+ 'Ask an open question only where a design choice or an ambiguity would make the '
181
+ 'implementer guess. "Nothing to ask" is the expected answer for most tasks: when '
182
+ 'the prompt and approach are clear, reply {"questions": []}. At most %d questions.\n\n'
183
+ 'Each question is answered by a person before or while earlier tasks are built, so '
184
+ 'make it short and answerable in a line, and give the options when there are a few.\n\n'
185
+ '## Reply format\n\n'
186
+ 'Reply with JSON only, no prose and no code fence:\n\n'
187
+ '{"questions": [{"text": "...", "why": "...", "options": ["..."], "default": "...", '
188
+ '"scope": "task", "must_answer": false}]}\n\n'
189
+ '- text: the question.\n'
190
+ '- why: what depends on the answer.\n'
191
+ '- options: the plausible answers, or [].\n'
192
+ '- default: what the implementer will do if nobody answers.\n'
193
+ '- scope: "task" when only this task needs the answer, "wave" when the other tasks '
194
+ 'that run alongside it do too, "plan" when the whole run does.\n'
195
+ '- must_answer: true only when the decision cannot be defaulted safely.\n' % MAX_QUESTIONS)
196
+ return '\n'.join(parts)
197
+
198
+
199
+ def _strip_fence(text: str) -> str:
200
+ text = text.strip()
201
+ if text.startswith('```'):
202
+ lines = text.splitlines()[1:]
203
+ if lines and lines[-1].strip().startswith('```'):
204
+ lines = lines[:-1]
205
+ text = '\n'.join(lines).strip()
206
+ return text
207
+
208
+
209
+ def parse_reply(reply):
210
+ """`(questions, None)` for a usable reply, else `(None, reason)`.
211
+
212
+ Each question is `{text, why, options, default, scope, must_answer}` and all six must
213
+ be there: a question without a `default` leaves the implementer to guess, which is what
214
+ the brief is for. A missing key, a wrong type, an empty `text`, `why` or `default`, or
215
+ an unknown scope makes the reply unusable.
216
+ """
217
+ if not isinstance(reply, str) or not reply.strip():
218
+ return None, 'empty reply'
219
+ text = _strip_fence(reply)
220
+ try:
221
+ data = json.loads(text)
222
+ except (ValueError, RecursionError):
223
+ start, end = text.find('{'), text.rfind('}')
224
+ data = None
225
+ if 0 <= start < end:
226
+ try:
227
+ data = json.loads(text[start:end + 1])
228
+ except (ValueError, RecursionError):
229
+ data = None
230
+ if data is None:
231
+ return None, 'reply is not valid JSON'
232
+ if not isinstance(data, dict) or not isinstance(data.get('questions'), list):
233
+ return None, 'reply has no "questions" list'
234
+ found = []
235
+ for index, item in enumerate(data['questions'], 1):
236
+ where = 'question %d' % index
237
+ if not isinstance(item, dict):
238
+ return None, '%s is not an object' % where
239
+ missing = [key for key in ('text', 'why', 'options', 'default', 'scope', 'must_answer') if key not in item]
240
+ if missing:
241
+ return None, '%s has no %s' % (where, ', '.join(missing))
242
+ text_value, why, default = item['text'], item['why'], item['default']
243
+ for name, value in (('text', text_value), ('why', why), ('default', default)):
244
+ if not isinstance(value, str) or not value.strip():
245
+ return None, '%s: %s must be a non-empty string' % (where, name)
246
+ options = item['options']
247
+ if not isinstance(options, list) or not all(isinstance(opt, str) for opt in options):
248
+ return None, '%s: options must be a list of strings' % where
249
+ scope = item['scope']
250
+ if scope not in SCOPES:
251
+ return None, '%s: scope must be task, wave or plan' % where
252
+ must = item['must_answer']
253
+ if not isinstance(must, bool):
254
+ return None, '%s: must_answer must be true or false' % where
255
+ entry = {'text': text_value.strip(), 'why': why.strip(), 'options': [o.strip() for o in options],
256
+ 'default': default.strip(), 'scope': scope, 'must_answer': must}
257
+ try: # a lone surrogate (JSON "\\ud800") parses but cannot be stored as UTF-8
258
+ _dump(entry).encode('utf-8')
259
+ except UnicodeError:
260
+ return None, '%s has characters that cannot be stored' % where
261
+ found.append(entry)
262
+ return found, None
263
+
264
+
265
+ def _parse_safely(reply):
266
+ """`parse_reply` that never raises: any surprise is an unusable reply."""
267
+ try:
268
+ return parse_reply(reply)
269
+ except Exception as error: # noqa: BLE001 - a broken reply must not hold the task
270
+ return None, 'reply could not be read (%s)' % type(error).__name__
271
+
272
+
273
+ def _ask(plan, task: dict, prompt: str, spec: str, timeout: int):
274
+ """One dispatch, a retry on an unusable reply. `(questions, None)`, `(None, error)` or `(None, None)` for a cap skip."""
275
+ reminder = ''
276
+ error = 'no reply'
277
+ for attempt in range(2):
278
+ result = forge_side.run('brief', plan, task['id'], prompt + reminder, spec, timeout=timeout)
279
+ if not result['ok']:
280
+ if result['reason'] == 'cap' and attempt == 0:
281
+ return None, None
282
+ if result['reason'] == 'cap':
283
+ # The first reply used the last slot: the task still gets its error brief.
284
+ return None, '%s (no retry: dispatch cap reached)' % error
285
+ return None, 'dispatch failed: %s' % (result['reason'] or 'error')
286
+ questions, error = _parse_safely(result['last'])
287
+ if questions is not None:
288
+ return questions, None
289
+ reminder = '\n\n' + REMINDER % error
290
+ return None, error
291
+
292
+
293
+ # --- write -----------------------------------------------------------------------
294
+
295
+ STORED = ('brief.json', 'brief.parked.json', 'brief.answers.json', 'brief.late.json')
296
+
297
+
298
+ def _archive(tdir: Path, stamp: str) -> None:
299
+ """Set a task's earlier brief aside before a new one replaces it.
300
+
301
+ Question ids restart at q1, so answers or late notes left next to a regenerated
302
+ brief.json would attach to unrelated new questions. They move to
303
+ `brief.history/<stamp>/` together with the old brief.json and parked file.
304
+ """
305
+ present = [name for name in STORED if (tdir / name).exists()]
306
+ if not present:
307
+ return
308
+ base = tdir / 'brief.history'
309
+ dest = base / stamp.replace(':', '')
310
+ number = 1
311
+ while dest.exists():
312
+ number += 1
313
+ dest = base / ('%s-%d' % (stamp.replace(':', ''), number))
314
+ dest.mkdir(parents=True)
315
+ for name in present:
316
+ if name == 'brief.json':
317
+ shutil.copy2(tdir / name, dest / name) # stays until the new one replaces it
318
+ else:
319
+ os.replace(tdir / name, dest / name)
320
+
321
+
322
+ @contextlib.contextmanager
323
+ def _task_lock(plan: Path, task: str):
324
+ """Exclusive per-task lock: two writers on one task take turns, so the second sees the first's brief.json."""
325
+ tdir = task_dir(plan, task)
326
+ tdir.mkdir(parents=True, exist_ok=True)
327
+ fd = os.open(str(tdir / '.brief.lock'), os.O_CREAT | os.O_RDWR, 0o644)
328
+ try:
329
+ fcntl.flock(fd, fcntl.LOCK_EX)
330
+ yield
331
+ finally:
332
+ os.close(fd)
333
+
334
+
335
+ def _record(plan: Path, task: str, model: str, level: str, questions, error) -> dict:
336
+ """Store brief.json (and brief.parked.json) for one task and emit the events."""
337
+ stamp = _now()
338
+ kept, parked = [], []
339
+ for number, question in enumerate((questions or [])[:MAX_QUESTIONS], 1):
340
+ entry = dict(question, id='q%d' % number)
341
+ entry['must_answer'] = bool(question['must_answer']) and level == 'gated'
342
+ (kept if question['scope'] == 'task' else parked).append(entry)
343
+ brief = {'questions': kept, 'model': model, 'generated_at': stamp}
344
+ if error:
345
+ brief['error'] = error
346
+ tdir = task_dir(plan, task)
347
+ _archive(tdir, stamp)
348
+ atomic_write(tdir / 'brief.json', _dump(brief))
349
+ parked_path = tdir / 'brief.parked.json'
350
+ if parked:
351
+ atomic_write(parked_path, _dump({'questions': parked, 'model': model, 'generated_at': stamp}))
352
+ else:
353
+ try:
354
+ parked_path.unlink()
355
+ except OSError:
356
+ pass
357
+ for entry, is_parked in [(q, False) for q in kept] + [(q, True) for q in parked]:
358
+ _emit(plan, task, entry, is_parked)
359
+ return {'questions': len(kept), 'parked': len(parked), 'error': error}
360
+
361
+
362
+ def _emit(plan: Path, task: str, question: dict, parked: bool) -> None:
363
+ """One `brief_question` dataset event. Fail-open, like every other capture."""
364
+ try:
365
+ from forge_dataset.capture import point
366
+ point('brief_question', str(plan), str(task), {
367
+ 'task': str(task), 'qid': question['id'], 'scope': question['scope'],
368
+ 'must_answer': question['must_answer'], 'parked': parked})
369
+ except Exception:
370
+ pass
371
+
372
+
373
+ def _guard(plan) -> tuple:
374
+ """`(plan Path, brief settings)`, or raise `NotAPlan` / `BriefOff`."""
375
+ plan = Path(plan)
376
+ if not plan.is_dir():
377
+ raise NotAPlan(str(plan))
378
+ found = forge_side.settings(plan)['brief']
379
+ if found['level'] == 'off':
380
+ raise BriefOff('env' if os.environ.get('FORGE_BRIEF', '').strip().lower() == 'off' else 'off')
381
+ return plan, found
382
+
383
+
384
+ def write(plan, task=None, jobs=DEFAULT_JOBS, force=False, timeout=900, progress=None) -> list:
385
+ """Write the questions of every task that has no brief.json (or only `task`).
386
+
387
+ Returns one `{task, status, reason, questions, parked}` per task considered, in the
388
+ order they were dispatched: status is `written`, `error` (an empty brief.json with the
389
+ error recorded) or `skipped` (with a reason: `exists`, `cap`, ...). Raises `NotAPlan`,
390
+ `BriefOff` (brief is off, or `allowed` refuses for a plan-wide reason) and `UnknownTask`.
391
+ """
392
+ plan, found = _guard(plan)
393
+ tasks = read_tasks(plan)
394
+ if task is not None and task not in {item['id'] for item in tasks}:
395
+ raise UnknownTask(task)
396
+ ok, reason = forge_side.allowed('brief', plan)
397
+ if not ok and reason != 'cap':
398
+ raise BriefOff(reason)
399
+ chosen = [item for item in ordered(plan, tasks) if task is None or item['id'] == task]
400
+ spec, level = found['model'], found['level']
401
+ repo = _text(plan / 'repo').strip()
402
+ report = {}
403
+
404
+ mute = threading.Lock()
405
+
406
+ def say(item, status, reason=None, stats=None):
407
+ stats = stats or {}
408
+ with mute:
409
+ report[item['id']] = {'task': item['id'], 'status': status, 'reason': reason,
410
+ 'questions': stats.get('questions', 0), 'parked': stats.get('parked', 0)}
411
+ if progress:
412
+ progress(report[item['id']])
413
+
414
+ # Workers prepare in parallel but dispatch in order. A worker may start only once the one
415
+ # before it has really begun its dispatch (its `side/brief/<task>/` gained a new run dir)
416
+ # or has finished without one (skipped, capped, failed; a skip waits its own turn first, so
417
+ # the chain of earlier tasks is never cut short): saying "I am about to" is not
418
+ # enough, the thread can still be descheduled before it dispatches.
419
+ todo = []
420
+ for item in chosen:
421
+ if (task_dir(plan, item['id']) / 'brief.json').exists() and not force:
422
+ say(item, 'skipped', 'exists')
423
+ else:
424
+ todo.append(item)
425
+ intent = [threading.Event() for _ in todo]
426
+ finished = [threading.Event() for _ in todo]
427
+ baseline = [0] * len(todo)
428
+
429
+ def runs(item) -> int:
430
+ try:
431
+ return sum(1 for _ in (plan / 'side' / 'brief' / item['id']).iterdir())
432
+ except OSError:
433
+ return 0
434
+
435
+ turned = [False] * len(todo)
436
+
437
+ def wait_for_turn(index):
438
+ if turned[index]:
439
+ return
440
+ turned[index] = True
441
+ if not index:
442
+ return
443
+ before = todo[index - 1]
444
+ intent[index - 1].wait()
445
+ while not finished[index - 1].is_set() and runs(before) <= baseline[index - 1]:
446
+ finished[index - 1].wait(0.01)
447
+
448
+ def work(index, item):
449
+ try:
450
+ with _task_lock(plan, item['id']):
451
+ if (task_dir(plan, item['id']) / 'brief.json').exists() and not force:
452
+ say(item, 'skipped', 'exists')
453
+ return
454
+ ok_now, why = forge_side.allowed('brief', plan)
455
+ if not ok_now:
456
+ say(item, 'skipped', why)
457
+ return
458
+ wait_for_turn(index)
459
+ prompt = build_prompt(plan, item, tasks, repo)
460
+ baseline[index] = runs(item)
461
+ intent[index].set()
462
+ questions, error = _ask(plan, item, prompt, spec, timeout)
463
+ if questions is None and error is None:
464
+ say(item, 'skipped', 'cap')
465
+ return
466
+ try:
467
+ stats = _record(plan, item['id'], spec, level, questions, error)
468
+ except Exception as failure: # noqa: BLE001
469
+ error = 'could not store the reply (%s)' % type(failure).__name__
470
+ stats = _record(plan, item['id'], spec, level, [], error)
471
+ say(item, 'error' if error else 'written', error, stats)
472
+ except BaseException as failure:
473
+ say(item, 'error', 'internal error: %s' % failure)
474
+ try: # a broken writer must not leave the task without a brief.json
475
+ if not (task_dir(plan, item['id']) / 'brief.json').exists():
476
+ _record(plan, item['id'], spec, level, [], 'internal error: %s' % type(failure).__name__)
477
+ except Exception: # noqa: BLE001
478
+ pass
479
+ finally:
480
+ # A worker that skips still takes its turn before it signals: otherwise the one
481
+ # after it would see "done" and overtake an earlier task that has not dispatched.
482
+ wait_for_turn(index)
483
+ intent[index].set()
484
+ finished[index].set()
485
+
486
+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=max(1, int(jobs)))
487
+ try:
488
+ for future in [pool.submit(work, index, item) for index, item in enumerate(todo)]:
489
+ future.result()
490
+ finally:
491
+ pool.shutdown(wait=True)
492
+ return [report[item['id']] for item in chosen]
493
+
494
+
495
+ # --- show ------------------------------------------------------------------------
496
+
497
+ def _entries(data) -> dict:
498
+ """`{qid: entry}` from an answers or late file: a dict by qid, or a list of entries with a `qid`."""
499
+ if isinstance(data, dict):
500
+ return {str(k): v for k, v in data.items() if isinstance(v, dict)}
501
+ if isinstance(data, list):
502
+ return {str(v['qid']): v for v in data if isinstance(v, dict) and 'qid' in v}
503
+ return {}
504
+
505
+
506
+ def _questions(data) -> list:
507
+ items = data.get('questions') if isinstance(data, dict) else None
508
+ return [q for q in items if isinstance(q, dict)] if isinstance(items, list) else []
509
+
510
+
511
+ def collect(plan, task=None) -> dict:
512
+ """Every question of the plan (or one task) with its state, flagged open ones first.
513
+
514
+ `{questions: [...], parked: [...], errors: [{task, error}]}`. A question carries
515
+ `task`, `id`, `text`, `why`, `options`, `default`, `scope`, `must_answer`, `state`
516
+ and, once answered, `answer`.
517
+ """
518
+ plan, _ = _guard(plan)
519
+ tasks = read_tasks(plan)
520
+ if task is not None and task not in {item['id'] for item in tasks}:
521
+ raise UnknownTask(task)
522
+ questions, parked, errors = [], [], []
523
+ for item in ordered(plan, tasks):
524
+ if task is not None and item['id'] != task:
525
+ continue
526
+ tdir = task_dir(plan, item['id'])
527
+ brief = _json(tdir / 'brief.json')
528
+ if brief is None:
529
+ continue
530
+ if isinstance(brief, dict) and brief.get('error'):
531
+ errors.append({'task': item['id'], 'error': str(brief['error'])})
532
+ answers = _entries(_json(tdir / 'brief.answers.json'))
533
+ late = _entries(_json(tdir / 'brief.late.json'))
534
+ whole_stale = isinstance(brief, dict) and brief.get('possibly_stale') is True
535
+ for q in _questions(brief):
536
+ qid = str(q.get('id', ''))
537
+ row = {'task': item['id'], 'id': qid, 'text': q.get('text', ''), 'why': q.get('why', ''),
538
+ 'options': q.get('options') or [], 'default': q.get('default', ''),
539
+ 'scope': q.get('scope', 'task'), 'must_answer': bool(q.get('must_answer'))}
540
+ if qid in answers:
541
+ row['state'], row['answer'] = 'answered', answers[qid]
542
+ elif qid in late:
543
+ row['state'], row['answer'] = 'late', late[qid]
544
+ elif q.get('possibly_stale') is True or whole_stale:
545
+ row['state'] = 'possibly_stale'
546
+ else:
547
+ row['state'] = 'open'
548
+ questions.append(row)
549
+ for q in _questions(_json(tdir / 'brief.parked.json')):
550
+ parked.append({'task': item['id'], 'id': str(q.get('id', '')), 'text': q.get('text', ''),
551
+ 'why': q.get('why', ''), 'options': q.get('options') or [],
552
+ 'default': q.get('default', ''), 'scope': q.get('scope', 'wave'),
553
+ 'must_answer': bool(q.get('must_answer')), 'state': 'parked'})
554
+
555
+ def rank(row):
556
+ if row['state'] in ('open', 'possibly_stale'):
557
+ return 0 if row['must_answer'] else 1
558
+ return 2
559
+ questions.sort(key=rank) # stable: wave order and question order inside a rank
560
+ return {'questions': questions, 'parked': parked, 'errors': errors}
561
+
562
+
563
+ def render(found: dict) -> str:
564
+ lines = []
565
+
566
+ def block(row):
567
+ flag = ' [must answer]' if row['must_answer'] else ''
568
+ lines.append('%s/%s %s%s' % (row['task'], row['id'], row['state'], flag))
569
+ lines.append(' %s' % row['text'])
570
+ if row['options']:
571
+ lines.append(' options: %s' % ' | '.join(row['options']))
572
+ if row['default']:
573
+ lines.append(' default: %s' % row['default'])
574
+ if row.get('answer'):
575
+ lines.append(' answer: %s (%s)' % (row['answer'].get('text', ''), row['answer'].get('actor', '')))
576
+ for row in found['questions']:
577
+ block(row)
578
+ if found['parked']:
579
+ lines.append('')
580
+ lines.append('Parked (wider scope):')
581
+ for row in found['parked']:
582
+ block(row)
583
+ for err in found['errors']:
584
+ lines.append('%s: the question writer failed: %s' % (err['task'], err['error']))
585
+ if not lines:
586
+ lines.append('no questions')
587
+ return '\n'.join(lines) + '\n'