@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,506 @@
1
+ """Record brief answers, and flag questions a merge may have made stale (#135, #136).
2
+
3
+ `answer` writes `tasks/<id>/brief.answers.json` as `{qid: {text, actor, t}}` while the
4
+ task is still PENDING and has no `attempts.tsv` row. Once it is past starting, nothing
5
+ about the task changes: the same object goes to `brief.late.json` instead. The command
6
+ prints the `tasks.tsv` row and the `prompt.md` a follow-up needs, then the
7
+ `forge control add` line that queues that row. `add` only takes the plan and a task id
8
+ that is already in `tasks.tsv`, and the prompt is what carries the answer.
9
+
10
+ A parked question (`brief.parked.json`: scope `wave` or `plan`) is answerable only when the
11
+ plan's brief scope is at least as wide as the question's: `--brief-scope wave` takes wave
12
+ questions, `plan` takes both, and the default `task` takes neither (the question id is then
13
+ unknown, as it always was). Such an answer goes to `brief.parked.answers.json` as `{qid: {text,
14
+ actor, t}}`, whatever the task's status, and the command prints `forge brief propose`. Answering
15
+ never changes a prompt: `proposals.py` turns the answer into a diff that waits for approval.
16
+
17
+ `stale` runs after a task has merged. When that merge's `changes.diff` (or, if the diff
18
+ is gone, the task's attempt events) names a file outside the task's declared files,
19
+ every open question of a direct dependent that has not started gets `possibly_stale:
20
+ true`. A declared directory covers everything under it, the same rule as `check_drift`:
21
+ `src/routes` covers `src/routes/api.py`.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import importlib.util
26
+ import json
27
+ import shlex
28
+ import sqlite3
29
+ import sys
30
+ import time
31
+ import unicodedata
32
+ from pathlib import Path
33
+
34
+ import forge_brief
35
+ import forge_side
36
+
37
+ # Bytes, matching the cap forge-prompt.py uses when it quotes an answer.
38
+ ANSWER_CAP = 4 * 1024
39
+ # Room to strip control characters before the cap, without reading an unbounded file.
40
+ READ_LIMIT = 1024 * 1024
41
+
42
+ _CONTROL = None
43
+
44
+
45
+ class Usage(Exception):
46
+ """The answer text or the actor is not usable. The command exits 2."""
47
+
48
+
49
+ class NoSuchTask(Exception):
50
+ """The task is not in this plan. `valid` is the ids the plan does have."""
51
+
52
+ def __init__(self, task, valid):
53
+ super().__init__(task)
54
+ self.task = task
55
+ self.valid = list(valid)
56
+
57
+
58
+ class NoSuchQuestion(Exception):
59
+ """The task has no question with this id. `valid` is the ids in its brief.json."""
60
+
61
+ def __init__(self, task, qid, valid):
62
+ super().__init__(qid)
63
+ self.task = task
64
+ self.qid = qid
65
+ self.valid = list(valid)
66
+
67
+
68
+ def _control():
69
+ """forge-control.py, loaded once. `audit` is the control.log writer to reuse."""
70
+ global _CONTROL
71
+ if _CONTROL is None:
72
+ path = Path(forge_brief.SCRIPTS) / 'forge-control.py'
73
+ spec = importlib.util.spec_from_file_location('forge_control_cli', path)
74
+ module = importlib.util.module_from_spec(spec)
75
+ spec.loader.exec_module(module)
76
+ _CONTROL = module
77
+ return _CONTROL
78
+
79
+
80
+ def _norm(path) -> str:
81
+ """A repo-relative path, comparable between tasks.tsv and a diff."""
82
+ text = str(path).strip().replace('\\', '/')
83
+ while text.startswith('./'):
84
+ text = text[2:]
85
+ return text
86
+
87
+
88
+ def status_of(plan, task) -> str:
89
+ """The task's status, read the way `task_status` reads it.
90
+
91
+ `tasks/<id>/merged` is MERGED even when `status` still says PASS: the merge
92
+ touches that file and does not rewrite status.
93
+ """
94
+ tdir = forge_brief.task_dir(plan, task)
95
+ if (tdir / 'merged').is_file():
96
+ return 'MERGED'
97
+ try:
98
+ words = (tdir / 'status').read_text(encoding='utf-8', errors='replace').split()
99
+ except OSError:
100
+ return 'PENDING'
101
+ return words[0] if words else 'PENDING'
102
+
103
+
104
+ def _attempt_rows(plan, task) -> bool:
105
+ path = forge_brief.task_dir(plan, task) / 'attempts.tsv'
106
+ try:
107
+ text = path.read_text(encoding='utf-8', errors='replace')
108
+ except OSError:
109
+ return False
110
+ return any(line.strip() and not line.startswith('#') for line in text.splitlines())
111
+
112
+
113
+ def past_start(plan, task) -> bool:
114
+ """Whether an answer can no longer change this task.
115
+
116
+ Past starting when `status` is RUNNING or any finished state (MERGED, FAIL,
117
+ BLOCKED, NEEDS_*, ACCEPTED, and every other status forge writes), or when
118
+ `attempts.tsv` has a row. Only PENDING with no attempt row is still in time.
119
+ """
120
+ if _attempt_rows(plan, task):
121
+ return True
122
+ return status_of(plan, task) != 'PENDING'
123
+
124
+
125
+ def question_ids(plan, task) -> list:
126
+ """Ids of the questions in `brief.json`, in file order. Parked questions are not answers."""
127
+ data = forge_brief._json(forge_brief.task_dir(plan, task) / 'brief.json')
128
+ found = []
129
+ for question in forge_brief._questions(data if isinstance(data, dict) else None):
130
+ qid = question.get('id')
131
+ if isinstance(qid, str) and qid:
132
+ found.append(qid)
133
+ return found
134
+
135
+
136
+ SCOPE_RANK = {'task': 0, 'wave': 1, 'plan': 2}
137
+
138
+
139
+ def parked_questions(plan, task) -> dict:
140
+ """`{qid: question}` for the task's parked questions, in file order. Every parked question, answerable or not."""
141
+ data = forge_brief._json(forge_brief.task_dir(plan, task) / 'brief.parked.json')
142
+ found = {}
143
+ for question in forge_brief._questions(data if isinstance(data, dict) else None):
144
+ qid = question.get('id')
145
+ if isinstance(qid, str) and qid:
146
+ found[qid] = question
147
+ return found
148
+
149
+
150
+ def answerable_parked(plan, task) -> dict:
151
+ """The parked questions an answer may be recorded for under the plan's brief scope.
152
+
153
+ A question of scope `wave` or `plan` is answerable when the brief scope is at that scope
154
+ or wider. With brief scope `task` (the default) none is.
155
+ """
156
+ reach = SCOPE_RANK.get(forge_side.settings(plan)['brief']['scope'], 0)
157
+ return {qid: question for qid, question in parked_questions(plan, task).items()
158
+ if SCOPE_RANK.get(question.get('scope'), 0) >= 1
159
+ and SCOPE_RANK[question.get('scope')] <= reach}
160
+
161
+
162
+ def propose_line(plan, task, qid) -> str:
163
+ return 'forge brief propose %s %s %s' % (shlex.quote(str(plan)), shlex.quote(task), shlex.quote(qid))
164
+
165
+
166
+ def clean_answer(text) -> str:
167
+ """Drop control characters, then keep the leading 4 KB of what remains."""
168
+ if text is None:
169
+ text = ''
170
+ elif not isinstance(text, str):
171
+ text = str(text)
172
+ kept = ''.join(ch for ch in text if unicodedata.category(ch) != 'Cc')
173
+ try:
174
+ raw = kept.encode('utf-8')
175
+ except UnicodeEncodeError:
176
+ raw = kept.encode('utf-8', errors='ignore')
177
+ kept = raw.decode('utf-8')
178
+ if len(raw) <= ANSWER_CAP:
179
+ return kept
180
+ return raw[:ANSWER_CAP].decode('utf-8', errors='ignore')
181
+
182
+
183
+ def _read_file(file) -> str:
184
+ if file == '-':
185
+ return sys.stdin.read(READ_LIMIT)
186
+ path = Path(file)
187
+ try:
188
+ with path.open('r', encoding='utf-8', errors='replace') as handle:
189
+ return handle.read(READ_LIMIT)
190
+ except OSError as error:
191
+ raise Usage('cannot read %s: %s' % (file, error.strerror or error)) from error
192
+
193
+
194
+ def _actor(value) -> str:
195
+ if value is None:
196
+ return 'cli'
197
+ actor = ''.join(ch for ch in str(value) if unicodedata.category(ch) != 'Cc').strip()
198
+ if not actor or any(ch.isspace() for ch in actor):
199
+ raise Usage('actor must be a single token')
200
+ if len(actor) > 64:
201
+ raise Usage('actor is too long')
202
+ return actor
203
+
204
+
205
+ def _load_map(path) -> dict:
206
+ return forge_brief._entries(forge_brief._json(path))
207
+
208
+
209
+ def _store(path, data: dict) -> None:
210
+ forge_brief.atomic_write(path, forge_brief._dump(data))
211
+
212
+
213
+ def _put(path, qid, record) -> str | None:
214
+ """Replace `qid` and keep every other answer. The previous text, if there was one."""
215
+ current = _load_map(path)
216
+ old = current.get(qid)
217
+ previous = old.get('text') if isinstance(old, dict) and isinstance(old.get('text'), str) else None
218
+ current[qid] = record
219
+ _store(path, current)
220
+ return previous
221
+
222
+
223
+ def _task_token(text) -> str:
224
+ """A tasks.tsv id: no slash, NUL, comma or whitespace, which would split a column or a dep."""
225
+ cleaned = ''.join('-' if ch in '/\0\t\r\n ,' else ch for ch in str(text))
226
+ return cleaned.strip('-')
227
+
228
+
229
+ def _follow_up_id(tasks, task, qid) -> str:
230
+ """An id that is free in tasks.tsv, so the caller can append a row and then `control add` it."""
231
+ taken = {item['id'] for item in tasks}
232
+ base = _task_token('%s-%s' % (task, qid))
233
+ if base in ('', '.', '..'):
234
+ base = _task_token('follow-up-%s' % qid) or 'follow-up'
235
+ candidate = base
236
+ number = 2
237
+ while candidate in taken or candidate in ('', '.', '..'):
238
+ candidate = '%s-%d' % (base, number)
239
+ number += 1
240
+ return candidate
241
+
242
+
243
+ def follow_up_line(plan, follow_id) -> str:
244
+ """`forge control add`: the plan, then the task id. Those are its only positional arguments."""
245
+ return 'forge control add %s %s' % (shlex.quote(str(plan)), shlex.quote(follow_id))
246
+
247
+
248
+ def _one_line(text) -> str:
249
+ return ' '.join(str(text or '').split())
250
+
251
+
252
+ def _question_text(plan, task, qid) -> str:
253
+ data = forge_brief._json(forge_brief.task_dir(plan, task) / 'brief.json')
254
+ for question in forge_brief._questions(data if isinstance(data, dict) else None):
255
+ if question.get('id') == qid:
256
+ text = question.get('text')
257
+ return text if isinstance(text, str) else ''
258
+ return ''
259
+
260
+
261
+ def _follow_row(source, follow_id, qid) -> str:
262
+ """A 7-column tasks.tsv row `check_row` can accept once the prompt exists.
263
+
264
+ Difficulty, files and the two specs are the source task's, so the row stays inside
265
+ the columns that task already used. The new id depends on the source task. The files
266
+ column has to be non-empty; a source row with no files falls back to `.`.
267
+ """
268
+ difficulty = source.get('difficulty')
269
+ if difficulty not in ('low', 'medium', 'high'):
270
+ difficulty = 'low'
271
+ files = str(source.get('files') or '').strip()
272
+ if files in ('', '-'):
273
+ files = '.'
274
+ title = _one_line('Late answer to %s %s' % (source.get('id') or follow_id, qid)) or 'Late answer'
275
+ return '\t'.join((follow_id, source.get('id') or '-', difficulty, files,
276
+ str(source.get('dwarf') or ''), str(source.get('qa') or ''), title))
277
+
278
+
279
+ def late_message(plan, task, follow_id, row, question, answer) -> str:
280
+ """What a late answer prints: the row and the prompt first, then the add command.
281
+
282
+ `forge control add` queues a task that is already a row in tasks.tsv and reads the
283
+ answer from that task's prompt.md. The command line itself has nowhere to put the text.
284
+ """
285
+ prompt = 'tasks/%s/prompt.md' % follow_id
286
+ return (
287
+ 'too late for task %s: the answer does not change this task\n'
288
+ 'Append this row to tasks.tsv and write %s with the question and the answer below. '
289
+ 'The prompt carries the answer. While a scheduler is live, run the command at the end.\n'
290
+ '%s\n'
291
+ 'question: %s\n'
292
+ 'answer: %s\n'
293
+ '%s\n'
294
+ % (task, prompt, row, _one_line(question), answer, follow_up_line(plan, follow_id)))
295
+
296
+
297
+ def _log(plan, actor, task, qid, text, previous, late) -> None:
298
+ """One control.log line in the shape `audit` writes, then the `brief_answer` event."""
299
+ try:
300
+ control = _control()
301
+ except Exception:
302
+ entry = {'at': time.time(), 'actor': actor, 'action': 'answer', 'task': task,
303
+ 'key': qid, 'value': text, 'previous': previous, 'late': bool(late)}
304
+ with (Path(plan) / 'control.log').open('a', encoding='utf-8') as handle:
305
+ handle.write(json.dumps(entry) + '\n')
306
+ else:
307
+ with control.control_lock(str(plan)):
308
+ control.audit(str(plan), actor, 'answer', task, qid, text, previous, late=bool(late))
309
+ _emit(plan, task, qid, actor, late)
310
+
311
+
312
+ def _emit(plan, task, qid, actor, late) -> None:
313
+ """One `brief_answer` dataset event. Fail-open, like every other capture."""
314
+ try:
315
+ from forge_dataset.capture import point
316
+ point('brief_answer', str(plan), str(task), {
317
+ 'task': str(task), 'qid': qid, 'actor': actor, 'late': bool(late)})
318
+ except Exception:
319
+ pass
320
+
321
+
322
+ def answer(plan, task, qid, text=None, actor='cli', file=None) -> dict:
323
+ """Record one answer. Raises `Usage`, `NotAPlan`, `NoSuchTask` or `NoSuchQuestion`.
324
+
325
+ Returns `{task, qid, late, parked, text, message}`. `message` is what the command prints.
326
+ A late answer's message gives the tasks.tsv row and the prompt text, then the
327
+ `forge control add` line that queues that follow-up once a scheduler is live. An answer to
328
+ a parked question is never late: it is stored in `brief.parked.answers.json` and the
329
+ message names the `forge brief propose` command.
330
+ """
331
+ if file is not None and text is not None:
332
+ raise Usage('give the answer as text or --file, not both')
333
+ if file is None and text is None:
334
+ raise Usage('give the answer as text or --file')
335
+ who = _actor(actor)
336
+ cleaned = clean_answer(_read_file(file) if file is not None else text)
337
+ if not cleaned:
338
+ raise Usage('the answer is empty')
339
+ plan = Path(plan)
340
+ tasks = forge_brief.read_tasks(plan)
341
+ ids = [item['id'] for item in tasks]
342
+ if task not in ids:
343
+ raise NoSuchTask(task, ids)
344
+ valid = question_ids(plan, task)
345
+ if qid not in valid and qid not in answerable_parked(plan, task):
346
+ raise NoSuchQuestion(task, qid, valid + list(answerable_parked(plan, task)))
347
+ tdir = forge_brief.task_dir(plan, task)
348
+ with forge_brief._task_lock(plan, task):
349
+ # The brief may have been regenerated while this answer waited for the lock.
350
+ valid = question_ids(plan, task)
351
+ parked = qid not in valid
352
+ if parked and qid not in answerable_parked(plan, task):
353
+ raise NoSuchQuestion(task, qid, valid + list(answerable_parked(plan, task)))
354
+ late = False if parked else past_start(plan, task)
355
+ record = {'text': cleaned, 'actor': who, 't': time.time()}
356
+ name = 'brief.parked.answers.json' if parked else ('brief.late.json' if late else 'brief.answers.json')
357
+ previous = _put(tdir / name, qid, record)
358
+ _log(plan, who, task, qid, cleaned, previous, late)
359
+ if parked:
360
+ message = '%s/%s answered (%s scope, parked); nothing changes until you propose and approve a diff\n%s\n' % (
361
+ task, qid, answerable_parked(plan, task).get(qid, {}).get('scope', 'wave'),
362
+ propose_line(plan, task, qid))
363
+ return {'task': task, 'qid': qid, 'late': False, 'parked': True, 'text': cleaned, 'message': message}
364
+ if late:
365
+ source = next(item for item in tasks if item['id'] == task)
366
+ follow = _follow_up_id(tasks, task, qid)
367
+ message = late_message(plan, task, follow, _follow_row(source, follow, qid),
368
+ _question_text(plan, task, qid), cleaned)
369
+ else:
370
+ message = '%s/%s answered\n' % (task, qid)
371
+ return {'task': task, 'qid': qid, 'late': late, 'parked': False, 'text': cleaned, 'message': message}
372
+
373
+
374
+ # --- stale -----------------------------------------------------------------------
375
+
376
+ def _declared(files_field) -> set:
377
+ if not files_field or str(files_field).strip() in ('', '-'):
378
+ return set()
379
+ return {_norm(part) for part in str(files_field).split(',') if part.strip() and part.strip() != '-'}
380
+
381
+
382
+ def _covers(declared: str, path: str) -> bool:
383
+ """Whether `check_drift` would treat `path` as inside this declared entry.
384
+
385
+ Exact match, or a declared directory prefix: `src/routes` covers `src/routes/api.py`.
386
+ A trailing slash is the same directory. `src/routes` does not cover `src/routes-extra.py`.
387
+ """
388
+ root = declared.rstrip('/')
389
+ if not root:
390
+ return False
391
+ return path == root or path.startswith(root + '/')
392
+
393
+
394
+ def _undeclared(changed: set, declared: set) -> set:
395
+ """Changed paths that sit outside every declared file and directory."""
396
+ return {path for path in changed if path and not any(_covers(item, path) for item in declared)}
397
+
398
+
399
+ def _diff_files(plan, task) -> set | None:
400
+ """Files in `changes.diff`, or None when that diff is not on disk."""
401
+ path = forge_brief.task_dir(plan, task) / 'changes.diff'
402
+ if not path.is_file():
403
+ return None
404
+ from forge_dataset.harvest import diff_summary
405
+ text = path.read_text(encoding='utf-8', errors='replace')
406
+ summary = diff_summary(text)
407
+ return {_norm(name) for name in summary.get('changed_files') or [] if isinstance(name, str)}
408
+
409
+
410
+ def _dataset_files(plan, task) -> set:
411
+ """`changed_files` of this plan's attempt events for the task, when the diff is gone.
412
+
413
+ Only this run's own events: a plan without a `run_id` reads nothing, so another run's
414
+ attempts (and the store beyond file lists) never reach the brief."""
415
+ repo = forge_brief._text(Path(plan) / 'repo').strip()
416
+ run_id = forge_brief._text(Path(plan) / 'run_id').strip()
417
+ if not repo or not run_id:
418
+ return set()
419
+ try:
420
+ from forge_dataset import dataset_dir, repo_id
421
+ path = dataset_dir() / 'dataset.sqlite'
422
+ if not path.is_file():
423
+ return set()
424
+ # The events table stores repo_id(repo), the same key live capture writes.
425
+ query = 'SELECT data FROM events WHERE kind = ? AND task = ? AND repo = ? AND run_id = ?'
426
+ params = ['attempt', task, repo_id(repo), run_id]
427
+ db = sqlite3.connect(str(path))
428
+ try:
429
+ rows = db.execute(query, params).fetchall()
430
+ finally:
431
+ db.close()
432
+ except Exception:
433
+ return set()
434
+ found = set()
435
+ for (raw,) in rows:
436
+ try:
437
+ data = json.loads(raw)
438
+ except (TypeError, ValueError):
439
+ continue
440
+ files = data.get('changed_files') if isinstance(data, dict) else None
441
+ if isinstance(files, list):
442
+ found.update(_norm(name) for name in files if isinstance(name, str))
443
+ return found
444
+
445
+
446
+ def changed_files(plan, task) -> set:
447
+ """What the merge changed. The diff on disk wins: an earlier attempt may have been reverted."""
448
+ found = _diff_files(plan, task)
449
+ if found is not None:
450
+ return found
451
+ return _dataset_files(plan, task)
452
+
453
+
454
+ def _flag_open(plan, task) -> list:
455
+ """Set `possibly_stale` on this task's open questions. `[(task, qid), ...]` in file order."""
456
+ tdir = forge_brief.task_dir(plan, task)
457
+ path = tdir / 'brief.json'
458
+ if not path.is_file():
459
+ return []
460
+ with forge_brief._task_lock(plan, task):
461
+ if past_start(plan, task):
462
+ return []
463
+ brief = forge_brief._json(path)
464
+ if not isinstance(brief, dict) or not isinstance(brief.get('questions'), list):
465
+ return []
466
+ answered = set(_load_map(tdir / 'brief.answers.json'))
467
+ answered.update(_load_map(tdir / 'brief.late.json'))
468
+ flagged = []
469
+ changed = False
470
+ for question in brief['questions']:
471
+ if not isinstance(question, dict):
472
+ continue
473
+ qid = question.get('id')
474
+ if not isinstance(qid, str) or not qid or qid in answered:
475
+ continue
476
+ flagged.append((task, qid))
477
+ if question.get('possibly_stale') is not True:
478
+ question['possibly_stale'] = True
479
+ changed = True
480
+ if changed:
481
+ forge_brief.atomic_write(path, forge_brief._dump(brief))
482
+ return flagged
483
+
484
+
485
+ def stale(plan, task) -> list:
486
+ """Flag direct dependents' open questions when `task` merged outside its declared files.
487
+
488
+ Returns `[(dependent, qid), ...]` in tasks.tsv order, then question order. An unknown
489
+ task raises `NoSuchTask`. A task that is not merged, or whose changes stay inside its
490
+ declared files and directories, flags nothing.
491
+ """
492
+ plan = Path(plan)
493
+ tasks = forge_brief.read_tasks(plan)
494
+ by_id = {item['id']: item for item in tasks}
495
+ if task not in by_id:
496
+ raise NoSuchTask(task, [item['id'] for item in tasks])
497
+ if status_of(plan, task) != 'MERGED':
498
+ return []
499
+ if not _undeclared(changed_files(plan, task), _declared(by_id[task]['files'])):
500
+ return []
501
+ flagged = []
502
+ for item in tasks:
503
+ if task not in item['deps'] or past_start(plan, item['id']):
504
+ continue
505
+ flagged.extend(_flag_open(plan, item['id']))
506
+ return flagged