@giamme/forge 0.17.0 → 0.19.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -0,0 +1,831 @@
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, so wider scopes are parked whatever `brief_scope` says.
9
+ A wave question from a task that belongs to a group also stores `"group": "<gid>"`;
10
+ a plan question from such a task stores `"group": null`. A task in no group stores
11
+ neither key, so its parked file stays as it was.
12
+
13
+ When the task belongs to a group (`<plan>/groups.tsv`), the prompt names that group's
14
+ title, goal and the other tasks in it, and says what `wave` and `plan` mean for the
15
+ group. A task in no group gets the prompt it got before groups existed. A `wave` or
16
+ `plan` brief scope with no `groups.tsv` prints one note and continues; `brief.groups.noted`
17
+ keeps that note to once per plan. Nothing here acts on an answer.
18
+
19
+ A broken writer never holds a task: a reply that is not valid JSON, or has the wrong
20
+ shape, is retried once, and a second failure (or a failed dispatch) stores
21
+ `{"questions": [], "error": "<reason>"}` as `brief.json`.
22
+
23
+ `show` lists every question with its state: `open`, `answered` (`brief.answers.json`),
24
+ `late` (`brief.late.json`) or `possibly_stale` (a flag in brief.json). A task with
25
+ `brief.affected` is marked `affected by <pid>`, and `flagged (already started)` when
26
+ that marker is `flag_only`. `--json` includes those rows as `affected`.
27
+
28
+ `answer` and `stale` (answers.py) write those. An answer given before the task starts
29
+ goes to `brief.answers.json`; one given after goes to `brief.late.json` and does not
30
+ change the task. `stale` sets `possibly_stale` on the open questions of tasks that
31
+ depend on a merge which changed files outside the ones it declared.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import concurrent.futures
36
+ import contextlib
37
+ import fcntl
38
+ import json
39
+ import os
40
+ from pathlib import Path
41
+ import shutil
42
+ import sys
43
+ import tempfile
44
+ import threading
45
+ import time
46
+
47
+ SCRIPTS = Path(__file__).resolve().parent.parent
48
+ if str(SCRIPTS) not in sys.path:
49
+ sys.path.insert(0, str(SCRIPTS))
50
+
51
+ import forge_groups # noqa: E402
52
+ import forge_side # noqa: E402
53
+
54
+ MAX_QUESTIONS = 3
55
+ DEP_PROMPT_LIMIT = 4096
56
+ SCOPES = ('task', 'wave', 'plan')
57
+ DEFAULT_JOBS = 4
58
+
59
+ REMINDER = (
60
+ 'Your last reply was not usable: %s.\n'
61
+ 'Reply again with the JSON object only, in exactly the format above: no prose, no code fence.\n'
62
+ 'If there is nothing to ask, reply {"questions": []}.\n')
63
+
64
+
65
+ class NotAPlan(Exception):
66
+ """The plan dir is missing or has no tasks.tsv. The command exits 3."""
67
+
68
+
69
+ class BriefOff(Exception):
70
+ """Brief mode is off for this plan. `reason` is why. The command exits 3."""
71
+
72
+ def __init__(self, reason: str):
73
+ super().__init__(reason)
74
+ self.reason = reason
75
+
76
+
77
+ class UnknownTask(Exception):
78
+ """`--task` names a task the plan does not have. The command exits 2."""
79
+
80
+
81
+ # --- plan reading ----------------------------------------------------------------
82
+
83
+ def _text(path: Path) -> str:
84
+ try:
85
+ return Path(path).read_text(encoding='utf-8', errors='replace')
86
+ except OSError:
87
+ return ''
88
+
89
+
90
+ def _json(path: Path):
91
+ try:
92
+ return json.loads(Path(path).read_text(encoding='utf-8'))
93
+ except (OSError, UnicodeError, ValueError):
94
+ return None
95
+
96
+
97
+ def task_dir(plan, task) -> Path:
98
+ return Path(plan) / 'tasks' / str(task)
99
+
100
+
101
+ def read_tasks(plan) -> list:
102
+ """The `tasks.tsv` rows, in file order: `{id, deps, difficulty, files, dwarf, qa, title, row}`."""
103
+ path = Path(plan) / 'tasks.tsv'
104
+ if not path.is_file():
105
+ raise NotAPlan(str(plan))
106
+ tasks = []
107
+ for line in _text(path).splitlines():
108
+ if not line.strip() or line.startswith('#'):
109
+ continue
110
+ cols = line.split('\t')
111
+ cols += [''] * (7 - len(cols))
112
+ deps = [dep for dep in cols[1].split(',') if dep and dep != '-']
113
+ tasks.append({'id': cols[0], 'deps': deps, 'difficulty': cols[2], 'files': cols[3],
114
+ 'dwarf': cols[4], 'qa': cols[5], 'title': '\t'.join(cols[6:]).strip(),
115
+ 'row': line})
116
+ return tasks
117
+
118
+
119
+ def _waves(plan) -> dict:
120
+ found = {}
121
+ for line in _text(Path(plan) / 'waves.tsv').splitlines():
122
+ cols = line.split('\t')
123
+ if len(cols) >= 2 and cols[0].strip().isdigit():
124
+ found.setdefault(cols[1].strip(), int(cols[0]))
125
+ return found
126
+
127
+
128
+ def ordered(plan, tasks: list) -> list:
129
+ """Earliest projected start first: wave order from waves.tsv, then tasks.tsv order."""
130
+ waves = _waves(plan)
131
+ last = max(waves.values(), default=0) + 1
132
+ ranked = sorted(enumerate(tasks), key=lambda item: (waves.get(item[1]['id'], last), item[0]))
133
+ return [task for _, task in ranked]
134
+
135
+
136
+ # --- storage ---------------------------------------------------------------------
137
+
138
+ def atomic_write(path: Path, text: str) -> None:
139
+ path = Path(path)
140
+ path.parent.mkdir(parents=True, exist_ok=True)
141
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
142
+ try:
143
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle:
144
+ handle.write(text)
145
+ os.replace(tmp, path)
146
+ except BaseException:
147
+ try:
148
+ os.unlink(tmp)
149
+ except OSError:
150
+ pass
151
+ raise
152
+
153
+
154
+ def _dump(value) -> str:
155
+ return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
156
+
157
+
158
+ def _now() -> str:
159
+ return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
160
+
161
+
162
+ # --- the prompt and the reply ----------------------------------------------------
163
+
164
+ def _task_group(plan, task_id):
165
+ """The task's group, or None when it is in none (or groups.tsv cannot be read).
166
+
167
+ A broken groups.tsv must not hold the task: the writer then behaves as it does for a
168
+ task in no group.
169
+ """
170
+ try:
171
+ return forge_groups.group_of(plan, task_id)
172
+ except (forge_groups.GroupError, OSError, UnicodeDecodeError):
173
+ return None
174
+
175
+
176
+ def _group_section(group, task: dict, tasks: list) -> str:
177
+ """The group block that follows the task's own prompt.md and approach.md.
178
+
179
+ The goal line is left out when the goal is `-`: that cell means the group has none,
180
+ and the prompt does not invent a `(no goal)` line. An empty title stays as `-`, which
181
+ is the cell groups.tsv stores.
182
+ """
183
+ by_id = {item['id']: item for item in tasks}
184
+ lines = ['Group %s: %s' % (group.id, group.title)]
185
+ if group.goal != '-':
186
+ lines.append('Goal: %s' % group.goal)
187
+ others = []
188
+ for member in group.members:
189
+ if member == task['id']:
190
+ continue
191
+ item = by_id.get(member)
192
+ title = (item['title'] if item else '') or '(no title)'
193
+ others.append('%s — %s' % (member, title))
194
+ if others:
195
+ lines.append('Other tasks in this group: %s' % ', '.join(others))
196
+ else:
197
+ lines.append('Other tasks in this group:')
198
+ return '\n'.join(lines) + '\n'
199
+
200
+
201
+ # The scope sentence is the only line that changes for a grouped task. The ungrouped
202
+ # wording stays the sentence the prompt had before groups, so that prompt is byte-identical.
203
+ _ASK = (
204
+ '## What to ask\n\n'
205
+ 'Ask an open question only where a design choice or an ambiguity would make the '
206
+ 'implementer guess. "Nothing to ask" is the expected answer for most tasks: when '
207
+ 'the prompt and approach are clear, reply {"questions": []}. At most %d questions.\n\n'
208
+ 'Each question is answered by a person before or while earlier tasks are built, so '
209
+ 'make it short and answerable in a line, and give the options when there are a few.\n\n'
210
+ '## Reply format\n\n'
211
+ 'Reply with JSON only, no prose and no code fence:\n\n'
212
+ '{"questions": [{"text": "...", "why": "...", "options": ["..."], "default": "...", '
213
+ '"scope": "task", "must_answer": false}]}\n\n'
214
+ '- text: the question.\n'
215
+ '- why: what depends on the answer.\n'
216
+ '- options: the plausible answers, or [].\n'
217
+ '- default: what the implementer will do if nobody answers.\n'
218
+ '%s'
219
+ '- must_answer: true only when the decision cannot be defaulted safely.\n')
220
+ _SCOPE_UNGROUPED = (
221
+ '- scope: "task" when only this task needs the answer, "wave" when the other tasks '
222
+ 'that run alongside it do too, "plan" when the whole run does.\n')
223
+ _SCOPE_GROUPED = (
224
+ '- scope: "task" when only this task needs the answer, "wave" when the answer would '
225
+ 'change how several tasks of this group are done, "plan" when the answer would add, '
226
+ 'remove or split tasks, or change their order.\n')
227
+
228
+
229
+ def build_prompt(plan, task: dict, tasks: list, repo: str) -> str:
230
+ plan = Path(plan)
231
+ tdir = task_dir(plan, task['id'])
232
+ by_id = {item['id']: item for item in tasks}
233
+ group = _task_group(plan, task['id'])
234
+ parts = [
235
+ 'You are preparing the open questions for ONE task of a multi-task coding run, '
236
+ 'before an implementer starts it.\n'
237
+ 'Read the task below. The repository is at %s: you may read it and you must not '
238
+ 'write to it.\n' % repo,
239
+ '## The task: %s\n' % task['id'],
240
+ '### prompt.md\n\n%s\n' % _text(tdir / 'prompt.md').strip(),
241
+ ]
242
+ approach = _text(tdir / 'approach.md').strip()
243
+ if approach:
244
+ parts.append('### approach.md\n\n%s\n' % approach)
245
+ if group is not None:
246
+ parts.append(_group_section(group, task, tasks))
247
+ parts.append('### Its tasks.tsv row\n\n(id, deps, difficulty, files, dwarf, qa, title)\n\n%s\n' % task['row'])
248
+ parts.append('### All tasks in this run\n\n%s\n' % '\n'.join(
249
+ '- %s: %s' % (item['id'], item['title'] or '(no title)') for item in tasks))
250
+ deps = [by_id[dep] for dep in task['deps'] if dep in by_id]
251
+ if deps:
252
+ parts.append('### Its dependencies\' prompts (each capped at 4 KB)\n')
253
+ for dep in deps:
254
+ parts.append('#### %s\n\n%s\n' % (
255
+ dep['id'], forge_side.cap(_text(task_dir(plan, dep['id']) / 'prompt.md').strip(),
256
+ DEP_PROMPT_LIMIT)))
257
+ scope = _SCOPE_GROUPED if group is not None else _SCOPE_UNGROUPED
258
+ parts.append(_ASK % (MAX_QUESTIONS, scope))
259
+ return '\n'.join(parts)
260
+
261
+
262
+ def _strip_fence(text: str) -> str:
263
+ text = text.strip()
264
+ if text.startswith('```'):
265
+ lines = text.splitlines()[1:]
266
+ if lines and lines[-1].strip().startswith('```'):
267
+ lines = lines[:-1]
268
+ text = '\n'.join(lines).strip()
269
+ return text
270
+
271
+
272
+ def parse_reply(reply):
273
+ """`(questions, None)` for a usable reply, else `(None, reason)`.
274
+
275
+ Each question is `{text, why, options, default, scope, must_answer}` and all six must
276
+ be there: a question without a `default` leaves the implementer to guess, which is what
277
+ the brief is for. A missing key, a wrong type, an empty `text`, `why` or `default`, or
278
+ an unknown scope makes the reply unusable.
279
+ """
280
+ if not isinstance(reply, str) or not reply.strip():
281
+ return None, 'empty reply'
282
+ text = _strip_fence(reply)
283
+ try:
284
+ data = json.loads(text)
285
+ except (ValueError, RecursionError):
286
+ start, end = text.find('{'), text.rfind('}')
287
+ data = None
288
+ if 0 <= start < end:
289
+ try:
290
+ data = json.loads(text[start:end + 1])
291
+ except (ValueError, RecursionError):
292
+ data = None
293
+ if data is None:
294
+ return None, 'reply is not valid JSON'
295
+ if not isinstance(data, dict) or not isinstance(data.get('questions'), list):
296
+ return None, 'reply has no "questions" list'
297
+ found = []
298
+ for index, item in enumerate(data['questions'], 1):
299
+ where = 'question %d' % index
300
+ if not isinstance(item, dict):
301
+ return None, '%s is not an object' % where
302
+ missing = [key for key in ('text', 'why', 'options', 'default', 'scope', 'must_answer') if key not in item]
303
+ if missing:
304
+ return None, '%s has no %s' % (where, ', '.join(missing))
305
+ text_value, why, default = item['text'], item['why'], item['default']
306
+ for name, value in (('text', text_value), ('why', why), ('default', default)):
307
+ if not isinstance(value, str) or not value.strip():
308
+ return None, '%s: %s must be a non-empty string' % (where, name)
309
+ options = item['options']
310
+ if not isinstance(options, list) or not all(isinstance(opt, str) for opt in options):
311
+ return None, '%s: options must be a list of strings' % where
312
+ scope = item['scope']
313
+ if scope not in SCOPES:
314
+ return None, '%s: scope must be task, wave or plan' % where
315
+ must = item['must_answer']
316
+ if not isinstance(must, bool):
317
+ return None, '%s: must_answer must be true or false' % where
318
+ entry = {'text': text_value.strip(), 'why': why.strip(), 'options': [o.strip() for o in options],
319
+ 'default': default.strip(), 'scope': scope, 'must_answer': must}
320
+ try: # a lone surrogate (JSON "\\ud800") parses but cannot be stored as UTF-8
321
+ _dump(entry).encode('utf-8')
322
+ except UnicodeError:
323
+ return None, '%s has characters that cannot be stored' % where
324
+ found.append(entry)
325
+ return found, None
326
+
327
+
328
+ def _parse_safely(reply):
329
+ """`parse_reply` that never raises: any surprise is an unusable reply."""
330
+ try:
331
+ return parse_reply(reply)
332
+ except Exception as error: # noqa: BLE001 - a broken reply must not hold the task
333
+ return None, 'reply could not be read (%s)' % type(error).__name__
334
+
335
+
336
+ def _ask(plan, task: dict, prompt: str, spec: str, timeout: int):
337
+ """One dispatch, a retry on an unusable reply. `(questions, None)`, `(None, error)` or `(None, None)` for a cap skip."""
338
+ reminder = ''
339
+ error = 'no reply'
340
+ for attempt in range(2):
341
+ result = forge_side.run('brief', plan, task['id'], prompt + reminder, spec, timeout=timeout)
342
+ if not result['ok']:
343
+ if result['reason'] == 'cap' and attempt == 0:
344
+ return None, None
345
+ if result['reason'] == 'cap':
346
+ # The first reply used the last slot: the task still gets its error brief.
347
+ return None, '%s (no retry: dispatch cap reached)' % error
348
+ return None, 'dispatch failed: %s' % (result['reason'] or 'error')
349
+ questions, error = _parse_safely(result['last'])
350
+ if questions is not None:
351
+ return questions, None
352
+ reminder = '\n\n' + REMINDER % error
353
+ return None, error
354
+
355
+
356
+ # --- write -----------------------------------------------------------------------
357
+
358
+ STORED = ('brief.json', 'brief.parked.json', 'brief.answers.json', 'brief.late.json')
359
+
360
+
361
+ def _archive(tdir: Path, stamp: str) -> None:
362
+ """Set a task's earlier brief aside before a new one replaces it.
363
+
364
+ Question ids restart at q1, so answers or late notes left next to a regenerated
365
+ brief.json would attach to unrelated new questions. They move to
366
+ `brief.history/<stamp>/` together with the old brief.json and parked file.
367
+ """
368
+ present = [name for name in STORED if (tdir / name).exists()]
369
+ if not present:
370
+ return
371
+ base = tdir / 'brief.history'
372
+ dest = base / stamp.replace(':', '')
373
+ number = 1
374
+ while dest.exists():
375
+ number += 1
376
+ dest = base / ('%s-%d' % (stamp.replace(':', ''), number))
377
+ dest.mkdir(parents=True)
378
+ for name in present:
379
+ if name == 'brief.json':
380
+ shutil.copy2(tdir / name, dest / name) # stays until the new one replaces it
381
+ else:
382
+ os.replace(tdir / name, dest / name)
383
+
384
+
385
+ @contextlib.contextmanager
386
+ def _task_lock(plan: Path, task: str):
387
+ """Exclusive per-task lock: two writers on one task take turns, so the second sees the first's brief.json."""
388
+ tdir = task_dir(plan, task)
389
+ tdir.mkdir(parents=True, exist_ok=True)
390
+ fd = os.open(str(tdir / '.brief.lock'), os.O_CREAT | os.O_RDWR, 0o644)
391
+ try:
392
+ fcntl.flock(fd, fcntl.LOCK_EX)
393
+ yield
394
+ finally:
395
+ os.close(fd)
396
+
397
+
398
+ def _record(plan: Path, task: str, model: str, level: str, questions, error) -> dict:
399
+ """Store brief.json (and brief.parked.json) for one task and emit the events.
400
+
401
+ A parked question from a grouped task records `group`: the group id for `wave`, null
402
+ for `plan`. An ungrouped task's parked questions have no `group` key.
403
+ """
404
+ stamp = _now()
405
+ group = _task_group(plan, task)
406
+ kept, parked = [], []
407
+ for number, question in enumerate((questions or [])[:MAX_QUESTIONS], 1):
408
+ entry = dict(question, id='q%d' % number)
409
+ entry['must_answer'] = bool(question['must_answer']) and level == 'gated'
410
+ if question['scope'] == 'task':
411
+ kept.append(entry)
412
+ else:
413
+ if group is not None:
414
+ entry['group'] = group.id if question['scope'] == 'wave' else None
415
+ parked.append(entry)
416
+ brief = {'questions': kept, 'model': model, 'generated_at': stamp}
417
+ if error:
418
+ brief['error'] = error
419
+ tdir = task_dir(plan, task)
420
+ _archive(tdir, stamp)
421
+ atomic_write(tdir / 'brief.json', _dump(brief))
422
+ parked_path = tdir / 'brief.parked.json'
423
+ if parked:
424
+ atomic_write(parked_path, _dump({'questions': parked, 'model': model, 'generated_at': stamp}))
425
+ else:
426
+ try:
427
+ parked_path.unlink()
428
+ except OSError:
429
+ pass
430
+ for entry, is_parked in [(q, False) for q in kept] + [(q, True) for q in parked]:
431
+ _emit(plan, task, entry, is_parked)
432
+ return {'questions': len(kept), 'parked': len(parked), 'error': error}
433
+
434
+
435
+ def _emit(plan: Path, task: str, question: dict, parked: bool) -> None:
436
+ """One `brief_question` dataset event. Fail-open, like every other capture.
437
+
438
+ `group` is set only for a parked question that names a group. A plan question, an
439
+ ungrouped question and a task question omit the field, so those events stay as they were.
440
+ """
441
+ try:
442
+ from forge_dataset.capture import point
443
+ body = {
444
+ 'task': str(task), 'qid': question['id'], 'scope': question['scope'],
445
+ 'must_answer': question['must_answer'], 'parked': parked}
446
+ if question.get('group'):
447
+ body['group'] = question['group']
448
+ point('brief_question', str(plan), str(task), body)
449
+ except Exception:
450
+ pass
451
+
452
+
453
+ # Said once per plan, when brief is on at wave or plan scope and the plan has no groups.
454
+ GROUPS_NOTE = (
455
+ 'brief scope %s: no groups.tsv — run plan --groups waves, or let the planner write groups; '
456
+ 'wave questions stay parked\n')
457
+
458
+
459
+ def _note_missing_groups(plan: Path, scope: str) -> None:
460
+ """One note when wave or plan scope has nothing to attach a wave question to.
461
+
462
+ The marker `brief.groups.noted` is created first, so a second writer, in this process
463
+ or another, does not say it again. The write itself is unchanged.
464
+ """
465
+ if scope not in ('wave', 'plan'):
466
+ return
467
+ if (plan / 'groups.tsv').is_file():
468
+ return
469
+ marker = plan / 'brief.groups.noted'
470
+ try:
471
+ fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
472
+ except FileExistsError:
473
+ return
474
+ except OSError:
475
+ sys.stderr.write(GROUPS_NOTE % scope)
476
+ sys.stderr.flush()
477
+ return
478
+ try:
479
+ os.write(fd, (scope + '\n').encode())
480
+ except OSError:
481
+ pass
482
+ finally:
483
+ os.close(fd)
484
+ sys.stderr.write(GROUPS_NOTE % scope)
485
+ sys.stderr.flush()
486
+
487
+
488
+ def note_missing_groups(plan) -> None:
489
+ """Say the missing-groups note now, on this process's stderr, if it is due.
490
+
491
+ `forge-parallel.sh` calls this before it starts the writer in the background (advisory and
492
+ gated), whose output goes to brief.out where nobody would read the note. The marker then
493
+ keeps the writer quiet. Never raises: a note is not worth stopping a run for.
494
+ """
495
+ try:
496
+ plan = Path(plan)
497
+ found = forge_side.settings(plan)['brief']
498
+ if found['level'] != 'off':
499
+ _note_missing_groups(plan, found['scope'])
500
+ except Exception:
501
+ pass
502
+
503
+
504
+ def _guard(plan) -> tuple:
505
+ """`(plan Path, brief settings)`, or raise `NotAPlan` / `BriefOff`."""
506
+ plan = Path(plan)
507
+ if not plan.is_dir():
508
+ raise NotAPlan(str(plan))
509
+ found = forge_side.settings(plan)['brief']
510
+ if found['level'] == 'off':
511
+ raise BriefOff('env' if os.environ.get('FORGE_BRIEF', '').strip().lower() == 'off' else 'off')
512
+ return plan, found
513
+
514
+
515
+ def write(plan, task=None, jobs=DEFAULT_JOBS, force=False, timeout=900, progress=None) -> list:
516
+ """Write the questions of every task that has no brief.json (or only `task`).
517
+
518
+ Returns one `{task, status, reason, questions, parked}` per task considered, in the
519
+ order they were dispatched: status is `written`, `error` (an empty brief.json with the
520
+ error recorded) or `skipped` (with a reason: `exists`, `cap`, ...). Raises `NotAPlan`,
521
+ `BriefOff` (brief is off, or `allowed` refuses for a plan-wide reason) and `UnknownTask`.
522
+
523
+ With brief scope `wave` or `plan` and no `groups.tsv`, prints one note to stderr and
524
+ continues. `brief.groups.noted` keeps the note to once per plan.
525
+ """
526
+ plan, found = _guard(plan)
527
+ tasks = read_tasks(plan)
528
+ if task is not None and task not in {item['id'] for item in tasks}:
529
+ raise UnknownTask(task)
530
+ ok, reason = forge_side.allowed('brief', plan)
531
+ if not ok and reason != 'cap':
532
+ raise BriefOff(reason)
533
+ # plan resolves these flags in the shell, before this writer starts. Say it here, once.
534
+ _note_missing_groups(plan, found['scope'])
535
+ chosen = [item for item in ordered(plan, tasks) if task is None or item['id'] == task]
536
+ spec, level = found['model'], found['level']
537
+ repo = _text(plan / 'repo').strip()
538
+ report = {}
539
+
540
+ mute = threading.Lock()
541
+
542
+ def say(item, status, reason=None, stats=None):
543
+ stats = stats or {}
544
+ with mute:
545
+ report[item['id']] = {'task': item['id'], 'status': status, 'reason': reason,
546
+ 'questions': stats.get('questions', 0), 'parked': stats.get('parked', 0)}
547
+ if progress:
548
+ progress(report[item['id']])
549
+
550
+ # Workers prepare in parallel but dispatch in order. A worker may start only once the one
551
+ # before it has really begun its dispatch (its `side/brief/<task>/` gained a new run dir)
552
+ # or has finished without one (skipped, capped, failed; a skip waits its own turn first, so
553
+ # the chain of earlier tasks is never cut short): saying "I am about to" is not
554
+ # enough, the thread can still be descheduled before it dispatches.
555
+ todo = []
556
+ for item in chosen:
557
+ if (task_dir(plan, item['id']) / 'brief.json').exists() and not force:
558
+ say(item, 'skipped', 'exists')
559
+ else:
560
+ todo.append(item)
561
+ intent = [threading.Event() for _ in todo]
562
+ finished = [threading.Event() for _ in todo]
563
+ baseline = [0] * len(todo)
564
+
565
+ def runs(item) -> int:
566
+ try:
567
+ return sum(1 for _ in (plan / 'side' / 'brief' / item['id']).iterdir())
568
+ except OSError:
569
+ return 0
570
+
571
+ turned = [False] * len(todo)
572
+
573
+ def wait_for_turn(index):
574
+ if turned[index]:
575
+ return
576
+ turned[index] = True
577
+ if not index:
578
+ return
579
+ before = todo[index - 1]
580
+ intent[index - 1].wait()
581
+ while not finished[index - 1].is_set() and runs(before) <= baseline[index - 1]:
582
+ finished[index - 1].wait(0.01)
583
+
584
+ def work(index, item):
585
+ try:
586
+ with _task_lock(plan, item['id']):
587
+ if (task_dir(plan, item['id']) / 'brief.json').exists() and not force:
588
+ say(item, 'skipped', 'exists')
589
+ return
590
+ ok_now, why = forge_side.allowed('brief', plan)
591
+ if not ok_now:
592
+ say(item, 'skipped', why)
593
+ return
594
+ wait_for_turn(index)
595
+ prompt = build_prompt(plan, item, tasks, repo)
596
+ baseline[index] = runs(item)
597
+ intent[index].set()
598
+ questions, error = _ask(plan, item, prompt, spec, timeout)
599
+ if questions is None and error is None:
600
+ say(item, 'skipped', 'cap')
601
+ return
602
+ try:
603
+ stats = _record(plan, item['id'], spec, level, questions, error)
604
+ except Exception as failure: # noqa: BLE001
605
+ error = 'could not store the reply (%s)' % type(failure).__name__
606
+ stats = _record(plan, item['id'], spec, level, [], error)
607
+ say(item, 'error' if error else 'written', error, stats)
608
+ except BaseException as failure:
609
+ say(item, 'error', 'internal error: %s' % failure)
610
+ try: # a broken writer must not leave the task without a brief.json
611
+ if not (task_dir(plan, item['id']) / 'brief.json').exists():
612
+ _record(plan, item['id'], spec, level, [], 'internal error: %s' % type(failure).__name__)
613
+ except Exception: # noqa: BLE001
614
+ pass
615
+ finally:
616
+ # A worker that skips still takes its turn before it signals: otherwise the one
617
+ # after it would see "done" and overtake an earlier task that has not dispatched.
618
+ wait_for_turn(index)
619
+ intent[index].set()
620
+ finished[index].set()
621
+
622
+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=max(1, int(jobs)))
623
+ try:
624
+ for future in [pool.submit(work, index, item) for index, item in enumerate(todo)]:
625
+ future.result()
626
+ finally:
627
+ pool.shutdown(wait=True)
628
+ return [report[item['id']] for item in chosen]
629
+
630
+
631
+ # --- show ------------------------------------------------------------------------
632
+
633
+ def _entries(data) -> dict:
634
+ """`{qid: entry}` from an answers or late file: a dict by qid, or a list of entries with a `qid`."""
635
+ if isinstance(data, dict):
636
+ return {str(k): v for k, v in data.items() if isinstance(v, dict)}
637
+ if isinstance(data, list):
638
+ return {str(v['qid']): v for v in data if isinstance(v, dict) and 'qid' in v}
639
+ return {}
640
+
641
+
642
+ def _questions(data) -> list:
643
+ items = data.get('questions') if isinstance(data, dict) else None
644
+ return [q for q in items if isinstance(q, dict)] if isinstance(items, list) else []
645
+
646
+
647
+ def _affected_rows(plan, tasks, only=None) -> list:
648
+ """`brief.affected` markers in tasks.tsv order: `{task, pid, reason, t, flag_only}`.
649
+
650
+ A task with no brief.json is included when it has a marker (an added task that was
651
+ marked and not regenerated yet). A marker that is not the object `apply` writes is skipped.
652
+ """
653
+ rows = []
654
+ for item in tasks:
655
+ if only is not None and item['id'] != only:
656
+ continue
657
+ data = _json(task_dir(plan, item['id']) / 'brief.affected')
658
+ if not isinstance(data, dict):
659
+ continue
660
+ pid, reason = data.get('pid'), data.get('reason')
661
+ if not isinstance(pid, str) or not pid or not isinstance(reason, str) or not reason:
662
+ continue
663
+ rows.append({'task': item['id'], 'pid': pid, 'reason': reason, 't': data.get('t'),
664
+ 'flag_only': data.get('flag_only') is True})
665
+ return rows
666
+
667
+
668
+ def collect(plan, task=None) -> dict:
669
+ """Every question of the plan (or one task) with its state, flagged open ones first.
670
+
671
+ `{questions: [...], parked: [...], errors: [{task, error}], affected: [...]}`. A question
672
+ carries `task`, `id`, `text`, `why`, `options`, `default`, `scope`, `must_answer`, `state`
673
+ and, once answered, `answer`. A parked question stores `group` when its file has that
674
+ key: the group id, or null for a plan question. `affected` is the `brief.affected` markers
675
+ (`task`, `pid`, `reason`, `t`, `flag_only`), in tasks.tsv order.
676
+ """
677
+ plan, _ = _guard(plan)
678
+ tasks = read_tasks(plan)
679
+ if task is not None and task not in {item['id'] for item in tasks}:
680
+ raise UnknownTask(task)
681
+ affected = _affected_rows(plan, tasks, task)
682
+ questions, parked, errors = [], [], []
683
+ for item in ordered(plan, tasks):
684
+ if task is not None and item['id'] != task:
685
+ continue
686
+ tdir = task_dir(plan, item['id'])
687
+ brief = _json(tdir / 'brief.json')
688
+ if brief is None:
689
+ continue
690
+ if isinstance(brief, dict) and brief.get('error'):
691
+ errors.append({'task': item['id'], 'error': str(brief['error'])})
692
+ answers = _entries(_json(tdir / 'brief.answers.json'))
693
+ late = _entries(_json(tdir / 'brief.late.json'))
694
+ whole_stale = isinstance(brief, dict) and brief.get('possibly_stale') is True
695
+ for q in _questions(brief):
696
+ qid = str(q.get('id', ''))
697
+ row = {'task': item['id'], 'id': qid, 'text': q.get('text', ''), 'why': q.get('why', ''),
698
+ 'options': q.get('options') or [], 'default': q.get('default', ''),
699
+ 'scope': q.get('scope', 'task'), 'must_answer': bool(q.get('must_answer'))}
700
+ if qid in answers:
701
+ row['state'], row['answer'] = 'answered', answers[qid]
702
+ elif qid in late:
703
+ row['state'], row['answer'] = 'late', late[qid]
704
+ elif q.get('possibly_stale') is True or whole_stale:
705
+ row['state'] = 'possibly_stale'
706
+ else:
707
+ row['state'] = 'open'
708
+ questions.append(row)
709
+ for q in _questions(_json(tdir / 'brief.parked.json')):
710
+ row = {'task': item['id'], 'id': str(q.get('id', '')), 'text': q.get('text', ''),
711
+ 'why': q.get('why', ''), 'options': q.get('options') or [],
712
+ 'default': q.get('default', ''), 'scope': q.get('scope', 'wave'),
713
+ 'must_answer': bool(q.get('must_answer')), 'state': 'parked'}
714
+ if 'group' in q:
715
+ row['group'] = q.get('group')
716
+ parked.append(row)
717
+
718
+ def rank(row):
719
+ if row['state'] in ('open', 'possibly_stale'):
720
+ return 0 if row['must_answer'] else 1
721
+ return 2
722
+ questions.sort(key=rank) # stable: wave order and question order inside a rank
723
+ return {'questions': questions, 'parked': parked, 'errors': errors, 'affected': affected}
724
+
725
+
726
+ def _question_lines(row) -> list:
727
+ flag = ' [must answer]' if row['must_answer'] else ''
728
+ out = ['%s/%s %s%s' % (row['task'], row['id'], row['state'], flag), ' %s' % row['text']]
729
+ if row['options']:
730
+ out.append(' options: %s' % ' | '.join(row['options']))
731
+ if row['default']:
732
+ out.append(' default: %s' % row['default'])
733
+ if row.get('answer'):
734
+ out.append(' answer: %s (%s)' % (row['answer'].get('text', ''), row['answer'].get('actor', '')))
735
+ return out
736
+
737
+
738
+ def _group_titles(plan) -> dict:
739
+ if not plan:
740
+ return {}
741
+ try:
742
+ return {g.id: g.title for g in forge_groups.load(plan)}
743
+ except (forge_groups.GroupError, OSError, UnicodeDecodeError):
744
+ return {}
745
+
746
+
747
+ def _grouped_parked_lines(rows, plan) -> list:
748
+ """Parked questions that carry a `group` key, listed by group, then under `Plan:`.
749
+
750
+ A wave question is `Group <gid> (<title>): <question>`, with the asking task on the
751
+ next line. The title comes from groups.tsv and the parentheses are left off when it
752
+ is `-` or the group is gone. A plan question (`group` null) goes under `Plan:`.
753
+ A question with no `group` key, in a plan that also has grouped ones, stays in the
754
+ old parked block so an older file is still shown.
755
+ """
756
+ titles = _group_titles(plan)
757
+ order, by, plans, loose = [], {}, [], []
758
+ for row in rows:
759
+ if 'group' not in row:
760
+ loose.append(row)
761
+ continue
762
+ gid = row.get('group')
763
+ if not isinstance(gid, str) or not gid:
764
+ plans.append(row)
765
+ continue
766
+ if gid not in by:
767
+ order.append(gid)
768
+ by[gid] = []
769
+ by[gid].append(row)
770
+ lines = []
771
+ for gid in order:
772
+ title = titles.get(gid, '-')
773
+ head = 'Group %s (%s)' % (gid, title) if title and title != '-' else 'Group %s' % gid
774
+ for row in by[gid]:
775
+ lines.append('%s: %s' % (head, row['text']))
776
+ flag = ' [must answer]' if row['must_answer'] else ''
777
+ lines.append(' %s/%s %s%s' % (row['task'], row['id'], row['state'], flag))
778
+ if row['options']:
779
+ lines.append(' options: %s' % ' | '.join(row['options']))
780
+ if row['default']:
781
+ lines.append(' default: %s' % row['default'])
782
+ if plans:
783
+ lines.append('Plan:')
784
+ for row in plans:
785
+ lines.extend(_question_lines(row))
786
+ if loose:
787
+ lines.append('Parked (wider scope):')
788
+ for row in loose:
789
+ lines.extend(_question_lines(row))
790
+ return lines
791
+
792
+
793
+ def _affected_lines(rows) -> list:
794
+ """One line per marked task: `a affected by p3`, plus `flagged (already started)`."""
795
+ lines = []
796
+ for row in rows:
797
+ line = '%s affected by %s' % (row['task'], row['pid'])
798
+ if row.get('flag_only'):
799
+ line += ' flagged (already started)'
800
+ lines.append(line)
801
+ return lines
802
+
803
+
804
+ def render(found: dict, plan=None) -> str:
805
+ """Text for `forge brief show`. `plan` is where group titles are read.
806
+
807
+ A plan whose parked questions have no `group` key renders as it did before groups.
808
+ Marked tasks are listed after the questions (`affected by <pid>`).
809
+ """
810
+ lines = []
811
+ for row in found['questions']:
812
+ lines.extend(_question_lines(row))
813
+ parked = found['parked']
814
+ if parked:
815
+ lines.append('')
816
+ if any('group' in row for row in parked):
817
+ lines.extend(_grouped_parked_lines(parked, plan))
818
+ else:
819
+ lines.append('Parked (wider scope):')
820
+ for row in parked:
821
+ lines.extend(_question_lines(row))
822
+ for err in found['errors']:
823
+ lines.append('%s: the question writer failed: %s' % (err['task'], err['error']))
824
+ affected = _affected_lines(found.get('affected') or [])
825
+ if affected:
826
+ if lines:
827
+ lines.append('')
828
+ lines.extend(affected)
829
+ if not lines:
830
+ lines.append('no questions')
831
+ return '\n'.join(lines) + '\n'