@giamme/forge 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +13 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/reviews.md +15 -1
  11. package/docs/safety.md +8 -0
  12. package/forge +24 -1
  13. package/package.json +1 -1
  14. package/references/dataset.md +143 -5
  15. package/references/decision-models.md +15 -2
  16. package/references/decompose.md +180 -11
  17. package/references/planning.md +3 -2
  18. package/references/solo.md +2 -1
  19. package/references/ui.md +5 -2
  20. package/scripts/forge-artifact.sh +14 -0
  21. package/scripts/forge-brief.py +132 -0
  22. package/scripts/forge-compare.py +11 -1
  23. package/scripts/forge-config.py +176 -9
  24. package/scripts/forge-contract.py +98 -4
  25. package/scripts/forge-control.py +86 -13
  26. package/scripts/forge-dispatch.sh +14 -10
  27. package/scripts/forge-du.py +167 -0
  28. package/scripts/forge-issues.py +4 -3
  29. package/scripts/forge-ledger.py +3 -1
  30. package/scripts/forge-lib-adopt.sh +8 -1
  31. package/scripts/forge-lib-plans.sh +5 -2
  32. package/scripts/forge-lib-review.sh +29 -1
  33. package/scripts/forge-metrics.sh +29 -3
  34. package/scripts/forge-parallel-options.sh +4 -0
  35. package/scripts/forge-parallel.sh +506 -10
  36. package/scripts/forge-plan-check.py +25 -2
  37. package/scripts/forge-planner.py +20 -6
  38. package/scripts/forge-prompt.py +120 -0
  39. package/scripts/forge-retro.py +115 -0
  40. package/scripts/forge-runs-compact.py +443 -0
  41. package/scripts/forge-runs-rm.py +2 -0
  42. package/scripts/forge-runs.py +18 -3
  43. package/scripts/forge-schedule.py +279 -4
  44. package/scripts/forge-shadow.py +35 -10
  45. package/scripts/forge-solo.sh +2 -0
  46. package/scripts/forge-summarize.py +698 -0
  47. package/scripts/forge-sweep.py +25 -10
  48. package/scripts/forge-ui-options.sh +10 -0
  49. package/scripts/forge_brief/__init__.py +587 -0
  50. package/scripts/forge_brief/answers.py +459 -0
  51. package/scripts/forge_dataset/__init__.py +10 -0
  52. package/scripts/forge_dataset/cli.py +83 -0
  53. package/scripts/forge_dataset/export.py +18 -4
  54. package/scripts/forge_dataset/facts.py +280 -0
  55. package/scripts/forge_dataset/harvest.py +56 -9
  56. package/scripts/forge_dataset/history.py +5 -3
  57. package/scripts/forge_dataset/outcomes.py +206 -58
  58. package/scripts/forge_dataset/pairs.py +174 -0
  59. package/scripts/forge_dataset/risk.py +108 -0
  60. package/scripts/forge_dataset/tiers.py +427 -0
  61. package/scripts/forge_decide/__init__.py +11 -1
  62. package/scripts/forge_decide/cli.py +23 -2
  63. package/scripts/forge_decide/labels.py +30 -6
  64. package/scripts/forge_decide/replay.py +10 -4
  65. package/scripts/forge_locations.py +366 -0
  66. package/scripts/forge_registry.py +19 -0
  67. package/scripts/forge_retro/__init__.py +417 -0
  68. package/scripts/forge_retro/issues.py +1193 -0
  69. package/scripts/forge_retro/report.py +671 -0
  70. package/scripts/forge_side/__init__.py +477 -0
  71. package/scripts/forge_storage.py +515 -0
  72. package/ui/README.md +68 -8
  73. package/ui/docs/api.md +217 -20
  74. package/ui/forge_ui/control.py +92 -11
  75. package/ui/forge_ui/export.py +31 -5
  76. package/ui/forge_ui/findings.py +4 -2
  77. package/ui/forge_ui/links.py +337 -0
  78. package/ui/forge_ui/models.py +57 -4
  79. package/ui/forge_ui/projects.py +4 -1
  80. package/ui/forge_ui/reader.py +732 -34
  81. package/ui/forge_ui/server.py +8 -0
  82. package/ui/forge_ui/static/app.js +92 -5
  83. package/ui/forge_ui/static/briefview.js +302 -0
  84. package/ui/forge_ui/static/checksview.js +6 -2
  85. package/ui/forge_ui/static/controls.js +5 -0
  86. package/ui/forge_ui/static/diffview.js +7 -3
  87. package/ui/forge_ui/static/index.html +3 -0
  88. package/ui/forge_ui/static/panel.js +311 -4
  89. package/ui/forge_ui/static/runmodel.js +13 -1
  90. package/ui/forge_ui/static/storageview.js +271 -0
  91. package/ui/forge_ui/static/style.css +100 -3
  92. package/ui/forge_ui/static/worktreesview.js +3 -3
  93. package/ui/forge_ui/storage.py +136 -0
  94. package/ui/forge_ui/transcripts.py +35 -10
  95. package/ui/forge_ui/worktrees.py +154 -13
