@giamme/forge 0.18.0 → 0.20.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 (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -0,0 +1,1630 @@
1
+ """Wave-scoped proposals: an answer to a parked wave question becomes a diff that waits for approval (#136).
2
+
3
+ forge never re-plans silently. A person answers a parked `wave` question
4
+ (`brief.parked.answers.json`, see answers.py); `propose` asks the plan's brief model what that
5
+ answer changes in the question's group, and records the result as `<plan>/proposals/<pid>/`:
6
+
7
+ - `proposal.json`: `{pid, scope: "wave", group, task, qid, answer, summary, changes, state,
8
+ reason, created, actor}`. `state` is `proposed`, `refused`, `approved` or `rejected`.
9
+ - `diff.patch`: a unified diff (`a/` and `b/` paths relative to the plan) of every file the
10
+ proposal would change: `tasks/<id>/prompt.md`, `tasks/<id>/approach.md` and, for a `files`
11
+ change, `tasks.tsv`.
12
+ - `hash`: the sha256 of `diff.patch` and the current contents of every target (a `files` target
13
+ is the task's `tasks.tsv` row). `apply --approve <hash>` must quote it, so an approval is for
14
+ exactly the diff that was shown.
15
+
16
+ Wave confinement. Every change must name a member of the question's group that has not started
17
+ (a status other than PENDING, an `attempt` file or an `attempts.tsv` row) and may only carry
18
+ `prompt`, `approach` and `files`. A change that names another task, a started member or any other
19
+ field is not dropped: the whole proposal is `refused` with the reason, its diff is still written
20
+ for information, and `apply` never takes it. A reply that changes nothing is refused as well.
21
+
22
+ `apply` takes the plan's control lock (and a proposals lock that `reject` shares) and refuses,
23
+ with nothing changed, when the hash differs, the state is not `proposed`, a target has started,
24
+ or a target changed since the proposal. A `files` change is validated with `forge_groups.validate`
25
+ against a copy of the new tasks.tsv before anything is written; if it fails nothing is written.
26
+ Otherwise the files are written atomically, `groups.frozen` is re-frozen in the same step (the
27
+ fingerprint covers each member's files) and `waves.tsv` is recomputed the way `plan` does
28
+ (`forge-parallel.sh _waves`; skipped when the plan has no waves.tsv yet, since that file is what
29
+ marks a plan as planned). A write that fails halfway restores what it had written.
30
+
31
+ A live run. `_task` (`do_task_body` in forge-parallel.sh) builds `dwarf.input` at the start of
32
+ every attempt from `tasks/<id>/prompt.md` and `approach.md` (`forge-prompt.py --requirements ...
33
+ --approach ...`), read at dispatch: an unstarted task picks up an applied prompt or approach
34
+ change. The scheduler, though, reads tasks.tsv once when it starts and decides overlap from those
35
+ cached rows (`schedule()` in forge-schedule.py, `tasks[name][3]`; only `forge control add` and an
36
+ escalation refresh a row). So while a scheduler is live `apply` refuses a `files` change and says
37
+ to apply it after the run; prompt and approach changes go through. Apply checks the start state
38
+ under the lock, but the scheduler does not take that lock: a task that starts in the instant
39
+ between the check and the write reads whichever prompt it finds, as it would for any edit.
40
+
41
+ Plan scope (`scope: "plan"`). A parked `plan` question (answerable under `--brief-scope plan`) can
42
+ change the plan's structure: `changes` is then `{edits, add, remove, deps}`: `edits` are the wave
43
+ kind of change (prompt, approach, files) on any unstarted task, `add` new tasks, `remove` unstarted
44
+ ones and `deps` new dependency lists for unstarted tasks (a split is a remove plus adds). Validation
45
+ (`_plan_check`) refuses, with the reason, whatever would not be a plan `plan` could have written. The
46
+ hash covers the diff, `tasks.tsv`, `groups.tsv` and every edited prompt or approach file. `apply`
47
+ with no live run writes `tasks.tsv`, `groups.tsv` and the task dirs (a removed task's dir moves to
48
+ `tasks/.removed/<id>-<pid>/`, never deleted; added rows get dwarf and qa `-`) and writes a stale
49
+ marker into `groups.frozen` (the fingerprint covers only groups.tsv and the members' rows, so an
50
+ ungrouped change, or a plan with no groups, would not otherwise stop `run`): `run` then refuses until
51
+ `plan` validates, routes and freezes again, which overwrites the marker or removes it. A wave apply
52
+ meanwhile keeps the marker, and its result lists `groups.frozen` only when this step re-froze it.
53
+ With a live run only additions apply, queued in dependency order, each through `forge control add`;
54
+ the task joins no group. If a later add is refused, the tasks already queued stay and the proposal
55
+ is stored `approved` so it cannot be applied again, but the apply still raises. That is not a
56
+ successful apply: it does not mark `brief.affected` and it does not emit the approved event.
57
+
58
+ `brief_diff` events (`{pid, scope, group, state, tasks}`) record proposed, refused, approved and
59
+ rejected. An approved event also carries `affected` and `flagged`, the task ids `apply` marked.
60
+ The dispatch is a read-only `side` dispatch of kind `brief-change`, on the plan's brief
61
+ model, under the same `allowed` checks as the brief writer.
62
+
63
+ After a successful apply, every task the proposal changed or added, and every unstarted task
64
+ that depends (directly or transitively) on a changed, added or removed task, is taken from the
65
+ post-apply `tasks.tsv` plus the removed ids. Each gets `tasks/<id>/brief.affected`. An unstarted
66
+ one is `{pid, reason, t}` with reason `changed`, `added` or `dependent`, and its questions are
67
+ regenerated with `write --force`: an answer whose question text is still there is kept, and any
68
+ other answer goes to `brief.answers.prev.json` (removed when a later regeneration drops nothing,
69
+ so an earlier drop does not stay behind). The note names only the tasks whose questions were
70
+ rewritten: brief off and a dispatch-cap skip leave the old brief and are not claimed. A task
71
+ that has already started (running, merged, or anything else past PENDING) is not rewritten
72
+ and not dispatched; its marker sets `flag_only`.
73
+ `apply --no-regenerate` writes the markers and skips the dispatches. The next approved proposal
74
+ that touches a task replaces that task's marker; earlier proposals stay where they are.
75
+ """
76
+ from __future__ import annotations
77
+
78
+ import argparse
79
+ import contextlib
80
+ import difflib
81
+ import io
82
+ import fcntl
83
+ import hashlib
84
+ import json
85
+ import os
86
+ from pathlib import Path
87
+ import re
88
+ import shlex
89
+ import subprocess
90
+ import tempfile
91
+ import calendar
92
+ import time
93
+
94
+ import forge_brief
95
+ import forge_brief.answers as answers
96
+ import forge_groups
97
+ import forge_side
98
+
99
+ CHANGE_FIELDS = ('prompt', 'approach', 'files')
100
+ FILE_CAP = 6 * 1024
101
+ DIFFICULTIES = ('low', 'medium', 'high')
102
+ ACCEPTANCE_RE = re.compile(r'^#{2,}\s+Acceptance criteria\s*$', re.IGNORECASE | re.MULTILINE)
103
+ PLAN_KEYS = ('edits', 'add', 'remove', 'deps')
104
+ ADD_KEYS = ('id', 'deps', 'difficulty', 'files', 'title', 'prompt', 'approach', 'group')
105
+ PID_RE = re.compile(r'p[1-9][0-9]*')
106
+ STATES = ('proposed', 'refused', 'approved', 'rejected')
107
+
108
+ REMINDER = (
109
+ 'Your last reply was not usable: %s.\n'
110
+ 'Reply again with the JSON object only, in exactly the format above: no prose, no code fence.\n')
111
+
112
+
113
+ class Refused(Exception):
114
+ """The proposal, the apply or the reject cannot go ahead. `reason` is why. The command exits 3."""
115
+
116
+ def __init__(self, reason: str):
117
+ super().__init__(reason)
118
+ self.reason = reason
119
+
120
+
121
+ class NoSuchProposal(Exception):
122
+ """No `proposals/<pid>/proposal.json`. `valid` is the ids the plan does have. The command exits 2."""
123
+
124
+ def __init__(self, pid, valid):
125
+ super().__init__(pid)
126
+ self.pid = pid
127
+ self.valid = list(valid)
128
+
129
+
130
+ # --- reading the plan ------------------------------------------------------------------
131
+
132
+ def _read_bytes(path):
133
+ try:
134
+ return Path(path).read_bytes()
135
+ except OSError:
136
+ return None
137
+
138
+
139
+ def _text(data) -> str:
140
+ return '' if data is None else data.decode('utf-8', errors='replace')
141
+
142
+
143
+ def started(plan, task) -> bool:
144
+ """Whether the task is past PENDING: any status but PENDING (or merged), an `attempt` file or an `attempts.tsv` row."""
145
+ if (forge_brief.task_dir(plan, task) / 'attempt').exists():
146
+ return True
147
+ return answers.past_start(plan, task)
148
+
149
+
150
+ def _group_of(plan, gid):
151
+ try:
152
+ groups = forge_groups.load(plan)
153
+ except forge_groups.GroupError as error:
154
+ raise Refused('groups.tsv cannot be read: %s' % ' '.join(str(error).split()))
155
+ for group in groups:
156
+ if group.id == gid:
157
+ return group
158
+ return None
159
+
160
+
161
+ def _task_file(plan, task, name) -> Path:
162
+ return forge_brief.task_dir(plan, task) / name
163
+
164
+
165
+ def _rel(task, field) -> str:
166
+ return 'tasks/%s/%s.md' % (task, field)
167
+
168
+
169
+ def _tsv_lines(plan) -> list:
170
+ return _text(_read_bytes(Path(plan) / 'tasks.tsv')).splitlines(True)
171
+
172
+
173
+ def _row_files(plan, task):
174
+ """The task's `tasks.tsv` row and its files column, or `(None, None)`."""
175
+ for item in forge_brief.read_tasks(plan):
176
+ if item['id'] == task:
177
+ return item['row'], item['files']
178
+ return None, None
179
+
180
+
181
+ def _with_files(lines: list, new_files: dict) -> list:
182
+ """The tasks.tsv lines with the files column of each `{task: files}` replaced. Every other byte stays."""
183
+ out = []
184
+ for line in lines:
185
+ body = line.rstrip('\n')
186
+ cols = body.split('\t')
187
+ if body.strip() and not body.startswith('#') and len(cols) >= 7 and cols[0] in new_files:
188
+ cols[3] = new_files[cols[0]]
189
+ line = '\t'.join(cols) + ('\n' if line.endswith('\n') else '')
190
+ out.append(line)
191
+ return out
192
+
193
+
194
+ # --- the diff and its hash -------------------------------------------------------------
195
+
196
+ def _udiff(rel: str, old, new: str) -> str:
197
+ """A unified diff of one file. `old` is None when the file does not exist yet."""
198
+ old_lines = [] if old is None else old.splitlines(True)
199
+ out = []
200
+ for line in difflib.unified_diff(old_lines, new.splitlines(True),
201
+ '/dev/null' if old is None else 'a/' + rel, 'b/' + rel):
202
+ if not line.endswith('\n'):
203
+ line += '\n\\n'
204
+ out.append(line)
205
+ return ''.join(out)
206
+
207
+
208
+ def _digest(diff_text: str, targets: list) -> str:
209
+ """sha256 of the diff text and the current content of every target, in a fixed order."""
210
+ h = hashlib.sha256()
211
+ h.update(diff_text.encode('utf-8'))
212
+ for key, content in sorted(targets, key=lambda item: item[0]):
213
+ h.update(b'\0' + key.encode('utf-8') + b'\0')
214
+ h.update(b'<missing>' if content is None else content)
215
+ return h.hexdigest()
216
+
217
+
218
+ def _plan_changes(plan, changes: list):
219
+ """`(diff text, targets, edits)` for the changes against the plan as it is now.
220
+
221
+ `targets` is `[(key, current bytes or None)]`, the inputs of the hash: a prompt or approach
222
+ file, or `tasks.tsv#<task>` (that task's row) for a files change. `edits` is what apply
223
+ writes: `[(task, field, new text)]`. A field that is null or equal to what is there is not an
224
+ edit. Only the first change of a task counts; a duplicate is refused before this matters.
225
+ """
226
+ diffs, targets, edits, new_files = [], [], [], {}
227
+ seen = set()
228
+ for change in changes:
229
+ task = change['task']
230
+ if task in seen or not forge_side._safe_component(task):
231
+ continue
232
+ seen.add(task)
233
+ for field in ('prompt', 'approach'):
234
+ new = change.get(field)
235
+ if not isinstance(new, str):
236
+ continue
237
+ current = _read_bytes(_task_file(plan, task, field + '.md'))
238
+ if current is not None and _text(current) == new:
239
+ continue
240
+ targets.append((_rel(task, field), current))
241
+ diffs.append(_udiff(_rel(task, field), None if current is None else _text(current), new))
242
+ edits.append((task, field, new))
243
+ files = change.get('files')
244
+ if isinstance(files, str):
245
+ row, old = _row_files(plan, task)
246
+ if row is not None and old != files:
247
+ targets.append(('tasks.tsv#' + task, row.encode('utf-8')))
248
+ edits.append((task, 'files', files))
249
+ new_files[task] = files
250
+ if new_files:
251
+ old_lines = _tsv_lines(plan)
252
+ diffs.append(_udiff('tasks.tsv', ''.join(old_lines), ''.join(_with_files(old_lines, new_files))))
253
+ return ''.join(diffs), targets, edits
254
+
255
+
256
+ # --- the prompt and the reply ----------------------------------------------------------
257
+
258
+ def _capped(plan, task, name) -> str:
259
+ text = _text(_read_bytes(_task_file(plan, task, name))).strip()
260
+ if len(text) <= FILE_CAP:
261
+ return text
262
+ return forge_side.cap(text, FILE_CAP) + (
263
+ '\n[truncated to 6 KB: this is not the whole file. The full file is %s. '
264
+ 'Leave this field null unless you can restate the whole file.]' % _task_file(plan, task, name))
265
+
266
+
267
+ def build_prompt(plan, group, asking: str, question: dict, answer: dict, repo: str) -> str:
268
+ plan = Path(plan)
269
+ by_id = {item['id']: item for item in forge_brief.read_tasks(plan)}
270
+ done = [member for member in group.members if started(plan, member)]
271
+ parts = [
272
+ 'You are revising the tasks of ONE group in a multi-task coding run, because a person '
273
+ 'answered an open question that affects several of them.\n'
274
+ 'The repository is at %s: you may read it and you must not write to it.\n' % repo,
275
+ '## The question (asked for task %s)\n\n%s\n\nwhy: %s\noptions: %s\ndefault: %s\n' % (
276
+ asking, question.get('text', ''), question.get('why', ''),
277
+ ' | '.join(question.get('options') or []) or '(none)', question.get('default', '')),
278
+ '## The answer\n\n%s\n' % answer.get('text', ''),
279
+ '## The group: %s\n\ntitle: %s\ngoal: %s\n' % (
280
+ group.id, group.title, group.goal if group.goal != '-' else '(none)'),
281
+ '## Which members have started\n\n%s\n' % (
282
+ ', '.join(done) + ' (you may not change them)' if done else 'none'),
283
+ '## The members (each file capped at 6 KB)\n',
284
+ ]
285
+ for member in group.members:
286
+ item = by_id.get(member)
287
+ parts.append('### %s\n\ntasks.tsv row (id, deps, difficulty, files, dwarf, qa, title):\n%s\n\n'
288
+ '#### prompt.md\n\n%s\n\n#### approach.md\n\n%s\n' % (
289
+ member, item['row'] if item else '(not in tasks.tsv)',
290
+ _capped(plan, member, 'prompt.md'), _capped(plan, member, 'approach.md') or '(none)'))
291
+ parts.append(
292
+ '## What to change\n\n'
293
+ 'Decide what the answer changes in the members above. Change only members that have not '
294
+ 'started. For each one you change, give the FULL new text of any file you change, never a '
295
+ 'patch. Leave a field null when it stays as it is. The only fields you may change are '
296
+ 'prompt (prompt.md), approach (approach.md) and files (the comma-separated files column '
297
+ 'of tasks.tsv). Do not touch any other task, any started member, deps or any other column. '
298
+ 'If the answer changes nothing, reply with an empty list of changes.\n\n'
299
+ '## Reply format\n\n'
300
+ 'Reply with JSON only, no prose and no code fence:\n\n'
301
+ '{"summary": "...", "changes": [{"task": "id", "prompt": "<full new prompt.md>"|null, '
302
+ '"approach": "<full new approach.md>"|null, "files": "<new files column>"|null}]}\n')
303
+ return '\n'.join(parts)
304
+
305
+
306
+ def _reply_object(reply):
307
+ """`(object, None)` for a reply holding one JSON object (a fence or prose around it is dropped), else `(None, reason)`."""
308
+ if not isinstance(reply, str) or not reply.strip():
309
+ return None, 'empty reply'
310
+ text = forge_brief._strip_fence(reply)
311
+ try:
312
+ data = json.loads(text)
313
+ except (ValueError, RecursionError):
314
+ start, end = text.find('{'), text.rfind('}')
315
+ data = None
316
+ if 0 <= start < end:
317
+ try:
318
+ data = json.loads(text[start:end + 1])
319
+ except (ValueError, RecursionError):
320
+ data = None
321
+ if data is None:
322
+ return None, 'reply is not valid JSON'
323
+ if not isinstance(data, dict):
324
+ return None, 'reply is not a JSON object'
325
+ return data, None
326
+
327
+
328
+ def _edit_list(items, where='change'):
329
+ """`(edits, None)` or `(None, reason)`: each edit a dict with a string `task`, and `prompt`,
330
+ `approach` and `files` each a string or null (a missing one is null). A field that is not one
331
+ of those three is kept as it came: confinement refuses it, the parser does not drop it."""
332
+ found = []
333
+ for index, item in enumerate(items, 1):
334
+ label = '%s %d' % (where, index)
335
+ if not isinstance(item, dict):
336
+ return None, '%s is not an object' % label
337
+ if not isinstance(item.get('task'), str) or not item['task'].strip():
338
+ return None, '%s has no "task" string' % label
339
+ change = dict(item, task=item['task'].strip())
340
+ for field in CHANGE_FIELDS:
341
+ value = change.setdefault(field, None)
342
+ if value is not None and not isinstance(value, str):
343
+ return None, '%s: %s must be a string or null' % (label, field)
344
+ found.append(change)
345
+ return found, None
346
+
347
+
348
+ def _storable(entry: dict):
349
+ try: # a lone surrogate parses but cannot be stored as UTF-8
350
+ forge_brief._dump(entry).encode('utf-8')
351
+ except UnicodeError:
352
+ return 'reply has characters that cannot be stored'
353
+ return None
354
+
355
+
356
+ def parse_reply(reply):
357
+ """`(data, None)` for a usable reply, else `(None, reason)`. `data` is `{summary, changes}`."""
358
+ data, reason = _reply_object(reply)
359
+ if data is None:
360
+ return None, reason
361
+ summary, changes = data.get('summary'), data.get('changes')
362
+ if not isinstance(summary, str):
363
+ return None, 'reply has no "summary" string'
364
+ if not isinstance(changes, list):
365
+ return None, 'reply has no "changes" list'
366
+ found, reason = _edit_list(changes)
367
+ if found is None:
368
+ return None, reason
369
+ entry = {'summary': ' '.join(summary.split()), 'changes': found}
370
+ reason = _storable(entry)
371
+ return (None, reason) if reason else (entry, None)
372
+
373
+
374
+ def parse_plan_reply(reply):
375
+ """`(data, None)` for a usable plan-scope reply, else `(None, reason)`.
376
+
377
+ `data` is `{summary, changes: {edits, add, remove, deps}}`. `changes` is that object, or a list
378
+ (the edits, as in wave scope) with `add`, `remove` and `deps` beside it; either spelling of those
379
+ three keys is read. Only the shape is checked here (lists of objects, of strings, with a string
380
+ `id` or `task`); whether the structure is a plan is `_plan_check`'s decision.
381
+ """
382
+ data, reason = _reply_object(reply)
383
+ if data is None:
384
+ return None, reason
385
+ summary, raw = data.get('summary'), data.get('changes')
386
+ if not isinstance(summary, str):
387
+ return None, 'reply has no "summary" string'
388
+ if isinstance(raw, list):
389
+ raw = {'edits': raw}
390
+ elif raw is None and any(key in data for key in ('add', 'remove', 'deps')):
391
+ raw = {}
392
+ if not isinstance(raw, dict):
393
+ return None, 'reply has no "changes" object or list'
394
+ unknown = sorted(set(raw) - set(PLAN_KEYS))
395
+ if unknown:
396
+ return None, '"changes" has unknown key(s): %s' % ', '.join(unknown)
397
+ pick = lambda key: raw.get(key) if raw.get(key) is not None else data.get(key) # noqa: E731
398
+ edits, add, remove, deps = pick('edits') or [], pick('add') or [], pick('remove') or [], pick('deps') or []
399
+ for name, value in (('edits', edits), ('add', add), ('remove', remove), ('deps', deps)):
400
+ if not isinstance(value, list):
401
+ return None, '"%s" is not a list' % name
402
+ edits, reason = _edit_list(edits)
403
+ if edits is None:
404
+ return None, reason
405
+ for index, item in enumerate(add, 1):
406
+ if not isinstance(item, dict):
407
+ return None, 'add %d is not an object' % index
408
+ if not all(isinstance(item, str) and item.strip() for item in remove):
409
+ return None, '"remove" must be a list of task ids'
410
+ for index, item in enumerate(deps, 1):
411
+ if not isinstance(item, dict) or not isinstance(item.get('task'), str) or not item['task'].strip():
412
+ return None, 'deps %d has no "task" string' % index
413
+ entry = {'summary': ' '.join(summary.split()),
414
+ 'changes': {'edits': edits, 'add': add, 'remove': [item.strip() for item in remove],
415
+ 'deps': [dict(item, task=item['task'].strip()) for item in deps]}}
416
+ reason = _storable(entry)
417
+ return (None, reason) if reason else (entry, None)
418
+
419
+
420
+ def _ask(plan, task, prompt, spec, timeout, parse=None):
421
+ """One dispatch, a retry on an unusable reply. `(data, None)` or `(None, why)`."""
422
+ reminder, error = '', 'no reply'
423
+ for attempt in range(2):
424
+ result = forge_side.run('brief-change', plan, task, prompt + reminder, spec, timeout=timeout)
425
+ if not result['ok']:
426
+ if result['reason'] == 'cap':
427
+ return None, 'the brief-change dispatch cap is reached' + (' (no retry)' if attempt else '')
428
+ return None, 'dispatch failed: %s' % (result['reason'] or 'error')
429
+ try:
430
+ data, error = (parse or parse_reply)(result['last'])
431
+ except Exception as failure: # noqa: BLE001 - a broken reply is an unusable reply
432
+ data, error = None, 'reply could not be read (%s)' % type(failure).__name__
433
+ if data is not None:
434
+ return data, None
435
+ reminder = '\n\n' + REMINDER % error
436
+ return None, error
437
+
438
+
439
+ # --- confinement -----------------------------------------------------------------------
440
+
441
+ def _confine_edits(plan, changes: list, where) -> list:
442
+ """The reasons these per-task edits must be refused. `where(task)` is None when the task may be
443
+ changed, else why not (a started task is always refused here)."""
444
+ reasons, seen = [], set()
445
+ for change in changes:
446
+ task = change['task']
447
+ extra = sorted(key for key in change if key != 'task' and key not in CHANGE_FIELDS)
448
+ if task in seen:
449
+ reasons.append('task %s is changed twice' % task)
450
+ seen.add(task)
451
+ why = where(task)
452
+ if why:
453
+ reasons.append(why)
454
+ elif started(plan, task):
455
+ reasons.append('task %s has started' % task)
456
+ if extra:
457
+ reasons.append('change for %s has field(s) other than prompt, approach and files: %s'
458
+ % (task, ', '.join(extra)))
459
+ for field in ('prompt', 'approach'):
460
+ if isinstance(change.get(field), str) and not change[field].strip():
461
+ reasons.append('%s for %s is empty' % (field, task))
462
+ files = change.get('files')
463
+ if isinstance(files, str) and (not files.strip() or any(ch in files for ch in '\t\r\n')):
464
+ reasons.append('files for %s must be one non-empty line without tabs' % task)
465
+ return reasons
466
+
467
+
468
+ def _confine(plan, group, changes: list) -> list:
469
+ """The reasons this proposal must be refused, in change order. Empty when it is confined."""
470
+ return _confine_edits(plan, changes, lambda task: None if task in group.members
471
+ else 'task %s is not a member of group %s' % (task, group.id))
472
+
473
+
474
+ def _normalize(changes: list) -> list:
475
+ """Each change with its three fields; a prompt or approach ends with a newline, files is stripped."""
476
+ out = []
477
+ for change in changes:
478
+ entry = dict(change)
479
+ for field in ('prompt', 'approach'):
480
+ value = entry.get(field)
481
+ if isinstance(value, str) and value and not value.endswith('\n'):
482
+ entry[field] = value + '\n'
483
+ if isinstance(entry.get('files'), str):
484
+ entry['files'] = entry['files'].strip()
485
+ out.append(entry)
486
+ return out
487
+
488
+
489
+ # --- storage ---------------------------------------------------------------------------
490
+
491
+ def _proposals(plan) -> Path:
492
+ return Path(plan) / 'proposals'
493
+
494
+
495
+ @contextlib.contextmanager
496
+ def _proposals_lock(plan):
497
+ base = _proposals(plan)
498
+ base.mkdir(parents=True, exist_ok=True)
499
+ fd = os.open(str(base / '.lock'), os.O_CREAT | os.O_RDWR, 0o644)
500
+ try:
501
+ fcntl.flock(fd, fcntl.LOCK_EX)
502
+ yield
503
+ finally:
504
+ os.close(fd)
505
+
506
+
507
+ @contextlib.contextmanager
508
+ def _control_lock(plan):
509
+ """The plan's control lock, as `forge control` takes it; a busy lock is a refusal."""
510
+ control = answers._control()
511
+ try:
512
+ with control.control_lock(os.path.realpath(str(plan))):
513
+ yield control
514
+ except (control.Refused, control.Invalid) as error:
515
+ raise Refused(str(error))
516
+
517
+
518
+ def _numbers(plan) -> list:
519
+ try:
520
+ names = [entry.name for entry in _proposals(plan).iterdir() if entry.is_dir()]
521
+ except OSError:
522
+ return []
523
+ return sorted(int(name[1:]) for name in names if PID_RE.fullmatch(name))
524
+
525
+
526
+ def _load(plan, pid) -> dict:
527
+ if not isinstance(pid, str) or not PID_RE.fullmatch(pid):
528
+ raise NoSuchProposal(pid, ['p%d' % n for n in _numbers(plan)])
529
+ data = forge_brief._json(_proposals(plan) / pid / 'proposal.json')
530
+ if not isinstance(data, dict):
531
+ raise NoSuchProposal(pid, ['p%d' % n for n in _numbers(plan)])
532
+ return data
533
+
534
+
535
+ def _store(plan, record: dict) -> None:
536
+ forge_brief.atomic_write(_proposals(plan) / record['pid'] / 'proposal.json', forge_brief._dump(record))
537
+
538
+
539
+ def _stored_hash(plan, pid) -> str:
540
+ return _text(_read_bytes(_proposals(plan) / pid / 'hash')).strip()
541
+
542
+
543
+ def _emit(plan, record: dict, extra: dict | None = None) -> None:
544
+ """One `brief_diff` dataset event. Fail-open, like every other capture.
545
+
546
+ `extra` is how an approved apply adds `affected` and `flagged`. Other states omit them,
547
+ so a proposed or refused event stays the shape it had.
548
+ """
549
+ body = {
550
+ 'pid': record['pid'], 'scope': record['scope'], 'group': record['group'],
551
+ 'state': record['state'], 'tasks': touched(record)}
552
+ if extra:
553
+ body.update(extra)
554
+ try:
555
+ from forge_dataset.capture import point
556
+ point('brief_diff', str(plan), str(record['task']), body)
557
+ except Exception:
558
+ pass
559
+
560
+
561
+ def _generated_at(plan, task):
562
+ data = forge_brief._json(forge_brief.task_dir(plan, task) / 'brief.parked.json')
563
+ try:
564
+ return calendar.timegm(time.strptime(data['generated_at'], '%Y-%m-%dT%H:%M:%SZ'))
565
+ except (TypeError, KeyError, ValueError):
566
+ return None
567
+
568
+
569
+ # --- propose ---------------------------------------------------------------------------
570
+
571
+ def propose(plan, task, qid, actor='cli', timeout=900) -> dict:
572
+ """Ask the brief model what the answer to a parked wave or plan question changes, and record the proposal.
573
+
574
+ Returns the proposal record (`state` is `proposed` or `refused`; a refused one carries its
575
+ `reason` and still has its diff). Raises `NotAPlan`, `BriefOff` (brief off, or `allowed`
576
+ refuses), `Usage` (no answer yet), `NoSuchTask`, `NoSuchQuestion` and `Refused` (the question
577
+ is not a wave question of a group or a plan question, or the writer failed). Nothing in the plan changes.
578
+ """
579
+ who = answers._actor(actor)
580
+ plan, found = forge_brief._guard(plan)
581
+ tasks = forge_brief.read_tasks(plan)
582
+ if task not in {item['id'] for item in tasks}:
583
+ raise answers.NoSuchTask(task, [item['id'] for item in tasks])
584
+ parked = answers.parked_questions(plan, task)
585
+ if qid not in parked:
586
+ raise answers.NoSuchQuestion(task, qid, list(parked))
587
+ question = parked[qid]
588
+ scope = question.get('scope')
589
+ if scope not in ('wave', 'plan'):
590
+ raise Refused('%s/%s is a %s-scoped question: only a parked wave or plan question can be proposed'
591
+ % (task, qid, scope))
592
+ gid, group = None, None
593
+ if scope == 'plan':
594
+ if qid not in answers.answerable_parked(plan, task):
595
+ raise Refused('%s/%s is a plan question: the plan needs --brief-scope plan to act on it' % (task, qid))
596
+ else:
597
+ gid = question.get('group')
598
+ if not isinstance(gid, str) or not gid:
599
+ raise Refused('%s/%s names no group, so there is nothing for a wave answer to act on' % (task, qid))
600
+ group = _group_of(plan, gid)
601
+ if group is None:
602
+ raise Refused('group %s is not in groups.tsv' % gid)
603
+ answer = answers._load_map(forge_brief.task_dir(plan, task) / 'brief.parked.answers.json').get(qid)
604
+ if not isinstance(answer, dict) or not isinstance(answer.get('text'), str) or not answer['text'].strip():
605
+ raise answers.Usage('%s/%s has no answer yet: forge brief answer %s %s %s TEXT' % (
606
+ task, qid, shlex.quote(str(plan)), task, qid))
607
+ made, written = answer.get('t'), _generated_at(plan, task)
608
+ if isinstance(made, (int, float)) and made > 0 and written is not None and made < written:
609
+ raise Refused('%s/%s was answered before its question was last written: answer it again' % (task, qid))
610
+ if scope == 'plan':
611
+ return _propose_plan(plan, task, qid, question, answer, who, found, timeout)
612
+ ok, reason = forge_side.allowed('brief-change', plan)
613
+ if not ok:
614
+ raise forge_brief.BriefOff(reason)
615
+ repo = forge_brief._text(plan / 'repo').strip()
616
+ prompt = build_prompt(plan, group, task, question, answer, repo)
617
+ data, error = _ask(plan, task, prompt, found['model'], timeout)
618
+ if data is None:
619
+ raise Refused('the change writer failed: %s' % error)
620
+ changes = _normalize(data['changes'])
621
+ reasons = _confine(plan, group, changes)
622
+ diff_text, targets, _ = _plan_changes(plan, changes)
623
+ if not reasons and not diff_text:
624
+ reasons.append('the proposal changes nothing')
625
+ state = 'refused' if reasons else 'proposed'
626
+ with _proposals_lock(plan):
627
+ number = (_numbers(plan) or [0])[-1] + 1
628
+ pid = 'p%d' % number
629
+ directory = _proposals(plan) / pid
630
+ directory.mkdir(parents=True)
631
+ record = {'pid': pid, 'scope': 'wave', 'group': gid, 'task': task, 'qid': qid,
632
+ 'answer': answer['text'], 'summary': data['summary'], 'changes': changes,
633
+ 'state': state, 'reason': '; '.join(reasons) or None,
634
+ 'created': forge_brief._now(), 'actor': who}
635
+ forge_brief.atomic_write(directory / 'diff.patch', diff_text)
636
+ forge_brief.atomic_write(directory / 'hash', _digest(diff_text, targets) + '\n')
637
+ _store(plan, record)
638
+ _emit(plan, record)
639
+ return record
640
+
641
+
642
+ # --- who an approved proposal leaves affected ------------------------------------------
643
+
644
+ def _touch_sets(record: dict) -> tuple:
645
+ """`(changed, added, removed)` task ids the proposal names.
646
+
647
+ A wave proposal only changes tasks. A plan proposal's edits and dep rewrites are changes,
648
+ its adds are added, and its removes are seeds for the dependency walk (the task itself is
649
+ gone, so it is not marked).
650
+ """
651
+ def clean(items):
652
+ return {item for item in items if isinstance(item, str) and item}
653
+
654
+ if record.get('scope') == 'plan':
655
+ changes = plan_changes_of(record)
656
+ changed = clean(item.get('task') for item in changes['edits'] if isinstance(item, dict)) | clean(
657
+ item.get('task') for item in changes['deps'] if isinstance(item, dict))
658
+ added = clean(item.get('id') for item in changes['add'] if isinstance(item, dict))
659
+ return changed, added, clean(changes['remove'])
660
+ changes = record.get('changes') if isinstance(record.get('changes'), list) else []
661
+ return clean(item.get('task') for item in changes if isinstance(item, dict)), set(), set()
662
+
663
+
664
+ def _dependents(tasks: list, seeds: set) -> set:
665
+ """Task ids that depend, directly or transitively, on `seeds`, from the post-apply rows.
666
+
667
+ A removed id is a seed even though it is no longer a row: a task whose deps still name it
668
+ is reached from here. Walking does not stop at a started task, so an unstarted task behind
669
+ a merged one is still found.
670
+ """
671
+ children = {}
672
+ for item in tasks:
673
+ for dep in item['deps']:
674
+ children.setdefault(dep, []).append(item['id'])
675
+ seen, stack = set(), list(seeds)
676
+ while stack:
677
+ node = stack.pop()
678
+ if node in seen:
679
+ continue
680
+ seen.add(node)
681
+ stack.extend(children.get(node, ()))
682
+ return {task for task in seen if task not in seeds}
683
+
684
+
685
+ def _classify(plan, record: dict) -> tuple:
686
+ """`(reasons, affected, flagged)` from the post-apply tasks.tsv and the removed ids.
687
+
688
+ `reasons` maps a still-present task to `changed`, `added` or `dependent` (a task the
689
+ proposal itself changed or added keeps that reason when it also sits downstream).
690
+ `affected` is the unstarted ids, `flagged` the ones that have already started, both in
691
+ tasks.tsv order.
692
+ """
693
+ changed, added, removed = _touch_sets(record)
694
+ tasks = forge_brief.read_tasks(plan)
695
+ downstream = _dependents(tasks, changed | added | removed)
696
+ reasons = {}
697
+ for item in tasks:
698
+ task = item['id']
699
+ if task in removed:
700
+ continue
701
+ if task in changed:
702
+ reasons[task] = 'changed'
703
+ elif task in added:
704
+ reasons[task] = 'added'
705
+ elif task in downstream:
706
+ reasons[task] = 'dependent'
707
+ affected, flagged = [], []
708
+ for item in tasks:
709
+ task = item['id']
710
+ if task not in reasons:
711
+ continue
712
+ if started(plan, task):
713
+ flagged.append(task)
714
+ else:
715
+ affected.append(task)
716
+ return reasons, affected, flagged
717
+
718
+
719
+ def _write_marker(plan, task: str, pid: str, reason: str, flag_only: bool, stamp: str) -> None:
720
+ """Replace `tasks/<id>/brief.affected`. The next approved proposal overwrites it again."""
721
+ body = {'pid': pid, 'reason': reason, 't': stamp}
722
+ if flag_only:
723
+ body['flag_only'] = True
724
+ forge_brief.atomic_write(forge_brief.task_dir(plan, task) / 'brief.affected', forge_brief._dump(body))
725
+
726
+
727
+ def _carry_answers(old_questions, old_answers, new_questions) -> tuple:
728
+ """`(kept, dropped)`: match answers to new questions by question text, first unused wins.
729
+
730
+ `kept` is `{new qid: answer}`. `dropped` is `{old qid: answer}` for every answer whose
731
+ question text is not in the new brief. An empty text never matches, so it is dropped
732
+ rather than glued to another blank question.
733
+ """
734
+ texts = {}
735
+ for question in old_questions:
736
+ qid, text = question.get('id'), question.get('text')
737
+ if isinstance(qid, str) and qid and isinstance(text, str):
738
+ texts.setdefault(qid, text)
739
+ pool = [{'qid': qid, 'text': texts.get(qid, ''), 'answer': answer, 'used': False}
740
+ for qid, answer in old_answers.items()]
741
+ kept = {}
742
+ for question in new_questions:
743
+ qid, text = question.get('id'), question.get('text')
744
+ if not isinstance(qid, str) or not qid or not isinstance(text, str) or not text:
745
+ continue
746
+ for item in pool:
747
+ if not item['used'] and item['text'] and item['text'] == text:
748
+ kept[qid] = item['answer']
749
+ item['used'] = True
750
+ break
751
+ dropped = {item['qid']: item['answer'] for item in pool if not item['used']}
752
+ return kept, dropped
753
+
754
+
755
+ def _regenerate_one(plan, task: str) -> bool:
756
+ """Rewrite one task's questions and put the answers that still fit back by their text.
757
+
758
+ `write --force` archives the old brief and its answers (question ids restart at q1).
759
+ Answers whose question text is in the new brief are written back under the new id; the
760
+ others go to `brief.answers.prev.json`, next to the archive, so nothing is thrown away.
761
+ A regeneration that drops nothing removes that file, so an earlier regeneration's drops
762
+ do not stay behind. A skipped write (the dispatch cap, or a brief that appeared under the
763
+ lock) leaves the answers where they were. Returns whether the brief was rewritten.
764
+ """
765
+ tdir = forge_brief.task_dir(plan, task)
766
+ old_brief = forge_brief._json(tdir / 'brief.json')
767
+ old_questions = forge_brief._questions(old_brief if isinstance(old_brief, dict) else None)
768
+ old_answers = forge_brief._entries(forge_brief._json(tdir / 'brief.answers.json'))
769
+ report = forge_brief.write(plan, task=task, force=True)
770
+ if not report or report[0].get('status') == 'skipped':
771
+ return False
772
+ new_brief = forge_brief._json(tdir / 'brief.json')
773
+ new_questions = forge_brief._questions(new_brief if isinstance(new_brief, dict) else None)
774
+ kept, dropped = _carry_answers(old_questions, old_answers, new_questions)
775
+ if kept:
776
+ forge_brief.atomic_write(tdir / 'brief.answers.json', forge_brief._dump(kept))
777
+ prev = tdir / 'brief.answers.prev.json'
778
+ if dropped:
779
+ forge_brief.atomic_write(prev, forge_brief._dump(dropped))
780
+ else:
781
+ prev.unlink(missing_ok=True)
782
+ return True
783
+
784
+
785
+ def _regenerate(plan, tasks: list) -> list:
786
+ """The unstarted affected tasks whose questions were actually rewritten, in tasks.tsv order.
787
+
788
+ This runs after the apply has been stored. A failure here does not undo the apply:
789
+ `BriefOff` stops the rest (every later task would fail the same way); a skipped write
790
+ is not rewritten. The caller names only what this returns, so a note never claims a
791
+ dispatch that did not happen. Any other error is left to the caller only when the
792
+ writer itself raises, which it does not for a bad reply.
793
+ """
794
+ done = []
795
+ for task in tasks:
796
+ try:
797
+ if _regenerate_one(plan, task):
798
+ done.append(task)
799
+ except forge_brief.BriefOff:
800
+ return done
801
+ return done
802
+
803
+
804
+ def _settle(plan, record: dict, result: dict, regenerate: bool) -> dict:
805
+ """Mark affected tasks, emit the approved event, then regenerate the unstarted ones.
806
+
807
+ Markers are written before the event and before any dispatch, so a writer failure still
808
+ leaves `brief.affected` and the event. Regeneration holds no plan lock: each `write` takes
809
+ only that task's brief lock. `regenerate` False writes the same markers and dispatches nothing.
810
+ """
811
+ reasons, affected, flagged = _classify(plan, record)
812
+ stamp = forge_brief._now()
813
+ for task in affected:
814
+ _write_marker(plan, task, record['pid'], reasons[task], False, stamp)
815
+ for task in flagged:
816
+ _write_marker(plan, task, record['pid'], reasons[task], True, stamp)
817
+ _emit(plan, record, {'affected': list(affected), 'flagged': list(flagged)})
818
+ notes = list(result.get('notes') or [])
819
+ if affected:
820
+ if regenerate:
821
+ done = _regenerate(plan, affected)
822
+ if done:
823
+ notes.append('regenerating questions for %d tasks: %s' % (len(done), ', '.join(done)))
824
+ else:
825
+ notes.append('marked affected, not regenerating: %s' % ', '.join(affected))
826
+ if flagged:
827
+ notes.append('flagged (already started): %s' % ', '.join(flagged))
828
+ result['notes'] = notes
829
+ result['affected'] = affected
830
+ result['flagged'] = flagged
831
+ return result
832
+
833
+
834
+ # --- apply -----------------------------------------------------------------------------
835
+
836
+ def _validate_new(plan, new_text: str, max_tasks: int, groups_text=None) -> None:
837
+ """Run the group validation against the tasks.tsv (and groups.tsv) an apply would write, touching nothing real."""
838
+ with tempfile.TemporaryDirectory(prefix='forge-validate-') as scratch:
839
+ scratch = Path(scratch)
840
+ (scratch / 'tasks.tsv').write_text(new_text, encoding='utf-8')
841
+ groups_file = Path(plan) / 'groups.tsv'
842
+ (scratch / 'groups.tsv').write_bytes(
843
+ groups_text.encode('utf-8') if groups_text is not None else _read_bytes(groups_file) or b'')
844
+ os.symlink(str(Path(plan) / 'tasks'), str(scratch / 'tasks')) # sweep.json is read from it
845
+ forge_groups.validate(scratch, forge_groups.load(scratch), max_tasks)
846
+
847
+
848
+ def _max_tasks(plan) -> int:
849
+ try:
850
+ return int(forge_brief._text(Path(plan) / 'group_max_tasks').split()[0])
851
+ except (IndexError, ValueError):
852
+ return 6
853
+
854
+
855
+ def _recompute_waves(plan) -> str | None:
856
+ """`forge-parallel.sh _waves`, the way `plan` computes waves. A failure message, or None."""
857
+ if not (Path(plan) / 'waves.tsv').exists():
858
+ return None # an unplanned plan gains nothing, and waves.tsv is what marks one as planned
859
+ script = Path(forge_brief.SCRIPTS) / 'forge-parallel.sh'
860
+ try:
861
+ done = subprocess.run(['/bin/bash', str(script), '_waves', str(plan)], stdin=subprocess.DEVNULL,
862
+ capture_output=True, text=True, timeout=120)
863
+ except (OSError, subprocess.SubprocessError) as error:
864
+ return 'waves.tsv was not refreshed: %s' % error
865
+ return None if done.returncode == 0 else 'waves.tsv was not refreshed: %s' % (done.stderr or done.stdout).strip()
866
+
867
+
868
+ def apply(plan, pid, approve_hash, actor='cli', regenerate=True) -> dict:
869
+ """Write an approved proposal. Raises `Refused` (nothing changed) or `NoSuchProposal`.
870
+
871
+ Returns `{pid, state: "approved", files, tasks, warning, affected, flagged, notes}`.
872
+ `files` are the plan files written, relative to the plan; `warning` says if waves.tsv
873
+ could not be refreshed. `affected` and `flagged` are the task ids marked after the write
874
+ (see `_settle`). `regenerate` asks the brief writer for new questions of the unstarted
875
+ affected tasks; `False` (`apply --no-regenerate`) only writes their markers.
876
+ """
877
+ who = answers._actor(actor)
878
+ plan = Path(plan)
879
+ if not plan.is_dir() or not (plan / 'tasks.tsv').is_file():
880
+ raise forge_brief.NotAPlan(str(plan))
881
+ if _load(plan, pid).get('scope') == 'plan': # the scope never changes, so reading it unlocked is safe
882
+ return _apply_plan(plan, pid, approve_hash, who, regenerate)
883
+ with _proposals_lock(plan), _control_lock(plan) as control:
884
+ record = _load(plan, pid)
885
+ if record.get('state') != 'proposed':
886
+ raise Refused('proposal %s is %s, not proposed' % (pid, record.get('state')))
887
+ stored = _stored_hash(plan, pid)
888
+ if not stored or str(approve_hash).strip().lower() != stored:
889
+ raise Refused('the hash does not match proposal %s: read its diff again and quote its hash' % pid)
890
+ changes = record.get('changes') if isinstance(record.get('changes'), list) else []
891
+ group = _group_of(plan, record.get('group'))
892
+ if group is None:
893
+ raise Refused('group %s is no longer in groups.tsv' % record.get('group'))
894
+ reasons = _confine(plan, group, changes)
895
+ if reasons:
896
+ raise Refused('proposal %s no longer fits its group: %s' % (pid, '; '.join(reasons)))
897
+ diff_text = _text(_read_bytes(_proposals(plan) / pid / 'diff.patch'))
898
+ current_diff, targets, edits = _plan_changes(plan, changes)
899
+ if _digest(diff_text, targets) != stored:
900
+ raise Refused('a target file changed since proposal %s: propose again' % pid)
901
+ files_edits = {task: value for task, field, value in edits if field == 'files'}
902
+ if files_edits and control.is_live(os.path.realpath(str(plan))):
903
+ raise Refused('a run is live and its scheduler keeps the files column it read at start: '
904
+ 'apply the files change after the run')
905
+ old_lines = _tsv_lines(plan)
906
+ new_lines = _with_files(old_lines, files_edits) if files_edits else old_lines
907
+ if files_edits:
908
+ try:
909
+ _validate_new(plan, ''.join(new_lines), _max_tasks(plan))
910
+ except forge_groups.GroupError as error:
911
+ raise Refused('group validation fails after the files change: %s' % ' '.join(str(error).split()))
912
+ written = [(plan / ('tasks/%s/%s.md' % (task, field)), value)
913
+ for task, field, value in edits if field != 'files']
914
+ if files_edits:
915
+ written.append((plan / 'tasks.tsv', ''.join(new_lines)))
916
+ before = {path: _read_bytes(path) for path, _ in written}
917
+ before_frozen = _read_bytes(plan / 'groups.frozen')
918
+ refroze = False
919
+ try:
920
+ for path, value in written:
921
+ forge_brief.atomic_write(path, value)
922
+ if files_edits and not plan_stale(plan): # a plan change awaiting `plan` stays stale
923
+ forge_groups.freeze(plan)
924
+ refroze = True
925
+ except BaseException:
926
+ for path, old in before.items():
927
+ if old is None:
928
+ path.unlink(missing_ok=True)
929
+ else:
930
+ forge_brief.atomic_write(path, _text(old))
931
+ if before_frozen is None:
932
+ (plan / 'groups.frozen').unlink(missing_ok=True)
933
+ else:
934
+ forge_brief.atomic_write(plan / 'groups.frozen', _text(before_frozen))
935
+ raise
936
+ warning = _recompute_waves(plan) if files_edits else None
937
+ record['state'] = 'approved'
938
+ record['applied'] = forge_brief._now()
939
+ record['applied_by'] = who
940
+ _store(plan, record)
941
+ names = [str(path.relative_to(plan)) for path, _ in written] + (['groups.frozen'] if refroze else [])
942
+ result = {'pid': pid, 'state': 'approved', 'files': names,
943
+ 'tasks': [change['task'] for change in changes], 'warning': warning,
944
+ 'message': None, 'notes': [], 'live': False}
945
+ return _settle(plan, record, result, regenerate)
946
+
947
+
948
+ # --- plan scope: structural changes ----------------------------------------------------
949
+
950
+ PLAN_MESSAGE = 'structural changes apply after the run ends (forge control stop, or wait), then plan again'
951
+
952
+
953
+ def plan_changes_of(record) -> dict:
954
+ """A stored plan-scope proposal's `changes` as `{edits, add, remove, deps}`, whatever was stored."""
955
+ raw = record.get('changes') if isinstance(record, dict) else None
956
+ raw = raw if isinstance(raw, dict) else {}
957
+ return {key: list(raw.get(key) or []) if isinstance(raw.get(key) or [], list) else [] for key in PLAN_KEYS}
958
+
959
+
960
+ def touched(record) -> list:
961
+ """The task ids a proposal names, in a stable order, for the `brief_diff` event."""
962
+ if record.get('scope') != 'plan':
963
+ return [change['task'] for change in record.get('changes') or []]
964
+ changes = plan_changes_of(record)
965
+ found = [item.get('task') for item in changes['edits']] + [item.get('id') for item in changes['add']] \
966
+ + list(changes['remove']) + [item.get('task') for item in changes['deps']]
967
+ return list(dict.fromkeys(item for item in found if isinstance(item, str)))
968
+
969
+
970
+ def _id_problem(name):
971
+ """Why `name` is not an id a new task may have, or None. The scheduler's rule (`_task_id_ok`), and no
972
+ whitespace, comma or backslash (they break tasks.tsv and deps), no leading `.` or `-`."""
973
+ if not isinstance(name, str) or not name:
974
+ return 'the id must be a non-empty string'
975
+ if name in ('.', '..') or '/' in name or '\0' in name:
976
+ return 'the id %r is not a valid task id' % name
977
+ if any(ch.isspace() or ch in ',\\' for ch in name) or name[0] in '.-':
978
+ return 'the id %r may not contain whitespace, commas or backslashes, nor start with . or -' % name
979
+ return None
980
+
981
+
982
+ def _normalize_plan(changes: dict) -> dict:
983
+ """Each added task cleaned: prompt and approach end with a newline, files a list, text fields stripped."""
984
+ out = {'edits': _normalize(changes['edits']), 'remove': [str(item).strip() for item in changes['remove']],
985
+ 'deps': [], 'add': []}
986
+ for item in changes['deps']:
987
+ entry = dict(item)
988
+ if isinstance(entry.get('deps'), list):
989
+ entry['deps'] = [str(dep).strip() if isinstance(dep, str) else dep for dep in entry['deps']]
990
+ out['deps'].append(entry)
991
+ for item in changes['add']:
992
+ entry = dict(item)
993
+ for field in ('id', 'difficulty', 'group'):
994
+ if isinstance(entry.get(field), str):
995
+ entry[field] = entry[field].strip()
996
+ if isinstance(entry.get('title'), str):
997
+ entry['title'] = ' '.join(entry['title'].split())
998
+ if isinstance(entry.get('files'), str):
999
+ entry['files'] = [part for part in entry['files'].split(',')]
1000
+ if isinstance(entry.get('files'), list):
1001
+ entry['files'] = [part.strip() if isinstance(part, str) else part for part in entry['files']]
1002
+ if isinstance(entry.get('deps'), list):
1003
+ entry['deps'] = [dep.strip() if isinstance(dep, str) else dep for dep in entry['deps']]
1004
+ for field in ('prompt', 'approach'):
1005
+ value = entry.get(field)
1006
+ if isinstance(value, str) and value and not value.endswith('\n'):
1007
+ entry[field] = value + '\n'
1008
+ out['add'].append(entry)
1009
+ return out
1010
+
1011
+
1012
+ def _check_added(plan, entry, taken, group_ids, reasons):
1013
+ """Append to `reasons` what is wrong with one `add` entry; True when it is sound enough to build a row from."""
1014
+ name = entry.get('id')
1015
+ label = 'add %s' % (name if isinstance(name, str) and name else '(no id)')
1016
+ before = len(reasons)
1017
+ extra = sorted(key for key in entry if key not in ADD_KEYS)
1018
+ if extra:
1019
+ reasons.append('%s: unknown field(s) %s' % (label, ', '.join(extra)))
1020
+ problem = _id_problem(name)
1021
+ if problem:
1022
+ reasons.append('%s: %s' % (label, problem))
1023
+ elif name in taken:
1024
+ reasons.append('%s: the id is already a task (an added id must be new)' % label)
1025
+ elif name in group_ids:
1026
+ reasons.append('%s: the id is also a group id' % label)
1027
+ elif (Path(plan) / 'tasks' / name).exists():
1028
+ reasons.append('%s: tasks/%s already exists (an added id must be new)' % (label, name))
1029
+ if entry.get('difficulty') not in DIFFICULTIES:
1030
+ reasons.append('%s: difficulty must be low, medium or high' % label)
1031
+ files = entry.get('files')
1032
+ if (not isinstance(files, list) or not files or not all(isinstance(part, str) and part for part in files)
1033
+ or any(ch in part for part in files if isinstance(part, str) for ch in ',\t\r\n')):
1034
+ reasons.append('%s: files must be a non-empty list of paths without tabs or commas' % label)
1035
+ title = entry.get('title')
1036
+ if not isinstance(title, str) or not title or '\t' in title:
1037
+ reasons.append('%s: title must be one non-empty line without tabs' % label)
1038
+ prompt = entry.get('prompt')
1039
+ if not isinstance(prompt, str) or not prompt.strip():
1040
+ reasons.append('%s: prompt is empty' % label)
1041
+ elif not ACCEPTANCE_RE.search(prompt):
1042
+ reasons.append('%s: prompt has no "## Acceptance criteria" section (the plan rule: references/decompose.md)' % label)
1043
+ approach = entry.get('approach')
1044
+ if approach is not None and (not isinstance(approach, str) or not approach.strip()):
1045
+ reasons.append('%s: approach must be a non-empty string or null' % label)
1046
+ group = entry.get('group')
1047
+ if group is not None and group not in group_ids:
1048
+ reasons.append('%s: group %s is not in groups.tsv' % (label, group))
1049
+ deps = entry.get('deps')
1050
+ if not isinstance(deps, list) or not all(isinstance(dep, str) and dep for dep in deps):
1051
+ reasons.append('%s: deps must be a list of task ids' % label)
1052
+ return len(reasons) == before
1053
+
1054
+
1055
+ def _rewrite_rows(lines: list, drop=(), files=None, deps=None) -> list:
1056
+ """The tasks.tsv lines without the dropped rows and with the files or deps column of the named rows replaced."""
1057
+ files, deps, out = files or {}, deps or {}, []
1058
+ for line in lines:
1059
+ body = line.rstrip('\n')
1060
+ cols = body.split('\t')
1061
+ if body.strip() and not body.startswith('#') and len(cols) >= 7:
1062
+ if cols[0] in drop:
1063
+ continue
1064
+ if cols[0] in files or cols[0] in deps:
1065
+ if cols[0] in files:
1066
+ cols[3] = files[cols[0]]
1067
+ if cols[0] in deps:
1068
+ cols[1] = ','.join(deps[cols[0]]) or '-'
1069
+ line = '\t'.join(cols) + ('\n' if line.endswith('\n') else '')
1070
+ out.append(line)
1071
+ return out
1072
+
1073
+
1074
+ def _rewrite_groups(lines: list, drop: set, join: dict) -> tuple:
1075
+ """`(new lines, reasons)`: each group row without the dropped members and with the joining ones appended."""
1076
+ out, reasons = [], []
1077
+ for line in lines:
1078
+ body = line.rstrip('\n')
1079
+ cols = body.split('\t')
1080
+ if body.strip() and not body.startswith('#') and len(cols) == 6:
1081
+ members = [member.strip() for member in cols[3].split(',')]
1082
+ kept = [member for member in members if member not in drop] + join.get(cols[0], [])
1083
+ if kept != members:
1084
+ if not kept:
1085
+ reasons.append('group %s would lose every member: take it out of groups.tsv by hand first' % cols[0])
1086
+ else:
1087
+ cols[3] = ','.join(kept)
1088
+ line = '\t'.join(cols) + ('\n' if line.endswith('\n') else '')
1089
+ out.append(line)
1090
+ return out, reasons
1091
+
1092
+
1093
+ def _has_cycle(graph: dict) -> list:
1094
+ """A cycle in `{task: [deps]}` as a list of ids, or []."""
1095
+ state, stack = {}, []
1096
+
1097
+ def visit(node):
1098
+ state[node] = 1
1099
+ stack.append(node)
1100
+ for dep in graph.get(node, []):
1101
+ if state.get(dep) == 1:
1102
+ return stack[stack.index(dep):] + [dep]
1103
+ if dep not in state and dep in graph:
1104
+ found = visit(dep)
1105
+ if found:
1106
+ return found
1107
+ state[node] = 2
1108
+ stack.pop()
1109
+ return []
1110
+
1111
+ for node in graph:
1112
+ if node not in state:
1113
+ found = visit(node)
1114
+ if found:
1115
+ return found
1116
+ return []
1117
+
1118
+
1119
+ def _plan_check(plan, changes: dict) -> tuple:
1120
+ """`(reasons, built)` for plan-scope `changes` against the plan as it is now.
1121
+
1122
+ `reasons` is why the proposal is refused (empty when it is a plan). `built` is what applying
1123
+ writes, computed from the sound parts even when there are reasons, so a refused proposal
1124
+ still shows its diff: `{tasks_old, tasks_new, groups_old, groups_new (None without a groups.tsv),
1125
+ edits [(task, field, text)], add [entry], remove [id], rows [new tasks.tsv rows added]}`.
1126
+ """
1127
+ plan = Path(plan)
1128
+ reasons = []
1129
+ rows = forge_brief.read_tasks(plan)
1130
+ by_id = {item['id']: item for item in rows}
1131
+ try:
1132
+ groups = forge_groups.load(plan)
1133
+ except forge_groups.GroupError as error:
1134
+ raise Refused('groups.tsv cannot be read: %s' % ' '.join(str(error).split()))
1135
+ group_ids = {group.id for group in groups}
1136
+
1137
+ removed = []
1138
+ for name in changes['remove']:
1139
+ if name in removed:
1140
+ reasons.append('task %s is removed twice' % name)
1141
+ elif name not in by_id:
1142
+ reasons.append('cannot remove %s: it is not in tasks.tsv' % name)
1143
+ elif started(plan, name):
1144
+ reasons.append('cannot remove %s: it has started' % name)
1145
+ else:
1146
+ removed.append(name)
1147
+
1148
+ added, taken = {}, set(by_id)
1149
+ for entry in changes['add']:
1150
+ sound = _check_added(plan, entry, taken | set(added), group_ids, reasons)
1151
+ name = entry.get('id')
1152
+ if isinstance(name, str) and name in added:
1153
+ reasons.append('add %s: the id is added twice' % name)
1154
+ elif sound:
1155
+ added[name] = entry
1156
+
1157
+ new_deps = {}
1158
+ for entry in changes['deps']:
1159
+ name, deps = entry['task'], entry.get('deps')
1160
+ extra = sorted(key for key in entry if key not in ('task', 'deps'))
1161
+ if extra:
1162
+ reasons.append('deps entry for %s has unknown field(s): %s' % (name, ', '.join(extra)))
1163
+ if not isinstance(deps, list) or not all(isinstance(dep, str) and dep for dep in deps):
1164
+ reasons.append('deps for %s must be a list of task ids' % name)
1165
+ elif name in new_deps:
1166
+ reasons.append('deps of %s are changed twice' % name)
1167
+ elif name in added:
1168
+ reasons.append('deps of %s: it is added in this proposal, so its deps are in its add entry' % name)
1169
+ elif name not in by_id:
1170
+ reasons.append('cannot change the deps of %s: it is not in tasks.tsv' % name)
1171
+ elif name in removed:
1172
+ reasons.append('cannot change the deps of %s: it is removed in this proposal' % name)
1173
+ elif started(plan, name):
1174
+ reasons.append('cannot change the deps of %s: it has started' % name)
1175
+ else:
1176
+ new_deps[name] = list(dict.fromkeys(deps))
1177
+
1178
+ edits_reasons = _confine_edits(plan, changes['edits'], lambda task: (
1179
+ 'task %s is removed in this proposal' % task if task in removed
1180
+ else 'task %s is not in tasks.tsv' % task if task not in by_id else None))
1181
+ reasons.extend(edits_reasons)
1182
+
1183
+ graph = {}
1184
+ for name, item in by_id.items():
1185
+ if name not in removed:
1186
+ graph[name] = new_deps.get(name, item['deps'])
1187
+ for name, entry in added.items():
1188
+ graph[name] = list(dict.fromkeys(entry.get('deps') or []))
1189
+ for name, deps in graph.items():
1190
+ for dep in deps:
1191
+ if dep == name:
1192
+ reasons.append('task %s depends on itself' % name)
1193
+ elif dep in removed:
1194
+ reasons.append('task %s depends on removed task %s: rewrite its deps in the same proposal' % (name, dep))
1195
+ elif dep not in graph:
1196
+ reasons.append('task %s depends on %s, which will not exist' % (name, dep))
1197
+ cycle = _has_cycle({name: [dep for dep in deps if dep in graph and dep != name] for name, deps in graph.items()})
1198
+ if cycle:
1199
+ reasons.append('the dependencies form a cycle: %s' % ' -> '.join(cycle))
1200
+
1201
+ files_new, edits = {}, []
1202
+ for change in changes['edits']:
1203
+ task = change['task']
1204
+ if task not in by_id or task in removed or not forge_side._safe_component(task):
1205
+ continue
1206
+ for field in ('prompt', 'approach'):
1207
+ new = change.get(field)
1208
+ if isinstance(new, str) and new.strip():
1209
+ current = _read_bytes(_task_file(plan, task, field + '.md'))
1210
+ if current is None or _text(current) != new:
1211
+ edits.append((task, field, new))
1212
+ files = change.get('files')
1213
+ if isinstance(files, str) and files.strip() and by_id[task]['files'] != files:
1214
+ files_new[task] = files
1215
+ edits.append((task, 'files', files))
1216
+
1217
+ tasks_old = _text(_read_bytes(plan / 'tasks.tsv'))
1218
+ lines = tasks_old.splitlines(True)
1219
+ if lines and not lines[-1].endswith('\n'):
1220
+ lines[-1] += '\n'
1221
+ lines = _rewrite_rows(lines, drop=set(removed), files=files_new, deps=new_deps)
1222
+ for name, entry in added.items():
1223
+ lines.append('\t'.join([name, ','.join(dict.fromkeys(entry.get('deps') or [])) or '-', entry['difficulty'],
1224
+ ','.join(entry['files']), '-', '-', entry['title']]) + '\n')
1225
+ tasks_new = ''.join(lines)
1226
+
1227
+ groups_old = _read_bytes(plan / 'groups.tsv')
1228
+ groups_old = None if groups_old is None else _text(groups_old)
1229
+ groups_new = groups_old
1230
+ if groups_old is not None:
1231
+ join = {}
1232
+ for name, entry in added.items():
1233
+ if entry.get('group'):
1234
+ join.setdefault(entry['group'], []).append(name)
1235
+ glines, more = _rewrite_groups(groups_old.splitlines(True), set(removed), join)
1236
+ reasons.extend(more)
1237
+ groups_new = ''.join(glines)
1238
+
1239
+ built = {'tasks_old': tasks_old, 'tasks_new': tasks_new, 'groups_old': groups_old, 'groups_new': groups_new,
1240
+ 'edits': edits, 'add': list(added.values()), 'remove': removed, 'deps': new_deps}
1241
+ if not reasons:
1242
+ if not (edits or added or removed or new_deps):
1243
+ reasons.append('the proposal changes nothing')
1244
+ else:
1245
+ try:
1246
+ _validate_new(plan, tasks_new, _max_tasks(plan), groups_new)
1247
+ except forge_groups.GroupError as error:
1248
+ reasons.append('group validation fails: %s' % ' '.join(str(error).split()))
1249
+ return reasons, built
1250
+
1251
+
1252
+ def _plan_diff(plan, built: dict) -> tuple:
1253
+ """`(diff text, targets)` of a built plan change. The hash covers tasks.tsv and groups.tsv whole."""
1254
+ diffs, targets = [], []
1255
+ if built['tasks_new'] != built['tasks_old']:
1256
+ diffs.append(_udiff('tasks.tsv', built['tasks_old'], built['tasks_new']))
1257
+ if built['groups_new'] != built['groups_old']:
1258
+ diffs.append(_udiff('groups.tsv', built['groups_old'], built['groups_new']))
1259
+ for task, field, new in built['edits']:
1260
+ if field == 'files':
1261
+ continue # the tasks.tsv diff shows it
1262
+ current = _read_bytes(_task_file(plan, task, field + '.md'))
1263
+ diffs.append(_udiff(_rel(task, field), None if current is None else _text(current), new))
1264
+ targets.append((_rel(task, field), current))
1265
+ for entry in built['add']:
1266
+ diffs.append(_udiff(_rel(entry['id'], 'prompt'), None, entry['prompt']))
1267
+ if entry.get('approach'):
1268
+ diffs.append(_udiff(_rel(entry['id'], 'approach'), None, entry['approach']))
1269
+ targets.append(('tasks/%s' % entry['id'], None))
1270
+ targets.append(('tasks.tsv', _read_bytes(Path(plan) / 'tasks.tsv')))
1271
+ targets.append(('groups.tsv', _read_bytes(Path(plan) / 'groups.tsv')))
1272
+ return ''.join(diffs), targets
1273
+
1274
+
1275
+ def build_plan_prompt(plan, asking: str, question: dict, answer: dict, repo: str) -> str:
1276
+ plan = Path(plan)
1277
+ rows = forge_brief.read_tasks(plan)
1278
+ groups = forge_groups.load(plan) if (plan / 'groups.tsv').is_file() else []
1279
+ parts = [
1280
+ 'You are revising the PLAN of a multi-task coding run (its tasks and their dependencies), because a '
1281
+ 'person answered an open question that affects the plan as a whole.\n'
1282
+ 'The repository is at %s: you may read it and you must not write to it.\n' % repo,
1283
+ '## The question (asked for task %s)\n\n%s\n\nwhy: %s\noptions: %s\ndefault: %s\n' % (
1284
+ asking, question.get('text', ''), question.get('why', ''),
1285
+ ' | '.join(question.get('options') or []) or '(none)', question.get('default', '')),
1286
+ '## The answer\n\n%s\n' % answer.get('text', ''),
1287
+ '## Every task (tasks.tsv: id, deps, difficulty, files, dwarf, qa, title) and its status\n',
1288
+ ]
1289
+ for item in rows:
1290
+ parts.append('%s [%s]' % (item['row'].rstrip('\n'), 'STARTED: you may not change it'
1291
+ if started(plan, item['id']) else 'unstarted'))
1292
+ parts.append('\n## groups.tsv (id, review, qa, members, title, goal)\n\n%s\n' % (
1293
+ _text(_read_bytes(plan / 'groups.tsv')).strip() if groups else '(no groups)'))
1294
+ parts.append('## The unstarted tasks (each file capped at 6 KB)\n')
1295
+ for item in rows:
1296
+ if not started(plan, item['id']):
1297
+ parts.append('### %s\n\n#### prompt.md\n\n%s\n\n#### approach.md\n\n%s\n' % (
1298
+ item['id'], _capped(plan, item['id'], 'prompt.md'), _capped(plan, item['id'], 'approach.md') or '(none)'))
1299
+ parts.append(
1300
+ '## What to change\n\n'
1301
+ 'Decide what the answer changes in the plan. You may change only tasks that have not started: edit '
1302
+ 'their prompt (prompt.md), approach (approach.md) or files column, remove them, or give them new '
1303
+ 'deps. You may add tasks. A split is a removal plus the added tasks that replace it; every task that '
1304
+ 'depended on a removed one needs its deps rewritten in the same reply. Added ids must be new. '
1305
+ 'An added task\'s deps must name tasks that will exist, with no cycle; its group is null or one '
1306
+ 'existing group id. Every added prompt must end with an "## Acceptance criteria" section of '
1307
+ 'observable checks. Give the FULL new text of any file you change, never a patch. Leave a field '
1308
+ 'null when it stays as it is. If the answer changes nothing, reply with empty lists.\n\n'
1309
+ '## Reply format\n\n'
1310
+ 'Reply with JSON only, no prose and no code fence:\n\n'
1311
+ '{"summary": "...", "changes": {\n'
1312
+ ' "edits": [{"task": "id", "prompt": "<full new prompt.md>"|null, "approach": "<full new approach.md>"|null, '
1313
+ '"files": "<new files column>"|null}],\n'
1314
+ ' "add": [{"id": "new-id", "deps": ["id"], "difficulty": "low|medium|high", "files": ["path"], '
1315
+ '"title": "...", "prompt": "<full prompt.md>", "approach": "<full approach.md>"|null, "group": "group id"|null}],\n'
1316
+ ' "remove": ["id"],\n'
1317
+ ' "deps": [{"task": "id", "deps": ["id"]}]}}\n')
1318
+ return '\n'.join(parts)
1319
+
1320
+
1321
+ def _split_word(changes: dict) -> bool:
1322
+ return bool(changes['remove']) and len(changes['add']) >= 1
1323
+
1324
+
1325
+ def _propose_plan(plan, task, qid, question, answer, who, found, timeout) -> dict:
1326
+ ok, reason = forge_side.allowed('brief-change', plan)
1327
+ if not ok:
1328
+ raise forge_brief.BriefOff(reason)
1329
+ repo = forge_brief._text(plan / 'repo').strip()
1330
+ prompt = build_plan_prompt(plan, task, question, answer, repo)
1331
+ data, error = _ask(plan, task, prompt, found['model'], timeout, parse=parse_plan_reply)
1332
+ if data is None:
1333
+ raise Refused('the change writer failed: %s' % error)
1334
+ changes = _normalize_plan(data['changes'])
1335
+ reasons, built = _plan_check(plan, changes)
1336
+ diff_text, targets = _plan_diff(plan, built)
1337
+ summary = data['summary']
1338
+ if _split_word(changes) and 'split' not in summary.lower():
1339
+ summary = 'split: ' + summary
1340
+ state = 'refused' if reasons else 'proposed'
1341
+ with _proposals_lock(plan):
1342
+ number = (_numbers(plan) or [0])[-1] + 1
1343
+ pid = 'p%d' % number
1344
+ directory = _proposals(plan) / pid
1345
+ directory.mkdir(parents=True)
1346
+ record = {'pid': pid, 'scope': 'plan', 'group': None, 'task': task, 'qid': qid,
1347
+ 'answer': answer['text'], 'summary': summary, 'changes': changes,
1348
+ 'state': state, 'reason': '; '.join(reasons) or None,
1349
+ 'created': forge_brief._now(), 'actor': who}
1350
+ forge_brief.atomic_write(directory / 'diff.patch', diff_text)
1351
+ forge_brief.atomic_write(directory / 'hash', _digest(diff_text, targets) + '\n')
1352
+ _store(plan, record)
1353
+ _emit(plan, record)
1354
+ return record
1355
+
1356
+
1357
+ # --- applying a plan-scope proposal ----------------------------------------------------
1358
+
1359
+ def _decompose_hint(plan) -> str:
1360
+ level = forge_brief._text(Path(plan) / 'decompose_level').strip()
1361
+ return ' --decompose-level %s' % level if level in DIFFICULTIES else ''
1362
+
1363
+
1364
+ def plan_again_message(plan) -> str:
1365
+ return 'plan changed; run forge-parallel.sh plan %s …%s again before run' % (shlex.quote(str(plan)), _decompose_hint(plan))
1366
+
1367
+
1368
+ STALE = 'stale: plan changed by proposal'
1369
+
1370
+
1371
+ def plan_stale(plan) -> bool:
1372
+ """True when a plan-scope apply left `groups.frozen` as a stale marker: `plan` has not run again."""
1373
+ return forge_brief._text(Path(plan) / 'groups.frozen').startswith(STALE)
1374
+
1375
+
1376
+ def _routing_for(rows: list, difficulty: str):
1377
+ """`(dwarf, qa)` an added row can take in a live run: explicit specs copied from an existing row
1378
+ (the same difficulty first), since `forge control add` refuses `-` and UNASSIGNED."""
1379
+ def explicit(item):
1380
+ return all(value not in ('', '-', 'UNASSIGNED') for value in (item['dwarf'], item['qa']))
1381
+ pool = [item for item in rows if explicit(item)]
1382
+ same = [item for item in pool if item['difficulty'] == difficulty]
1383
+ chosen = (same or pool or [None])[0]
1384
+ return (chosen['dwarf'], chosen['qa']) if chosen else None
1385
+
1386
+
1387
+ def _write_edits(written: list) -> list:
1388
+ """Write `[(path, text)]` atomically, returning the undo list `[(path, old bytes or None)]`."""
1389
+ undo = []
1390
+ for path, value in written:
1391
+ undo.append((path, _read_bytes(path)))
1392
+ forge_brief.atomic_write(path, value)
1393
+ return undo
1394
+
1395
+
1396
+ def _undo_files(undo: list) -> None:
1397
+ for path, old in reversed(undo):
1398
+ try:
1399
+ if old is None:
1400
+ Path(path).unlink(missing_ok=True)
1401
+ else:
1402
+ forge_brief.atomic_write(path, _text(old))
1403
+ except OSError:
1404
+ pass
1405
+
1406
+
1407
+ def _apply_plan_offline(plan, pid, built: dict) -> list:
1408
+ """Write the new plan files, create the new task dirs, move the removed ones. Rolled back whole on a failure."""
1409
+ import shutil
1410
+ moved, created, undo = [], [], []
1411
+ try:
1412
+ for entry in built['add']:
1413
+ tdir = plan / 'tasks' / entry['id']
1414
+ tdir.mkdir(parents=True)
1415
+ created.append(tdir)
1416
+ forge_brief.atomic_write(tdir / 'prompt.md', entry['prompt'])
1417
+ forge_brief.atomic_write(tdir / 'approach.md', entry.get('approach') or '')
1418
+ for name in built['remove']:
1419
+ source = plan / 'tasks' / name
1420
+ if source.is_dir():
1421
+ target = plan / 'tasks' / '.removed' / ('%s-%s' % (name, pid))
1422
+ target.parent.mkdir(parents=True, exist_ok=True)
1423
+ os.rename(str(source), str(target))
1424
+ moved.append((source, target))
1425
+ written = [(plan / ('tasks/%s/%s.md' % (task, field)), value)
1426
+ for task, field, value in built['edits'] if field != 'files']
1427
+ written.append((plan / 'tasks.tsv', built['tasks_new']))
1428
+ if built['groups_new'] != built['groups_old']:
1429
+ written.append((plan / 'groups.tsv', built['groups_new']))
1430
+ # The frozen fingerprint covers groups.tsv and the rows of group members only, so a change to
1431
+ # an ungrouped task, or a plan with no groups, would leave `run` free to go on with rows `plan`
1432
+ # never routed. A stale marker never matches a fingerprint, and with no groups.tsv its mere
1433
+ # presence is refused by `check_frozen`: either way `run` stops until `plan` freezes again
1434
+ # (it overwrites the marker, or removes it when there are no groups).
1435
+ written.append((plan / 'groups.frozen', '%s %s\n' % (STALE, pid)))
1436
+ undo = _write_edits(written)
1437
+ except BaseException:
1438
+ _undo_files(undo)
1439
+ for source, target in reversed(moved):
1440
+ try:
1441
+ os.rename(str(target), str(source))
1442
+ except OSError:
1443
+ pass
1444
+ for tdir in created:
1445
+ shutil.rmtree(str(tdir), ignore_errors=True)
1446
+ raise
1447
+ names = [str(path.relative_to(plan)) for path, _ in written]
1448
+ names += ['tasks/%s/' % entry['id'] for entry in built['add']]
1449
+ names += [str(target.relative_to(plan)) + '/' for _, target in moved]
1450
+ return names
1451
+
1452
+
1453
+ def _control_args(plan, task, actor):
1454
+ return argparse.Namespace(plan=str(plan), task=task, json=False, actor='ui' if actor == 'ui' else 'cli')
1455
+
1456
+
1457
+ def _dependency_order(adds: list) -> list:
1458
+ """The added entries, each after the added entries it depends on (proposal order otherwise):
1459
+ `forge control add` refuses a row whose dependency is not in tasks.tsv yet."""
1460
+ ids = {entry['id'] for entry in adds}
1461
+ ordered, placed, pending = [], set(), list(adds)
1462
+ while pending:
1463
+ ready = [entry for entry in pending
1464
+ if all(dep in placed or dep not in ids for dep in (entry.get('deps') or []))]
1465
+ if not ready: # a cycle among the adds: _plan_check refuses it, never reached
1466
+ ready = pending[:1]
1467
+ ordered.append(ready[0])
1468
+ placed.add(ready[0]['id'])
1469
+ pending.remove(ready[0])
1470
+ return ordered
1471
+
1472
+
1473
+ def _apply_plan_live(plan, pid, built: dict, control, actor, rows) -> tuple:
1474
+ """Queue each added task through `forge control add`. Returns `(names, notes)`; raises `Refused`."""
1475
+ import shutil
1476
+ adds = _dependency_order(built['add'])
1477
+ routes = {}
1478
+ for entry in adds:
1479
+ route = _routing_for(rows, entry['difficulty'])
1480
+ if route is None:
1481
+ raise Refused('a live run needs explicit dwarf and qa specs for an added task, and no task of '
1482
+ 'this plan has them yet: apply after the run ends, then plan again')
1483
+ routes[entry['id']] = route
1484
+ queued, notes = [], []
1485
+ for entry in adds:
1486
+ name, (dwarf, qa) = entry['id'], routes[entry['id']]
1487
+ tdir = plan / 'tasks' / name
1488
+ undo = []
1489
+ try:
1490
+ with control.control_lock(os.path.realpath(str(plan))):
1491
+ tdir.mkdir(parents=True)
1492
+ forge_brief.atomic_write(tdir / 'prompt.md', entry['prompt'])
1493
+ forge_brief.atomic_write(tdir / 'approach.md', entry.get('approach') or '')
1494
+ old = _text(_read_bytes(plan / 'tasks.tsv'))
1495
+ if old and not old.endswith('\n'):
1496
+ old += '\n'
1497
+ row = '\t'.join([name, ','.join(dict.fromkeys(entry.get('deps') or [])) or '-', entry['difficulty'],
1498
+ ','.join(entry['files']), dwarf, qa, entry['title']]) + '\n'
1499
+ undo = _write_edits([(plan / 'tasks.tsv', old + row)])
1500
+ with contextlib.redirect_stdout(io.StringIO()):
1501
+ control.cmd_add(_control_args(plan, name, actor))
1502
+ except (control.Refused, control.Invalid, OSError) as error:
1503
+ with contextlib.suppress(Exception), control.control_lock(os.path.realpath(str(plan))):
1504
+ _undo_files(undo)
1505
+ shutil.rmtree(str(tdir), ignore_errors=True)
1506
+ done = ('; already queued: %s' % ', '.join(queued)) if queued else ''
1507
+ failure = Refused('forge control add refused %s: %s%s' % (name, error, done))
1508
+ failure.queued = queued
1509
+ raise failure
1510
+ queued.append(name)
1511
+ if entry.get('group'):
1512
+ notes.append('task %s joins no group (a live-added task joins none), whatever the proposal says' % name)
1513
+ names = ['tasks.tsv'] + ['tasks/%s/' % name for name in queued]
1514
+ return names, notes
1515
+
1516
+
1517
+ def _apply_plan(plan, pid, approve_hash, who, regenerate=True) -> dict:
1518
+ """`apply` for a plan-scope proposal. No live run: the plan files change and `plan` must run again.
1519
+ A live run: only added tasks, each through `forge control add`; anything else refuses, nothing changed."""
1520
+ with _proposals_lock(plan):
1521
+ queued = None
1522
+ with _control_lock(plan) as control:
1523
+ record = _load(plan, pid)
1524
+ if record.get('state') != 'proposed':
1525
+ raise Refused('proposal %s is %s, not proposed' % (pid, record.get('state')))
1526
+ stored = _stored_hash(plan, pid)
1527
+ if not stored or str(approve_hash).strip().lower() != stored:
1528
+ raise Refused('the hash does not match proposal %s: read its diff again and quote its hash' % pid)
1529
+ changes = plan_changes_of(record)
1530
+ reasons, built = _plan_check(plan, changes)
1531
+ if reasons:
1532
+ raise Refused('proposal %s no longer fits the plan: %s' % (pid, '; '.join(reasons)))
1533
+ _, targets = _plan_diff(plan, built)
1534
+ if _digest(_text(_read_bytes(_proposals(plan) / pid / 'diff.patch')), targets) != stored:
1535
+ raise Refused('a target file changed since proposal %s: propose again' % pid)
1536
+ live = control.is_live(os.path.realpath(str(plan)))
1537
+ if live and (changes['edits'] or changes['remove'] or changes['deps']):
1538
+ raise Refused(PLAN_MESSAGE)
1539
+ notes = []
1540
+ if not live:
1541
+ names = _apply_plan_offline(plan, pid, built)
1542
+ message = plan_again_message(plan)
1543
+ record.update(state='approved', applied=forge_brief._now(), applied_by=who, live=False)
1544
+ _store(plan, record)
1545
+ if live: # forge control add takes the control lock itself
1546
+ rows = forge_brief.read_tasks(plan)
1547
+ try:
1548
+ names, notes = _apply_plan_live(plan, pid, built, answers._control(), who, rows)
1549
+ except Refused as failure:
1550
+ queued = getattr(failure, 'queued', None)
1551
+ if queued: # some rows are in the plan and queued: the proposal cannot be applied again
1552
+ record.update(state='approved', applied=forge_brief._now(), applied_by=who, live=True,
1553
+ queued=queued, partial=failure.reason)
1554
+ _store(plan, record)
1555
+ # The apply still raises, so it is not the successful apply that marks
1556
+ # brief.affected and emits the approved event.
1557
+ raise
1558
+ order = [entry['id'] for entry in _dependency_order(built['add'])]
1559
+ message = 'queued %s into the live run through forge control add' % ', '.join(order)
1560
+ record.update(state='approved', applied=forge_brief._now(), applied_by=who, live=True, queued=order)
1561
+ _store(plan, record)
1562
+ result = {'pid': pid, 'state': 'approved', 'files': names, 'tasks': touched(record), 'warning': None,
1563
+ 'message': message, 'notes': notes, 'live': live}
1564
+ return _settle(plan, record, result, regenerate)
1565
+
1566
+
1567
+ # --- reject and list -------------------------------------------------------------------
1568
+
1569
+ def reject(plan, pid, actor='cli', reason=None) -> dict:
1570
+ """State `rejected`, the event, and no plan file touched. A proposed or refused proposal can be rejected."""
1571
+ who = answers._actor(actor)
1572
+ plan = Path(plan)
1573
+ if not plan.is_dir():
1574
+ raise forge_brief.NotAPlan(str(plan))
1575
+ with _proposals_lock(plan):
1576
+ record = _load(plan, pid)
1577
+ if record.get('state') not in ('proposed', 'refused'):
1578
+ raise Refused('proposal %s is %s: only a proposed or refused one can be rejected' % (pid, record.get('state')))
1579
+ record['state'] = 'rejected'
1580
+ record['rejected'] = forge_brief._now()
1581
+ record['rejected_by'] = who
1582
+ if reason:
1583
+ record['reject_reason'] = ' '.join(str(reason).split())
1584
+ _store(plan, record)
1585
+ _emit(plan, record)
1586
+ return record
1587
+
1588
+
1589
+ def apply_line(plan, pid, digest) -> str:
1590
+ return 'forge brief apply %s %s --approve %s' % (shlex.quote(str(plan)), pid, digest)
1591
+
1592
+
1593
+ def listing(plan) -> list:
1594
+ """Every proposal, oldest first: its record plus `hash`, `diff` and, when it can be applied, `apply`."""
1595
+ plan = Path(plan)
1596
+ out = []
1597
+ for number in _numbers(plan):
1598
+ pid = 'p%d' % number
1599
+ record = forge_brief._json(_proposals(plan) / pid / 'proposal.json')
1600
+ if not isinstance(record, dict):
1601
+ continue
1602
+ item = dict(record, hash=_stored_hash(plan, pid),
1603
+ diff=_text(_read_bytes(_proposals(plan) / pid / 'diff.patch')))
1604
+ if record.get('state') == 'proposed':
1605
+ item['apply'] = apply_line(plan, pid, item['hash'])
1606
+ out.append(item)
1607
+ return out
1608
+
1609
+
1610
+ def render_one(item: dict) -> str:
1611
+ """The text `forge brief proposals` shows for one proposal."""
1612
+ lines = ['%s %s scope %s%s (asked by %s/%s)' % (
1613
+ item['pid'], item['state'], item.get('scope'),
1614
+ ' group %s' % item.get('group') if item.get('group') else '', item.get('task'), item.get('qid')),
1615
+ ' %s' % (item.get('summary') or '(no summary)')]
1616
+ if item.get('reason'):
1617
+ lines.append(' refused: %s' % item['reason'] if item['state'] == 'refused' else ' %s' % item['reason'])
1618
+ if item.get('diff'):
1619
+ lines.append('')
1620
+ lines.append(item['diff'].rstrip('\n'))
1621
+ lines.append('')
1622
+ if item.get('apply'):
1623
+ lines.append(' apply: %s' % item['apply'])
1624
+ return '\n'.join(lines) + '\n'
1625
+
1626
+
1627
+ def render(items: list) -> str:
1628
+ if not items:
1629
+ return 'no proposals\n'
1630
+ return '\n'.join(render_one(item) for item in items)