@giamme/forge 0.17.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 (76) hide show
  1. package/CHANGELOG.md +24 -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 +5 -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/safety.md +8 -0
  11. package/forge +24 -1
  12. package/package.json +1 -1
  13. package/references/dataset.md +19 -0
  14. package/references/decompose.md +134 -1
  15. package/references/solo.md +2 -1
  16. package/references/ui.md +5 -2
  17. package/scripts/forge-artifact.sh +14 -0
  18. package/scripts/forge-brief.py +132 -0
  19. package/scripts/forge-compare.py +11 -1
  20. package/scripts/forge-config.py +176 -9
  21. package/scripts/forge-contract.py +46 -3
  22. package/scripts/forge-control.py +86 -13
  23. package/scripts/forge-dispatch.sh +14 -10
  24. package/scripts/forge-du.py +167 -0
  25. package/scripts/forge-lib-adopt.sh +1 -0
  26. package/scripts/forge-lib-plans.sh +5 -2
  27. package/scripts/forge-lib-review.sh +29 -1
  28. package/scripts/forge-metrics.sh +7 -3
  29. package/scripts/forge-parallel-options.sh +4 -0
  30. package/scripts/forge-parallel.sh +503 -9
  31. package/scripts/forge-prompt.py +120 -0
  32. package/scripts/forge-retro.py +115 -0
  33. package/scripts/forge-runs-compact.py +443 -0
  34. package/scripts/forge-runs-rm.py +2 -0
  35. package/scripts/forge-runs.py +18 -3
  36. package/scripts/forge-schedule.py +279 -4
  37. package/scripts/forge-shadow.py +7 -1
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-summarize.py +698 -0
  40. package/scripts/forge-ui-options.sh +10 -0
  41. package/scripts/forge_brief/__init__.py +587 -0
  42. package/scripts/forge_brief/answers.py +459 -0
  43. package/scripts/forge_dataset/__init__.py +10 -0
  44. package/scripts/forge_dataset/export.py +18 -4
  45. package/scripts/forge_dataset/facts.py +6 -4
  46. package/scripts/forge_dataset/harvest.py +40 -6
  47. package/scripts/forge_dataset/history.py +5 -3
  48. package/scripts/forge_decide/__init__.py +11 -1
  49. package/scripts/forge_locations.py +366 -0
  50. package/scripts/forge_registry.py +19 -0
  51. package/scripts/forge_retro/__init__.py +417 -0
  52. package/scripts/forge_retro/issues.py +1193 -0
  53. package/scripts/forge_retro/report.py +671 -0
  54. package/scripts/forge_side/__init__.py +477 -0
  55. package/scripts/forge_storage.py +515 -0
  56. package/ui/README.md +68 -8
  57. package/ui/docs/api.md +205 -17
  58. package/ui/forge_ui/control.py +92 -11
  59. package/ui/forge_ui/export.py +24 -5
  60. package/ui/forge_ui/links.py +337 -0
  61. package/ui/forge_ui/models.py +57 -4
  62. package/ui/forge_ui/projects.py +4 -1
  63. package/ui/forge_ui/reader.py +661 -30
  64. package/ui/forge_ui/static/app.js +86 -4
  65. package/ui/forge_ui/static/briefview.js +302 -0
  66. package/ui/forge_ui/static/checksview.js +6 -2
  67. package/ui/forge_ui/static/controls.js +5 -0
  68. package/ui/forge_ui/static/index.html +3 -0
  69. package/ui/forge_ui/static/panel.js +268 -2
  70. package/ui/forge_ui/static/runmodel.js +13 -1
  71. package/ui/forge_ui/static/storageview.js +271 -0
  72. package/ui/forge_ui/static/style.css +99 -3
  73. package/ui/forge_ui/static/worktreesview.js +3 -3
  74. package/ui/forge_ui/storage.py +136 -0
  75. package/ui/forge_ui/transcripts.py +35 -10
  76. package/ui/forge_ui/worktrees.py +154 -13
