@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
@@ -655,7 +655,27 @@ def _rollback(plan: Path, original: bytes, moved: list, made_pre: bool, replaced
655
655
  pre.rmdir()
656
656
 
657
657
 
658
- def commit_collapse(plan: Path, original: bytes, rows: list, row: dict, prompt: str, approach, info: dict) -> None:
658
+ RISK_RANK = {'low': 0, 'medium': 1, 'high': 2}
659
+
660
+
661
+ def read_risk(path: Path):
662
+ """A task's recorded risk (#122): the first word of tasks/<id>/risk when it is low, medium or high, else None."""
663
+ try:
664
+ words = (_read_task_file(path) or '').split()
665
+ except PlanShapeError: # a label nothing routes on never stops a collapse
666
+ return None
667
+ return words[0] if words and words[0] in RISK_RANK else None
668
+
669
+
670
+ def combined_risk(risks: list):
671
+ """The highest risk of the parts when every part was rated, else None: an unrated part could be the riskiest."""
672
+ if not risks or any(risk is None for risk in risks):
673
+ return None
674
+ return max(risks, key=RISK_RANK.get)
675
+
676
+
677
+ def commit_collapse(plan: Path, original: bytes, rows: list, row: dict, prompt: str, approach, info: dict,
678
+ risk=None) -> None:
659
679
  """Move the chain aside and write the combined task. A failure restores the plan."""
660
680
  moved, made_pre, replaced, made_combined = [], False, False, False
661
681
  try:
@@ -676,6 +696,8 @@ def commit_collapse(plan: Path, original: bytes, rows: list, row: dict, prompt:
676
696
  _atomic_write(combined / 'prompt.md', prompt)
677
697
  if approach is not None:
678
698
  _atomic_write(combined / 'approach.md', approach)
699
+ if risk is not None:
700
+ _atomic_write(combined / 'risk', risk + '\n')
679
701
  ids = [task['id'] for task in _parts_in_wave_order(rows)]
680
702
  _atomic_write(plan / COLLAPSED_JSON, _collapsed_text(ids, info))
681
703
  except Exception as err:
@@ -728,7 +750,8 @@ def command_collapse(plan: Path) -> int:
728
750
  if approach is not None:
729
751
  approaches[row['id']] = approach
730
752
  combined, prompt, approach = collapse_rows(rows, prompts, approaches)
731
- commit_collapse(plan, original, rows, combined, prompt, approach, info)
753
+ risk = combined_risk([read_risk(plan / 'tasks' / row['id'] / 'risk') for row in rows])
754
+ commit_collapse(plan, original, rows, combined, prompt, approach, info, risk)
732
755
  except PlanShapeError as err:
733
756
  print('forge-plan-check: %s' % err, file=sys.stderr)
734
757
  return 2
@@ -8,7 +8,8 @@ gate and the one-task plan. Standard library only; no shell wiring.
8
8
 
9
9
  forge-planner.py parse --plan P --reply FILE
10
10
  Turns the planner's reply into P/tasks.tsv, P/tasks/<id>/prompt.md and, when it is not
11
- empty, P/tasks/<id>/approach.md. It never guesses or repairs: a reply that breaks one
11
+ empty, P/tasks/<id>/approach.md; a task's `risk` (#122) goes to P/tasks/<id>/risk, and a
12
+ missing or unknown one writes nothing. It never guesses or repairs: a reply that breaks one
12
13
  rule writes nothing but P/planner.refused (the first reason and the reply's path), prints
13
14
  both and exits 4. P/request.md must hold the user's request (exit 2 when it is missing);
14
15
  it is attached to every task prompt so no requirement is lost.
@@ -43,7 +44,11 @@ MAX_REQUIREMENTS = 6
43
44
 
44
45
  MAX_TASKS = 20
45
46
  TASK_KEYS = ('id', 'deps', 'difficulty', 'files', 'title', 'approach', 'prompt')
47
+ # #122: a task's risk, recorded in shadow beside its difficulty. Optional, and the one key that never refuses a
48
+ # reply: a missing or unknown value records nothing, because a label nothing routes on must not cost a plan.
49
+ OPTIONAL_KEYS = ('risk',)
46
50
  DIFFICULTIES = ('low', 'medium', 'high')
51
+ RISKS = ('low', 'medium', 'high')
47
52
  LEVELS = DIFFICULTIES
48
53
  ID_RE = re.compile(r'[a-z0-9][a-z0-9-]{0,39}')
49
54
  ACCEPTANCE_RE = re.compile(r'## Acceptance criteria[ \t]*:?[ \t]*')
@@ -75,7 +80,7 @@ worktree of its own, and a reviewer judges each task against its prompt."""
75
80
  EXAMPLE = """\
76
81
  ```forge-plan
77
82
  {"tasks": [
78
- {"id": "parse-config", "deps": [], "difficulty": "medium",
83
+ {"id": "parse-config", "deps": [], "difficulty": "medium", "risk": "low",
79
84
  "files": ["src/config.py", "tests/test_config.py"],
80
85
  "title": "Parse the new config section",
81
86
  "approach": "Add parse_section() beside load(); keep load()'s signature.",
@@ -153,6 +158,12 @@ def build_prompt(request: str, level: str | None) -> str:
153
158
  'judgment, touches cross-cutting behaviour, has subtle edge cases or state or concurrency, or '
154
159
  'the right approach is not obvious from the request. A five-hundred-line mechanical rename is '
155
160
  '`low`; a ten-line concurrency fix is `high`.',
161
+ 'Rate `risk` apart from difficulty, by what a mistake that gets through would cost: what breaks, for '
162
+ 'whom, and how hard it is to undo. `low`: local and easy to see and revert (docs, a test, an internal '
163
+ 'helper). `medium`: wrong behaviour users would notice, undone by a revert. `high`: hard to undo or '
164
+ 'reaching everyone: release and CI files, migrations and persisted data, auth and permissions, public '
165
+ 'APIs. A one-line change to a release script is low difficulty and high risk. The rating is recorded '
166
+ 'only; it changes no model or reviewer.',
156
167
  '**Each task\'s `prompt`** carries the whole requirement it owns, written so that someone who '
157
168
  'sees only that prompt can do it, and ends with a `## Acceptance criteria` section of checks '
158
169
  'a reviewer can verify (a behaviour, a command that passes, a file that exists), not restated '
@@ -190,6 +201,7 @@ these keys and no others:
190
201
  - `id`: lowercase slug matching `^[a-z0-9][a-z0-9-]{{0,39}}$`, unique in the plan;
191
202
  - `deps`: list of ids of tasks that must land first (`[]` for none), no cycles;
192
203
  - `difficulty`: `low`, `medium` or `high`;
204
+ - `risk`: `low`, `medium` or `high`, as the rules above define it;
193
205
  - `files`: non-empty list of repo-relative paths the task creates or edits (no absolute path, no
194
206
  `..`, no tab, comma or newline in a path);
195
207
  - `title`: one line without a tab;
@@ -237,11 +249,11 @@ def no_duplicate_keys(pairs):
237
249
  return dict(pairs)
238
250
 
239
251
 
240
- def check_keys(obj, expected, where: str):
252
+ def check_keys(obj, expected, where: str, optional=()):
241
253
  if not isinstance(obj, dict):
242
254
  raise Refusal(f'{where} is not a JSON object')
243
255
  missing = [k for k in expected if k not in obj]
244
- extra = [k for k in obj if k not in expected]
256
+ extra = [k for k in obj if k not in expected and k not in optional]
245
257
  if missing or extra:
246
258
  parts = []
247
259
  if missing:
@@ -290,7 +302,7 @@ def check_path(path, where: str):
290
302
 
291
303
  def check_task(task, index: int, seen: set) -> dict:
292
304
  where = f'task {index + 1}'
293
- check_keys(task, TASK_KEYS, where)
305
+ check_keys(task, TASK_KEYS, where, OPTIONAL_KEYS)
294
306
  tid = task['id']
295
307
  if not isinstance(tid, str) or not ID_RE.fullmatch(tid):
296
308
  raise Refusal(f'{where}: id {tid!r} does not match ^[a-z0-9][a-z0-9-]{{0,39}}$')
@@ -323,7 +335,8 @@ def check_task(task, index: int, seen: set) -> dict:
323
335
  check_text(prompt, where)
324
336
  if not has_acceptance_heading(prompt):
325
337
  raise Refusal(f'{where}: prompt has no "## Acceptance criteria" heading')
326
- return task
338
+ risk = task.get('risk')
339
+ return dict(task, risk=risk if isinstance(risk, str) and risk in RISKS else None)
327
340
 
328
341
 
329
342
  def check_graph(tasks: list):
@@ -397,6 +410,7 @@ def cmd_parse(args) -> int:
397
410
  text = t['prompt'].rstrip('\n') + f'\n\n{WHOLE_REQUEST}\n\n' + request
398
411
  outputs.append((folder / 'prompt.md', text.encode('utf-8')))
399
412
  outputs.append((folder / 'approach.md', t['approach'].encode('utf-8') if t['approach'].strip() else None))
413
+ outputs.append((folder / 'risk', (t['risk'] + '\n').encode('utf-8') if t['risk'] else None))
400
414
  outputs.append((plan / 'tasks.tsv', ('\n'.join(rows) + '\n').encode('utf-8')))
401
415
  for path, data in outputs:
402
416
  if data is None:
@@ -3,10 +3,15 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
+ import json
6
7
  from pathlib import Path
7
8
 
8
9
  DIFF_INLINE_CAP = 100 * 1024
9
10
  REPLY_CAP = 8 * 1024
11
+ # A brief answer, and each brief section, stay small enough to leave the task itself
12
+ # in the prompt. The cut matches the reply cap: keep the leading bytes, then a marker.
13
+ ANSWER_CAP = 4 * 1024
14
+ BRIEF_CHUNK_CAP = 16 * 1024
10
15
 
11
16
  # What a reviewer is asked to do with the previous round's report. The labelled-line rule
12
17
  # matters: the severity gate, `forge issues` and forge-ui count every `- [Px][...]` line as open.
@@ -72,6 +77,119 @@ def qa_round(findings: str, diff: str | None, span: str | None, stat: str | None
72
77
  return '\n\n'.join(parts) + '\n'
73
78
 
74
79
 
80
+ # Brief is opt-in. `<plan>/brief` names the level and `<plan>/tasks/<id>/brief.json` holds
81
+ # the questions. Answers given before the task starts live in `brief.answers.json`.
82
+ # `brief.late.json` is written after the start and is never read here. No level file, no
83
+ # brief.json, or no questions: nothing is added, and the prompt stays byte-identical.
84
+ DECISIONS_TITLE = 'Decisions the user made'
85
+ OPEN_TITLE = 'Open questions: follow the stated default'
86
+ DECISIONS_NOTE = (
87
+ 'Treat these as constraints that override anything in the requirements or approach '
88
+ 'they contradict.'
89
+ )
90
+ DECISIONS_QA = (
91
+ "These are the user's own decisions, so following them is not a deviation and must "
92
+ 'not be reported as a finding.'
93
+ )
94
+ OPEN_NOTE = (
95
+ 'Follow the default for each question below, and say in the final message which '
96
+ 'defaults were used.'
97
+ )
98
+ OPEN_QA = (
99
+ 'These are the defaults the implementer was told to follow. The implementer was told '
100
+ 'to say in the final message which defaults were used.'
101
+ )
102
+ OPEN_LEVELS = ('advisory', 'gated')
103
+
104
+
105
+ def clip(text: str, limit: int, marker: str) -> str:
106
+ """Keep the leading bytes. A cut keeps the marker, as a long reply does."""
107
+ raw = text.encode()
108
+ if len(raw) <= limit:
109
+ return text
110
+ return raw[:limit].decode(errors='ignore') + marker
111
+
112
+
113
+ def load_json(path: Path):
114
+ if not path.is_file():
115
+ return None
116
+ try:
117
+ return json.loads(path.read_text(encoding='utf-8'))
118
+ except (OSError, UnicodeError, json.JSONDecodeError):
119
+ return None
120
+
121
+
122
+ def task_dir_of(requirements: str | None, approach: str | None) -> Path | None:
123
+ """`<plan>/tasks/<id>`, from the prompt.md or approach.md path callers already pass.
124
+
125
+ A solo run and a fixture that is not that shape have no plan brief, so they get nothing.
126
+ """
127
+ found = None
128
+ for path in (requirements, approach):
129
+ if not path:
130
+ continue
131
+ candidate = Path(path)
132
+ if candidate.name not in ('prompt.md', 'approach.md'):
133
+ continue
134
+ # candidate = <plan>/tasks/<id>/<file>
135
+ if candidate.parent.parent.name != 'tasks':
136
+ continue
137
+ if candidate.name == 'prompt.md':
138
+ return candidate.parent
139
+ found = candidate.parent
140
+ return found
141
+
142
+
143
+ def brief_rows(questions: list, answers: dict) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:
144
+ decided, pending = [], []
145
+ for question in questions:
146
+ if not isinstance(question, dict):
147
+ continue
148
+ qid, text = question.get('id'), question.get('text')
149
+ if not isinstance(qid, str) or not qid or not isinstance(text, str) or not text.strip():
150
+ continue
151
+ entry = answers.get(qid)
152
+ answer = entry.get('text') if isinstance(entry, dict) else None
153
+ if isinstance(answer, str):
154
+ decided.append((text.strip(), clip(answer, ANSWER_CAP,
155
+ '\n[... the answer continues; cut here ...]')))
156
+ else:
157
+ default = question.get('default')
158
+ pending.append((text.strip(), default if isinstance(default, str) else ''))
159
+ return decided, pending
160
+
161
+
162
+ def brief_section(title: str, note: str, rows: list[tuple[str, str]], label: str) -> str:
163
+ items = '\n\n'.join('- ' + text + '\n ' + label + ': ' + value for text, value in rows)
164
+ # Trailing newline matches the other sections, whose source files end with one.
165
+ body = '## ' + title + '\n' + note + '\n\n' + items + '\n'
166
+ return clip(body, BRIEF_CHUNK_CAP, '\n[... the brief continues; cut here ...]\n')
167
+
168
+
169
+ def brief_chunks(requirements: str | None, approach: str | None, role: str) -> list[str]:
170
+ task = task_dir_of(requirements, approach)
171
+ if task is None:
172
+ return []
173
+ plan = task.parent.parent
174
+ if not (plan / 'brief').is_file() or not (task / 'brief.json').is_file():
175
+ return []
176
+ spec = load_json(task / 'brief.json')
177
+ questions = spec.get('questions') if isinstance(spec, dict) else None
178
+ if not isinstance(questions, list) or not questions:
179
+ return []
180
+ answers = load_json(task / 'brief.answers.json')
181
+ decided, pending = brief_rows(questions, answers if isinstance(answers, dict) else {})
182
+ chunks = []
183
+ if decided:
184
+ note = DECISIONS_NOTE + (' ' + DECISIONS_QA if role == 'qa' else '')
185
+ chunks.append(brief_section(DECISIONS_TITLE, note, decided, 'Answer'))
186
+ # strict has no open questions: run refuses to start until every one is answered.
187
+ if pending and read(str(plan / 'brief')).strip() in OPEN_LEVELS:
188
+ note = OPEN_QA if role == 'qa' else OPEN_NOTE
189
+ chunks.append(brief_section(OPEN_TITLE, note, pending, 'Default'))
190
+ return chunks
191
+
192
+
75
193
  def context(
76
194
  requirements: str, approach: str | None = None, capsule: str | None = None,
77
195
  retry: str | None = None, goal: str | None = None, memories: tuple[str, ...] = (),
@@ -85,6 +203,8 @@ def context(
85
203
  ('Complete implementation requirements', requirements),
86
204
  ('Intended approach', approach),
87
205
  (RETRY_HEADINGS[retry_source], retry)]:
206
+ if title == RETRY_HEADINGS[retry_source]:
207
+ chunks.extend(brief_chunks(requirements, approach, role))
88
208
  data = read(path) if path and Path(path).is_file() else ''
89
209
  if data:
90
210
  if role == 'qa' and path == retry:
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env python3
2
+ """Retro notes for one plan.
3
+
4
+ record PLAN --role ROLE --dir DISPATCH [--task ID] [--attempt N] [--inbox PATH]
5
+ Parse the dispatch's FORGE_RETRO lines (and, for a dwarf, its inbox), check them
6
+ against the log, and store them.
7
+ note PLAN --type T --fixable-by F --summary S [--command C --exit N --error E]
8
+ [--blocking] [--tried TEXT]
9
+ Record one orchestrator note. It is always claimed.
10
+ report PLAN [--json]
11
+ Write PLAN/retro.md from the stored notes and print its path. --json prints the
12
+ structure instead of the path.
13
+ issues PLAN [--json] [--choice rN=new|comment:N|skip ...] [--apply --approve HASH]
14
+ Draft one redacted issue per forge-group pattern for forge's own repository.
15
+ The dry run prints the text and posts nothing. --apply posts only when HASH is
16
+ the sha256 of those drafts and choices.
17
+
18
+ Exit codes: 0 stored, reported, drafted or posted, 2 usage, 3 PLAN is not a directory,
19
+ never-send, gh is missing or unauthenticated, or the approval hash does not match.
20
+ `record` and `note` print each stored note as one JSON line.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
30
+ import forge_retro # noqa: E402
31
+ import forge_retro.issues as retro_issues # noqa: E402
32
+ import forge_retro.report as retro_report # noqa: E402
33
+
34
+
35
+ def _parser() -> argparse.ArgumentParser:
36
+ parser = argparse.ArgumentParser(
37
+ prog='forge retro',
38
+ description='Notes on what got in a run\'s way. Kept on this machine, never in a prompt.')
39
+ sub = parser.add_subparsers(dest='command', required=True)
40
+ record = sub.add_parser('record', help='parse a dispatch and store its retro notes')
41
+ record.add_argument('plan', help='the plan directory')
42
+ record.add_argument('--role', required=True, help='the dispatch role, e.g. dwarf or qa')
43
+ record.add_argument('--dir', required=True, dest='dispatch_dir',
44
+ help='the directory that holds <role>.last and <role>.log')
45
+ record.add_argument('--task', help='task id; also writes tasks/<id>/retro.json')
46
+ record.add_argument('--attempt', type=int, help='the attempt number')
47
+ record.add_argument('--inbox', help="the dwarf worktree's .forge/retro-inbox.jsonl")
48
+ note = sub.add_parser('note', help='record an orchestrator note (always claimed)')
49
+ note.add_argument('plan', help='the plan directory')
50
+ note.add_argument('--type', required=True, choices=forge_retro.TYPES)
51
+ note.add_argument('--fixable-by', required=True, dest='fixable_by', choices=forge_retro.FIXABLE)
52
+ note.add_argument('--summary', required=True)
53
+ note.add_argument('--command', dest='command_text', help='the command that failed')
54
+ note.add_argument('--exit', dest='exit_code', type=int, help='that command\'s exit code')
55
+ note.add_argument('--error', help='the error text, kept up to 2 KB')
56
+ note.add_argument('--blocking', action='store_true', help='the run could not finish without this')
57
+ note.add_argument('--tried', help='what was tried before giving up')
58
+ report = sub.add_parser('report', help='write retro.md from the stored notes')
59
+ report.add_argument('plan', help='the plan directory')
60
+ report.add_argument('--json', action='store_true', dest='as_json',
61
+ help='print the report structure instead of the path')
62
+ issues = sub.add_parser('issues', help='draft redacted issues for forge\'s own repository')
63
+ issues.add_argument('plan', help='the plan directory')
64
+ issues.add_argument('--json', action='store_true', dest='as_json',
65
+ help='print the drafts as JSON')
66
+ issues.add_argument('--choice', action='append', default=[],
67
+ help='rN=new, rN=comment:N or rN=skip; repeatable')
68
+ issues.add_argument('--apply', action='store_true',
69
+ help='post the chosen drafts; requires a matching --approve hash')
70
+ issues.add_argument('--approve', help='sha256 of the draft texts and choices to post')
71
+ return parser
72
+
73
+
74
+ def _emit(notes: list) -> None:
75
+ if not notes:
76
+ return
77
+ blob = ''.join(json.dumps(note, ensure_ascii=False, sort_keys=True) + '\n' for note in notes)
78
+ sys.stdout.buffer.write(blob.encode('utf-8'))
79
+ sys.stdout.buffer.flush()
80
+
81
+
82
+ def _report(args) -> int:
83
+ document, path = retro_report.write(args.plan)
84
+ if args.as_json:
85
+ text = json.dumps(document, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
86
+ else:
87
+ text = str(path) + '\n'
88
+ sys.stdout.write(text)
89
+ sys.stdout.flush()
90
+ return 0
91
+
92
+
93
+ def main(argv=None) -> int:
94
+ args = _parser().parse_args(argv)
95
+ try:
96
+ if args.command == 'report':
97
+ return _report(args)
98
+ if args.command == 'issues':
99
+ return retro_issues.execute(args)
100
+ if args.command == 'record':
101
+ notes = forge_retro.record(args.plan, args.role, args.dispatch_dir, task=args.task,
102
+ attempt=args.attempt, inbox=args.inbox)
103
+ else:
104
+ notes = forge_retro.note(args.plan, type=args.type, fixable_by=args.fixable_by,
105
+ summary=args.summary, command=args.command_text, exit=args.exit_code,
106
+ error=args.error, blocking=args.blocking, tried=args.tried)
107
+ except FileNotFoundError as error:
108
+ sys.stderr.write('forge retro: not a plan dir: %s\n' % error)
109
+ return 3
110
+ _emit(notes)
111
+ return 0
112
+
113
+
114
+ if __name__ == '__main__':
115
+ sys.exit(main())