@giamme/forge 0.18.0 → 0.20.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 (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -3,7 +3,7 @@
3
3
 
4
4
  Subcommands, stdlib only, no network:
5
5
 
6
- qa --part head|tail [--kind task|final|solo|sweep] [--threshold P0|P1|P2|P3|none]
6
+ qa --part head|tail [--kind task|final|solo|sweep|adopt|group|script] [--threshold P0|P1|P2|P3|none]
7
7
  Prints one piece of the QA prompt. The caller prints everything between and
8
8
  after the pieces itself (scope notes, the diff fence, the memory note and the
9
9
  "Place any learning notes before the final FORGE_VERDICT ..." sentence).
@@ -17,6 +17,13 @@ Subcommands, stdlib only, no network:
17
17
  Prints ONE tab-separated line
18
18
  decision <TAB> worst_confirmed <TAB> n_confirmed <TAB> n_unlabelled <TAB> n_below
19
19
  and, when findings were tolerated, writes them to OUT.
20
+ outside --qa-last FILE [--threshold Pn|none]
21
+ Prints a JSON list, one object per parsed finding: n (1-based), severity (P0-P3
22
+ or null), status, blocking (the gate's per-finding rule at the threshold) and
23
+ outside (the paths of that finding's last {outside=…} brace).
24
+ blocked --message FILE
25
+ Prints a JSON list of {"path", "why"} from every FORGE_BLOCKED line. The why may
26
+ be empty. A repeated path keeps the first line.
20
27
 
21
28
  Severity. Reviewers label every finding P0 (data loss, security hole, crash or wrong
22
29
  result on the main path), P1 (wrong behaviour on realistic input, breaks an existing
@@ -60,11 +67,14 @@ line (`[P2]`, `(P2)`, `**P2**`, `P2:`, `P2 -` or a standalone `P2`; uppercase on
60
67
  Facts (#119). A finding may end its first line (or, wrapped, its last) with
61
68
  `{reach=main|realistic|unusual origin=new|existing evidence=ran|traced|suspected}`. They are
62
69
  recorded in shadow and decide nothing: the gate never reads them, and `split_facts` cuts the
63
- suffix for readers that show the line. A missing or malformed suffix changes nothing.
70
+ suffix for readers that show the line. A missing or malformed suffix changes nothing. A group
71
+ review may put `{tasks=…}` on that same line; the facts are still read when that brace follows
72
+ them, and still when the facts brace is what closes the line. `{outside=…}` is cut the same
73
+ way, on its own or beside `{tasks=…}`, in either order.
64
74
 
65
75
  Phantom findings. A reviewer may echo the contract it was given. Three layers keep that
66
- from creating findings or blocking: (1) FORGE_VERDICT, FORGE_LEARNING, FORGE_TESTS and FORGE_RETRO text is removed
67
- before parsing (the verdict line itself says "CONFIRMED"); (2) any line that is a
76
+ from creating findings or blocking: (1) FORGE_VERDICT, FORGE_LEARNING, FORGE_TESTS, FORGE_RETRO and
77
+ FORGE_BLOCKED text is removed before parsing (the verdict line itself says "CONFIRMED"); (2) any line that is a
68
78
  contiguous fragment of this module's own contract text (all parts, kinds and thresholds,
69
79
  whitespace-collapsed, at least 25 characters, list marker ignored) is removed, which
70
80
  covers the example bullet, the severity definitions and the instructions even when
@@ -72,7 +82,7 @@ re-wrapped; (3) a block whose first line holds the literal placeholder
72
82
  `path/file.py:123` is ignored. A leftover false match can only add a finding or a
73
83
  blocker, and an added CONFIRMED finding without a label blocks.
74
84
 
75
- Exit codes: 0 ok (even for `keep`), 2 usage, 3 unreadable QA file or unwritable OUT
85
+ Exit codes: 0 ok (even for `keep`), 2 usage, 3 unreadable input file or unwritable OUT
76
86
  file. On any nonzero exit callers must treat the decision as `keep`.
77
87
  """
78
88
  from __future__ import annotations
@@ -80,13 +90,14 @@ from __future__ import annotations
80
90
  import argparse
81
91
  import collections
82
92
  import functools
93
+ import json
83
94
  import os
84
95
  import re
85
96
  import sys
86
97
 
87
98
  SEVERITIES = ('P0', 'P1', 'P2', 'P3')
88
99
  PLACEHOLDER = 'path/file.py:123'
89
- KINDS = ('task', 'final', 'solo', 'sweep', 'adopt')
100
+ KINDS = ('task', 'final', 'solo', 'sweep', 'adopt', 'group', 'script')
90
101
  DEFAULT_THRESHOLD = 'P2'
91
102
  QA_TEST_MINUTES = 5 # the reviewer's own test time, beyond which it says the check is too broad (#89)
92
103
 
@@ -158,13 +169,29 @@ _HEAD = {
158
169
  ],
159
170
  }
160
171
 
172
+ # A scripted task (#142): its diff is what tasks/<id>/run produced; the reviewer judges the command
173
+ # and its result. Same tail as `task`.
174
+ _HEAD['script'] = _HEAD['task'] + [
175
+ 'This diff was produced by the command below, not written by hand. Check the command and its',
176
+ 'result: is the result complete and correct for the requirements, and did the command do only',
177
+ 'what it should? When the change is mechanical you need not read every changed file; sample it,',
178
+ 'and say what you sampled.',
179
+ ]
180
+ # Group review (#140) is the task contract plus one review over several tasks. The shared
181
+ # preamble stays the task one, so a change to it reaches group; these lines are the addition.
182
+ _HEAD['group'] = _HEAD['task'] + [
183
+ 'This review covers several tasks, listed with their own requirements and acceptance',
184
+ 'criteria. Judge each task against its own criteria, and judge the combined change',
185
+ 'as a whole, including how the tasks fit together.',
186
+ ]
187
+
161
188
  _FINDINGS = [
162
189
  'Report findings only — do not edit any file. For each finding give the file and line,',
163
190
  'what breaks, and a concrete input that triggers it. Mark each CONFIRMED if you traced',
164
191
  'it in the code, or PLAUSIBLE if you could not fully verify it.',
165
192
  ]
166
193
  # #69: task reviews returned a few findings per round. These two lines follow _FINDINGS for
167
- # task and solo only, so the findings rules stay one paragraph. Final and sweep omit them.
194
+ # task, solo, adopt and group, so the findings rules stay one paragraph. Final and sweep omit them.
168
195
  _ALL_CONFIRMED = ['List every CONFIRMED finding you find, not only the most important few.']
169
196
  _SOLO_EXTRA = ['If the diff is correct, say so plainly rather than inventing something to report.']
170
197
 
@@ -210,6 +237,36 @@ _SEVERITY = [
210
237
  FACTS = {'reach': ('main', 'realistic', 'unusual'), 'origin': ('new', 'existing'),
211
238
  'evidence': ('ran', 'traced', 'suspected')}
212
239
 
240
+ # Group review (#140) attributes each finding to a member. The facts brace above is a different
241
+ # tag and may sit on the same bullet; `{tasks=…}` has to be its own brace or the two are confused.
242
+ # The facts brace still closes the line (`split_facts` reads a group that ends it). `{tasks=…}`
243
+ # sits immediately before that brace. A tasks brace written after the facts is still parsed, so a
244
+ # reviewer who ends on `{tasks=…}` does not drop the shadow measurement, but the prompt names one order.
245
+ _GROUP_ATTRIB = [
246
+ 'Attribute each finding to the task whose diff changed the file it names.',
247
+ 'When a finding is about a different task than the file suggests, or it spans',
248
+ 'several tasks, end its bullet with {tasks=a,b}, the ids of the tasks that must',
249
+ 'change. A finding with no file needs {tasks=…}.',
250
+ 'The {reach=… origin=… evidence=…} facts may sit on the same bullet. They are not',
251
+ 'the tasks tag. Write {tasks=…} in its own braces, immediately before the facts',
252
+ 'brace, so the facts brace still ends the line:',
253
+ ' - [P1][CONFIRMED] path/file.py:123 — {tasks=a,b} {reach=realistic origin=new evidence=traced}',
254
+ ]
255
+
256
+ # #149. The only fix is a file this task did not declare. The brace is its own, immediately
257
+ # before the facts, like `{tasks=…}`. Final, sweep and adopt do not say it: those reviews
258
+ # are not sending one task back to edit its own files. outside-stop reads the brace.
259
+ # The example is one line: tail lines other than the two verdict lines are at most 95
260
+ # characters, and it keeps path/file.py:123 so an echoed bullet is not a finding.
261
+ _OUTSIDE = [
262
+ 'When the only fix for a finding is a change in a file outside the files this task',
263
+ 'declared, end the finding\'s first line with {outside=<repo-relative path>},',
264
+ 'several paths comma-separated. Write {outside=…} in its own braces,',
265
+ 'immediately before the facts brace, like the tasks tag. Use it only when the fix',
266
+ 'cannot be made inside the task\'s files:',
267
+ ' - [P1][CONFIRMED] path/file.py:123 — {outside=a.py,b.py} {reach=main origin=new evidence=ran}',
268
+ ]
269
+
213
270
  _SWEEP_FINDINGS = [
214
271
  'Report findings only — do not edit any file. A finding here is a regression the change',
215
272
  'introduced: give its file and line, what breaks, and a concrete input that triggers it. Mark it',
@@ -258,10 +315,14 @@ def qa_text(part: str, kind: str = 'task', threshold=None) -> str:
258
315
  if part != 'tail':
259
316
  raise ValueError('part must be head or tail')
260
317
  lines = list(_SWEEP_FINDINGS if kind == 'sweep' else _FINDINGS)
261
- if kind in ('task', 'solo', 'adopt'):
318
+ if kind in ('task', 'solo', 'adopt', 'group', 'script'):
262
319
  lines += _ALL_CONFIRMED + _SOLO_EXTRA
263
320
  lines += [''] + _VERIFY
264
321
  lines += [''] + _SEVERITY
322
+ if kind in ('task', 'solo', 'group', 'script'):
323
+ lines += [''] + _OUTSIDE
324
+ if kind == 'group':
325
+ lines += [''] + _GROUP_ATTRIB
265
326
  lines += [''] + _threshold_clause(rank, kind) + _CHECKED
266
327
  if kind == 'sweep':
267
328
  lines += [''] + _SWEEP_STATUS
@@ -300,6 +361,10 @@ _DWARF = [
300
361
  '- Finish every measurement and test run BEFORE your last message and report its actual',
301
362
  ' result. If you could not run something, say so explicitly instead of claiming it passed.',
302
363
  '- State precisely which verification commands you ran and what each one returned.',
364
+ # #149. Do not edit a file the task does not own. outside-stop reads these lines.
365
+ '- When a fix you need is in a file outside your task\'s files, do not edit that file;',
366
+ ' finish your work, then end your final message with one line per path,',
367
+ ' FORGE_BLOCKED: <path>: <why>',
303
368
  ]
304
369
 
305
370
 
@@ -354,7 +419,7 @@ def dwarf_text(pre_review: bool = False, verify_after_merge: bool = False) -> st
354
419
 
355
420
  # --- parsing ---------------------------------------------------------------------
356
421
 
357
- _PROTOCOL = re.compile(r'FORGE_(?:VERDICT|LEARNING|TESTS|RETRO):.*$')
422
+ _PROTOCOL = re.compile(r'FORGE_(?:VERDICT|LEARNING|TESTS|RETRO|BLOCKED):.*$')
358
423
  _QUOTE = re.compile(r'^\s*(?:>[ \t]?)+')
359
424
  _MARKER = re.compile(r'^(?:[-*+•–]|\d{1,3}[.)]|#{1,6})\s+')
360
425
  _HEADING = re.compile(r'^ {0,3}#{1,6}[ \t]+\S')
@@ -468,25 +533,45 @@ def _finding(number: int, lines: list):
468
533
  # when it names at least one of the three facts: a finding's own text may end in braces (`{}`, `{a=1}`).
469
534
  _FACTS_SUFFIX = re.compile(r'[ \t]*[`*_]*\{([^{}\n]*)\}[`*_.]*[ \t]*$')
470
535
  _FACT = re.compile(r'([A-Za-z]+)[ \t]*[=:][ \t]*([A-Za-z]+)')
536
+ # `{tasks=…}` and `{outside=…}` are their own braces. When either (or both, in either order)
537
+ # follows the facts, the facts group no longer closes the line. Cut every such trailing brace
538
+ # and try the facts suffix on what remains. A brace of either kind before the facts stays.
539
+ _ATTR_TAIL = re.compile(
540
+ r'(?:[ \t]*[`*_]*\{[ \t]*(?:tasks|outside)[ \t]*=[ \t]*[^{}\n]*\}[`*_.]*)+[ \t]*$',
541
+ re.IGNORECASE)
542
+ _OUTSIDE_TAG = re.compile(r'\{[ \t]*outside[ \t]*=[ \t]*([^{}]*)\}', re.IGNORECASE)
543
+ _PATH_SPLIT = re.compile(r'[\s,]+')
471
544
 
472
545
 
473
546
  def split_facts(line: str):
474
547
  """(line without its facts suffix, {reach, origin, evidence}) or (line, None) when it has none.
475
548
 
476
549
  A fact whose value is not one of its words reads None, and keys other than the three are ignored:
477
- a malformed suffix is still cut from the line, so it never reaches a location or a title."""
478
- match = _FACTS_SUFFIX.search(line or '')
479
- if not match:
480
- return line, None
481
- said = {key.lower(): value.lower() for key, value in _FACT.findall(match.group(1))}
482
- if not any(key in said for key in FACTS):
483
- return line, None
484
- return line[:match.start()], {key: said[key] if said.get(key) in words else None
485
- for key, words in FACTS.items()}
550
+ a malformed suffix is still cut from the line, so it never reaches a location or a title.
551
+ `{tasks=…}` or `{outside=…}` after the facts is not a facts suffix: those braces are cut, in
552
+ either order, and the facts are kept. Either brace before the facts stays on the returned line,
553
+ as it does when it is the only brace."""
554
+ original = line or ''
555
+ bodies = [original]
556
+ tail = _ATTR_TAIL.search(original)
557
+ if tail:
558
+ bodies.append(original[:tail.start()])
559
+ for body in bodies:
560
+ match = _FACTS_SUFFIX.search(body)
561
+ if not match:
562
+ continue
563
+ said = {key.lower(): value.lower() for key, value in _FACT.findall(match.group(1))}
564
+ if not any(key in said for key in FACTS):
565
+ continue
566
+ return body[:match.start()], {key: said[key] if said.get(key) in words else None
567
+ for key, words in FACTS.items()}
568
+ return original, None
486
569
 
487
570
 
488
571
  def facts(text: str):
489
- """The facts of one finding block: its first line's suffix, else its last line's (a wrapped bullet)."""
572
+ """The facts of one finding block: its first line's suffix, else its last line's (a wrapped bullet).
573
+
574
+ A `{tasks=…}` or `{outside=…}` brace after the facts does not hide them."""
490
575
  lines = [line for line in (text or '').split('\n') if line.strip()]
491
576
  for line in lines[:1] + lines[-1:]:
492
577
  found = split_facts(line)[1]
@@ -495,6 +580,22 @@ def facts(text: str):
495
580
  return None
496
581
 
497
582
 
583
+ def outside_paths(finding_text: str) -> list:
584
+ """Paths of the last `{outside=…}` brace in a finding block, in the order written.
585
+
586
+ Paths are comma or space separated. Backticks and quotes are removed, and a repeated
587
+ path is dropped. No brace, or a brace that names no path, is an empty list."""
588
+ matches = list(_OUTSIDE_TAG.finditer(finding_text or ''))
589
+ if not matches:
590
+ return []
591
+ seen = []
592
+ for part in _PATH_SPLIT.split(matches[-1].group(1).strip()):
593
+ path = part.strip('`"\'')
594
+ if path and path not in seen:
595
+ seen.append(path)
596
+ return seen
597
+
598
+
498
599
  def parse_findings(text: str) -> list:
499
600
  """Finding blocks of a QA reply, in order; see the module docstring for the rules."""
500
601
  found = (_finding(start, lines) for start, _, lines in _blocks(_clean(text)))
@@ -503,6 +604,16 @@ def parse_findings(text: str) -> list:
503
604
 
504
605
  # --- the gate --------------------------------------------------------------------
505
606
 
607
+ def finding_blocks(finding, threshold=None) -> bool:
608
+ """Whether one finding blocks at the threshold: the gate's per-finding rule.
609
+
610
+ CONFIRMED or UNSTATED blocks when it has no severity, or a severity at the threshold
611
+ or worse. PLAUSIBLE never blocks. `none` is P3, and an empty threshold is the default."""
612
+ rank = _rank(threshold)
613
+ return (finding.status in ('CONFIRMED', 'UNSTATED')
614
+ and (finding.severity is None or finding.severity <= rank))
615
+
616
+
506
617
  def gate(verdict: str, text: str, threshold=None) -> GateResult:
507
618
  """Check a QA verdict against its findings: a FAIL may be accepted as
508
619
  PASS-with-known-issues, a PASS that lists a blocking finding fails."""
@@ -514,8 +625,7 @@ def gate(verdict: str, text: str, threshold=None) -> GateResult:
514
625
  + sum(1 for f in findings if f.status == 'UNSTATED'))
515
626
  worst = 'P%d' % min(f.severity for f in labelled) if labelled else '-'
516
627
  below = tuple(f for f in labelled if f.severity > rank)
517
- blocking = any(f.status in ('CONFIRMED', 'UNSTATED')
518
- and (f.severity is None or f.severity <= rank) for f in findings)
628
+ blocking = any(finding_blocks(f, threshold) for f in findings)
519
629
  if verdict == 'PASS' and blocking:
520
630
  decision = 'fail'
521
631
  elif (verdict == 'FAIL' and confirmed and unlabelled == 0
@@ -541,6 +651,32 @@ def _tests_reason(text: str) -> str | None:
541
651
  return ''.join(ch for ch in text.strip(_TESTS_TRIM) if ch.isprintable())[:_TESTS_REASON_MAX] or None
542
652
 
543
653
 
654
+ # An implementer's report that a fix lives outside the task's files (#149). Same leading
655
+ # markdown as a FORGE_TESTS line. The why may be empty; a repeated path keeps the first.
656
+ _BLOCKED_LINE = re.compile(r'^[ \t>*_`+-]*FORGE_BLOCKED:[ \t*_`]*(.*?)[ \t*_`]*$', re.M)
657
+
658
+
659
+ def blocked_lines(message: str) -> list:
660
+ """`(path, why)` for every `FORGE_BLOCKED: <path>: <why>` line, in order.
661
+
662
+ Leading markdown (`-`, `*`, `>`, backticks) is ignored. The why may be empty.
663
+ A repeated path keeps the first line."""
664
+ found = []
665
+ seen = set()
666
+ text = (message or '').replace('\r\n', '\n').replace('\r', '\n')
667
+ for raw in _BLOCKED_LINE.findall(text):
668
+ if ':' not in raw:
669
+ continue
670
+ path, why = raw.split(':', 1)
671
+ path = path.strip().strip('`"\'')
672
+ why = why.strip()
673
+ if not path or path in seen:
674
+ continue
675
+ seen.add(path)
676
+ found.append((path, why))
677
+ return found
678
+
679
+
544
680
  def tests_report(text) -> dict | None:
545
681
  """{status: ran|not_needed|could_not_run|unclear, reason} from a QA reply, or None when it does not say."""
546
682
  report = None
@@ -555,6 +691,20 @@ def tests_report(text) -> dict | None:
555
691
  return report
556
692
 
557
693
 
694
+ def outside_report(text: str, threshold=None) -> list:
695
+ """One object per parsed finding: n, severity, status, blocking, outside paths."""
696
+ rows = []
697
+ for number, finding in enumerate(parse_findings(text or ''), 1):
698
+ rows.append({
699
+ 'n': number,
700
+ 'severity': None if finding.severity is None else 'P%d' % finding.severity,
701
+ 'status': finding.status,
702
+ 'blocking': finding_blocks(finding, threshold),
703
+ 'outside': outside_paths(finding.text),
704
+ })
705
+ return rows
706
+
707
+
558
708
  def known_issues_text(threshold, tolerated) -> str:
559
709
  name = SEVERITIES[_rank(threshold)]
560
710
  lines = ['## Known issues (QA findings below blocking threshold %s)' % name, '',
@@ -582,6 +732,20 @@ def _emit(text: str) -> None:
582
732
  sys.stdout.buffer.flush()
583
733
 
584
734
 
735
+ def _emit_json(data) -> None:
736
+ _emit(json.dumps(data, indent=2, ensure_ascii=False) + '\n')
737
+
738
+
739
+ def _read_text(path: str):
740
+ """The file's text, or None when it cannot be read (the caller exits 3)."""
741
+ try:
742
+ with open(path, 'rb') as handle:
743
+ return handle.read().decode('utf-8', 'replace')
744
+ except OSError as error:
745
+ sys.stderr.write('forge-contract: cannot read %s: %s\n' % (path, error))
746
+ return None
747
+
748
+
585
749
  def _parser() -> argparse.ArgumentParser:
586
750
  parser = argparse.ArgumentParser(
587
751
  prog='forge-contract.py', formatter_class=argparse.RawDescriptionHelpFormatter,
@@ -597,7 +761,8 @@ def _parser() -> argparse.ArgumentParser:
597
761
  help='head = review preamble, tail = findings format + verdict contract')
598
762
  qa.add_argument('--kind', choices=KINDS, default='task',
599
763
  help='task (default), final (whole-run review), solo (solo wording), sweep (a finding '
600
- 'sweep task: per-finding FIXED lines, regressions only) or adopt (a range made outside forge)')
764
+ 'sweep task: per-finding FIXED lines, regressions only), adopt (a range made outside '
765
+ 'forge) or group (one review over several tasks; attribute each finding)')
601
766
  qa.add_argument('--threshold', type=_threshold_arg, default=None, metavar='P0..P3|none',
602
767
  help='least severe level that still blocks; none = P3 (default: %s)' % DEFAULT_THRESHOLD)
603
768
  dwarf = sub.add_parser('dwarf', help='print the implementer rules block')
@@ -618,6 +783,13 @@ def _parser() -> argparse.ArgumentParser:
618
783
  help='write tolerated findings here when there are any')
619
784
  tests = sub.add_parser('tests', help='print what the reply says about its tests: status, a tab, the reason')
620
785
  tests.add_argument('--qa-last', required=True, metavar='FILE', help='the QA reply')
786
+ outside = sub.add_parser('outside', help='print each finding\'s outside paths as JSON')
787
+ outside.add_argument('--qa-last', required=True, metavar='FILE', help='the QA reply')
788
+ outside.add_argument('--threshold', type=_threshold_arg, default=None, metavar='P0..P3|none',
789
+ help='least severe level that still blocks; none = P3 (default: %s)'
790
+ % DEFAULT_THRESHOLD)
791
+ blocked = sub.add_parser('blocked', help='print FORGE_BLOCKED lines from an implementer message')
792
+ blocked.add_argument('--message', required=True, metavar='FILE', help='the implementer message')
621
793
  return parser
622
794
 
623
795
 
@@ -632,17 +804,20 @@ def main(argv=None) -> int:
632
804
  if args.command == 'retro':
633
805
  _emit(retro_text(args.role))
634
806
  return 0
635
- try:
636
- with open(args.qa_last, 'rb') as handle:
637
- text = handle.read().decode('utf-8', 'replace')
638
- except OSError as error:
639
- sys.stderr.write('forge-contract: cannot read %s: %s\n' % (args.qa_last, error))
807
+ text = _read_text(args.message if args.command == 'blocked' else args.qa_last)
808
+ if text is None:
640
809
  return 3
641
810
  if args.command == 'tests':
642
811
  report = tests_report(text)
643
812
  if report:
644
813
  _emit('%s\t%s\n' % (report['status'], report['reason'] or ''))
645
814
  return 0
815
+ if args.command == 'outside':
816
+ _emit_json(outside_report(text, args.threshold))
817
+ return 0
818
+ if args.command == 'blocked':
819
+ _emit_json([{'path': path, 'why': why} for path, why in blocked_lines(text)])
820
+ return 0
646
821
  result = gate(args.verdict, text, args.threshold)
647
822
  if args.known_issues and result.n_below >= 1:
648
823
  temporary = args.known_issues + '.%d.tmp' % os.getpid()
@@ -14,6 +14,10 @@
14
14
  pin <plan> <task> <spec> the model the task's next FULL implementer retry uses
15
15
  unpin <plan> <task>
16
16
  retry <plan> <task> [--dwarf SPEC] queue a retry of a stopped or failed task into the live run
17
+ retry <plan> <task> --answer TEXT answer a NEEDS_INPUT task's question (or --answer-file F, - for stdin):
18
+ queued into the live run, which writes tasks/<id>/answer.md and
19
+ requeues the task; with no run live, `forge-parallel.sh retry
20
+ --answer-file --no-dispatch` prepares it for the next `run`
17
21
  a NEEDS_DECISION task (reviews that do not converge, or a stop with no
18
22
  stronger model) is resumed only by a decision: --decide retry=N or
19
23
  threshold=P0..P3, or --dwarf SPEC, each with --reason TEXT --approved
@@ -50,6 +54,9 @@ A pin, a retry's --dwarf and an added row's specs are checked with `forge-dispat
50
54
  FORGE_CONTROL_DOCTOR replaces `bash forge-dispatch.sh doctor` with another command line, which
51
55
  then gets `--spec <spec> --role <role>`; tests use it.
52
56
 
57
+ An answer is 1 to 8000 characters (after stripping), with no NUL byte, and its request must fit the
58
+ scheduler's 64 KiB limit. control.log records the retry with the value `answer` and `answer_chars`, never the text.
59
+
53
60
  Exit codes: 0 ok, 2 usage or invalid input (including an unsafe path), 3 refused (not live, MERGED,
54
61
  Fractal, a spec that fails doctor, the control lock busy for over 5 s).
55
62
  """
@@ -66,6 +73,7 @@ import shlex
66
73
  import stat
67
74
  import subprocess
68
75
  import sys
76
+ import tempfile
69
77
  import time
70
78
  from pathlib import Path
71
79
 
@@ -838,10 +846,11 @@ def check_row(plan, rows, task):
838
846
  return dwarf, qa
839
847
 
840
848
 
841
- def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None):
849
+ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None, answer=None):
842
850
  """Write the request under the control lock, live only; log it with its id.
843
851
  decision: a retry's (--decide choice or None, reason, approved) for a NEEDS_DECISION task.
844
- accept_reason: an accept's reason; it is given with --approved (#138)."""
852
+ accept_reason: an accept's reason; it is given with --approved (#138).
853
+ answer: a NEEDS_INPUT task's answer (#147); the log records that there was one, never the text."""
845
854
  with control_lock(plan):
846
855
  probe(plan, 'control.log')
847
856
  if not is_live(plan):
@@ -859,13 +868,22 @@ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None):
859
868
  if accept_reason is not None:
860
869
  request.update(reason=accept_reason, approved=True)
861
870
  extra['reason'] = accept_reason
862
- write_atomic(plan, f'{REQUESTS}/{name}', json.dumps(request) + '\n')
863
- audit(plan, args.actor, verb, task, None, dwarf or (decision[0] if decision else None), None, request=name, **extra)
871
+ if answer is not None:
872
+ request['answer'] = answer
873
+ extra['answer_chars'] = len(answer)
874
+ body = json.dumps(request) + '\n'
875
+ if len(body.encode('utf-8')) > REQUEST_MAX:
876
+ raise Refused(f'the answer does not fit in a request ({len(body.encode("utf-8"))} bytes, the scheduler reads '
877
+ f'at most {REQUEST_MAX}): shorten it')
878
+ write_atomic(plan, f'{REQUESTS}/{name}', body)
879
+ audit(plan, args.actor, verb, task, None,
880
+ 'answer' if answer is not None else dwarf or (decision[0] if decision else None), None, request=name, **extra)
864
881
  if args.json:
865
882
  json.dump(dict(queued=True, request=name), sys.stdout)
866
883
  sys.stdout.write('\n')
867
884
  else:
868
- print(f'queued {verb} of task {task}' + (f' on {dwarf}' if dwarf else '') + f' (request {name}); '
885
+ print(f'queued {verb} of task {task}' + (f' on {dwarf}' if dwarf else '') + (' with an answer' if answer is not None else '')
886
+ + f' (request {name}); '
869
887
  'the scheduler applies or refuses it at its next pass and logs the outcome in control.log')
870
888
  return 0
871
889
 
@@ -897,9 +915,101 @@ def decision_of(plan, args, dwarf):
897
915
  return args.decide, reason, True
898
916
 
899
917
 
918
+ ANSWER_MAX = 8000 # characters; the scheduler reads the same limit
919
+ REQUEST_MAX = 64 * 1024 # bytes of one request file; the scheduler ignores a larger one
920
+ ANSWER_READ = ANSWER_MAX * 4 + 1024 # bytes; one more means the file continues past the read
921
+
922
+
923
+ def read_capped(handle):
924
+ """Up to ANSWER_READ bytes, and whether at least one byte follows."""
925
+ data = handle.read(ANSWER_READ)
926
+ extra = handle.read(1) if len(data) == ANSWER_READ else b''
927
+ return data, extra
928
+
929
+
930
+ def answer_file_text(path):
931
+ """The answer file's text. A file that continues past the read is over the character limit:
932
+ a prefix of only whitespace is not an empty answer, and a character split by the read is not bad UTF-8."""
933
+ try:
934
+ if path == '-':
935
+ data, extra = read_capped(sys.stdin.buffer)
936
+ else:
937
+ with open(path, 'rb') as handle:
938
+ data, extra = read_capped(handle)
939
+ except OSError as error:
940
+ raise Invalid(f'--answer-file {path}: {error.strerror or error}')
941
+ try:
942
+ text = data.decode('utf-8')
943
+ except UnicodeDecodeError as error:
944
+ if extra and error.reason == 'unexpected end of data':
945
+ raise Invalid(f'the answer is limited to {ANSWER_MAX} characters')
946
+ raise Invalid('the answer is not valid UTF-8 text')
947
+ if extra and not text.strip():
948
+ raise Invalid(f'the answer is limited to {ANSWER_MAX} characters')
949
+ return text
950
+
951
+
952
+ def answer_of(args):
953
+ """The answer --answer or --answer-file gives (stripped), None when neither is given."""
954
+ if args.answer is None and args.answer_file is None:
955
+ return None
956
+ if args.answer is not None and args.answer_file is not None:
957
+ raise Invalid('give --answer or --answer-file, not both')
958
+ if args.dwarf is not None or args.decide is not None:
959
+ raise Invalid('--answer answers a NEEDS_INPUT task and is not combined with --dwarf or --decide')
960
+ if args.reason is not None or args.approved:
961
+ raise Invalid('--answer answers a NEEDS_INPUT task and is not combined with --reason or --approved')
962
+ text = args.answer
963
+ if args.answer_file is not None:
964
+ text = answer_file_text(args.answer_file)
965
+ text = text.strip()
966
+ if not text:
967
+ raise Invalid('the answer is empty')
968
+ if '\0' in text:
969
+ raise Invalid('the answer contains a NUL byte')
970
+ if len(text) > ANSWER_MAX:
971
+ raise Invalid(f'the answer is limited to {ANSWER_MAX} characters')
972
+ return text
973
+
974
+
975
+ def retry_prepared(args, plan, answer):
976
+ """No scheduler is live: prepare the answered task for the next `run`, as `forge-parallel.sh retry
977
+ --answer-file --no-dispatch` does, and pass its exit code through."""
978
+ fd, tmp = tempfile.mkstemp(dir=plan, prefix='.answer-', suffix='.txt') # 0600
979
+ try:
980
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
981
+ handle.write(answer + '\n')
982
+ command = ['bash', os.path.join(SKILL, 'scripts', 'forge-parallel.sh'), 'retry', plan, args.task,
983
+ '--answer-file', tmp, '--no-dispatch']
984
+ if args.json: # stdout is the JSON: the command's own words go to stderr
985
+ done = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True, text=True)
986
+ sys.stderr.write(done.stdout + done.stderr)
987
+ else:
988
+ done = subprocess.run(command, stdin=subprocess.DEVNULL)
989
+ finally:
990
+ with contextlib.suppress(OSError):
991
+ os.unlink(tmp)
992
+ if done.returncode == 0 and args.json:
993
+ json.dump(dict(queued=False, prepared=True), sys.stdout)
994
+ sys.stdout.write('\n')
995
+ elif done.returncode == 0:
996
+ print(f'no run is live: task {args.task} is prepared with your answer; the next `forge-parallel.sh run {plan}` '
997
+ 'dispatches it')
998
+ return done.returncode
999
+
1000
+
900
1001
  def cmd_retry(args):
901
1002
  plan, rows = load(args.plan)
902
1003
  require_task(rows, args.task)
1004
+ answer = answer_of(args)
1005
+ if answer is not None:
1006
+ refuse_task(plan, args.task, pin=True)
1007
+ status = task_status(plan, args.task, strict=True)
1008
+ if status != 'NEEDS_INPUT':
1009
+ raise Refused(f'task {args.task} is {status}, not waiting for an answer: --answer only answers a NEEDS_INPUT task')
1010
+ if not is_live(plan):
1011
+ return retry_prepared(args, plan, answer)
1012
+ return queue(args, plan, 'retry', args.task, None, answer=answer)
903
1013
  dwarf = None
904
1014
  if args.dwarf is not None:
905
1015
  dwarf = clean_spec(args.dwarf, '--dwarf')
@@ -1040,6 +1150,8 @@ def parser():
1040
1150
  p.add_argument('task')
1041
1151
  p.add_argument('--dwarf', metavar='SPEC', help='the implementer for this retry (an explicit escalation)')
1042
1152
  p.add_argument('--decide', metavar='CHOICE', help='decide a NEEDS_DECISION task: retry=N (1 to 20) or threshold=P0..P3')
1153
+ p.add_argument('--answer', metavar='TEXT', help="answer a NEEDS_INPUT task's question (1 to 8000 characters)")
1154
+ p.add_argument('--answer-file', metavar='FILE', help='the answer, read from FILE (- for stdin)')
1043
1155
  p.add_argument('--reason', metavar='TEXT', help='why (a decision needs it)')
1044
1156
  p.add_argument('--approved', action='store_true', help='the decision is the user\'s (a decision needs it)')
1045
1157
  p.set_defaults(func=cmd_retry)
@@ -54,7 +54,8 @@
54
54
  # provider_down, network, or an empty answer; forge_infra.py says what each
55
55
  # means): the model never got to do its work. $ROLE.infra says which.
56
56
  # A DWARF that exits 0 with an empty final message also writes $ROLE.infra
57
- # (class=empty) but still exits 0; consult the file only if the diff is empty.
57
+ # (class=empty) but still exits 0, as does one its CLI cancelled (class=cancelled);
58
+ # consult the file only if the diff is empty.
58
59
  # 9 the session was not continued (--continue-session only): the harness cannot
59
60
  # continue one, or it ran and failed. The caller may dispatch fresh; dispatch
60
61
  # never does, so each dispatch keeps its own record. $ROLE.continue says why.
@@ -446,6 +447,7 @@ if [ "$PREFLIGHT" != 1 ] && [ "$DRY" != 1 ]; then
446
447
  for watcher in ${wpid:-} ${spid:-}; do pkill -P "$watcher" 2>/dev/null; kill "$watcher" 2>/dev/null; done
447
448
  [ -z "${cpid:-}" ] || kill "$cpid" 2>/dev/null
448
449
  rm -f "$RUN_DIR/$ROLE.harness" "$RUN_DIR/$ROLE.tracked"
450
+ case "${ROLE_TMP:-}" in "$RUN_DIR"/.*-tmp.*) [ ! -d "$ROLE_TMP" ] || rm -rf -- "$ROLE_TMP" ;; esac
449
451
  }
450
452
  # What the EXIT trap's `finish` archives. Pessimistic until an outcome is known, so every
451
453
  # path out of a continue request (a signal, a usage error after this point) leaves a record.
@@ -531,6 +533,19 @@ cp "$PROMPT_FILE" "$RUN_DIR/$ROLE.delivered"
531
533
  case "$HARNESS" in opencode|antigravity) PROMPT="$(cat "$PROMPT_FILE")" ;; esac
532
534
 
533
535
  # --- build argv ---------------------------------------------------------------
536
+ # A read-only codex role: the read-only sandbox, plus a permissions profile that reads everything
537
+ # and writes only ROLE_TMP (#148). The sandbox mode stays as the fallback: a codex that does not
538
+ # know profiles keeps a plain read-only sandbox. Probed with `codex sandbox -P` and
539
+ # `codex debug prompt-input` (0.164): the profile wins, and the repository stays read-only.
540
+ codex_read_only() {
541
+ CMD+=(-c 'sandbox_mode="read-only"')
542
+ [ -n "$ROLE_TMP" ] || return 0
543
+ local path="${ROLE_TMP//\\/\\\\}"
544
+ path="${path//\"/\\\"}"
545
+ CMD+=(-c 'default_permissions="forge-read-only"'
546
+ -c "permissions.forge-read-only.filesystem={\"/\"=\"read\", \"$path\"=\"write\"}")
547
+ }
548
+
534
549
  # Sets CMD (and PROMPT_VIA_STDIN) for the dispatch, or for the fresh one when CONTINUE_ID is empty.
535
550
  build_cmd() {
536
551
  CMD=()
@@ -558,7 +573,7 @@ build_cmd() {
558
573
  [ -n "$EFFORT" ] && CMD+=(-c "model_reasoning_effort=$EFFORT")
559
574
  [ "$SERVICE_TIER" = fast ] && CMD+=(-c "service_tier=fast")
560
575
  if [ "$YOLO" = 1 ]; then CMD+=(--dangerously-bypass-approvals-and-sandbox)
561
- else CMD+=(-c 'sandbox_mode="read-only"'); fi
576
+ else codex_read_only; fi
562
577
  case "$CONTINUE_ID" in -*) CMD+=(-- "$CONTINUE_ID") ;; esac
563
578
  CMD+=(-)
564
579
  PROMPT_VIA_STDIN=1
@@ -569,7 +584,7 @@ build_cmd() {
569
584
  # --approve-for-me and --dangerously-bypass-... are mutually exclusive.
570
585
  if [ "$YOLO" = 1 ]; then CMD+=(--dangerously-bypass-approvals-and-sandbox)
571
586
  elif [ "$ROLE" = "dwarf" ]; then CMD+=(--approve-for-me)
572
- else CMD+=(-s read-only); fi
587
+ else codex_read_only; fi
573
588
  CMD+=(-)
574
589
  PROMPT_VIA_STDIN=1
575
590
  fi
@@ -679,6 +694,19 @@ build_cmd() {
679
694
  *) die "no dispatch recipe for harness '$HARNESS'" ;;
680
695
  esac
681
696
  }
697
+ # A read-only role's own writable temp dir (#148). Test runners need one (Vitest's EPERM in a
698
+ # read-only sandbox), and the role gets none otherwise. It sits in the run dir, outside the
699
+ # repository, so the tree under review and its fingerprint are untouched; TMPDIR, TMP and TEMP
700
+ # point at it, and the dispatch removes it when it ends. A dry run or a preflight only shows
701
+ # its shape.
702
+ ROLE_TMP=""
703
+ if read_only_role; then
704
+ if [ -n "$ATTEMPT" ]; then
705
+ ROLE_TMP="$(mktemp -d "$RUN_DIR/.$ROLE-tmp.XXXXXX")" || ROLE_TMP=""
706
+ else
707
+ ROLE_TMP="$RUN_DIR/.$ROLE-tmp.XXXXXX"
708
+ fi
709
+ fi
682
710
  build_cmd
683
711
 
684
712
  # Offline validation uses the exact command recipe, never a model request.
@@ -834,10 +862,11 @@ case "${FORGE_ORPHAN_GUARD:-on}" in off|OFF|Off|0|no|false) ;; *)
834
862
  esac
835
863
  RUNCMD=("${CMD[@]}")
836
864
  [ "$GUARD_ON" != 1 ] || RUNCMD=(python3 "$GUARD" session -- "${CMD[@]}")
865
+ role_env() { [ -z "$ROLE_TMP" ] || export TMPDIR="$ROLE_TMP" TMP="$ROLE_TMP" TEMP="$ROLE_TMP"; }
837
866
  if [ "$PROMPT_VIA_STDIN" = 1 ]; then
838
- ( cd "$REPO" && exec "${RUNCMD[@]}" < "$PROMPT_FILE" ) > "$LOG" 2>&1 &
867
+ ( cd "$REPO" && role_env && exec "${RUNCMD[@]}" < "$PROMPT_FILE" ) > "$LOG" 2>&1 &
839
868
  else
840
- ( cd "$REPO" && exec "${RUNCMD[@]}" </dev/null ) > "$LOG" 2>&1 &
869
+ ( cd "$REPO" && role_env && exec "${RUNCMD[@]}" </dev/null ) > "$LOG" 2>&1 &
841
870
  fi
842
871
  hpid=$!
843
872
  # Log clock: when the log grew, so forge-ui can time the commands of a harness whose events