@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,1193 @@
1
+ """Draft GitHub issues for forge's own repository from a retro report's forge group.
2
+
3
+ One draft per pattern in the forge group. The text is built from the report, then redacted,
4
+ and nothing is posted unless ``--apply`` carries the sha256 of those exact drafts and choices.
5
+ The repository is the skill's ``package.json`` repository, never the plan's.
6
+
7
+ forge retro issues PLAN [--json] [--choice rN=new|comment:N|skip ...] [--apply --approve HASH]
8
+
9
+ Exit codes: 0 drafted or posted, 2 usage, 3 refused (not a plan, never-send, ``gh`` unavailable,
10
+ or the approval hash does not match).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import importlib.util
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ import re
20
+ import sys
21
+ import tempfile
22
+
23
+ from forge_decide.providers import privacy_floor
24
+ from forge_retro import SKILL
25
+ import forge_retro.report as report
26
+
27
+ _FILER = None
28
+ _CHOICE = re.compile(r'^(r[1-9]\d*)=(new|skip|comment:([1-9]\d*))$')
29
+ _ORIGIN = re.compile(r'[:/](?P<owner>[^/:\s]+)/(?P<slug>[^/\s]+?)(?:\.git)?/?$')
30
+ _KEPT = re.compile(r'<(?:path|repo|branch|host|prompt text)>')
31
+ _WORD = re.compile(r'[a-z]{4,}')
32
+ _QUERY_SKIP = {
33
+ 'path', 'repo', 'branch', 'host', 'prompt', 'text', 'what', 'happened', 'models',
34
+ 'harnesses', 'checks', 'verified', 'claimed', 'tasks', 'earlier', 'runs', 'none',
35
+ 'forge', 'blocking', 'possibly', 'specific',
36
+ }
37
+ # Absolute paths, as the retro report matches them, without first lowercasing the draft.
38
+ _QUOTED_PATH = re.compile(
39
+ r'''(?<![A-Za-z0-9_])(?:"(?:~|/|[A-Za-z]:[\\/])[^"]*"|'(?:~|/|[A-Za-z]:[\\/])[^']*')''')
40
+ # A path may follow a colon (`builder01:/home/x`, `line 3:/Users/x`), but `https://` is a URL.
41
+ _UNIX_PATH = re.compile(r'(?:(?<![A-Za-z0-9_.:/~])|(?<=:)(?!//))/\S+')
42
+ _HOME_PATH = re.compile(r'(?<![A-Za-z0-9_./])~/\S+')
43
+ _WIN_PATH = re.compile(r'(?<![A-Za-z0-9_])[A-Za-z]:[\\/]\S+')
44
+ # file:///Users/... never matches _UNIX_PATH: the slashes after the scheme fail its lookbehind.
45
+ _FILE_URL = re.compile(r'(?i)(?<![A-Za-z0-9_])file://\S*')
46
+ _QUOTED_FILE = re.compile(r'(?i)"file://[^"]*"|\'file://[^\']*\'')
47
+ _TRAILING = '.,;:)]}\'"'
48
+ _ESC_SPACE = '\ue000'
49
+ _IPV4 = re.compile(
50
+ r'(?<![0-9])(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![0-9])')
51
+ _IPV6 = re.compile(r'(?<![A-Za-z0-9:])(?:[A-Fa-f0-9]{0,4}:){2,7}[A-Fa-f0-9]{0,4}(?![A-Za-z0-9:])')
52
+ _LOCALHOST = re.compile(r'(?<![A-Za-z0-9_-])localhost(?![A-Za-z0-9_-])', re.I)
53
+ _HOST = re.compile(
54
+ r'(?<![A-Za-z0-9_-])(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}'
55
+ r'(?![A-Za-z0-9_-])')
56
+ _CODE_EXT = {
57
+ 'py', 'js', 'ts', 'tsx', 'jsx', 'mjs', 'cjs', 'md', 'json', 'sh', 'css', 'html', 'yml',
58
+ 'yaml', 'txt', 'toml', 'lock', 'ini', 'cfg', 'xml', 'csv', 'tsv', 'rb', 'go', 'rs',
59
+ 'java', 'c', 'h', 'cpp', 'hpp', 'sql', 'vue', 'svg',
60
+ }
61
+ # scheme://authority, so a host whose suffix is also a filename extension (.sh, .py) is still a host.
62
+ _URL_AUTH = re.compile(
63
+ r'(?i)(?<![A-Za-z0-9+.-])(?P<scheme>[a-z][a-z0-9+.-]*://)(?P<auth>[^/\s]+)')
64
+ # The next word of these commands is a host (`ssh builder01`). curl and wget are not
65
+ # here: their operand is usually a URL, already redacted, or ordinary words.
66
+ _NET_HOST_CMDS = 'ssh|sftp|ping|telnet|mosh|nslookup|ftp|mysql|psql|nc|netcat'
67
+ _NET_CMDS = _NET_HOST_CMDS + '|curl|wget'
68
+ # A real invocation, not `ssh://` and not the `ssh:` prefix of an error line.
69
+ _NET_CMD = re.compile(
70
+ r'(?i)(?<![A-Za-z0-9_-])(?P<cmd>' + _NET_HOST_CMDS + r')(?![A-Za-z0-9_-])(?=\s|$)')
71
+ _NET_BEFORE = re.compile(r'(?i)(?:' + _NET_CMDS + r')\s+$')
72
+ # mysql and psql take the host as `-h` / `--host`. Their positional is a database name.
73
+ _POSITIONAL_HOST = frozenset({
74
+ 'ssh', 'sftp', 'ping', 'telnet', 'mosh', 'nslookup', 'ftp', 'nc', 'netcat',
75
+ })
76
+ # Short flags whose next token is an ordinary value, and those whose value is a host.
77
+ # Anything else (`-v`, `-vv`, `-4`) is boolean and must not swallow the hostname.
78
+ _VALUE_LETTERS = {
79
+ 'ssh': 'cDeFIiLlmOopQRSw',
80
+ 'sftp': 'BFiloPRS',
81
+ 'ping': 'cipstWw',
82
+ 'telnet': 'l',
83
+ 'mosh': 'cDeFIiLlmOopQRSw',
84
+ 'nc': 'ipw',
85
+ 'netcat': 'ipw',
86
+ 'mysql': 'DePpSu',
87
+ 'psql': 'cdfFpPU',
88
+ }
89
+ _HOST_LETTERS = {
90
+ 'ssh': 'bJW',
91
+ 'sftp': 'J',
92
+ 'mosh': 'bJW',
93
+ 'ping': 'IS',
94
+ 'nc': 's',
95
+ 'netcat': 's',
96
+ 'mysql': 'h',
97
+ 'psql': 'h',
98
+ }
99
+ _HOST_LONG = frozenset({'host', 'hostname', 'jump', 'bind', 'bind-address', 'source'})
100
+ _VALUE_LONG = frozenset({
101
+ 'port', 'identity', 'identity-file', 'user', 'login', 'config', 'option',
102
+ 'count', 'interval', 'timeout', 'wait', 'size', 'file', 'output', 'password',
103
+ 'command', 'local', 'remote', 'dynamic', 'proxy-command',
104
+ })
105
+ # "Could not resolve host: internal-api.sh" is a host even though `.sh` is also a filename.
106
+ # The same phrases introduce a bare name with no dot (`hostname builder01`).
107
+ _HOST_DIAGNOSTIC = re.compile(
108
+ r'(?i)(?:(?<![A-Za-z0-9_])(?:'
109
+ r'could not resolve host(?:name)?'
110
+ r'|unknown host(?:name)?'
111
+ r'|no such host'
112
+ r'|name or service not known'
113
+ r'|temporary failure in name resolution'
114
+ r'|nodename nor servname'
115
+ r'|getaddrinfo'
116
+ r'|connect(?:ing|ed)? to'
117
+ r'|dial(?:ing)?(?:\s+tcp|\s+udp)?'
118
+ r'|host(?:name)?'
119
+ r'))[\s:=(]*$')
120
+ _DIAG_BARE = re.compile(
121
+ r'(?i)(?<![A-Za-z0-9_])(?:'
122
+ r'could not resolve host(?:name)?'
123
+ r'|unknown host(?:name)?'
124
+ r'|connect(?:ing|ed)? to(?:\s+host)?'
125
+ r'|dial(?:ing)?(?:\s+tcp|\s+udp)?'
126
+ r'|hostname'
127
+ # Plain "host machine" / "Host key verification" is prose. Only `host:` or `host=` names one.
128
+ r'|host(?=[ \t]*[:=])'
129
+ r')'
130
+ r'(?P<sep>[\s:=]+)'
131
+ # tcp/udp/host are part of the phrase (`dial tcp`, `connect to host`). Backtracking
132
+ # must not redact those words and leave the real name in place.
133
+ r'(?P<host>(?!(?:tcp|udp|host|hostname)\b)'
134
+ r'[A-Za-z](?:[A-Za-z0-9-]{0,62}[A-Za-z0-9])?)'
135
+ r'(?![A-Za-z0-9_.-])')
136
+ # A hyphenated `forge-issues.py` after one of these is still a file.
137
+ _FILE_BEFORE = re.compile(
138
+ r'(?i)(?:(?<![A-Za-z0-9_./])(?:'
139
+ r'python3?|bash|sh|zsh|dash|node|ruby|perl|php|lua|cat|ls|vim|nvim|emacs|'
140
+ r'make|cargo|go|rustc|gcc|clang|source|exec)\s+|[/\\])$')
141
+ _TITLE_LIMIT = 240
142
+
143
+
144
+ class Usage(Exception):
145
+ pass
146
+
147
+
148
+ def _filer():
149
+ """forge-issues.py, loaded by path: fingerprint and the ``gh`` runner live there."""
150
+ global _FILER
151
+ if _FILER is None:
152
+ spec = importlib.util.spec_from_file_location(
153
+ 'forge_issues', Path(__file__).resolve().parents[1] / 'forge-issues.py')
154
+ module = importlib.util.module_from_spec(spec)
155
+ spec.loader.exec_module(module)
156
+ _FILER = module
157
+ return _FILER
158
+
159
+
160
+ def _warn(text: str) -> None:
161
+ sys.stderr.write(text if text.endswith('\n') else text + '\n')
162
+
163
+
164
+ def _emit(text: str) -> None:
165
+ sys.stdout.buffer.write(text.encode('utf-8'))
166
+ sys.stdout.buffer.flush()
167
+
168
+
169
+ def _read(path: Path) -> str:
170
+ try:
171
+ return path.read_text(encoding='utf-8', errors='replace')
172
+ except OSError:
173
+ return ''
174
+
175
+
176
+ def _first_line(path: Path):
177
+ for line in _read(path).splitlines():
178
+ line = line.strip()
179
+ if line:
180
+ return line
181
+ return None
182
+
183
+
184
+ def _repo_path(plan: Path):
185
+ text = _first_line(plan / 'repo')
186
+ return text or None
187
+
188
+
189
+ def forge_slug() -> str:
190
+ """Owner/name from the skill's package.json. Never the plan repository."""
191
+ data = json.loads((SKILL / 'package.json').read_text(encoding='utf-8'))
192
+ repo = data.get('repository')
193
+ url = repo.get('url') if isinstance(repo, dict) else repo
194
+ match = re.search(r'github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?/?$', url or '')
195
+ if not match:
196
+ raise Usage('package.json has no GitHub repository')
197
+ return '%s/%s' % (match.group(1), match.group(2))
198
+
199
+
200
+ def _split_origin(url: str):
201
+ match = _ORIGIN.search(url or '')
202
+ if not match:
203
+ return None, None
204
+ return match.group('owner'), match.group('slug')
205
+
206
+
207
+ def _add(found: list, text, placeholder: str) -> None:
208
+ text = (text or '').strip()
209
+ # A branch, repository or owner can be one or two characters (`qa`, `ab`).
210
+ # Empty text would match every position.
211
+ if not text or any(text == item[0] for item in found):
212
+ return
213
+ found.append((text, placeholder))
214
+
215
+
216
+ def _branches(plan: Path) -> list:
217
+ """Branch names the plan recorded: integration.base, results.tsv, and the run's own names."""
218
+ found = []
219
+ _add(found, _first_line(plan / 'integration.base'), '<branch>')
220
+ run_id = _first_line(plan / 'run_id')
221
+ if run_id:
222
+ _add(found, 'forge/%s-integration' % run_id, '<branch>')
223
+ seen = []
224
+ for path in (plan / 'results.tsv', plan / 'tasks.tsv'):
225
+ for line in _read(path).splitlines():
226
+ if not line.strip() or line.startswith('#'):
227
+ continue
228
+ parts = line.split('\t')
229
+ name = parts[0].strip()
230
+ if path.name == 'results.tsv' and len(parts) >= 3:
231
+ _add(found, parts[2], '<branch>')
232
+ if run_id and name and name not in seen:
233
+ seen.append(name)
234
+ _add(found, 'forge/%s/%s' % (run_id, name), '<branch>')
235
+ return found
236
+
237
+
238
+ def _git_config(repo: Path):
239
+ """The repository's shared config file. In a linked worktree `.git` is a file naming the
240
+ worktree's git dir, and the config lives in the common dir it points to."""
241
+ dotgit = repo / '.git'
242
+ if dotgit.is_dir():
243
+ return dotgit / 'config'
244
+ try:
245
+ line = dotgit.read_text(errors='replace').strip()
246
+ except OSError:
247
+ return None
248
+ if not line.startswith('gitdir:'):
249
+ return None
250
+ gitdir = Path(line.split(':', 1)[1].strip())
251
+ if not gitdir.is_absolute():
252
+ gitdir = repo / gitdir
253
+ try:
254
+ common = (gitdir / 'commondir').read_text(errors='replace').strip()
255
+ except OSError:
256
+ return gitdir / 'config'
257
+ common_dir = Path(common) if Path(common).is_absolute() else gitdir / common
258
+ return common_dir / 'config'
259
+
260
+
261
+ def _origin(repo: Path):
262
+ """The origin URL, read from the git config without running git (a worktree's too)."""
263
+ config = _git_config(repo)
264
+ try:
265
+ lines = config.read_text(errors='replace').splitlines() if config else []
266
+ except OSError:
267
+ return None
268
+ section = None
269
+ for line in lines:
270
+ stripped = line.strip()
271
+ if stripped.startswith('['):
272
+ section = stripped
273
+ elif section == '[remote "origin"]' and stripped.startswith('url') and '=' in stripped:
274
+ return stripped.split('=', 1)[1].strip()
275
+ return None
276
+
277
+
278
+ def _literals(plan: Path) -> list:
279
+ """(secret, placeholder) longest first, so a full origin URL goes before its owner."""
280
+ found = []
281
+ repo = _repo_path(plan)
282
+ if repo:
283
+ _add(found, Path(repo).name, '<repo>')
284
+ origin = _origin(Path(repo)) or ''
285
+ _add(found, origin, '<repo>')
286
+ owner, slug = _split_origin(origin)
287
+ _add(found, owner, '<repo>')
288
+ _add(found, slug, '<repo>')
289
+ for branch, placeholder in _branches(plan):
290
+ _add(found, branch, placeholder)
291
+ found.sort(key=lambda item: len(item[0]), reverse=True)
292
+ return found
293
+
294
+
295
+ def _prompts(plan: Path) -> list:
296
+ """Task prompt.md and request.md, plus the plan's own request. Shorter than 40 cannot match."""
297
+ paths = [plan / 'request.md', plan / 'prompt.md']
298
+ tasks = plan / 'tasks'
299
+ if tasks.is_dir():
300
+ for child in sorted(tasks.iterdir()):
301
+ if child.is_dir():
302
+ paths.append(child / 'prompt.md')
303
+ paths.append(child / 'request.md')
304
+ found = []
305
+ for path in paths:
306
+ text = _read(path).replace('\r\n', '\n').replace('\r', '\n')
307
+ if len(text) >= 40:
308
+ found.append(text)
309
+ return found
310
+
311
+
312
+ def _map_outside(text: str, fn) -> str:
313
+ """Run fn on the text, leaving placeholders already written untouched."""
314
+ pieces = []
315
+ cursor = 0
316
+ for kept in _KEPT.finditer(text):
317
+ pieces.append(fn(text[cursor:kept.start()]))
318
+ pieces.append(kept.group(0))
319
+ cursor = kept.end()
320
+ pieces.append(fn(text[cursor:]))
321
+ return ''.join(pieces)
322
+
323
+
324
+ def _sub_outside(text: str, pattern, repl) -> str:
325
+ return _map_outside(text, lambda chunk: pattern.sub(repl, chunk))
326
+
327
+
328
+ def _path_token(token: str) -> str:
329
+ stripped = token.rstrip(_TRAILING)
330
+ if len(stripped) < 2 or re.fullmatch(r'[A-Za-z]:[\\/]', stripped):
331
+ return token
332
+ return '<path>' + token[len(stripped):]
333
+
334
+
335
+ def _next_segment(text: str, index: int):
336
+ """The next space-separated segment, or None when the path has ended.
337
+
338
+ Only spaces join a path. A tab, newline or shell metacharacter is the next
339
+ command, and a flag or a placeholder is the next argument.
340
+ """
341
+ length = len(text)
342
+ if index >= length or text[index] != ' ':
343
+ return None
344
+ start = index
345
+ while start < length and text[start] == ' ':
346
+ start += 1
347
+ if start >= length or text[start] in '\t\r\n|&;<>()':
348
+ return None
349
+ stop = start
350
+ while stop < length and text[stop] not in ' \t\r\n|&;<>()':
351
+ stop += 1
352
+ segment = text[start:stop]
353
+ if not segment or segment.startswith(('-', '<')):
354
+ return None
355
+ return stop, segment
356
+
357
+
358
+ def _path_continues(text: str, index: int) -> bool:
359
+ """True when a later segment of this same path still contains a separator.
360
+
361
+ `/Users/Secret Middle Person/key.txt` is one path: `Middle` has no slash,
362
+ and `Person/key.txt` does. A slashless word with nothing slashed after it
363
+ is the next argument (`cat /tmp/out.txt notes`).
364
+ """
365
+ while True:
366
+ found = _next_segment(text, index)
367
+ if found is None:
368
+ return False
369
+ stop, segment = found
370
+ if '/' in segment or '\\' in segment:
371
+ return True
372
+ index = stop
373
+
374
+
375
+ def _path_end(text: str, end: int) -> int:
376
+ """Include later segments of one unquoted path, spaces included.
377
+
378
+ The first token stops at the space. `Person/key.txt` still holds the private
379
+ name, and so does a slashless segment that sits in front of it.
380
+ """
381
+ best = end
382
+ index = end
383
+ while True:
384
+ found = _next_segment(text, index)
385
+ if found is None:
386
+ break
387
+ stop, segment = found
388
+ if '/' not in segment and '\\' not in segment and not _path_continues(text, stop):
389
+ break
390
+ best = stop
391
+ index = stop
392
+ return best
393
+
394
+
395
+ def _replace_paths(chunk: str, pattern) -> str:
396
+ pieces = []
397
+ cursor = 0
398
+ for match in pattern.finditer(chunk):
399
+ if match.start() < cursor:
400
+ continue
401
+ end = _path_end(chunk, match.end())
402
+ pieces.append(chunk[cursor:match.start()])
403
+ pieces.append(_path_token(chunk[match.start():end]))
404
+ cursor = end
405
+ pieces.append(chunk[cursor:])
406
+ return ''.join(pieces)
407
+
408
+
409
+ def _redact_prompts(text: str, prompts: list) -> str:
410
+ prompts = [prompt for prompt in prompts if len(prompt) >= 40]
411
+ if not prompts:
412
+ return text
413
+ out = []
414
+ index = 0
415
+ length = len(text)
416
+ while index < length:
417
+ if index + 40 <= length and any(text[index:index + 40] in prompt for prompt in prompts):
418
+ end = index + 40
419
+ while end < length and any(text[index:end + 1] in prompt for prompt in prompts):
420
+ end += 1
421
+ out.append('<prompt text>')
422
+ index = end
423
+ else:
424
+ out.append(text[index])
425
+ index += 1
426
+ return ''.join(out)
427
+
428
+
429
+ def _redact_paths(text: str) -> str:
430
+ text = text.replace('\\ ', _ESC_SPACE)
431
+ text = _sub_outside(text, _QUOTED_PATH, '<path>')
432
+ text = _sub_outside(text, _QUOTED_FILE, '<path>')
433
+ text = _map_outside(text, lambda chunk: _replace_paths(chunk, _FILE_URL))
434
+ text = _map_outside(text, lambda chunk: _replace_paths(chunk, _WIN_PATH))
435
+ text = _map_outside(text, lambda chunk: _replace_paths(chunk, _UNIX_PATH))
436
+ text = _map_outside(text, lambda chunk: _replace_paths(chunk, _HOME_PATH))
437
+ return text.replace(_ESC_SPACE, ' ')
438
+
439
+
440
+ def _literal_pattern(needle: str):
441
+ escaped = re.escape(needle)
442
+ # A short word is a token (`main`), so it does not eat the middle of another word.
443
+ # A path-like or long secret is removed wherever it sits.
444
+ if len(needle) >= 8 or any(char in needle for char in '/\\.@:'):
445
+ return re.compile(escaped, re.I)
446
+ return re.compile(r'(?<![A-Za-z0-9_])' + escaped + r'(?![A-Za-z0-9_])', re.I)
447
+
448
+
449
+ def _redact_literals(text: str, literals: list) -> str:
450
+ for needle, placeholder in literals:
451
+ text = _sub_outside(text, _literal_pattern(needle), placeholder)
452
+ return text
453
+
454
+
455
+ def _bare_filename(match) -> bool:
456
+ """True when the token is a filename (`build.py`), not a hostname.
457
+
458
+ `.sh` and `.py` are filename extensions and real public suffixes. A token in a
459
+ URL, followed by a path, given to a network command, or named in a resolver
460
+ error is a host. `internal-api.sh` is a host that merely uses that suffix;
461
+ `build.py` has no hyphen and stays a filename.
462
+ """
463
+ name = match.group(0)
464
+ if name.rsplit('.', 1)[-1].lower() not in _CODE_EXT:
465
+ return False
466
+ before = match.string[:match.start()]
467
+ after = match.string[match.end():]
468
+ if before.endswith(('://', '@', '//')):
469
+ return False
470
+ if after.startswith('/') or re.match(r':\d', after):
471
+ return False
472
+ if _NET_BEFORE.search(before) or _HOST_DIAGNOSTIC.search(before):
473
+ return False
474
+ labels = name.split('.')
475
+ if any('-' in label for label in labels[:-1]):
476
+ # internal-api.sh is a host. forge-issues.py after python3 or bash is a file.
477
+ if _FILE_BEFORE.search(before):
478
+ return True
479
+ return False
480
+ return True
481
+
482
+
483
+ def _host_repl(match) -> str:
484
+ if _bare_filename(match):
485
+ return match.group(0)
486
+ return '<host>'
487
+
488
+
489
+ def _url_repl(match) -> str:
490
+ # file:// is a path. _redact_paths has already replaced it, and a missed one
491
+ # must not lose its path by keeping only the authority.
492
+ if match.group('scheme').lower().startswith('file'):
493
+ return match.group(0)
494
+ return match.group('scheme') + '<host>'
495
+
496
+
497
+ def _token_at(text: str, index: int):
498
+ """The next command token, or None at a newline or shell metacharacter.
499
+
500
+ `<path>` is a token. A path redacted earlier is the argument of `-i`, not the
501
+ end of the command, and `alice@<host>` is still one destination.
502
+ """
503
+ length = len(text)
504
+ while index < length and text[index] in ' \t':
505
+ index += 1
506
+ if index >= length or text[index] in '\r\n|&;>()':
507
+ return None
508
+ if text[index] == '<':
509
+ kept = _KEPT.match(text, index)
510
+ if not kept:
511
+ return None
512
+ return index, kept.end(), kept.group(0)
513
+ stop = index
514
+ while stop < length and text[stop] not in ' \t\r\n|&;<>()':
515
+ stop += 1
516
+ if stop < length and text[stop] == '<' and text[:stop].endswith(('@', '=')):
517
+ kept = _KEPT.match(text, stop)
518
+ if kept:
519
+ stop = kept.end()
520
+ return index, stop, text[index:stop]
521
+
522
+
523
+ def _flag_kind(token: str, cmd: str) -> str:
524
+ """How this token consumes what follows: flag, value, host, attached, or end.
525
+
526
+ `-v` is boolean. Treating every flag as taking an optional argument redacts
527
+ the command word and leaves `ssh -v builder01` in the draft.
528
+ """
529
+ if token == '--':
530
+ return 'end'
531
+ if not token.startswith('-') or token == '-':
532
+ return 'positional'
533
+ host = _HOST_LETTERS.get(cmd, '')
534
+ value = _VALUE_LETTERS.get(cmd, '')
535
+ if token.startswith('--'):
536
+ name, sep, _rest = token[2:].partition('=')
537
+ key = name.lower()
538
+ if sep:
539
+ return 'host-attached' if key in _HOST_LONG else 'attached'
540
+ if key in _HOST_LONG:
541
+ return 'host'
542
+ if key in _VALUE_LONG:
543
+ return 'value'
544
+ return 'flag'
545
+ body = token[1:]
546
+ if not body or not re.fullmatch(r'[A-Za-z0-9]+', body):
547
+ head = body[:1]
548
+ if head in host:
549
+ return 'host-attached'
550
+ if head in value:
551
+ return 'attached'
552
+ return 'flag'
553
+
554
+ def role(char: str) -> str:
555
+ if char in host:
556
+ return 'host'
557
+ if char in value:
558
+ return 'value'
559
+ return 'flag'
560
+
561
+ roles = [role(char) for char in body]
562
+ if all(item == 'flag' for item in roles):
563
+ return 'flag'
564
+ if len(body) > 1 and roles[0] == 'host':
565
+ return 'host-attached'
566
+ if len(body) > 1 and roles[0] == 'value':
567
+ return 'attached'
568
+ return roles[-1]
569
+
570
+
571
+ def _redact_destination(token: str) -> str:
572
+ """The whole destination, including `alice@builder02`.
573
+
574
+ Replacing only the letters before `@` leaves the hostname in the draft.
575
+ """
576
+ if _KEPT.fullmatch(token) or token.startswith('<path>'):
577
+ return token
578
+ return '<host>'
579
+
580
+
581
+ def _redact_attached_host(token: str) -> str:
582
+ if token.startswith('--'):
583
+ name, sep, _value = token[2:].partition('=')
584
+ return '--' + name + sep + '<host>'
585
+ return token[:2] + '<host>'
586
+
587
+
588
+ def _consume_destination(text: str, pos: int, cmd: str, pieces: list) -> int:
589
+ while True:
590
+ found = _token_at(text, pos)
591
+ if found is None:
592
+ return pos
593
+ start, stop, token = found
594
+ kind = _flag_kind(token, cmd)
595
+ if kind == 'positional':
596
+ if cmd not in _POSITIONAL_HOST:
597
+ return pos
598
+ # `ssh -i <path> builder01`: the path is an argument, and the host follows.
599
+ # `ssh alice@<host>` is already redacted; do not write a second placeholder.
600
+ if _KEPT.fullmatch(token) and token != '<host>':
601
+ pieces.append(text[pos:stop])
602
+ pos = stop
603
+ continue
604
+ if token == '<host>':
605
+ return pos
606
+ if token.endswith('@<host>'):
607
+ pieces.append(text[pos:start])
608
+ pieces.append('<host>')
609
+ return stop
610
+ if not re.match(r'[A-Za-z0-9@]', token):
611
+ return pos
612
+ pieces.append(text[pos:start])
613
+ pieces.append(_redact_destination(token))
614
+ return stop
615
+ if kind == 'end':
616
+ pieces.append(text[pos:stop])
617
+ if cmd not in _POSITIONAL_HOST:
618
+ return stop
619
+ nxt = _token_at(text, stop)
620
+ if nxt is None:
621
+ return stop
622
+ nstart, nstop, ntoken = nxt
623
+ pieces.append(text[stop:nstart])
624
+ pieces.append(_redact_destination(ntoken))
625
+ return nstop
626
+ if kind == 'host-attached':
627
+ pieces.append(text[pos:start])
628
+ pieces.append(_redact_attached_host(token))
629
+ pos = stop
630
+ continue
631
+ if kind in ('host', 'value'):
632
+ pieces.append(text[pos:stop])
633
+ nxt = _token_at(text, stop)
634
+ if nxt is None:
635
+ return stop
636
+ nstart, nstop, ntoken = nxt
637
+ if _flag_kind(ntoken, cmd) != 'positional':
638
+ pos = stop
639
+ continue
640
+ pieces.append(text[stop:nstart])
641
+ if kind == 'host':
642
+ pieces.append(_redact_destination(ntoken))
643
+ else:
644
+ pieces.append(ntoken)
645
+ pos = nstop
646
+ continue
647
+ pieces.append(text[pos:stop])
648
+ pos = stop
649
+
650
+
651
+ def _redact_command_hosts(text: str) -> str:
652
+ pieces = []
653
+ cursor = 0
654
+ for match in _NET_CMD.finditer(text):
655
+ if match.start() < cursor:
656
+ continue
657
+ pieces.append(text[cursor:match.end()])
658
+ cursor = _consume_destination(text, match.end(), match.group('cmd').lower(), pieces)
659
+ pieces.append(text[cursor:])
660
+ return ''.join(pieces)
661
+
662
+
663
+ # `builder01:/home/x` (scp, rsync) and `builder01:22`: a single-label host in front of a path or
664
+ # port. A user may precede it (`deploy@buildbox:`). Words that commonly sit before a colon are
665
+ # not hosts; the path itself is already `<path>` by the time hosts are redacted.
666
+ _LABEL_DEST = re.compile(
667
+ r'(?<![A-Za-z0-9_.@/<>+-])(?P<user>[A-Za-z0-9._+-]+@)?(?P<label>[A-Za-z][A-Za-z0-9-]{0,62})'
668
+ r'(?=:(?:<path>|\d{1,5}(?![A-Za-z0-9])))')
669
+ _NOT_HOSTS = frozenset({
670
+ 'error', 'warning', 'warn', 'info', 'debug', 'note', 'fatal', 'trace', 'line', 'lines',
671
+ 'col', 'column', 'port', 'code', 'status', 'pid', 'exit', 'at', 'in', 'from', 'file',
672
+ 'path', 'dir', 'cwd', 'pwd', 'see', 'step', 'attempt', 'task', 'tasks', 'version', 'time',
673
+ 'id', 'count', 'size', 'total', 'rc', 'errno', 'signal', 'http', 'https', 'ssh', 'ftp',
674
+ 'git', 'file', 'localhost', 'try', 'retry', 'timeout', 'ms', 'sec', 'exitcode',
675
+ # Extensionless build and config files: `Makefile:23: *** missing separator`.
676
+ 'makefile', 'gnumakefile', 'dockerfile', 'containerfile', 'jenkinsfile', 'vagrantfile',
677
+ 'gemfile', 'rakefile', 'procfile', 'justfile', 'podfile',
678
+ })
679
+
680
+
681
+ def _label_repl(match) -> str:
682
+ if match.group('label').lower() in _NOT_HOSTS and not match.group('user'):
683
+ return match.group(0)
684
+ return '<host>'
685
+
686
+
687
+ def _diag_bare_repl(match) -> str:
688
+ host = match.group('host')
689
+ return match.group(0)[:-len(host)] + '<host>'
690
+
691
+
692
+ def _redact_hosts(text: str) -> str:
693
+ text = _sub_outside(text, _URL_AUTH, _url_repl)
694
+ text = _sub_outside(text, _IPV4, '<host>')
695
+ text = _sub_outside(text, _IPV6, '<host>')
696
+ text = _sub_outside(text, _LOCALHOST, '<host>')
697
+ text = _sub_outside(text, _HOST, _host_repl)
698
+ text = _LABEL_DEST.sub(_label_repl, text)
699
+ text = _sub_outside(text, _DIAG_BARE, _diag_bare_repl)
700
+ return _redact_command_hosts(text)
701
+
702
+
703
+ class Redactor:
704
+ """Secrets of one plan. Applied to every draft before it is shown or hashed."""
705
+
706
+ def __init__(self, plan: Path):
707
+ self.prompts = _prompts(plan)
708
+ self.literals = _literals(plan)
709
+
710
+ def __call__(self, text: str) -> str:
711
+ if not text:
712
+ return ''
713
+ text = text.replace('\r\n', '\n').replace('\r', '\n')
714
+ text = _redact_prompts(text, self.prompts)
715
+ text = _redact_paths(text)
716
+ text = _redact_literals(text, self.literals)
717
+ return _redact_hosts(text)
718
+
719
+
720
+ def _names(values) -> str:
721
+ return ', '.join(values) if values else 'none'
722
+
723
+
724
+ def _one_line(text: str) -> str:
725
+ return ' '.join((text or '').split())
726
+
727
+
728
+ def _cap(text: str, limit: int = _TITLE_LIMIT) -> str:
729
+ text = _one_line(text)
730
+ if len(text) <= limit:
731
+ return text
732
+ cut = text[:limit]
733
+ last = cut.rfind('<')
734
+ if last >= 0 and '>' not in cut[last:]:
735
+ cut = cut[:last]
736
+ cut = cut.rstrip()
737
+ return (cut or text[:limit]) + '…'
738
+
739
+
740
+ def _version_os(notes: list) -> tuple:
741
+ versions, systems = [], []
742
+ for note in notes:
743
+ version = note.get('version')
744
+ system = note.get('os')
745
+ if isinstance(version, str) and version.strip() and version.strip() not in versions:
746
+ versions.append(version.strip())
747
+ if isinstance(system, str) and system.strip() and system.strip() not in systems:
748
+ systems.append(system.strip())
749
+ if not versions:
750
+ versions.append(_read(SKILL / 'VERSION').strip() or 'unknown')
751
+ if not systems:
752
+ systems.append(os.uname().sysname)
753
+ return ', '.join(versions), ', '.join(systems)
754
+
755
+
756
+ def _forge_patterns(plan: Path) -> list:
757
+ """(key, pattern, notes) for the forge group, in the report's order.
758
+
759
+ The pattern dict is the one the report builds. Version and OS stay on the notes,
760
+ which the report reads and does not copy onto the pattern.
761
+ """
762
+ document = report.build(plan)
763
+ notes, _malformed = report._load(plan / 'retro' / 'notes.jsonl')
764
+ buckets, order = {}, []
765
+ for note in notes:
766
+ key = report._pattern_key(note)
767
+ if key is None:
768
+ continue
769
+ if key not in buckets:
770
+ order.append(key)
771
+ buckets[key] = []
772
+ buckets[key].append(note)
773
+ earlier = report._earlier_index(report._current_ids(plan))
774
+ found = []
775
+ for key in order:
776
+ group = buckets[key]
777
+ if report._owner(group) != 'forge':
778
+ continue
779
+ pattern = report._pattern(group, document['tasks'], document['models'], earlier, 'forge')
780
+ found.append((key, pattern, group))
781
+ found.sort(key=lambda item: (
782
+ -item[1]['tasks_hit'], item[1]['summary'].lower(), item[1]['type'], item[1]['command'] or ''))
783
+ return found
784
+
785
+
786
+ def _fingerprint(slug: str, key) -> str:
787
+ """The forge-issues fingerprint of this pattern, so a later run recognises the issue."""
788
+ kind, basis, normalised = key
789
+ return _filer().fingerprint(slug, {'file': kind, 'text': '%s %s' % (basis, normalised)})
790
+
791
+
792
+ def _title(pattern: dict, redact) -> str:
793
+ return _cap(redact(_one_line(pattern['summary'] or pattern['type'])))
794
+
795
+
796
+ def _body(pattern: dict, notes: list, fingerprint: str, redact) -> str:
797
+ bits = [pattern['type']]
798
+ if pattern['blocking']:
799
+ bits.append('blocking')
800
+ if pattern['model_specific']:
801
+ bits.append('possibly specific to %s, not forge' % pattern['model_specific'])
802
+ lines = [
803
+ '## What happened', '',
804
+ '. '.join(bits) + '.', '',
805
+ pattern['summary'] or pattern['type'], '',
806
+ '%d of %d tasks, %d earlier runs.' % (
807
+ pattern['tasks_hit'], pattern['tasks'], pattern['earlier_runs']),
808
+ 'Models: %s. Harnesses: %s.' % (_names(pattern['models']), _names(pattern['harnesses'])),
809
+ ]
810
+ lines.extend(report._render_evidence(pattern))
811
+ lines += ['', 'Checks: %d verified, %d claimed.' % (pattern['verified'], pattern['claimed'])]
812
+ # The word "forge" on the version line is ours. Redact the values, then append it,
813
+ # so a repository whose name is forge does not eat the label.
814
+ text = redact('\n'.join(lines) + '\n')
815
+ version, system = _version_os(notes)
816
+ text += 'forge %s on %s.\n' % (redact(version), redact(system))
817
+ text = _filer().escape(text)
818
+ text += '\n<!-- forge:finding fp=%s source=forge:retro -->\n' % fingerprint
819
+ return text
820
+
821
+
822
+ def _drafts(plan: Path, slug: str) -> list:
823
+ redact = Redactor(plan)
824
+ drafts = []
825
+ for number, (key, pattern, notes) in enumerate(_forge_patterns(plan), start=1):
826
+ fingerprint = _fingerprint(slug, key)
827
+ title = _filer().escape(_title(pattern, redact))
828
+ drafts.append({
829
+ 'id': 'r%d' % number,
830
+ 'title': title,
831
+ 'body': _body(pattern, notes, fingerprint, redact),
832
+ 'fingerprint': fingerprint,
833
+ 'related': [],
834
+ 'choice': 'new',
835
+ })
836
+ return drafts
837
+
838
+
839
+ def _parse_choices(values) -> dict:
840
+ found = {}
841
+ for value in values or []:
842
+ match = _CHOICE.fullmatch(value)
843
+ if not match:
844
+ raise Usage('choice must be rN=new, rN=comment:N or rN=skip, not %r' % value)
845
+ found[match.group(1)] = match.group(2)
846
+ return found
847
+
848
+
849
+ def _queries(draft: dict) -> list:
850
+ """Key terms, then the fingerprint on its own.
851
+
852
+ GitHub search ANDs every term. A fingerprint in the same query as the key terms
853
+ hides an issue that shares the words and was not filed by forge. The fingerprint
854
+ query is what finds an issue already filed under a different title.
855
+ """
856
+ words = []
857
+ for word in sorted(_filer().content_words(draft['title'])):
858
+ if word in _QUERY_SKIP or word in words:
859
+ continue
860
+ words.append(word)
861
+ if len(words) == 6:
862
+ break
863
+ queries = [' '.join(words)] if words else []
864
+ if draft['fingerprint'] not in queries:
865
+ queries.append(draft['fingerprint'])
866
+ return queries
867
+
868
+
869
+ def _search(slug: str, query: str, state: str) -> list:
870
+ filer = _filer()
871
+ res = filer.run(
872
+ ['gh', 'search', 'issues', '--repo', slug, '--state', state, '--limit', '20',
873
+ '--json', 'number,title,state,url,body', query], check=False)
874
+ if res.returncode != 0:
875
+ detail = (res.stderr or res.stdout or '').strip()[:400]
876
+ raise filer.Fail('gh search issues failed: %s' % detail)
877
+ try:
878
+ data = json.loads(res.stdout or '[]')
879
+ except ValueError:
880
+ data = None
881
+ if not isinstance(data, list):
882
+ raise filer.Fail('gh search issues returned no JSON')
883
+ found = []
884
+ for item in data:
885
+ if not isinstance(item, dict):
886
+ continue
887
+ number = item.get('number')
888
+ if isinstance(number, bool) or not isinstance(number, int):
889
+ continue
890
+ issue_state = str(item.get('state') or '').lower()
891
+ comments = item.get('comments')
892
+ found.append({
893
+ 'number': number,
894
+ 'state': 'closed' if issue_state == 'closed' else 'open',
895
+ 'title': str(item.get('title') or ''),
896
+ 'url': str(item.get('url') or ''),
897
+ 'body': item.get('body') if isinstance(item.get('body'), str) else '',
898
+ 'comments': comments if isinstance(comments, list) else [],
899
+ })
900
+ return found
901
+
902
+
903
+ def _fill_related(slug: str, drafts: list) -> None:
904
+ threads = {}
905
+ for draft in drafts:
906
+ merged = {}
907
+ for query in _queries(draft):
908
+ for state in ('open', 'closed'):
909
+ for issue in _search(slug, query, state):
910
+ merged[issue['number']] = issue
911
+ related = [merged[number] for number in sorted(merged)]
912
+ fingerprint = draft['fingerprint']
913
+ for issue in related:
914
+ # Search JSON is the issue body. A fingerprint posted with comment:N
915
+ # lives on the comment, so a closed issue still has to be read.
916
+ if issue['state'] != 'closed' or fingerprint in _known_markers(issue):
917
+ continue
918
+ number = issue['number']
919
+ if number not in threads:
920
+ threads[number] = _fetch_issue(slug, number)
921
+ issue['thread'] = threads[number]
922
+ draft['related'] = related
923
+
924
+
925
+ def _marked(body: str) -> set:
926
+ return set(_filer().FP_MARK_RE.findall(body or ''))
927
+
928
+
929
+ def _comment_blob(comments) -> str:
930
+ if not isinstance(comments, list):
931
+ return ''
932
+ parts = []
933
+ for item in comments:
934
+ if isinstance(item, str):
935
+ text = item
936
+ elif isinstance(item, dict) and isinstance(item.get('body'), str):
937
+ text = item['body']
938
+ else:
939
+ continue
940
+ if text.strip():
941
+ parts.append(text)
942
+ return '\n'.join(parts)
943
+
944
+
945
+ def _known_markers(issue: dict) -> set:
946
+ """Markers already on the search result, before a separate issue view."""
947
+ return _marked((issue.get('body') or '') + '\n' + _comment_blob(issue.get('comments')))
948
+
949
+
950
+ def _issue_markers(issue: dict) -> set:
951
+ return _marked('\n'.join([
952
+ issue.get('body') or '',
953
+ _comment_blob(issue.get('comments')),
954
+ issue.get('thread') or '',
955
+ ]))
956
+
957
+
958
+ def _default_choice(draft: dict) -> str:
959
+ """`skip` when a closed issue already carries this fingerprint.
960
+
961
+ The marker may be in the issue body or in a comment left by `comment:N`.
962
+ Closing the issue does not move the comment into the body.
963
+ """
964
+ fingerprint = draft['fingerprint']
965
+ for issue in draft['related']:
966
+ if issue['state'] == 'closed' and fingerprint in _issue_markers(issue):
967
+ return 'skip'
968
+ return 'new'
969
+
970
+
971
+ def _apply_overrides(drafts: list, overrides: dict) -> None:
972
+ known = {draft['id'] for draft in drafts}
973
+ unknown = sorted(key for key in overrides if key not in known)
974
+ if unknown:
975
+ raise Usage('unknown draft %s' % ', '.join(unknown))
976
+ for draft in drafts:
977
+ if draft['id'] in overrides:
978
+ draft['choice'] = overrides[draft['id']]
979
+
980
+
981
+ def _fetch_issue(slug: str, number: str) -> str:
982
+ """The issue body and every comment body.
983
+
984
+ A comment does not change the issue body, so the body alone cannot show that
985
+ this draft was already posted.
986
+ """
987
+ filer = _filer()
988
+ res = filer.run(
989
+ ['gh', 'issue', 'view', str(number), '--repo', slug, '--json', 'body,comments'],
990
+ check=False)
991
+ if res.returncode != 0:
992
+ detail = (res.stderr or res.stdout or '').strip()[:400]
993
+ raise filer.Fail('gh issue view failed: %s' % detail)
994
+ try:
995
+ data = json.loads(res.stdout or '{}')
996
+ except ValueError:
997
+ data = None
998
+ if not isinstance(data, dict):
999
+ raise filer.Fail('gh issue view returned no JSON')
1000
+ parts = []
1001
+ body = data.get('body')
1002
+ if isinstance(body, str) and body.strip():
1003
+ parts.append(body)
1004
+ comments = _comment_blob(data.get('comments'))
1005
+ if comments:
1006
+ parts.append(comments)
1007
+ return '\n'.join(parts)
1008
+
1009
+
1010
+ def _adds(draft: dict, existing: str) -> bool:
1011
+ """False when this draft's text is already on the issue or one of its comments.
1012
+
1013
+ The fingerprint follows the command, not the error. A later run can carry the
1014
+ same marker and a new error, and that comment still adds something. The marker
1015
+ alone is not "already posted".
1016
+ """
1017
+ if not existing or not existing.strip():
1018
+ return True
1019
+ core = draft['body']
1020
+ marker = '<!-- forge:finding fp=%s' % draft['fingerprint']
1021
+ at = core.find(marker)
1022
+ if at >= 0:
1023
+ core = core[:at]
1024
+ core = core.strip()
1025
+ return bool(core) and core not in existing
1026
+
1027
+
1028
+ def _hash(drafts: list) -> str:
1029
+ """sha256 of every draft text and the choice that would be posted for it."""
1030
+ chunks = []
1031
+ for draft in drafts:
1032
+ chunks.append(draft['id'])
1033
+ chunks.append(draft['choice'])
1034
+ chunks.append(draft['title'])
1035
+ chunks.append(draft['body'])
1036
+ return hashlib.sha256('\n'.join(chunks).encode('utf-8')).hexdigest()
1037
+
1038
+
1039
+ def _public(draft: dict) -> dict:
1040
+ return {
1041
+ 'id': draft['id'],
1042
+ 'title': draft['title'],
1043
+ 'body': draft['body'],
1044
+ 'choice': draft['choice'],
1045
+ 'fingerprint': draft['fingerprint'],
1046
+ 'related': [
1047
+ {'number': issue['number'], 'state': issue['state'], 'title': issue['title'],
1048
+ 'url': issue['url']}
1049
+ for issue in draft['related']
1050
+ ],
1051
+ }
1052
+
1053
+
1054
+ def _render(slug: str, drafts: list, approve: str, posted=None, as_json=False) -> str:
1055
+ if as_json:
1056
+ payload = {'approve': approve, 'repo': slug, 'drafts': [_public(draft) for draft in drafts]}
1057
+ if posted is not None:
1058
+ payload['posted'] = posted
1059
+ return json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
1060
+ lines = ['repo: %s' % slug, '']
1061
+ if posted is not None:
1062
+ for item in posted:
1063
+ if item.get('url'):
1064
+ lines.append('posted %s %s %s' % (item['id'], item['choice'], item['url']))
1065
+ elif item.get('skipped'):
1066
+ lines.append('skipped %s %s %s' % (item['id'], item['choice'], item['skipped']))
1067
+ elif item.get('issue'):
1068
+ lines.append('posted %s %s #%s' % (item['id'], item['choice'], item['issue']))
1069
+ else:
1070
+ lines.append('skipped %s %s' % (item['id'], item['choice']))
1071
+ lines.append('approve: %s' % approve)
1072
+ return '\n'.join(lines) + '\n'
1073
+ for draft in drafts:
1074
+ lines.append(draft['id'])
1075
+ lines.append('choice: %s' % draft['choice'])
1076
+ lines.append('related:')
1077
+ if draft['related']:
1078
+ for issue in draft['related']:
1079
+ lines.append(' #%s %s - %s' % (issue['number'], issue['state'], issue['title']))
1080
+ else:
1081
+ lines.append(' none')
1082
+ lines.append('title:')
1083
+ lines.append(draft['title'])
1084
+ lines.append('body:')
1085
+ lines.append(draft['body'].rstrip('\n'))
1086
+ lines.append('')
1087
+ lines.append('approve: %s' % approve)
1088
+ return '\n'.join(lines) + '\n'
1089
+
1090
+
1091
+ def _send(slug: str, draft: dict) -> dict:
1092
+ filer = _filer()
1093
+ choice = draft['choice']
1094
+ with tempfile.NamedTemporaryFile('w', suffix='.md', delete=False, encoding='utf-8') as handle:
1095
+ handle.write(draft['body'])
1096
+ path = handle.name
1097
+ try:
1098
+ if choice == 'new':
1099
+ res = filer.run(['gh', 'issue', 'create', '--repo', slug, '--title', draft['title'],
1100
+ '--body-file', path])
1101
+ url = next((word for word in res.stdout.split() if word.startswith('https://')),
1102
+ res.stdout.strip())
1103
+ return {'id': draft['id'], 'choice': 'new', 'url': url}
1104
+ number = choice.split(':', 1)[1]
1105
+ filer.run(['gh', 'issue', 'comment', number, '--repo', slug, '--body-file', path])
1106
+ return {'id': draft['id'], 'choice': choice, 'issue': int(number)}
1107
+ finally:
1108
+ os.unlink(path)
1109
+
1110
+
1111
+ def _post(slug: str, drafts: list) -> list:
1112
+ posted = []
1113
+ for draft in drafts:
1114
+ choice = draft['choice']
1115
+ if choice == 'skip':
1116
+ posted.append({'id': draft['id'], 'choice': 'skip'})
1117
+ continue
1118
+ if choice.startswith('comment:'):
1119
+ number = choice.split(':', 1)[1]
1120
+ if not _adds(draft, _fetch_issue(slug, number)):
1121
+ posted.append({'id': draft['id'], 'choice': choice, 'skipped': 'adds nothing'})
1122
+ continue
1123
+ posted.append(_send(slug, draft))
1124
+ return posted
1125
+
1126
+
1127
+ def execute(args) -> int:
1128
+ plan = Path(args.plan)
1129
+ if not plan.is_dir():
1130
+ _warn('forge retro: not a plan dir: %s' % plan)
1131
+ return 3
1132
+ try:
1133
+ overrides = _parse_choices(args.choice)
1134
+ slug = forge_slug()
1135
+ except Usage as error:
1136
+ _warn('forge retro: %s' % error)
1137
+ return 2
1138
+ repo = _repo_path(plan)
1139
+ # Before any gh call, including auth. A never-send repo posts nothing.
1140
+ if repo and privacy_floor(repo):
1141
+ _warn('forge retro: the repository is never-send; nothing was posted')
1142
+ return 3
1143
+ try:
1144
+ drafts = _drafts(plan, slug)
1145
+ _apply_overrides(drafts, overrides)
1146
+ except Usage as error:
1147
+ _warn('forge retro: %s' % error)
1148
+ return 2
1149
+ except FileNotFoundError as error:
1150
+ _warn('forge retro: not a plan dir: %s' % error)
1151
+ return 3
1152
+ filer = _filer()
1153
+ gh_error = None
1154
+ try:
1155
+ filer.run(['gh', 'auth', 'status'])
1156
+ _fill_related(slug, drafts)
1157
+ except filer.Fail as error:
1158
+ gh_error = error
1159
+ for draft in drafts:
1160
+ draft['related'] = []
1161
+ for draft in drafts:
1162
+ if gh_error is None:
1163
+ draft['choice'] = _default_choice(draft)
1164
+ else:
1165
+ draft['choice'] = 'new'
1166
+ try:
1167
+ _apply_overrides(drafts, overrides)
1168
+ except Usage as error:
1169
+ _warn('forge retro: %s' % error)
1170
+ return 2
1171
+ approve = _hash(drafts)
1172
+ as_json = args.as_json
1173
+ if gh_error is not None:
1174
+ _emit(_render(slug, drafts, approve, as_json=as_json))
1175
+ _warn('forge retro: %s' % gh_error)
1176
+ _warn('forge retro: nothing was posted')
1177
+ return 3
1178
+ if not args.apply:
1179
+ _emit(_render(slug, drafts, approve, as_json=as_json))
1180
+ return 0
1181
+ given = (args.approve or '').strip().lower()
1182
+ if given != approve:
1183
+ _emit(_render(slug, drafts, approve, as_json=as_json))
1184
+ _warn('forge retro: approval hash mismatch')
1185
+ return 3
1186
+ try:
1187
+ posted = _post(slug, drafts)
1188
+ except filer.Fail as error:
1189
+ _warn('forge retro: %s' % error)
1190
+ _warn('forge retro: nothing further was posted')
1191
+ return 3
1192
+ _emit(_render(slug, drafts, approve, posted=posted, as_json=as_json))
1193
+ return 0