@@ -0,0 +1,671 @@
1
+ """The end-of-run retro report: `<plan>/retro.md` from `retro/notes.jsonl`.
2
+
3
+ Notes that share a type and a normalised evidence command are one pattern. A note with no
4
+ command is matched on its normalised summary instead. Normalising lowercases, collapses
5
+ whitespace, and replaces absolute paths, hex ids and numbers with placeholders, so two
6
+ tasks that failed the same way under different worktree paths are one pattern.
7
+
8
+ Who can fix a pattern is decided after that merge. Notes that name different owners stay
9
+ one pattern: the majority `fixable_by` is the group, and a tie is unsure.
10
+ `forge retro report` writes the file atomically.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ import re
18
+ import tempfile
19
+
20
+ from forge_retro import TYPES
21
+
22
+ # The error shown for a pattern. The stored text can be 2 KB; the report keeps the head.
23
+ ERROR_LINES = 10
24
+
25
+ GROUPS = (
26
+ ('user', 'You can fix this on this machine'),
27
+ ('forge', 'forge should fix this'),
28
+ ('unsure', 'Not sure who should fix this'),
29
+ )
30
+
31
+ # What the user can do about a pattern, and why that makes the next run faster or more
32
+ # reliable. Sandbox is built below: the setting depends on the harness that blocked it.
33
+ _FIXES = {
34
+ 'environment': (
35
+ 'Install the missing dependency, or set `.forge/setup` so worktrees get it.',
36
+ 'The next run starts with that dependency already installed, so agents do not spend an attempt finding it.',
37
+ ),
38
+ 'tooling': (
39
+ 'Install the missing tool, or add that install to `.forge/setup` so worktrees get it.',
40
+ 'The next run finds the tool on the first try, so agents do not retry a command that cannot exist yet.',
41
+ ),
42
+ 'prompt': (
43
+ 'Change the task prompt so the instruction matches what the agent is allowed to do.',
44
+ 'The next run spends its attempt on the task, not on an instruction it cannot follow.',
45
+ ),
46
+ 'forge-bug': (
47
+ 'Update forge, or stop asking agents to run the command that fails.',
48
+ 'The next run does not hit the same forge failure, so the attempt is spent on the task.',
49
+ ),
50
+ 'other': (
51
+ 'Remove the obstacle named above before starting the next run.',
52
+ 'The next run does not stop on the same obstacle, so it finishes in fewer attempts.',
53
+ ),
54
+ }
55
+ _SANDBOX_WHY = ('The next run is not stopped by the same permission denial, so the agent can finish the command.')
56
+
57
+ # The flag forge's `--yolo-dwarf` / `--yolo-qa` turns on for that harness (references/harnesses.md).
58
+ _BYPASS = {
59
+ 'codex': '--dangerously-bypass-approvals-and-sandbox',
60
+ 'claude': '--dangerously-skip-permissions',
61
+ 'openclaude': '--dangerously-skip-permissions',
62
+ 'opencode': '--auto',
63
+ 'antigravity': '--dangerously-skip-permissions',
64
+ 'agy': '--dangerously-skip-permissions',
65
+ 'grok': '--always-approve',
66
+ }
67
+
68
+ # A quoted absolute path may contain spaces (`"/tmp/Review One/project"`). The quotes are
69
+ # part of the match, so two worktrees whose names differ only inside them collapse to one
70
+ # placeholder. `_quoted_path` decides whether the quotes hold a path or a command line.
71
+ # Replaced before the unquoted forms, which stop at whitespace.
72
+ _QUOTED_PATH = re.compile(
73
+ r'''(?<![a-z0-9_])(?:"(?:~|/|[a-z]:[\\/])[^"]*"|'(?:~|/|[a-z]:[\\/])[^']*')''')
74
+ # Stands in for a shell-escaped space (`/tmp/Review\ One`) while a path is matched.
75
+ # It is not whitespace, so the escaped space stays inside the path token.
76
+ _ESC_SPACE = '\ue000'
77
+ # A filesystem path, not the slash in https://host/path. The lookbehind rejects a scheme
78
+ # colon, a doubled slash, and a leading tilde, so a URL stays a URL and `~/...` is one
79
+ # home path rather than a unix path with the tilde left in front.
80
+ _UNIX_PATH = re.compile(r'(?<![a-z0-9_.:/~])/\S+')
81
+ _HOME_PATH = re.compile(r'(?<![a-z0-9_.:/])~/\S+')
82
+ _WIN_PATH = re.compile(r'(?<![a-z0-9_])[a-z]:[\\/]\S+')
83
+ _TRAILING = '.,;:)]}\'"'
84
+
85
+ # UUIDs are replaced whole, before the hex run, or the dashes would split them. A hex id
86
+ # is seven or more characters with a letter: `git rev-parse --short` prints seven. A long
87
+ # decimal has no letter, so a port or a size stays a number.
88
+ _UUID = re.compile(
89
+ r'(?<![0-9a-f])[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![0-9a-f])')
90
+ _HEX = re.compile(r'(?<![0-9a-f])(?=[0-9a-f]*[a-f])[0-9a-f]{7,}(?![0-9a-f])')
91
+ _NUMBER = re.compile(r'\d+')
92
+
93
+ EMPTY = "Nothing got in the agents' way in this run.\n"
94
+
95
+
96
+ def normalise(text: str) -> str:
97
+ """Lowercase, collapse whitespace, and replace paths, hex ids and numbers.
98
+
99
+ Paths are replaced before hex ids and hex ids before numbers, so a path is one
100
+ placeholder and a hex id is not split into numbers. A shell-escaped space stays
101
+ inside the path (`/tmp/Review\\ One`). A quoted command keeps a flag that follows
102
+ the path (`bash -c "/tmp/wt/test.sh --unit"`).
103
+ """
104
+ if not isinstance(text, str):
105
+ return ''
106
+ collapsed = text.lower().replace('\\ ', _ESC_SPACE)
107
+ collapsed = ' '.join(collapsed.split())
108
+ collapsed = _QUOTED_PATH.sub(_quoted_path, collapsed)
109
+ collapsed = _WIN_PATH.sub(_path_token, collapsed)
110
+ collapsed = _UNIX_PATH.sub(_path_token, collapsed)
111
+ collapsed = _HOME_PATH.sub(_path_token, collapsed)
112
+ collapsed = ' '.join(collapsed.replace(_ESC_SPACE, ' ').split())
113
+ collapsed = _UUID.sub('<hex>', collapsed)
114
+ collapsed = _HEX.sub('<hex>', collapsed)
115
+ return _NUMBER.sub('<n>', collapsed)
116
+
117
+
118
+ _COMMAND_LINE = re.compile(r'(?:^|\s)(?:-[a-z]*c|eval)\s*$')
119
+ # Commands whose quoted argument is a command line for another shell.
120
+ _REMOTE = re.compile(r'(?:^|\s)(?:ssh|mosh)\s')
121
+
122
+
123
+ def _quoted_path(match) -> str:
124
+ """Replace the quoted absolute path. Keep the arguments of a quoted command line.
125
+
126
+ A quoted string is one of two things. The text before it decides which:
127
+
128
+ - a command line, when it follows `-c` / `eval` or when the command is `ssh` / `mosh`
129
+ (`bash -c "/usr/bin/npm test tests/unit"`, `ssh host "/usr/bin/npm test"`). The path is
130
+ the first word only; every other word is an argument and is kept, so `"/usr/bin/npm test"`
131
+ and `"/usr/bin/npm install"` stay two patterns, and so do `"/usr/bin/pytest tests/unit -q"`
132
+ and `"/usr/bin/pytest tests/integration -q"`.
133
+ - otherwise one path, spaces and dashes included: `cat "/tmp/Review One"` and
134
+ `cat "/tmp/Review -One"` are both `cat <path>`. A word that looks like a flag does not
135
+ make the quote a command line.
136
+
137
+ A space inside a directory name of a quoted command line (`"/tmp/Review One/t.sh -q"`)
138
+ cannot be told from an argument, so the rest of that name is kept and two worktrees
139
+ named differently stay two patterns. Splitting is the safe failure: the report shows
140
+ the same problem twice, never two different problems as one.
141
+ """
142
+ parts = match.group(0)[1:-1].split(' ')
143
+ before = match.string[:match.start()]
144
+ if not (_COMMAND_LINE.search(before) or _REMOTE.search(before)):
145
+ return '<path>'
146
+ return ' '.join(['<path>'] + parts[1:])
147
+
148
+
149
+ def build(plan) -> dict:
150
+ """The report structure for a plan directory. Raises FileNotFoundError when it is not one."""
151
+ plan = Path(plan)
152
+ if not plan.is_dir():
153
+ raise FileNotFoundError(plan)
154
+ notes, malformed = _load(plan / 'retro' / 'notes.jsonl')
155
+ rows = _task_rows(plan)
156
+ run_models = _run_models(rows, notes)
157
+ earlier = _earlier_index(_current_ids(plan))
158
+ grouped = _patterns(notes, len(rows), run_models, earlier)
159
+ groups = []
160
+ for key, title in GROUPS:
161
+ if grouped[key]:
162
+ groups.append({'id': key, 'title': title, 'patterns': grouped[key]})
163
+ return {
164
+ 'empty': not notes and not malformed,
165
+ 'tasks': len(rows),
166
+ 'models': run_models,
167
+ 'groups': groups,
168
+ 'malformed': malformed,
169
+ }
170
+
171
+
172
+ def render(document: dict) -> str:
173
+ """The Markdown report. Empty when nothing was recorded."""
174
+ if document.get('empty'):
175
+ return EMPTY
176
+ out = ['# Retro', '']
177
+ for group in document['groups']:
178
+ out.append('## ' + group['title'])
179
+ out.append('')
180
+ for pattern in group['patterns']:
181
+ out.extend(_render_pattern(pattern))
182
+ out.append('')
183
+ malformed = document.get('malformed') or []
184
+ if malformed:
185
+ noun = 'note' if len(malformed) == 1 else 'notes'
186
+ out.append('## Malformed notes')
187
+ out.append('')
188
+ out.append('%d %s could not be parsed.' % (len(malformed), noun))
189
+ out.append('')
190
+ for text in malformed:
191
+ out.append('- %s' % text)
192
+ out.append('')
193
+ return '\n'.join(out).rstrip() + '\n'
194
+
195
+
196
+ def write(plan) -> tuple[dict, Path]:
197
+ """Write `<plan>/retro.md` atomically and return the structure and the path."""
198
+ plan = Path(plan)
199
+ document = build(plan)
200
+ path = plan / 'retro.md'
201
+ _atomic(path, render(document))
202
+ return document, path
203
+
204
+
205
+ # --- patterns --------------------------------------------------------------------
206
+
207
+ def _pattern_key(note: dict):
208
+ if not isinstance(note, dict) or note.get('malformed') is True:
209
+ return None
210
+ kind = note.get('type') if note.get('type') in TYPES else 'other'
211
+ command = _command(note)
212
+ if command is not None:
213
+ text = normalise(command)
214
+ if text:
215
+ return (kind, 'command', text)
216
+ summary = note.get('summary')
217
+ if not isinstance(summary, str):
218
+ summary = ''
219
+ return (kind, 'summary', normalise(summary))
220
+
221
+
222
+ def _owner(notes) -> str:
223
+ """The group for one pattern.
224
+
225
+ Merging happens first, so a failure that several tasks recorded stays one pattern
226
+ when those notes disagree about who should fix it. The majority `fixable_by` wins.
227
+ A tie is `unsure`: the notes do not agree, and an unknown value counts as that.
228
+ """
229
+ counts = {'user': 0, 'forge': 0, 'unsure': 0}
230
+ for note in notes:
231
+ bucket = note.get('fixable_by')
232
+ counts[bucket if bucket in counts else 'unsure'] += 1
233
+ best = max(counts.values())
234
+ winners = [name for name in counts if counts[name] == best]
235
+ if len(winners) == 1:
236
+ return winners[0]
237
+ return 'unsure'
238
+
239
+
240
+ def _patterns(notes, task_total, run_models, earlier) -> dict:
241
+ order = []
242
+ buckets = {}
243
+ for note in notes:
244
+ key = _pattern_key(note)
245
+ if key not in buckets:
246
+ order.append(key)
247
+ buckets[key] = []
248
+ buckets[key].append(note)
249
+ grouped = {key: [] for key, _title in GROUPS}
250
+ for key in order:
251
+ owner = _owner(buckets[key])
252
+ grouped[owner].append(
253
+ _pattern(buckets[key], task_total, run_models, earlier, owner))
254
+ for items in grouped.values():
255
+ items.sort(key=lambda item: (
256
+ -item['tasks_hit'], item['summary'].lower(), item['type'], item['command'] or ''))
257
+ return grouped
258
+
259
+
260
+ def _pattern(notes, task_total, run_models, earlier, group_id) -> dict:
261
+ tasks = []
262
+ seen = set()
263
+ models, harnesses = [], []
264
+ verified = claimed = 0
265
+ blocking = False
266
+ for note in notes:
267
+ task = _text_field(note.get('task'))
268
+ if task and task not in seen:
269
+ seen.add(task)
270
+ tasks.append(task)
271
+ _remember(models, _text_field(note.get('alias')))
272
+ _remember(harnesses, _text_field(note.get('harness')))
273
+ if note.get('check') == 'verified':
274
+ verified += 1
275
+ elif note.get('check') == 'claimed':
276
+ claimed += 1
277
+ if note.get('blocking') is True:
278
+ blocking = True
279
+ models.sort()
280
+ harnesses.sort()
281
+ representative = _representative(notes)
282
+ kind = representative.get('type') if representative.get('type') in TYPES else 'other'
283
+ specific = models[0] if len(run_models) >= 2 and len(models) == 1 else None
284
+ key = _pattern_key(representative)
285
+ return {
286
+ 'type': kind,
287
+ 'summary': _summary(notes, representative),
288
+ 'command': _command(representative),
289
+ 'exit': _exit(representative),
290
+ 'error': _cap_lines(_error(representative)),
291
+ 'tasks_hit': len(tasks),
292
+ 'tasks': task_total,
293
+ 'earlier_runs': len(earlier.get(key, ())),
294
+ 'models': models,
295
+ 'harnesses': harnesses,
296
+ 'verified': verified,
297
+ 'claimed': claimed,
298
+ 'blocking': blocking,
299
+ 'model_specific': specific,
300
+ 'fix': _fix(kind, harnesses) if group_id == 'user' else None,
301
+ }
302
+
303
+
304
+ def _representative(notes) -> dict:
305
+ """The first note that carries an error, else the first note. File order."""
306
+ for note in notes:
307
+ if _error(note):
308
+ return note
309
+ return notes[0]
310
+
311
+
312
+ def _summary(notes, representative) -> str:
313
+ for note in (representative, *notes):
314
+ text = _one_line(note.get('summary'))
315
+ if text:
316
+ return text
317
+ return ''
318
+
319
+
320
+ def _fix(kind: str, harnesses: list):
321
+ if kind == 'sandbox':
322
+ return {'action': _sandbox_action(harnesses), 'why': _SANDBOX_WHY}
323
+ action, why = _FIXES.get(kind) or _FIXES['other']
324
+ return {'action': action, 'why': why}
325
+
326
+
327
+ def _sandbox_action(harnesses: list) -> str:
328
+ flags = []
329
+ for name in harnesses:
330
+ flag = _BYPASS.get(name.lower())
331
+ if flag and flag not in flags:
332
+ flags.append(flag)
333
+ if not harnesses:
334
+ subject = 'the harness sandbox'
335
+ elif len(harnesses) == 1:
336
+ subject = 'the %s sandbox' % harnesses[0]
337
+ else:
338
+ subject = 'the %s sandboxes' % _and(harnesses)
339
+ loosening = '`--yolo-dwarf` or `--yolo-qa`'
340
+ if flags:
341
+ passed = ' and '.join('`%s`' % flag for flag in flags)
342
+ return 'Loosen %s with %s, which passes %s.' % (subject, loosening, passed)
343
+ return 'Loosen %s with %s.' % (subject, loosening)
344
+
345
+
346
+ def _and(names: list) -> str:
347
+ if len(names) == 2:
348
+ return '%s and %s' % (names[0], names[1])
349
+ return '%s, and %s' % (', '.join(names[:-1]), names[-1])
350
+
351
+
352
+ # --- markdown --------------------------------------------------------------------
353
+
354
+ def _render_pattern(pattern: dict) -> list:
355
+ out = ['### ' + (pattern['summary'] or pattern['type']), '']
356
+ bits = [pattern['type']]
357
+ if pattern['blocking']:
358
+ bits.append('blocking')
359
+ if pattern['model_specific']:
360
+ bits.append('possibly specific to %s, not forge' % pattern['model_specific'])
361
+ out.append('. '.join(bits) + '.')
362
+ earlier = pattern['earlier_runs']
363
+ if earlier == 1:
364
+ earlier_text = 'and 1 earlier run'
365
+ else:
366
+ earlier_text = 'and %d earlier runs' % earlier
367
+ out.append('%d of %d tasks in this run, %s.' % (pattern['tasks_hit'], pattern['tasks'], earlier_text))
368
+ out.append('Models: %s. Harnesses: %s.' % (_names(pattern['models']), _names(pattern['harnesses'])))
369
+ out.append('Checks: %d verified, %d claimed.' % (pattern['verified'], pattern['claimed']))
370
+ out.extend(_render_evidence(pattern))
371
+ if pattern.get('fix'):
372
+ out.append('')
373
+ out.append('Fix: ' + pattern['fix']['action'])
374
+ out.append(pattern['fix']['why'])
375
+ return out
376
+
377
+
378
+ def _render_evidence(pattern: dict) -> list:
379
+ """The command, exit code and error, each only when the note recorded it.
380
+
381
+ A note can carry an exit code and an error with no command. Those still belong in
382
+ the report; the command is not what makes the other two real.
383
+ """
384
+ command = pattern.get('command') or None
385
+ exit_code = pattern.get('exit')
386
+ error = pattern.get('error') or None
387
+ if command is None and exit_code is None and error is None:
388
+ return []
389
+ if command and exit_code is not None:
390
+ line = 'Evidence: `%s` exited %s.' % (command, exit_code)
391
+ elif command:
392
+ line = 'Evidence: `%s`.' % command
393
+ elif exit_code is not None:
394
+ line = 'Evidence: exited %s.' % exit_code
395
+ else:
396
+ line = None
397
+ out = ['']
398
+ if line:
399
+ out.append(line)
400
+ if error:
401
+ if line:
402
+ out.append('')
403
+ out.append(_fence(error))
404
+ return out
405
+
406
+
407
+ def _fence(text: str) -> str:
408
+ body = text.splitlines() or ['']
409
+ marker = '```'
410
+ while any(line.startswith(marker) for line in body):
411
+ marker += '`'
412
+ return marker + '\n' + text + '\n' + marker
413
+
414
+
415
+ def _names(values) -> str:
416
+ return ', '.join(values) if values else 'none'
417
+
418
+
419
+ # --- notes and tasks -------------------------------------------------------------
420
+
421
+ def _load(path: Path):
422
+ notes, malformed = [], []
423
+ for line in _text(path).splitlines():
424
+ if not line.strip():
425
+ continue
426
+ try:
427
+ obj = json.loads(line)
428
+ except json.JSONDecodeError:
429
+ malformed.append(_clip(line))
430
+ continue
431
+ if not isinstance(obj, dict):
432
+ malformed.append(_clip(line))
433
+ continue
434
+ if obj.get('malformed') is True:
435
+ summary = obj.get('summary')
436
+ malformed.append(_clip(summary if isinstance(summary, str) and summary.strip() else line))
437
+ continue
438
+ notes.append(obj)
439
+ return notes, malformed
440
+
441
+
442
+ def _task_rows(plan: Path) -> list:
443
+ rows = []
444
+ for line in _text(plan / 'tasks.tsv').splitlines():
445
+ if not line.strip() or line.startswith('#'):
446
+ continue
447
+ parts = line.split('\t')
448
+ if parts and parts[0].strip():
449
+ rows.append(parts)
450
+ return rows
451
+
452
+
453
+ def _run_models(rows, notes) -> list:
454
+ found = []
455
+ for row in rows:
456
+ _remember(found, _spec_alias(row, 4))
457
+ _remember(found, _spec_alias(row, 5))
458
+ for note in notes:
459
+ _remember(found, _text_field(note.get('alias')))
460
+ found.sort()
461
+ return found
462
+
463
+
464
+ def _spec_alias(row, index):
465
+ if len(row) <= index:
466
+ return None
467
+ text = row[index].strip()
468
+ if not text or text == '-' or text.upper() == 'UNASSIGNED':
469
+ return None
470
+ head = text.split(':', 1)[0].strip()
471
+ if not head or head == '-' or head.upper() == 'UNASSIGNED':
472
+ return None
473
+ return head
474
+
475
+
476
+ def _current_ids(plan: Path) -> set:
477
+ """Ids that can mean this plan, so its own retro_note events are not earlier runs.
478
+
479
+ The dataset uid and the legacy uid identify the run. The run id is the plan's
480
+ display name: directory basenames repeat, so it is only a fallback for an event
481
+ that has no uid at all.
482
+
483
+ Note capture resolves the plan (`locate` → `Path.resolve`) before `run_uid` hashes
484
+ a legacy id. Hash that same absolute path. `report ./plan` on a plan with no
485
+ `dataset.uid` must not treat this plan's own events as another run.
486
+ """
487
+ found = set()
488
+ for name in ('dataset.uid', 'run_id'):
489
+ value = _first_line(plan / name)
490
+ if value:
491
+ found.add(value)
492
+ try:
493
+ from forge_dataset.harvest import legacy_uid
494
+ found.add(legacy_uid(plan.resolve()))
495
+ except Exception:
496
+ pass
497
+ return found
498
+
499
+
500
+ def _earlier_index(current: set) -> dict:
501
+ """pattern key -> set of other runs that recorded a retro_note of that pattern."""
502
+ found = {}
503
+ for run, run_id, data in _retro_events():
504
+ if _is_current(run, run_id, data, current):
505
+ continue
506
+ key = _pattern_key(data)
507
+ if key is None:
508
+ continue
509
+ identity = _run_identity(run, run_id) or _run_identity(data.get('run'), data.get('run_id'))
510
+ if not identity:
511
+ continue
512
+ found.setdefault(key, set()).add(identity)
513
+ return found
514
+
515
+
516
+ def _retro_events() -> list:
517
+ """retro_note events from the local dataset. A missing store is no events, and is not created."""
518
+ try:
519
+ from forge_dataset import connect, dataset_dir, enabled
520
+ if not enabled() or not (dataset_dir() / 'dataset.sqlite').is_file():
521
+ return []
522
+ db = connect()
523
+ try:
524
+ # json.dumps writes `"name": "retro_note"` (default separators). The name check below is the filter.
525
+ rows = db.execute(
526
+ "SELECT run, run_id, data FROM events WHERE kind = 'event' AND data LIKE ?",
527
+ ('%"name": "retro_note"%',)).fetchall()
528
+ finally:
529
+ db.close()
530
+ except Exception:
531
+ return []
532
+ found = []
533
+ for run, run_id, raw in rows:
534
+ try:
535
+ data = json.loads(raw)
536
+ except (TypeError, ValueError):
537
+ continue
538
+ if isinstance(data, dict) and data.get('name') == 'retro_note':
539
+ found.append((run, run_id, data))
540
+ return found
541
+
542
+
543
+ def _is_current(run, run_id, data, current: set) -> bool:
544
+ """True when this event is the plan being reported.
545
+
546
+ `events.run` is the dataset uid. Another plan with the same display name and a
547
+ different uid is an earlier run, not this one. An event with no uid falls back to
548
+ the display name, which is the only link it has.
549
+ """
550
+ if not current:
551
+ return False
552
+ if not isinstance(data, dict):
553
+ data = {}
554
+ event_uid = _text_field(run) or _text_field(data.get('run'))
555
+ if event_uid:
556
+ return event_uid in current
557
+ return _in(run_id, current) or _in(data.get('run_id'), current)
558
+
559
+
560
+ def _in(value, current: set) -> bool:
561
+ return isinstance(value, str) and value.strip() in current
562
+
563
+
564
+ def _run_identity(run, run_id):
565
+ if isinstance(run, str) and run.strip():
566
+ return run.strip()
567
+ if isinstance(run_id, str) and run_id.strip():
568
+ return run_id.strip()
569
+ return None
570
+
571
+
572
+ # --- fields ----------------------------------------------------------------------
573
+
574
+ def _command(note: dict):
575
+ evidence = note.get('evidence')
576
+ if not isinstance(evidence, dict):
577
+ return None
578
+ command = evidence.get('command')
579
+ if not isinstance(command, str):
580
+ return None
581
+ command = command.strip()
582
+ return command or None
583
+
584
+
585
+ def _exit(note: dict):
586
+ evidence = note.get('evidence')
587
+ if not isinstance(evidence, dict):
588
+ return None
589
+ value = evidence.get('exit')
590
+ if isinstance(value, bool) or not isinstance(value, int):
591
+ return None
592
+ return value
593
+
594
+
595
+ def _error(note: dict):
596
+ evidence = note.get('evidence')
597
+ if not isinstance(evidence, dict):
598
+ return None
599
+ error = evidence.get('error')
600
+ if not isinstance(error, str) or not error.strip():
601
+ return None
602
+ return error
603
+
604
+
605
+ def _cap_lines(text):
606
+ if not text:
607
+ return None
608
+ lines = text.splitlines()
609
+ if len(lines) > ERROR_LINES:
610
+ lines = lines[:ERROR_LINES]
611
+ return '\n'.join(lines)
612
+
613
+
614
+ def _path_token(match) -> str:
615
+ token = match.group(0)
616
+ stripped = token.rstrip(_TRAILING)
617
+ if len(stripped) < 2 or re.fullmatch(r'[a-z]:[\\/]', stripped):
618
+ return token
619
+ return '<path>' + token[len(stripped):]
620
+
621
+
622
+ def _one_line(value) -> str:
623
+ if not isinstance(value, str):
624
+ return ''
625
+ return ' '.join(value.split())
626
+
627
+
628
+ def _text_field(value):
629
+ if not isinstance(value, str):
630
+ return None
631
+ text = value.strip()
632
+ return text or None
633
+
634
+
635
+ def _clip(value) -> str:
636
+ return _one_line(value)[:200]
637
+
638
+
639
+ def _remember(found: list, value) -> None:
640
+ if value and value not in found:
641
+ found.append(value)
642
+
643
+
644
+ def _text(path: Path) -> str:
645
+ try:
646
+ return path.read_text(encoding='utf-8', errors='replace')
647
+ except OSError:
648
+ return ''
649
+
650
+
651
+ def _first_line(path: Path):
652
+ for line in _text(path).splitlines():
653
+ line = line.strip()
654
+ if line:
655
+ return line
656
+ return None
657
+
658
+
659
+ def _atomic(path: Path, text: str) -> None:
660
+ path.parent.mkdir(parents=True, exist_ok=True)
661
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
662
+ try:
663
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as handle:
664
+ handle.write(text)
665
+ os.replace(tmp, path)
666
+ except BaseException:
667
+ try:
668
+ os.unlink(tmp)
669
+ except OSError:
670
+ pass
671
+ raise