@@ -0,0 +1,698 @@
1
+ #!/usr/bin/env python3
2
+ """Generated task summaries. One side dispatch per task, and only when its facts changed.
3
+
4
+ forge summarize PLAN [--task ID] [--force] [--json]
5
+
6
+ Facts are a compact JSON object, in this order: id, title, status, the attempt trail
7
+ (attempt, dwarf spec, verdict, findings count, worst severity, retry reason), the latest
8
+ review's finding titles and severities, known-issue titles, dependencies, and the tasks
9
+ that wait on this one. The prompt gets that JSON capped at 8 KB. It never includes the
10
+ repository, the diff or the task prompt.
11
+
12
+ inputs_hash is the sha256 of the canonical facts (sorted keys, no whitespace). An existing
13
+ summary.json with the same hash is left in place, unless --force is given.
14
+
15
+ Exit codes: 0 when the plan was read, including when every task was skipped; 2 usage;
16
+ 3 when PLAN is not a directory.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import hashlib
22
+ import importlib.util
23
+ import json
24
+ import math
25
+ import os
26
+ from pathlib import Path
27
+ import re
28
+ import sys
29
+ import tempfile
30
+ import time
31
+
32
+ import fcntl
33
+
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
35
+ import forge_side # noqa: E402
36
+
37
+ # The facts the model sees. 8 KB, the same cut forge uses for a reply it carries forward.
38
+ FACTS_CAP = 8 * 1024
39
+ # A reply whose text is longer than this is rejected. The prompt asks for 3 to 5 lines.
40
+ TEXT_LINES = 8
41
+
42
+ _CONTRACT = None
43
+ _BULLET = re.compile(r'^(?:[-*+]|[0-9]{1,3}[.)])\s+')
44
+ _TAG = re.compile(r'\b(?:P[0-3]|CONFIRMED|PLAUSIBLE|UNSTATED)\b')
45
+ _LOCATION = re.compile(r'[\w./\\-]+\.\w+:\d+(?:[-:]\d+)?')
46
+ _MARKUP = re.compile(r'[*_`\[\]]+')
47
+
48
+ _INSTRUCTIONS = (
49
+ 'Reply with JSON only, no other text:\n'
50
+ '{"text": "<3 to 5 short lines: what the task is for, what each attempt did, '
51
+ 'why it was retried, where it stands>", "sentence": "<one sentence>"}\n'
52
+ '\n'
53
+ 'Use only the facts given. Invent nothing. Do not restate the live "Now" facts.\n'
54
+ '\n'
55
+ 'Facts:\n'
56
+ )
57
+
58
+
59
+ def _contract():
60
+ """forge-contract.py, loaded by path: the file name is not importable."""
61
+ global _CONTRACT
62
+ if _CONTRACT is None:
63
+ path = Path(__file__).resolve().parent / 'forge-contract.py'
64
+ spec = importlib.util.spec_from_file_location('forge_contract_summary', path)
65
+ module = importlib.util.module_from_spec(spec)
66
+ spec.loader.exec_module(module)
67
+ _CONTRACT = module
68
+ return _CONTRACT
69
+
70
+
71
+ def _safe(task) -> bool:
72
+ """A single path component. `..` or a slash would leave the task directory."""
73
+ return (isinstance(task, str) and bool(task) and task not in ('.', '..')
74
+ and '/' not in task and '\\' not in task and '\0' not in task)
75
+
76
+
77
+ def _text(path: Path):
78
+ try:
79
+ return Path(path).read_text(encoding='utf-8', errors='replace')
80
+ except OSError:
81
+ return None
82
+
83
+
84
+ def _json(path: Path) -> dict:
85
+ try:
86
+ value = json.loads(path.read_text(encoding='utf-8'))
87
+ except (OSError, ValueError, UnicodeError):
88
+ return {}
89
+ return value if isinstance(value, dict) else {}
90
+
91
+
92
+ def _lines(path: Path) -> list:
93
+ text = _text(path)
94
+ if not text:
95
+ return []
96
+ return [line for line in text.splitlines() if line and not line.startswith('#')]
97
+
98
+
99
+ def _atomic(path: Path, text: str) -> None:
100
+ """Replace `path` with `text`. A crash leaves the previous file in place."""
101
+ path.parent.mkdir(parents=True, exist_ok=True)
102
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
103
+ try:
104
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle:
105
+ handle.write(text)
106
+ os.replace(tmp, path)
107
+ except BaseException:
108
+ try:
109
+ os.unlink(tmp)
110
+ except OSError:
111
+ pass
112
+ raise
113
+
114
+
115
+ def _tasks(plan: Path) -> tuple:
116
+ """`(order, rows)` from tasks.tsv. A repeated id keeps its first row."""
117
+ order, rows = [], {}
118
+ for line in _lines(plan / 'tasks.tsv'):
119
+ cells = line.split('\t')
120
+ ident = cells[0].strip()
121
+ if not ident or ident in rows:
122
+ continue
123
+ rows[ident] = cells
124
+ order.append(ident)
125
+ return order, rows
126
+
127
+
128
+ def _cell(cells: list, index: int) -> str:
129
+ return cells[index].strip() if index < len(cells) else ''
130
+
131
+
132
+ def _deps(cell: str) -> list:
133
+ if not cell or cell == '-':
134
+ return []
135
+ found = []
136
+ for item in cell.split(','):
137
+ item = item.strip()
138
+ if item and item != '-' and item not in found:
139
+ found.append(item)
140
+ return found
141
+
142
+
143
+ def _title_of(finding) -> str:
144
+ """The finding's first line, without the marker, the severity tag or the location."""
145
+ first = finding.text.split('\n', 1)[0]
146
+ first = _contract().split_facts(first)[0]
147
+ first = _BULLET.sub('', first.strip())
148
+ first = re.sub(r'^#{1,6}\s+', '', first)
149
+ first = _TAG.sub('', first)
150
+ first = _LOCATION.sub('', first)
151
+ first = _MARKUP.sub('', first)
152
+ first = first.strip(' \t—–-:`*|')
153
+ first = ' '.join(first.split())
154
+ if first:
155
+ return first
156
+ return ' '.join(finding.text.split())[:120]
157
+
158
+
159
+ def _severity(finding):
160
+ if type(finding.severity) is int and 0 <= finding.severity <= 3:
161
+ return 'P%d' % finding.severity
162
+ return None
163
+
164
+
165
+ def _parsed(text: str) -> list:
166
+ if not text:
167
+ return []
168
+ return list(_contract().parse_findings(text))
169
+
170
+
171
+ def _worst(findings: list):
172
+ ranks = [finding.severity for finding in findings if type(finding.severity) is int]
173
+ if not ranks:
174
+ return None
175
+ return 'P%d' % min(ranks)
176
+
177
+
178
+ def _attempt_rows(task_dir: Path) -> list:
179
+ """One dict per attempts.tsv row: epoch, attempt, verdict (the status column), dwarf."""
180
+ rows = []
181
+ for line in _lines(task_dir / 'attempts.tsv'):
182
+ parts = line.split('\t')
183
+ if len(parts) < 3 or not parts[1].isdigit():
184
+ continue
185
+ dwarf = parts[4].strip() if len(parts) > 4 else ''
186
+ rows.append({
187
+ 'epoch': int(parts[0]) if parts[0].isdigit() else None,
188
+ 'attempt': int(parts[1]),
189
+ 'verdict': parts[2].strip() or None,
190
+ 'dwarf': dwarf or None,
191
+ })
192
+ return rows
193
+
194
+
195
+ def _reasons(task_dir: Path) -> dict:
196
+ """`{attempt: source}` from retry_sources.tsv. The last row for an attempt wins."""
197
+ found = {}
198
+ for line in _lines(task_dir / 'retry_sources.tsv'):
199
+ parts = line.split('\t')
200
+ if len(parts) < 2 or not parts[0].isdigit():
201
+ continue
202
+ source = parts[1].strip()
203
+ if source:
204
+ found[int(parts[0])] = source
205
+ return found
206
+
207
+
208
+ def _shadow(path: Path) -> bool:
209
+ return _json(path / 'metrics.json').get('shadow') is True
210
+
211
+
212
+ def _number(value):
213
+ """A finite float, or None. A bool is not a timestamp."""
214
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
215
+ return None
216
+ try:
217
+ value = float(value)
218
+ except OverflowError:
219
+ return None
220
+ if not math.isfinite(value):
221
+ return None
222
+ return value
223
+
224
+
225
+ def _finished(path: Path, started: float):
226
+ """Wall time the review finished, or None when metrics never closed it.
227
+
228
+ begin() stores wall_started. finish() adds elapsed_s.total, the monotonic
229
+ seconds until the dispatch ended, so wall_started plus that total is the
230
+ completion. date +%s then truncates it into the attempt log.
231
+ """
232
+ metrics = _json(path / 'metrics.json')
233
+ elapsed = metrics.get('elapsed_s')
234
+ total = _number(elapsed.get('total') if isinstance(elapsed, dict) else None)
235
+ if total is None or total < 0:
236
+ return None
237
+ # A metrics file from begin() has no total. A zero total with no exit is the
238
+ # same unfinished state, not a review that ended on its start instant.
239
+ if total == 0 and metrics.get('exit_code') is None:
240
+ return None
241
+ return started + total
242
+
243
+
244
+ def _log_mtime(task_dir: Path):
245
+ """When attempts.tsv was last appended, or None. Sub-second when the filesystem gives it."""
246
+ try:
247
+ return (task_dir / 'attempts.tsv').stat().st_mtime
248
+ except OSError:
249
+ return None
250
+
251
+
252
+ def _open_attempt(rows: list, task_dir: Path):
253
+ """The attempt a review belongs to when no attempts.tsv row owns it.
254
+
255
+ The counter advances before the attempt starts. record_attempt appends the
256
+ row when it ends. Until that append, the counter is this attempt and the
257
+ last row is the previous one. Once the counter has caught up, a review that
258
+ was never archived belongs to the last logged attempt.
259
+ """
260
+ current = _counter(task_dir)
261
+ last = rows[-1]['attempt'] if rows else None
262
+ if current is not None and (last is None or current > last):
263
+ return current
264
+ return last
265
+
266
+
267
+ def _review_end(item: dict) -> float:
268
+ """When this review was over. Without a finish, the start is the only bound."""
269
+ if item['finished'] is not None:
270
+ return item['finished']
271
+ return item['started']
272
+
273
+
274
+ def _after_append(started: float, rows: list, task_dir: Path) -> bool:
275
+ """True when the review started after attempts.tsv was last appended.
276
+
277
+ record_attempt runs after the review, so a start later than that write is not
278
+ one of the logged rows. It belongs to the attempt the counter already holds.
279
+ A mtime that is only the truncated epoch cannot say: date +%s drops the
280
+ fraction, and a one-second timestamp does too. This is the whole log, not
281
+ only its last row: an earlier row in the same second was written before the
282
+ final append as well.
283
+ """
284
+ written = _log_mtime(task_dir)
285
+ if written is None or not started > written:
286
+ return False
287
+ if not written.is_integer():
288
+ return True
289
+ last = None
290
+ for row in rows:
291
+ if row['epoch'] is not None:
292
+ last = row['epoch']
293
+ return last is None or written > last
294
+
295
+
296
+ def _append_rejects(epoch: int, started: float, finished, task_dir: Path, ahead: bool) -> bool:
297
+ """The last logged row does not own this review.
298
+
299
+ Its second can also hold the start of the next attempt, whose row is still
300
+ missing. The same rules as `_after_append`, for a one-second mtime that the
301
+ coarser check cannot decide: a review that did not finish inside the second
302
+ then belongs to the open attempt.
303
+ """
304
+ written = _log_mtime(task_dir)
305
+ started_before_append = written is not None and started <= written
306
+ if written is not None and written > epoch and not started_before_append:
307
+ return True
308
+ if ahead and finished is None and started > epoch and not started_before_append:
309
+ return True
310
+ return False
311
+
312
+
313
+ def _matching_group(rows: list, mark: float):
314
+ """`[start, end)` of the attempts logged in the first second that contains `mark`.
315
+
316
+ A row at truncated epoch E owns a review that finished before the next second
317
+ (`mark < E + 1`). Every later row shares that test until its own epoch is
318
+ larger, so the earliest matching second is the one the review finished in.
319
+ Rows logged in that same second stay in the group; the next second does not.
320
+ """
321
+ start = None
322
+ epoch = None
323
+ for index, row in enumerate(rows):
324
+ row_epoch = row['epoch']
325
+ if row_epoch is None or not mark < row_epoch + 1:
326
+ continue
327
+ start = index
328
+ epoch = row_epoch
329
+ break
330
+ if start is None:
331
+ return None
332
+ end = start + 1
333
+ while end < len(rows) and rows[end]['epoch'] == epoch:
334
+ end += 1
335
+ return start, end
336
+
337
+
338
+ def _assign_timed(items: list, rows: list, task_dir: Path) -> dict:
339
+ """`{id(item): attempt}` for reviews with no dataset.json attempt_now.
340
+
341
+ Items are in start order. An attempt the log does not own yet is the open
342
+ attempt from the counter. A review that falls in a second shared by several
343
+ logged attempts is left out: its attempt is not knowable.
344
+ """
345
+ opened = _open_attempt(rows, task_dir)
346
+ last = rows[-1]['attempt'] if rows else None
347
+ ahead = opened is not None and opened != last
348
+ assigned = {}
349
+ buckets = {}
350
+ order = []
351
+ for item in items:
352
+ if _after_append(item['started'], rows, task_dir):
353
+ assigned[id(item)] = opened
354
+ continue
355
+ group = _matching_group(rows, item['mark'])
356
+ if group is None:
357
+ assigned[id(item)] = opened
358
+ continue
359
+ if group not in buckets:
360
+ buckets[group] = []
361
+ order.append(group)
362
+ buckets[group].append(item)
363
+ for start, end in order:
364
+ if end - start != 1:
365
+ continue
366
+ epoch = rows[start]['epoch']
367
+ for item in buckets[(start, end)]:
368
+ if end == len(rows) and _append_rejects(
369
+ epoch, item['started'], item['finished'], task_dir, ahead):
370
+ assigned[id(item)] = opened
371
+ else:
372
+ assigned[id(item)] = rows[start]['attempt']
373
+ # Several attempts logged in one truncated second: the fraction of a second
374
+ # cannot say which of them a review is, and an attempt that stopped before QA
375
+ # (an empty diff, a backend error) looks like one that was reviewed. Those
376
+ # reviews stay unassigned rather than guessed.
377
+ return assigned
378
+
379
+
380
+ def _reviews(task_dir: Path, rows: list) -> tuple:
381
+ """`({attempt: qa.last text}, {texts whose newest review has no knowable attempt})`.
382
+
383
+ Reviews come from attempts/qa-*/, newest start wins. Shadow reviews are skipped.
384
+
385
+ dataset.json's attempt_now wins when a capture wrote one. Production archives
386
+ do not persist it, so the attempt log is the fallback. Its epoch is date +%s
387
+ at the end of the attempt, which drops the fraction: a review that starts at
388
+ E.2 and finishes at E.8 is stored as E. Comparing the raw start with <= E
389
+ skips that row and takes the next attempt. The finish, when metrics closed,
390
+ matches a row when it falls before the next second. Without a finish, the
391
+ start uses that window.
392
+
393
+ The live qa.last is the review still in the task dir. When no archive holds the same
394
+ text, it belongs to the open attempt when the counter is ahead of the log, and
395
+ otherwise to the last recorded attempt (a review that was not archived). A live text
396
+ equal to an unassignable archive stays unassigned too.
397
+ """
398
+ items = []
399
+ root = task_dir / 'attempts'
400
+ if root.is_dir():
401
+ for path in root.iterdir():
402
+ if not path.is_dir() or not path.name.startswith('qa-') or _shadow(path):
403
+ continue
404
+ text = _text(path / 'qa.last')
405
+ if text is None:
406
+ continue
407
+ pinned = _json(path / 'dataset.json').get('attempt_now')
408
+ if type(pinned) is not int or pinned <= 0:
409
+ pinned = None
410
+ started = _number(_json(path / 'metrics.json').get('wall_started'))
411
+ finished = _finished(path, started) if started is not None else None
412
+ if started is None:
413
+ if pinned is None:
414
+ continue
415
+ try:
416
+ started = path.stat().st_mtime
417
+ except OSError:
418
+ started = 0.0
419
+ finished = None
420
+ items.append({
421
+ 'started': started,
422
+ 'finished': finished,
423
+ 'mark': finished if finished is not None else started,
424
+ 'name': path.name,
425
+ 'text': text,
426
+ 'pinned': pinned,
427
+ })
428
+ items.sort(key=lambda item: (item['started'], item['name']))
429
+ assigned = _assign_timed([item for item in items if item['pinned'] is None], rows, task_dir)
430
+ found = {}
431
+ unassignable = set()
432
+ newest = {}
433
+ for item in items:
434
+ number = item['pinned'] if item['pinned'] is not None else assigned.get(id(item))
435
+ # Items are in start order, so the last one kept per text is its newest review.
436
+ newest[item['text']] = number
437
+ if number is None:
438
+ unassignable.add(item['text'])
439
+ continue
440
+ found[number] = item['text']
441
+ live = _text(task_dir / 'qa.last')
442
+ if live is not None and live not in unassignable and all(text != live for text in found.values()):
443
+ number = _open_attempt(rows, task_dir)
444
+ if number is not None:
445
+ found[number] = live
446
+ undecided = {text for text, number in newest.items() if number is None}
447
+ return found, undecided
448
+
449
+
450
+ def _counter(task_dir: Path):
451
+ text = _text(task_dir / 'attempt')
452
+ if text and text.strip().isdigit():
453
+ return int(text.strip())
454
+ return None
455
+
456
+
457
+ def _latest(task_dir: Path, rows: list, reviews: dict, undecided: set):
458
+ """`(attempt, text)` of the latest review, or `(None, None)` when the task has none."""
459
+ live = _text(task_dir / 'qa.last')
460
+ if live is not None:
461
+ if live in undecided:
462
+ return None, live
463
+ # The same text can sit on an older archive and on the latest attempt. The finding
464
+ # refs name the newest attempt that still holds it.
465
+ matches = [number for number, text in reviews.items() if text == live]
466
+ if matches:
467
+ return max(matches), live
468
+ return _open_attempt(rows, task_dir), live
469
+ if not reviews:
470
+ return None, None
471
+ number = max(reviews)
472
+ return number, reviews[number]
473
+
474
+
475
+ def _finding_items(text) -> list:
476
+ return [{'title': _title_of(finding), 'severity': _severity(finding)} for finding in _parsed(text)]
477
+
478
+
479
+ def _known_titles(task_dir: Path) -> list:
480
+ return [_title_of(finding) for finding in _parsed(_text(task_dir / 'known_issues.md') or '')]
481
+
482
+
483
+ def collect(plan: Path, task: str) -> tuple:
484
+ """`(facts, sources)` for one task. Facts keys are in the order the prompt shows them.
485
+
486
+ Sources name every attempt row and each finding of the latest review, as
487
+ `{kind: attempt, ref: n}` and `{kind: finding, ref: attempt:title}`.
488
+ """
489
+ order, rows = _tasks(plan)
490
+ cells = rows.get(task, [])
491
+ task_dir = plan / 'tasks' / task
492
+ attempts = _attempt_rows(task_dir)
493
+ reasons = _reasons(task_dir)
494
+ reviews, undecided = _reviews(task_dir, attempts)
495
+ latest_n, latest_text = _latest(task_dir, attempts, reviews, undecided)
496
+ trail = []
497
+ for row in attempts:
498
+ review = reviews.get(row['attempt'])
499
+ parsed = _parsed(review) if review is not None else None
500
+ trail.append({
501
+ 'attempt': row['attempt'],
502
+ 'dwarf': row['dwarf'],
503
+ 'verdict': row['verdict'],
504
+ 'findings': None if parsed is None else len(parsed),
505
+ 'worst': None if parsed is None else _worst(parsed),
506
+ 'reason': reasons.get(row['attempt']),
507
+ })
508
+ status = _text(task_dir / 'status')
509
+ waiting = [other for other in order if other != task and task in _deps(_cell(rows[other], 1))]
510
+ body = {
511
+ 'id': task,
512
+ 'title': _cell(cells, 6) or None,
513
+ 'status': status.strip() or None if status is not None else None,
514
+ 'attempts': trail,
515
+ 'findings': _finding_items(latest_text) if latest_text is not None else [],
516
+ 'known_issues': _known_titles(task_dir),
517
+ 'dependencies': _deps(_cell(cells, 1)),
518
+ 'waiting': waiting,
519
+ }
520
+ ref = '0' if latest_n is None else str(latest_n)
521
+ sources = [{'kind': 'attempt', 'ref': str(row['attempt'])} for row in trail]
522
+ sources += [{'kind': 'finding', 'ref': '%s:%s' % (ref, item['title'])} for item in body['findings']]
523
+ return body, sources
524
+
525
+
526
+ def canonical(body: dict) -> str:
527
+ """Sorted keys, no whitespace. This is the string inputs_hash covers."""
528
+ return json.dumps(body, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
529
+
530
+
531
+ def _hash(body: dict) -> str:
532
+ return hashlib.sha256(canonical(body).encode('utf-8')).hexdigest()
533
+
534
+
535
+ def _stored_hash(path: Path):
536
+ data = _json(path)
537
+ value = data.get('inputs_hash')
538
+ return value if isinstance(value, str) and value else None
539
+
540
+
541
+ def _prompt(body: dict) -> str:
542
+ shown = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
543
+ return _INSTRUCTIONS + forge_side.cap(shown, FACTS_CAP) + '\n'
544
+
545
+
546
+ def _reply(last):
547
+ """`(text, sentence)` or a reason string. A bad reply names why it was refused."""
548
+ raw = (last or '').strip().lstrip('\ufeff')
549
+ if not raw:
550
+ return 'not json'
551
+ try:
552
+ data = json.loads(raw)
553
+ except (ValueError, UnicodeError):
554
+ return 'not json'
555
+ if not isinstance(data, dict):
556
+ return 'not json'
557
+ text, sentence = data.get('text'), data.get('sentence')
558
+ if not isinstance(text, str):
559
+ return 'missing text'
560
+ if not isinstance(sentence, str):
561
+ return 'missing sentence'
562
+ if len(text.splitlines()) > TEXT_LINES:
563
+ return 'text over 8 lines'
564
+ return text, sentence
565
+
566
+
567
+ def _result(task: str, status: str, reason) -> dict:
568
+ return {'task': task, 'status': status, 'reason': reason}
569
+
570
+
571
+ def _lock(task_dir: Path):
572
+ """Exclusive non-blocking lock on summary.lock. None when another summariser holds it.
573
+
574
+ The caller closes the fd, which releases the lock. Two triggers of one task never
575
+ dispatch together: the second finds the lock taken and returns busy.
576
+ """
577
+ task_dir.mkdir(parents=True, exist_ok=True)
578
+ try:
579
+ fd = os.open(task_dir / 'summary.lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o644)
580
+ except OSError:
581
+ return None
582
+ try:
583
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
584
+ except OSError:
585
+ os.close(fd)
586
+ return None
587
+ return fd
588
+
589
+
590
+ def _fail(task_dir: Path, task: str, reason: str) -> dict:
591
+ """Keep the previous summary.json and record why this attempt did not replace it."""
592
+ try:
593
+ _atomic(task_dir / 'summary.error', reason + '\n')
594
+ except OSError:
595
+ pass
596
+ return _result(task, 'skipped', reason)
597
+
598
+
599
+ def _write(task_dir: Path, task: str, text: str, sentence: str, spec: str, digest: str, sources: list) -> dict:
600
+ body = {
601
+ 'text': text,
602
+ 'sentence': sentence,
603
+ 'model': spec,
604
+ 'generated_at': int(time.time()),
605
+ 'inputs_hash': digest,
606
+ 'sources': sources,
607
+ }
608
+ _atomic(task_dir / 'summary.json', json.dumps(body, ensure_ascii=False, indent=2) + '\n')
609
+ try:
610
+ (task_dir / 'summary.error').unlink()
611
+ except FileNotFoundError:
612
+ pass
613
+ except OSError:
614
+ pass
615
+ return _result(task, 'done', None)
616
+
617
+
618
+ def summarize_task(plan: Path, task: str, force: bool) -> dict:
619
+ """Summarise one task. Skips when the switch is off, the lock is held, or nothing changed.
620
+
621
+ The switch is checked before the task directory is created, so a refusal leaves the
622
+ plan untouched. It is checked again under the lock: the cap may have filled.
623
+ """
624
+ if not _safe(task):
625
+ return _result(task, 'skipped', 'unsafe')
626
+ ok, reason = forge_side.allowed('summary', plan, task)
627
+ if not ok:
628
+ return _result(task, 'skipped', reason)
629
+ task_dir = plan / 'tasks' / task
630
+ fd = _lock(task_dir)
631
+ if fd is None:
632
+ if (task_dir / 'summary.lock').exists():
633
+ return _result(task, 'skipped', 'busy')
634
+ return _result(task, 'skipped', 'error')
635
+ try:
636
+ ok, reason = forge_side.allowed('summary', plan, task)
637
+ if not ok:
638
+ return _result(task, 'skipped', reason)
639
+ body, sources = collect(plan, task)
640
+ digest = _hash(body)
641
+ if not force and _stored_hash(task_dir / 'summary.json') == digest:
642
+ return _result(task, 'skipped', 'unchanged')
643
+ spec = forge_side.settings(plan)['summaries']['model']
644
+ outcome = forge_side.run('summary', plan, task, _prompt(body), spec)
645
+ if not outcome.get('ok'):
646
+ return _fail(task_dir, task, outcome.get('reason') or 'error')
647
+ parsed = _reply(outcome.get('last'))
648
+ if isinstance(parsed, str):
649
+ return _fail(task_dir, task, parsed)
650
+ text, sentence = parsed
651
+ return _write(task_dir, task, text, sentence, spec, digest, sources)
652
+ finally:
653
+ os.close(fd)
654
+
655
+
656
+ def _report(item: dict, as_json: bool) -> None:
657
+ if as_json:
658
+ sys.stdout.write(json.dumps(item, ensure_ascii=False, sort_keys=True) + '\n')
659
+ return
660
+ if item['reason']:
661
+ print('%s %s %s' % (item['task'], item['status'], item['reason']))
662
+ else:
663
+ print('%s %s' % (item['task'], item['status']))
664
+
665
+
666
+ def _parser() -> argparse.ArgumentParser:
667
+ parser = argparse.ArgumentParser(
668
+ prog='forge summarize',
669
+ description='Write a generated summary for each task, again only when its inputs changed.')
670
+ parser.add_argument('plan', help='the plan directory')
671
+ parser.add_argument('--task', help='summarise this task only')
672
+ parser.add_argument('--force', action='store_true', help='dispatch even when the inputs are unchanged')
673
+ parser.add_argument('--json', action='store_true', help='print one JSON object per task: task, status, reason')
674
+ return parser
675
+
676
+
677
+ def main(argv=None) -> int:
678
+ args = _parser().parse_args(argv)
679
+ plan = Path(args.plan)
680
+ if not plan.is_dir():
681
+ sys.stderr.write('forge summarize: not a plan dir: %s\n' % plan)
682
+ return 3
683
+ if args.task is not None and not _safe(args.task):
684
+ sys.stderr.write('forge summarize: bad task id: %s\n' % args.task)
685
+ return 2
686
+ order, _ = _tasks(plan)
687
+ chosen = [args.task] if args.task else list(order)
688
+ for task in chosen:
689
+ if task not in order:
690
+ item = _result(task, 'skipped', 'unknown')
691
+ else:
692
+ item = summarize_task(plan, task, args.force)
693
+ _report(item, args.json)
694
+ return 0
695
+
696
+
697
+ if __name__ == '__main__':
698
+ sys.exit(main())