@giamme/forge 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +5 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/safety.md +8 -0
  11. package/forge +24 -1
  12. package/package.json +1 -1
  13. package/references/dataset.md +19 -0
  14. package/references/decompose.md +134 -1
  15. package/references/solo.md +2 -1
  16. package/references/ui.md +5 -2
  17. package/scripts/forge-artifact.sh +14 -0
  18. package/scripts/forge-brief.py +132 -0
  19. package/scripts/forge-compare.py +11 -1
  20. package/scripts/forge-config.py +176 -9
  21. package/scripts/forge-contract.py +46 -3
  22. package/scripts/forge-control.py +86 -13
  23. package/scripts/forge-dispatch.sh +14 -10
  24. package/scripts/forge-du.py +167 -0
  25. package/scripts/forge-lib-adopt.sh +1 -0
  26. package/scripts/forge-lib-plans.sh +5 -2
  27. package/scripts/forge-lib-review.sh +29 -1
  28. package/scripts/forge-metrics.sh +7 -3
  29. package/scripts/forge-parallel-options.sh +4 -0
  30. package/scripts/forge-parallel.sh +503 -9
  31. package/scripts/forge-prompt.py +120 -0
  32. package/scripts/forge-retro.py +115 -0
  33. package/scripts/forge-runs-compact.py +443 -0
  34. package/scripts/forge-runs-rm.py +2 -0
  35. package/scripts/forge-runs.py +18 -3
  36. package/scripts/forge-schedule.py +279 -4
  37. package/scripts/forge-shadow.py +7 -1
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-summarize.py +698 -0
  40. package/scripts/forge-ui-options.sh +10 -0
  41. package/scripts/forge_brief/__init__.py +587 -0
  42. package/scripts/forge_brief/answers.py +459 -0
  43. package/scripts/forge_dataset/__init__.py +10 -0
  44. package/scripts/forge_dataset/export.py +18 -4
  45. package/scripts/forge_dataset/facts.py +6 -4
  46. package/scripts/forge_dataset/harvest.py +40 -6
  47. package/scripts/forge_dataset/history.py +5 -3
  48. package/scripts/forge_decide/__init__.py +11 -1
  49. package/scripts/forge_locations.py +366 -0
  50. package/scripts/forge_registry.py +19 -0
  51. package/scripts/forge_retro/__init__.py +417 -0
  52. package/scripts/forge_retro/issues.py +1193 -0
  53. package/scripts/forge_retro/report.py +671 -0
  54. package/scripts/forge_side/__init__.py +477 -0
  55. package/scripts/forge_storage.py +515 -0
  56. package/ui/README.md +68 -8
  57. package/ui/docs/api.md +205 -17
  58. package/ui/forge_ui/control.py +92 -11
  59. package/ui/forge_ui/export.py +24 -5
  60. package/ui/forge_ui/links.py +337 -0
  61. package/ui/forge_ui/models.py +57 -4
  62. package/ui/forge_ui/projects.py +4 -1
  63. package/ui/forge_ui/reader.py +661 -30
  64. package/ui/forge_ui/static/app.js +86 -4
  65. package/ui/forge_ui/static/briefview.js +302 -0
  66. package/ui/forge_ui/static/checksview.js +6 -2
  67. package/ui/forge_ui/static/controls.js +5 -0
  68. package/ui/forge_ui/static/index.html +3 -0
  69. package/ui/forge_ui/static/panel.js +268 -2
  70. package/ui/forge_ui/static/runmodel.js +13 -1
  71. package/ui/forge_ui/static/storageview.js +271 -0
  72. package/ui/forge_ui/static/style.css +99 -3
  73. package/ui/forge_ui/static/worktreesview.js +3 -3
  74. package/ui/forge_ui/storage.py +136 -0
  75. package/ui/forge_ui/transcripts.py +35 -10
  76. package/ui/forge_ui/worktrees.py +154 -13
package/ui/docs/api.md CHANGED
@@ -52,8 +52,10 @@ written), and the reader must never raise because of one.
52
52
  | `attribution.json` | the result of `forge-parallel.sh attribute`: `culprit` (a task id or `null`), `base_fails`, `inconclusive` (a reason or `null`), `merges`, `steps`, `verification_runs`, `gate` (`null` without the gate, else `{mode, ranking, tried, outcome}`); returned as `attribution`, see RunDetail |
53
53
  | `max_parallel`, `escalate_after`, `verify_retries` | one integer each |
54
54
  | `qa_threshold` | `P0`..`P3`, the least severe finding that still blocks; `final_qa` the final review's QA spec |
55
+ | `summaries`, `summaries_model` | the run's task-summary switch (`on` or `off`; absent is `off`) and its model spec, from `forge control set summaries`; returned as `summaries`, see RunDetail |
55
56
  | `profile.json` | the profile the run froze: `name`, `level` (`user`, `repo` or `builtin`), `body` (the profile object), `shadowed` (levels the winning copy hid), `frozen_at` (UTC, `YYYY-MM-DDTHH:MM:SSZ`), `overridden` (the sorted dotted keys a flag of the run replaced, such as `routing.qa.any`; empty when none). RunDetail returns `settings.profile` `{name, level, overridden}`, `null` when the file is absent, unreadable or not that shape |
56
57
  | `deferrals.txt` | one line per task the wave planner deferred |
58
+ | `retro.md`, `retro/notes.jsonl` | written when retro mode is on: the report (Markdown) and one JSON note per line (`fixable_by` `user`, `forge` or `unsure`, `check` `verified` or `claimed`, `blocking` a boolean). Returned as `retro`, see RunDetail |
57
59
  | `integration.base`, `accepted.integration` | one commit each: where the integration branch started, the revision the run accepted |
58
60
  | `attempts/<role>-<uuid>/` | one *execution* (below) of the run itself: `parallel` (a `run`) or `verification` |
59
61
  | `final-review-<epoch>-<pid>/` | one whole-run review: `qa.input`, `qa.last`, `verdict` (`PASS FAIL UNKNOWN INVALIDATED ACCEPTED`; absent while it runs or when nothing was judged), `qa.infra`, `qa.gate`, `known_issues.md`, `review.meta` (`key=value`: `base tip source spec threshold integration`, `threshold=none` when unset; `integration` is the integration-branch commit the reviewed result contains and is absent on older runs), `tasks.summary`, `attempts/qa-<uuid>/` |
@@ -75,6 +77,14 @@ written), and the reader must never raise because of one.
75
77
  | `tasks/<id>/accepted.by` | who accepted a task over a reviewer's FAIL, and why (`key=value`: `task`, `status`, `reason`, `by`, `at`, `epoch`, `attempt`, `reviewed_commit`; older runs are free text; returned as text) |
76
78
  | `tasks/<id>/qa.gate` | `threshold<TAB>decision<TAB>worst<TAB>n_confirmed<TAB>n_unlabelled<TAB>n_below` (`decision` is `accept` (the reviewer said FAIL, every CONFIRMED finding was below the threshold), `fail` (the reviewer said PASS, but listed a blocking CONFIRMED finding) or `keep`, `-` for none) |
77
79
  | `tasks/<id>/known_issues.md` | the confirmed findings a threshold tolerated |
80
+ | `tasks/<id>/summary.json` | the task's generated summary: `{text, sentence, model, generated_at, inputs_hash, sources}`, `generated_at` in epoch seconds, `sources` a list of `{kind, ref}` (`kind` `attempt` or `finding`; a finding's `ref` is `<attempt>:<title>`); returned as `summary`, see Task |
81
+ | `tasks/<id>/summary.error` | the reason the last generation failed; the previous `summary.json` is kept. Returned as `error` inside `summary` |
82
+ | `tasks/<id>/summaries` | the task's summary switch, `on` or `off`, from `forge control set summaries --task <id>`; `inherit` removes the file. Returned as `summaries_override` |
83
+ | `brief` | the plan's brief level: `advisory`, `gated` or `strict`. `off`, any other word, or a missing file means brief mode is off. Returned as RunDetail `brief` (`null` when off) |
84
+ | `tasks/<id>/brief.json` | the task's questions: `{questions: [{id, text, why, options, default, scope, must_answer, possibly_stale}], model, generated_at}`. Returned inside the task's `brief.questions` |
85
+ | `tasks/<id>/brief.parked.json` | wider-scope questions (`wave` or `plan`), the same shape. Returned as `brief.parked` |
86
+ | `tasks/<id>/brief.answers.json` | `{qid: {text, actor, t}}`: answers given before the task started. A question with an entry here is `answered` |
87
+ | `tasks/<id>/brief.late.json` | the same shape, for answers given after the task started. Returned as `brief.late`; a question that has one and no answer yet is `late` |
78
88
  | `tasks/<id>/prereview.json`, `prereview.md` | the pre-review tests of the latest attempt (opt-in `plan --pre-review-tests`): `status` (`passed`, `flaky`, `pre-existing`, `failed`, `skipped`, `error`), `reason`, `command`, `selected`, `failing`, `preexisting`, `flaky`, `runs`, `seconds`; returned on a task as `pre_review` `{status, reason, command, selected, failing, preexisting, flaky, seconds, tail}` (`tail`: the end of the last failing run's output), `null` without the file. `prereview.md` is the implementer's findings of a `failed` check |
79
89
  | `tasks/<id>/dwarf.input`, `qa.input` | the prompts forge assembled; `<role>.delivered`, `<role>.resolved` the live dispatch files |
80
90
  | `tasks/<id>/<role>.log`, `<role>.clock` | the running dispatch's harness log and its clock: one `<epoch> <bytes>` line each time the log grew (forge-dispatch.sh samples it every second; `FORGE_LOG_CLOCK=off` writes none) |
@@ -139,6 +149,7 @@ raise because of one. Older solo dirs have `verdict` and not `status`.
139
149
  | `dwarf.log`, `qa.log` | raw logs. The summary stats them and does not read them, so `updated` moves while a model writes |
140
150
  | `changes.diff`, `existing.diff` | the run's change, and the uncommitted changes the repo already had when it started |
141
151
  | `fractal-selection.json` | as for a plan |
152
+ | `retro.md`, `retro/notes.jsonl` | as for a plan; `retro` in the detail is read the same way |
142
153
 
143
154
  **Solo status** is the first word of `status`, otherwise the first word of `verdict`, otherwise
144
155
  `UNKNOWN`.
@@ -225,7 +236,7 @@ loaded. When it cannot be loaded, `findings_available` is `false` and every find
225
236
  is `null`; verdicts and `gate` do not need it.
226
237
 
227
238
  Text fields are capped so one huge file cannot blow up a response: `request`, `prompt`,
228
- `approach`, `retry_findings`, `needs_input` and the `decision` text keep their first 20,000 characters, and an `infra` `detail` its first 400; `qa_tail`, `dwarf_tail`
239
+ `approach`, `retry_findings`, `needs_input`, the `decision` text, `retro`'s `text`, a summary's `text`, `sentence` and `error` and each source `ref`, a brief question's `text`, `why`, `default`, each option and its `answer`, a parked question's text and a late answer's `text` keep their first 20,000 characters, and an `infra` `detail` its first 400; `qa_tail`, `dwarf_tail`
229
240
  and `verification.log_tail` keep their last 4,000. A capped field ends (or, for tails,
230
241
  starts) with `…` and the value of `truncated` lists the field names that were cut.
231
242
 
@@ -264,6 +275,7 @@ its last 20,000 behind a leading `…`. Their `truncated` lists the field names
264
275
  | `GET /api/health` | `200 {"app": "forge-ui", "version", "build", "pid", "controls": true\|false}`; `version` is forge's own (the root `VERSION` file, read when this server started), `null` when that file cannot be read; `controls` is `false` in read-only mode |
265
276
  | `GET /api/runs/<key>/controls` | `200` the `forge control show --json` object of a plan run (see Controls); `404` for a solo or unknown run |
266
277
  | `POST /api/runs/<key>/controls` | change one control or pin; authenticated, see Controls (write endpoints) |
278
+ | `POST /api/runs/<key>/tasks/<id>/brief/<qid>` | record a brief answer (`forge brief answer … --file - --actor ui`); authenticated, see Controls |
267
279
  | `GET /api/runs/<key>/issues?scope=run\|repo&offline=0\|1&plausible=0\|1&dismissed=0\|1&only=fp,fp` | `200` the `forge issues --json` listing, run fresh on every request (no cache); see Controls (write endpoints) |
268
280
  | `POST /api/runs/<key>/issues` | file GitHub issues for chosen findings; authenticated, 300 s timeout |
269
281
  | `POST /api/runs/<key>/issues/dismiss` | dismiss or (`undo`) restore findings; authenticated |
@@ -274,6 +286,7 @@ its last 20,000 behind a leading `…`. Their `truncated` lists the field names
274
286
  | `GET /api/projects/<id>/findings[?refresh=1]` | `200 ProjectFindings`: every review's findings with their status |
275
287
  | `GET /api/projects/<id>/memories[?refresh=1]` | `200 ProjectMemories`: what each checkout's memory gives models and every learning's state |
276
288
  | `GET /api/worktrees[?refresh=1]` | `200 Worktrees`: every worktree forge created, with its status and the commands to remove it; cached 60 s (see Worktrees) |
289
+ | `GET /api/storage[?refresh=1]` | `200 Storage`: what forge takes on disk and the commands that take it back, measured in the background; cached 600 s (see Storage) |
277
290
  | `GET /api/config?run=<key>` | `200` the `forge config show --json` of that run's repository root (see Config) |
278
291
  | `POST /api/config` | set or unset one allowed key (`repo.verify`, `repo.setup`, `repo.verify-subset`, `decide.gate.<gate>`, `decide.gate.<gate>.provider`, `decide.gate.<gate>.model`); `jev.enabled` is gone; authenticated |
279
292
  | `GET /api/config/profiles?run=<key>` | `200` every profile of that run's repository, each with its level, shadowed levels, default flag and body (see Profiles) |
@@ -397,6 +410,10 @@ Every RunSummary field, plus:
397
410
  ```json
398
411
  {
399
412
  "request": "the user's request, verbatim",
413
+ "retro": {"text": "# Retro\n…", "notes": 6, "user": 2, "forge": 2, "unsure": 1,
414
+ "verified": 3, "claimed": 3, "blocking": 3},
415
+ "summaries": {"mode": "on", "model": "sol:low"},
416
+ "brief": {"level": "gated", "open": 2, "flagged": 1},
400
417
  "settings": {"explore": 0.5, "shadow_rate": 0.5, "shadow_qa": ["opus", "sol:xhigh"], "timeout": 3600,
401
418
  "max_parallel": 2, "qa_threshold": "P2", "escalate_after": 3, "verify_retries": 1,
402
419
  "final_qa": "opus",
@@ -449,6 +466,22 @@ Every RunSummary field, plus:
449
466
  not a frozen profile (`name` and `level` non-empty strings, `overridden` a list of strings). A solo run
450
467
  reads `$RUN/profile.json` the same way and has no other plan settings: every other value is
451
468
  `null`, including `shadow_qa`, except `qa_threshold` and its source, which read the same way.
469
+ - `retro` is `null` when the run has neither `retro.md` nor `retro/notes.jsonl`; a solo run has the same
470
+ field. Otherwise `text` is `retro.md`, capped like `request` (`null` when that file is missing), and the
471
+ other values count `retro/notes.jsonl`: `notes` is the number of lines that are JSON objects; `user`,
472
+ `forge` and `unsure` count the notes whose `fixable_by` is that value; `verified` and `claimed` those
473
+ whose `check` is that value; `blocking` those whose `blocking` is `true`. A note with any other
474
+ `fixable_by` or `check` counts only in `notes`. A non-blank line that is not a JSON object is skipped,
475
+ with one warning per file (`retro/notes.jsonl: N malformed lines skipped`). `text` is among the texts
476
+ an export leaves out unless it is asked to include them.
477
+ - `summaries` is the run's task-summary switch from its plan files: `mode` is `on` only when `summaries` holds
478
+ `on` (absent, `off` or anything else is `off`), and `model` is the first line of `summaries_model`, or `null`.
479
+ A solo run has `null`. A task's own switch is its `summaries_override` (Task).
480
+ - `brief` is `null` when brief mode is off: the `brief` file is missing, or its first word is not
481
+ `advisory`, `gated` or `strict` (`off` and any other word are off). A solo run's `brief` is always
482
+ `null`. Otherwise `{level, open, flagged}`: `level` is that word; `open` counts task questions whose
483
+ state is `open`; `flagged` counts those that also have `must_answer` true. Parked questions are not
484
+ counted. Each task's own questions are its `brief` (Task).
452
485
  - `attribution` is the result of `forge-parallel.sh attribute` from `attribution.json`, or `null` when
453
486
  the file is missing. `culprit` is the merged task's id or `null`; `base_fails` is `true` only when the
454
487
  base verified FAIL; `inconclusive` is the reason the search stopped without a culprit, or `null`;
@@ -553,6 +586,14 @@ Every RunSummary field, plus:
553
586
  {
554
587
  "id": "reader",
555
588
  "title": "Read plan dirs into plain dicts",
589
+ "header": {"title": "Read plan dirs into plain dicts",
590
+ "goal": "The first paragraph of approach.md, else of prompt.md.",
591
+ "criteria": "The Acceptance criteria section of prompt.md.",
592
+ "links": [{"kind": "issue", "number": 133, "url": "https://github.com/acme/widgets/issues/133", "source": "prompt.md"}]},
593
+ "trail": [{"attempt": 1, "dwarf": "luna", "verdict": "FAIL", "findings": FindingsSummary, "worst": "P1",
594
+ "reason": "first", "executions": ["task-…", "dwarf-…", "qa-…"]},
595
+ {"attempt": 2, "dwarf": "sol", "verdict": "PASS", "findings": FindingsSummary, "worst": null,
596
+ "reason": "review", "executions": ["task-…"]}],
556
597
  "deps": [],
557
598
  "difficulty": "high",
558
599
  "files": ["forge_ui/reader.py", "tests/test_reader.py"],
@@ -603,7 +644,18 @@ Every RunSummary field, plus:
603
644
  "waiting": null,
604
645
  "sweep": null,
605
646
  "swept": [{"id": "S1", "severity": "P2", "confidence": "CONFIRMED", "task": "reader", "location": "ui/reader.py:12",
606
- "summary": "Status is read twice.", "status": "fixed", "note": null, "by": "sweep-1"}]
647
+ "summary": "Status is read twice.", "status": "fixed", "note": null, "by": "sweep-1"}],
648
+ "summary": {"text": "Reads the plan dirs.\n…", "sentence": "Reads plan dirs into plain dicts.", "model": "sol:low",
649
+ "generated_at": 1760621300, "sources": [{"kind": "attempt", "ref": "2"},
650
+ {"kind": "finding", "ref": "1:Missing status file"}],
651
+ "stale": false, "error": null},
652
+ "summaries_override": null,
653
+ "brief": {"questions": [{"id": "q1", "text": "Which module?", "why": "two readers", "options": ["ui", "cli"],
654
+ "default": "ui", "must_answer": true, "possibly_stale": false,
655
+ "state": "open", "answer": null}],
656
+ "parked": [{"id": "q2", "text": "For the whole plan?", "why": "scope", "options": [],
657
+ "default": null, "scope": "plan", "must_answer": false, "possibly_stale": false}],
658
+ "late": [{"id": "q3", "text": "ship it", "actor": "ui", "t": 1760621400.0}]}
607
659
  }
608
660
  ```
609
661
 
@@ -614,6 +666,44 @@ Every RunSummary field, plus:
614
666
  task has a `tasks/<id>/` dir; else `null`.
615
667
  - `attempt`: integer from `tasks/<id>/attempt`, else the highest attempt in `attempts`,
616
668
  else `null`.
669
+ - `header`: `{title, goal, criteria, links}`. `title` is the task's title. `goal` is the first
670
+ paragraph of `approach.md`, or else of `prompt.md`, after a leading `# ` title line, as plain
671
+ text with its whitespace collapsed, capped at 600 characters. Plain text drops code-span
672
+ backticks, `*` and `**` emphasis and `~~strikethrough~~` markers, and keeps the label of a
673
+ `[label](url)` or image; underscores stay, so a file name is unchanged. `null` when neither
674
+ file has one.
675
+ `criteria` is the text of `prompt.md`'s `## Acceptance criteria` section (an optional colon is
676
+ allowed), up to the next `## ` heading or the end of the file, capped like `prompt`; a `### `
677
+ subsection stays inside it, and a fenced `## ` does not end it. `null` when there is no such
678
+ section, or the section is empty. `links` is `[{kind, number, url, source}]`, deduplicated, in
679
+ order of appearance across `prompt.md`, `approach.md` and the run's `request.md`. A full
680
+ `https://github.com/<owner>/<repo>/issues/<n>` or `.../pull/<n>` URL is kind `issue` or `pr`,
681
+ with that number and the canonical URL (query and fragment dropped). Any other
682
+ `https://github.com/...` URL is kind `url`, `number` `null`. A `#N` reference is kind `issue`;
683
+ its url is `https://github.com/<owner>/<repo>/issues/N` for the GitHub origin of the run's
684
+ repo (the `repo` file, then that repo's `.git/config`, SSH or HTTPS, with no network), or
685
+ `null` when that origin is not GitHub. `#N` inside a code span or a fenced block, and a
686
+ markdown heading, are not links. A fence whose marker lines are block-quoted (`> ~~~`) is
687
+ still a fence. A digit run longer than Python will convert does not raise: `#N` is skipped,
688
+ and an issue or pull URL is kept as kind `url`. `source` is the file name. The same link in a
689
+ later file is kept from the first. The export leaves `goal` and `criteria` out unless texts are chosen;
690
+ `links` stay.
691
+ - `trail`: one entry per `attempts.tsv` row, in that order:
692
+ `{attempt, dwarf, verdict, findings, worst, reason, executions}`. `attempt` and `dwarf` come
693
+ from the row (`dwarf` is its 5th column; empty, `-` and `UNASSIGNED` are `null`; a row without
694
+ the column is `null`). `verdict`, `findings` and `worst` come from the newest done non-shadow
695
+ `qa` execution of that attempt (`worst` is that summary's worst severity, `P0`…`P3`, or
696
+ `null`). With no such execution all three are `null` — the task's `qa.last` is not a fallback.
697
+ `findings` is a FindingsSummary. `executions` is the ids of that attempt's executions, in the
698
+ order of `executions`. `reason` is why the attempt ran: `first` for attempt 1; otherwise the
699
+ source recorded in `tasks/<id>/retry_sources.tsv` (`<attempt>`, `<source>`, `<epoch>`), one of
700
+ `review`, `prereview`, `bounce`, `message`, `answer` (the last known source for that attempt;
701
+ an unknown source is warned and skipped); otherwise `escalation` when this row's dwarf differs
702
+ from the previous row's and `escalations` is not empty; otherwise `manual` when a `control.log`
703
+ line queued a `retry` for this task (actor `cli` or `ui`, no `outcome`) and this row is the
704
+ attempt that ends at or after that queue (a scheduler line, which carries `outcome`, does not);
705
+ otherwise `unknown`. A run from before `retry_sources.tsv` existed has `unknown` for every
706
+ later attempt the other rules do not explain.
617
707
  - `infra` in an attempt: `null` for empty, `-` or missing.
618
708
  - `source` in an escalation: the 5th column of `escalations.tsv` (`policy`, `retry` or `pin`, as forge wrote it); `policy` when the row has only 4 columns or the cell is empty.
619
709
  - `verdict`: `"PASS"`, `"FAIL"` or `null`, from `qa.last` as described above.
@@ -683,7 +773,10 @@ Every RunSummary field, plus:
683
773
  `infra` (a pause in `scheduler.pauses` holds it: scope `all`, or its id in `tasks`; the pause's
684
774
  keys plus `kind`), then for a `PENDING` task `deps` (`on`: its deps not merged, `stopped`: those
685
775
  in a stopped status such as `FAIL`; a dep at `NEEDS_INPUT` or `NEEDS_DECISION` is in `on` only, as the user
686
- holds it and the retry policy did not stop it), `stopping` (`mode`), `drained`, `overlap` (`on`: running
776
+ holds it and the retry policy did not stop it), `stopping` (`mode`), `drained`, `brief` (`questions`: a gated
777
+ plan holds it for the ids of its `must_answer` questions with no entry in `brief.answers.json`, or `[]`
778
+ while `brief.json` is not written yet and `brief.pid` names a running process; the same two files
779
+ `forge-schedule.py` reads), `overlap` (`on`: running
687
780
  tasks whose files overlap its own, as forge-schedule.py tells overlap), `slot` (`running`,
688
781
  `max_parallel`: the run is at its capacity) or `next` (nothing holds it).
689
782
  - `sweep`: `null` unless the task is a finding sweep's fix task (it has a `sweep.json`). Then `file`
@@ -692,6 +785,38 @@ Every RunSummary field, plus:
692
785
  `not-fixed`, or `unreported` when it merged without a line for it; read from `sweep.outcome.json`)
693
786
  and `null` until the fix task merged, `note` the review's words on it.
694
787
  - `swept`: this task's findings a fix task took, the same objects plus `by` (the fix task); `[]`.
788
+ - `summary`: `null` unless `tasks/<id>/summary.json` is a JSON object with a string `text` and a number
789
+ `generated_at` (anything else is `null` and warned, as is a file that is not JSON). Then
790
+ `{text, sentence, model, generated_at, sources, stale, error}`: `sentence` and `model` are `null`
791
+ when the file's are not strings; `generated_at` is its epoch seconds; `sources` keeps the entries that are
792
+ `{kind, ref}` with `kind` `attempt` or `finding` and a string `ref`, and drops the others. `stale` is `true`
793
+ when `attempts.tsv`, `status`, `merged` or `qa.last` has a later mtime than `generated_at`, compared in whole
794
+ seconds (a file written in the second `generated_at` was made in is not later). `merged` counts because
795
+ a merge changes the status the page shows. `error` is the text of `tasks/<id>/summary.error`, or `null` when
796
+ the file is missing or blank. A task whose first generation failed has no `summary.json`, so its `summary` is
797
+ `null` and its error is not shown. The export blanks `text` and `error` unless texts are chosen.
798
+ - `summaries_override`: `on` or `off` from `tasks/<id>/summaries`, or `null` when the file is missing or holds
799
+ anything else (the task then follows the run's switch). A solo run's task has `null` for `summary` and
800
+ `summaries_override`.
801
+ - `brief`: `null` when the run's brief is off, on a solo task, or when the task has none of `brief.json`,
802
+ `brief.parked.json` and `brief.late.json`. Otherwise `{questions, parked, late}`.
803
+ `questions` is `brief.json`'s list, in file order. Each is `{id, text, why, options, default, must_answer,
804
+ possibly_stale, state, answer}`. `state` is `answered` when `brief.answers.json` has the id, else `late`
805
+ when `brief.late.json` has it, else `open`. An id in both files is `answered`: the answer given before
806
+ the task started is the one shown. `answer` is that entry's `text`, or `null` when the entry has no
807
+ string `text`. `must_answer` and `possibly_stale` are true only when the file says `true`
808
+ (`possibly_stale` is also true when the whole `brief.json` says so). `options` keeps the entries that
809
+ are strings; `default` is the string, or `null` when the file's value is not one. A question that is
810
+ not an object, or has no string `id`, is skipped, with one warning for the file
811
+ (`tasks/<id>/brief.json: N question(s) skipped`). `parked` is `brief.parked.json`'s questions, the same
812
+ fields except `state` and `answer`, plus `scope` (a string, or `null`). `late` is `brief.late.json` in
813
+ file order, each `{id, text, actor, t}`: `actor` is a string or `null`, and `t` is a finite number or
814
+ `null`. `text`, `why`, `default`, each option, `answer` and a late `text` are capped like `prompt`
815
+ (the cut is named `tasks/<id>/brief/<qid>.text`, and the same way for `why`, `default`, `options`,
816
+ `answer`, `brief.parked/<qid>.*` and `brief.late/<qid>.text`). The export leaves `text`, `why`,
817
+ `options`, `default` and `answer` out unless texts are chosen (`answer` is only on a task question;
818
+ a late answer's private text is its `text`). `id`, `state`, `must_answer`, `possibly_stale`, `scope`,
819
+ `actor` and `t` stay.
695
820
  - Text fields are `null` when the file is missing.
696
821
 
697
822
  A solo run's one task uses this same shape. `id` is `solo` and `title` is the goal, or
@@ -705,7 +830,10 @@ in `attempts.tsv`, or `null`. `escalations`, `route` and `shadow` are empty. `ve
705
830
  false; `accepted_attempt` and `accepted_over` are `null`; `explored` is false; `waiting` and `sweep` are `null`, `swept` is `[]`.
706
831
  `infra` and `decision` are `null`, `lateral`, `ledger` and `decisions` are `[]`, `attempt_cap` is `null`, and `attempts_total`
707
832
  counts the run dir's `attempts.tsv` rows that are not `INFRA`. `request` on
708
- the detail is `request.md`.
833
+ the detail is `request.md`. `header` and `trail` follow the same rules. `prompt.md`, `approach.md`
834
+ and `retry_sources.tsv` are read from the run directory (next to `attempts.tsv`); `escalations` is
835
+ empty, so a later attempt whose dwarf changed is `unknown` unless a retry source or a queued retry
836
+ explains it. `goal` and `criteria` are capped as `tasks/solo/goal` and `tasks/solo/criteria`.
709
837
 
710
838
  ## Execution
711
839
 
@@ -1291,8 +1419,10 @@ difficulty paths deps model` each), `decomposition_history` (its newest 20, each
1291
1419
  (under their tail paths; line ranges are not stored, so the page shows the tail).
1292
1420
  - `texts=0` (the default) nulls these keys wherever they hold a string, list or object: `prompt
1293
1421
  last request log_tail dwarf_tail qa_tail qa_last qa_input tasks_summary known_issues texts text
1294
- planning_last approach retry_findings needs_input dwarf_input error last_line message excerpt tail lines call split detail`,
1295
- and stores no diff, no transcript, no checks and no environment problems (a command is a text). A finding keeps its `summary`, a failing test its `name`.
1422
+ planning_last approach retry_findings needs_input dwarf_input error last_line message excerpt tail lines call split detail`.
1423
+ Under each brief `questions` or `parked` entry it also nulls `why`, `options`, `default` and `answer`
1424
+ (`scope`, `state`, `id`, `must_answer` and `possibly_stale` stay; a late answer's `text` is in the list above).
1425
+ It stores no diff, no transcript, no checks and no environment problems (a command is a text). A finding keeps its `summary`, a failing test its `name`.
1296
1426
  - `paths=0` (the default) makes every string that is a whole absolute path (but `/api/…`, `url`s
1297
1427
  and `command`s) its last component, and replaces the run dir, the repo and the home dir inside other
1298
1428
  strings with their last component (`~` for home).
@@ -1317,16 +1447,17 @@ dir, a repo or config; a write route builds an argv, runs it, and answers with w
1317
1447
  validation, the call and the exit-code mapping; `server.py` does the authentication and gives
1318
1448
  each authenticated POST to the table, so a new write route is one entry in it.
1319
1449
 
1320
- **The call.** `[<forge root>/forge, ...]`, an argv list with no shell, `stdin` closed, in a process
1321
- group of its own. `<forge root>` is two directories above `forge_ui/` and can be replaced as
1450
+ **The call.** `[<forge root>/forge, ...]`, an argv list with no shell, in a process
1451
+ group of its own. `stdin` is closed, except for a profile create or edit (the profile object) and a
1452
+ brief answer (the answer text), both via `--file -`. `<forge root>` is two directories above `forge_ui/` and can be replaced as
1322
1453
  `forge_ui.server.forge_cli`. A call that outlives its timeout (60 s) gets SIGTERM for its whole
1323
1454
  group, SIGKILL 5 s later if anything is left, and is reaped, all before the run's lock is
1324
1455
  released; the answer is `504 {"error": "timeout", "detail": "the operation may have partly
1325
1456
  completed; reload to see the current state"}`.
1326
1457
 
1327
- **Runs are named by key.** The path holds the 12-hex run key and nothing else; the server finds
1328
- the run dir with `Catalog.locate(key)`. A body field never names a path, and a field the route does
1329
- not know is a `400`.
1458
+ **Runs are named by key.** The path holds the 12-hex run key; the server finds
1459
+ the run dir with `Catalog.locate(key)`. A brief answer's path also names the task id and the question
1460
+ id. A body field never names a path, and a field the route does not know is a `400`.
1330
1461
 
1331
1462
  **Authentication.** Each server process makes a random token (`secrets.token_urlsafe(32)`). `GET /`
1332
1463
  (and `/index.html`) carries it as `<meta name="forge-ui-token" content="...">` as the first element
@@ -1398,6 +1529,10 @@ object its stdout holds, when that parses as one.
1398
1529
  | anything else, a signal, a missing CLI, or a 0 with no JSON object | `502` | `bad gateway` |
1399
1530
  | timeout | `504` | `timeout` |
1400
1531
 
1532
+ A brief answer is the exception to the exit-0 row: its CLI prints text, and exit 0 (including a late
1533
+ answer's notice) is `200 {"exit": 0, "output": "<stdout>"}` rather than `502` for a missing JSON object.
1534
+ A non-zero exit uses the row above and also carries `exit` and `output`.
1535
+
1401
1536
  For the controls routes, unknown run keys, solo runs (they have no controls) and runs the
1402
1537
  catalog does not hold are `404 {"error": "not found"}`. The issues, dismiss, delete, config and
1403
1538
  profile routes below accept plan and solo runs alike (`forge issues` and `forge runs rm` take both);
@@ -1429,6 +1564,8 @@ known or a spec runs is for the CLI to say (its `400` or `409` comes back as abo
1429
1564
  |---|---|
1430
1565
  | `{"action": "set", "key": "qa-threshold", "value": "P2"}` (`default` at run level removes the setting, `none` is P3; for a task `inherit` drops the override) | `control set <dir> qa-threshold P2 --actor ui --json` |
1431
1566
  | `{"action": "set", "key": "retry-budget", "value": "inherit", "task": "reader"}` | `control set <dir> retry-budget inherit --task reader --actor ui --json` |
1567
+ | `{"action": "set", "key": "summaries", "value": "on"}` (or `off`) | `control set <dir> summaries on --actor ui --json` |
1568
+ | `{"action": "set", "key": "summaries", "value": "inherit", "task": "reader"}` (`on` or `off` with `task` too) | `control set <dir> summaries inherit --task reader --actor ui --json` |
1432
1569
  | `{"action": "pin", "task": "graph", "spec": "sol:high:codex"}` | `control pin <dir> graph sol:high:codex --actor ui --json` |
1433
1570
  | `{"action": "unpin", "task": "graph"}` | `control unpin <dir> graph --actor ui --json` |
1434
1571
  | `{"action": "drain"}` | `control drain <dir> --actor ui --json` |
@@ -1440,7 +1577,8 @@ known or a spec runs is for the CLI to say (its `400` or `409` comes back as abo
1440
1577
 
1441
1578
  `value` is always a string. `task` is optional on `set`, and only for the keys the CLI allows it
1442
1579
  for; the page sets `max-parallel`, `infra-backoff` (`none` drops it) and `escalate-effort`
1443
- (`on`/`off`) plan-wide. `now` is a boolean. `add` is not exposed: a row is added to `tasks.tsv` by
1580
+ (`on`/`off`) plan-wide. `summaries` takes `on` or `off`, for the run or with a `task`, and `inherit` only with a `task`; `on`
1581
+ for a finished run makes the CLI start `forge summarize` (detached), which the route does not wait for. `now` is a boolean. `add` is not exposed: a row is added to `tasks.tsv` by
1444
1582
  hand, so its CLI is the place to queue it. A success is
1445
1583
  `200 {"ok": true, "changed": {...}, "applies": "...", "controls": {...}}`, where `controls` is the
1446
1584
  `GET` object after the change; `drain`, `resume` and `stop` answer the same way and are refused
@@ -1448,6 +1586,25 @@ hand, so its CLI is the place to queue it. A success is
1448
1586
  Its refusals before queueing (not live, a MERGED task, a spec that fails doctor) are the CLI's
1449
1587
  `409`/`400`; the scheduler applies or refuses it later, in the `log` line with that `request` id.
1450
1588
 
1589
+ ### `POST /api/runs/<key>/tasks/<id>/brief/<qid>`
1590
+
1591
+ Record one answer to a brief question. Body: `{"answer": "<text>"}`. `<id>` matches
1592
+ `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$` (a task id safe to pass as one argv). `<qid>` must match
1593
+ `^q[0-9]+$`; a path whose question segment does not is `400`, and the CLI is not called. `answer` is a
1594
+ string of 1 to 4096 characters with no NUL. A value that cannot be encoded as UTF-8 is refused too.
1595
+ Any other field, a missing or empty answer, or one longer than 4096 characters is
1596
+ `400 {"error": "invalid", "detail": ...}` before the CLI runs.
1597
+
1598
+ Runs `brief answer <plan dir> <id> <qid> --file - --actor ui`, with the answer as UTF-8 on stdin.
1599
+ Under the run's write lock (`409 {"error": "busy"}`). A solo run or an unknown key is `404`.
1600
+ Timeout 60 s. Read-only mode refuses it with every other write (`405`).
1601
+
1602
+ The CLI prints text and exits 0, including when the answer is late (the task had already started):
1603
+ that prints a notice and still exits 0, so the page can show it. The success body is
1604
+ `200 {"exit": 0, "output": "<stdout>"}`. A non-zero exit uses the mapping above (`2` is `400`
1605
+ `invalid`, `3` is `409` `refused`) and the body also has `exit` (the CLI's code) and `output`
1606
+ (stdout). `detail` is stderr, as for every other write.
1607
+
1451
1608
  ### `GET /api/runs/<key>/issues`
1452
1609
 
1453
1610
  `forge issues <dir> --json [flags]`: the findings the run left open. Query (all optional, an
@@ -1532,7 +1689,11 @@ it lists, and the repositories `forge dataset worktrees --json` names), `git sta
1532
1689
  worktree on disk, one `git show` per repository for the last commits and one `for-each-ref --merged
1533
1690
  HEAD` for merged branches; it lists the folders under each `.forge-worktrees` that no repository
1534
1691
  lists, and adds the dataset's history through `dataset worktrees --json`. Who owns a worktree is
1535
- forge's rule (`scripts/forge_worktrees.py`, the one `forge runs rm` uses). The answer is cached
1692
+ forge's rule (`scripts/forge_worktrees.py`, the one `forge runs rm` uses), given the task ids of the run
1693
+ plus the worktree's own folder name when its branch is `forge/<run id>/<that name>`. Every worktree folder
1694
+ under the `.forge-worktrees` folders it knows is asked too (`git -C <worktree> worktree list`), so a
1695
+ repository is listed even when every checkout the dataset names is gone; a repository git cannot list is
1696
+ named in `notes`. The answer is cached
1536
1697
  for 60 s per server; `refresh=1` reads everything again, any other parameter is a `400`. Sizes are
1537
1698
  walked in a background thread and are `null` until measured (`sizes_pending` counts the rest).
1538
1699
 
@@ -1548,17 +1709,41 @@ Row = {
1548
1709
  attribute | null), status, merged (branch merged into the repository's HEAD; null unknown),
1549
1710
  head, commit: {sha, time, subject} | null, created, removed (unix times or null), derived
1550
1711
  (true: from a run dir or the dataset, no dates), locked (git's reason, '' for none, null when
1551
- not locked), size (bytes or null), note, commands: [{label, command}]
1712
+ not locked), size (bytes or null), note, commands: [{label, command}], leftover (unknown rows only)
1552
1713
  }
1553
1714
  ```
1554
1715
 
1555
1716
  `status` is one of `in_use`, `dirty`, `locked`, `needed`, `failed`, `finished`, `missing`,
1556
- `foreign`, `unknown`, `removed`. Commands: `dirty` gets `git -C <path> status`; `failed` gets
1717
+ `foreign`, `unknown`, `removed`. A row on disk is never `removed`. Commands: `unknown` with `leftover` (no `.git`,
1718
+ or a `.git` file whose gitdir is gone) gets `rm -rf -- <path>`; `dirty` gets `git -C <path> status`; `failed` gets
1557
1719
  `git -C <repo> worktree remove <path>`; `finished` gets the same plus `git -C <repo> branch -d
1558
1720
  <branch>` when the branch is merged; `missing` gets `git -C <repo> worktree prune`; every other
1559
1721
  status gets none. Paths are quoted for the shell and no command has `--force`. `runs[].command` is
1560
1722
  `forge runs rm <run-dir> --worktrees --branches --dry-run`, null while the run is active.
1561
1723
 
1724
+ ### `GET /api/storage`
1725
+
1726
+ The Disk screen (`forge_ui/storage.py`). Read-only, so it answers in `--read-only` mode too, and it runs
1727
+ no forge command. It loads `scripts/forge_storage.py` read-only and calls its `report` for every
1728
+ registered run (the same as `forge du --all`, without writing its footprint file). The first ask starts
1729
+ one measurement in a background thread and answers `measuring`; the result is kept for 600 s per server,
1730
+ and `refresh=1` measures again (one measurement at a time). Any other parameter is a `400`.
1731
+
1732
+ ```
1733
+ Storage = {state: measuring | ready | error | unavailable, error, started, progress: {done, of} | null,
1734
+ data: Report | null (the last measurement, kept while the next one runs)}
1735
+ Report = {repo: null, computed, complete, totals: {runs, worktrees, data_home, reclaimable, snapshots, logs, strays},
1736
+ runs: [{path, run_id, repo, updated, total, snapshots, snapshot_count, logs, gz, compressible, strays,
1737
+ fractal, other, reclaimable, complete, commands: [{label, command}]}],
1738
+ strays: [{path, bytes, kind: dependencies | git, run}], worktrees: [{repo, run_id, path, bytes, complete}],
1739
+ data_home: {path, bytes, parts: {dataset, blobs, archive, exports, legacy, storage, other}} | null,
1740
+ commands: [{label, command, bytes?}]}
1741
+ ```
1742
+
1743
+ Sizes are disk usage in bytes. `reclaimable` is the snapshots plus an estimate for gzipping the log copies.
1744
+ A run's commands are `forge runs compact <run-dir> --logs` (when something can go) and `forge runs rm
1745
+ <run-dir> --dry-run`; the report's are `forge runs compact --all --logs` and `forge du --all`.
1746
+
1562
1747
  ### `GET /api/config?run=<key>` and `POST /api/config`
1563
1748
 
1564
1749
  The repository is the run's `repo_root` (see RunSummary) when that is an existing absolute directory,
@@ -1632,7 +1817,8 @@ set to `{"ok": false, "error"}` when the CLI printed one.
1632
1817
 
1633
1818
  A `body` is written to the CLI's stdin as JSON (`--file -`). That text is refused at 64 KiB
1634
1819
  with `400`; the HTTP body is already capped at 64 KiB (`413`) by the server, and a re-encode
1635
- can be the larger of the two. This is the one write that passes stdin. Checked before any CLI
1820
+ can be the larger of the two. A brief answer is the other write that passes stdin (the answer text,
1821
+ not a JSON object). Checked before any CLI
1636
1822
  runs, and a failure there calls nothing: `action` is one of the six; `name` and `from` match
1637
1823
  `^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$`; `key` matches `^(routing|policy)\.[a-z_.]+$` (the CLI still
1638
1824
  rejects a key of that shape that is not a real profile key); `value` is a string with no
@@ -1690,9 +1876,11 @@ Plain scripts unless noted; each defines one global and none parses API text as
1690
1876
  |---|---|---|
1691
1877
  | `runmodel.js` | `ForgeRunModel` | pure data, no DOM: the plate layout (archivision's `plate()`), the atlas, plan and execution models, forge-schedule's rules projected forward, the critical path, concurrency, the state of every node at a time `t` (replay, verification lanes included), the finish node's verification LEDs (`verifyLeds`: one per lane in lanes mode, else one per run), filters. Also a CommonJS module, for `node --test` |
1692
1878
  | `gantt.js` | `ForgeGantt` | `render(container, run, {now, onSelect, sel, replay, critical, ghosts})`: attempts on wall-clock time in lanes; `strip(container, run, {now, replay})`: busy attempts and model calls against `max_parallel`. Under the attempts, the finish rows: `verify` (single-command verifications; the newest split into its runs back to back from its start, dashed because that placement is approximate), a `verify · <lane>` row per lane of a lanes verification (each run and rerun at its own time; a run with no exit is UNKNOWN once it ended, never FAIL) and `final review`. A lane or run item opens the verification inspector |
1693
- | `panel.js` | `ForgePanel` | `render(host, ctx)`: the inspector for a run, task, execution, final review, verification, integration or Fractal node; fetches the lazy endpoints once per node; `ctx.diffHash(spec)` links into the diff viewer, `ctx.onFractal(task, TaskFractal)` hands a task's tree to the stage |
1879
+ | `panel.js` | `ForgePanel` | `render(host, ctx)`: the inspector for a run, task, execution, final review, verification, integration or Fractal node; for a task it opens on its `header` (its Prompt, Approach and Acceptance criteria texts, from the lazy detail once loaded), then its `trail`, its `summary` with the `summaries_override` switch, and `ForgeBrief`'s questions; fetches the lazy endpoints once per node; `ctx.diffHash(spec)` links into the diff viewer, `ctx.onFractal(task, TaskFractal)` hands a task's tree to the stage |
1694
1880
  | `verifyview.js` | `ForgeVerify` | `render(host, {run, now, fetchJSON, rerender})`: the verification inspector panel.js delegates to: while it runs, the elapsed time, step, last line and a flag past 5 minutes without output, and a live tail of the followed lane's log (or the single log) read again each poll; when it failed, the failing tests first, grouped by lane with new or known, each opening its lane's log at its line (in an export, the tail); a lanes table (state, time, reruns, counts). Pure helpers (`model`, `laneRow`, `groupFailing`, `idleWarning`, `openStep`, `tailLane`, `logPath`, `linesPath`, `tailLines`) are a CommonJS module too |
1695
1881
  | `checksview.js` | `ForgeChecks` | where each task stands and the checks its agents ran: `cell(task, now, ctx)` (the task table's Now column: the running call and for how long, a `quiet N min` flag past 5 minutes without output, or why it waits), `nowSection`, `execSection` and the attempts' checks and acceptance-criteria lines (`taskChecks`, `underExecution`, `attemptCriteria`) for panel.js, `schedulerFields` (the run inspector), `banner(head, ctx)` (the run header: environment problems more than one task met, read again at most every 15 s while tasks run) and `tick(root, now)`, which app.js calls each refresh to move `data-since`, `data-until` and `data-quiet` times. Pure helpers (`nowModel`, `waitingModel`, `nowRank`, `checkRow`, `countsText`, `coverageModel`, `bannerProblems`, `schedulerModel`, `quietText`, `untilText`) are a CommonJS module too |
1882
+ | `controls.js` | `ForgeControls` | the run and task control panels that panel.js mounts (`mountRun`, `mountTask`) and the pure model under them: what each key is called and where it applies (`KEYS`), `prepare` (a draft's request body and confirm text), `bodyFor`, `savedText` and `agoText`. Every change goes through `ForgeUI` (uikit.js) to `POST /api/runs/<key>/controls`. Also a CommonJS module |
1883
+ | `briefview.js` | `ForgeBrief` | a task's brief questions in the inspector (`taskSection(host, ctx, task)`: each question with its flags and answer, the parked ones in a collapsed *Parked (wider scope)*, and an answer box per question where the page can write, which posts to `POST …/brief/<qid>`), and the run's open questions above the task table (`renderList(host, {run, projections, now, href})`, flagged first, then by projected start). Pure helpers (`openQuestions`, `orderQuestions`, `startLine`) are a CommonJS module too |
1696
1884
  | `diffview.js` | `ForgeDiff` | `render(host, {run, spec, fetchJSON, rerender, href, closeHref})`: a DiffDetail with its findings under their lines; `spec` is `{kind: task, task, source, file}`, `{kind: final, name, file}` or `{kind: fractal, task, node, file}` |
1697
1885
  | `convo.js` | `ForgeConvo` | `render(host, {run, spec: {task, exec}, brief, live, fetchJSON, rerender, diffHash, closeHref, focus})`: an ExecutionTranscript as a timeline, with search, the errors and, while the execution runs, a read of its log every 2.5 s; `focus` (an event index) opens it at that event once and stops following the end |
1698
1886
  | `files.js` | `ForgeFiles` | `matrix(data, run, opts)` (pure: Files as rows of dirs and files against task columns by wave) and `render(host, data, {run, sel, onSelectTask, diffHref, prefs, savePrefs})`: the run's Files mode. Also a CommonJS module |
@@ -4,8 +4,8 @@ The server never writes a run dir, a repo or forge's config itself. A write is o
4
4
  `<forge root>/forge ...` with an argv list and no shell, in its own process group, under a lock;
5
5
  this module holds the route table, the body validation, the call and the mapping of the CLI's
6
6
  exit code to an HTTP answer. server.py does the authentication and hands each authenticated POST
7
- to `dispatch`. Profile create and edit are the one call that writes a JSON body to the CLI's
8
- stdin (`--file -`); every other call has no stdin.
7
+ to `dispatch`. Profile create and edit write a JSON body to the CLI's stdin (`--file -`);
8
+ a brief answer writes the answer text the same way. Every other call has no stdin.
9
9
  """
10
10
  from __future__ import annotations
11
11
 
@@ -34,6 +34,10 @@ MAX_DECIDE_VALUE = 256
34
34
  # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
35
35
  # at 64 KiB by the server; this caps the stdin text itself, which a re-encode can make larger.
36
36
  MAX_PROFILE_BODY = 64 * 1024
37
+ # A brief answer, in characters. The CLI then keeps the leading 4 KiB of what remains after it
38
+ # strips control characters; this bound is the one the route enforces before that call.
39
+ MAX_ANSWER = 4096
40
+ _QID = re.compile(r'^q[0-9]+$')
37
41
  _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
38
42
  _PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
39
43
  _PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
@@ -133,8 +137,9 @@ def run_cli(argv, timeout, stdin=None):
133
137
  On timeout the whole group gets SIGTERM, then SIGKILL after TERM_WAIT_S, and the leader is
134
138
  reaped before this returns, so a caller that holds a lock can release it knowing nothing of
135
139
  the call is still running. The CLI's environment is the server's plus `cli_env`. `stdin` is
136
- bytes written to the process and then closed, or None. Only a profile create or edit passes
137
- any, and only after its size was checked; every other call keeps stdin closed.
140
+ bytes written to the process and then closed, or None. A profile create or edit passes the
141
+ profile object, and a brief answer passes the answer text, each only after its size was
142
+ checked; every other call keeps stdin closed.
138
143
  """
139
144
  env = dict(os.environ, **cli_env) if cli_env else None
140
145
  try:
@@ -205,6 +210,26 @@ def map_exit(result):
205
210
  return status, body
206
211
 
207
212
 
213
+ def _text_exit(result):
214
+ """(status, body) for a CLI that prints text. Exit 0 is success even with no JSON object.
215
+
216
+ A late brief answer prints a notice and exits 0. `output` is stdout, so the page can show it.
217
+ A non-zero exit uses the same status mapping as `map_exit` and also carries `exit` and `output`.
218
+ """
219
+ if result.timed_out:
220
+ return 504, {'error': 'timeout', 'detail': TIMEOUT_DETAIL}
221
+ if result.error:
222
+ return 502, {'error': 'bad gateway', 'detail': result.error[:DETAIL_MAX]}
223
+ output = result.stdout
224
+ if result.code == 0:
225
+ return 200, {'exit': 0, 'output': output}
226
+ status, error = _EXITS.get(result.code, (502, 'bad gateway'))
227
+ detail = _message(result.stderr) if result.code == 3 else _last_line(result.stderr)
228
+ body = {'error': error, 'detail': detail or f'the forge CLI exited {result.code}',
229
+ 'exit': result.code, 'output': output}
230
+ return status, body
231
+
232
+
208
233
  # -------------------------------------------------------------------------------------- validation
209
234
 
210
235
  class BadBody(Exception):
@@ -268,12 +293,14 @@ class Context:
268
293
  found = self.server.catalog.locate(self.key)
269
294
  return found[0] if found and found[1] in kinds else None
270
295
 
271
- def call(self, *args, limit=None, stdin=None):
296
+ def call(self, *args, limit=None, stdin=None, json_stdout=True):
272
297
  """One CLI call, mapped to (status, body); the run's lock is the caller's to hold.
273
298
 
274
299
  `limit` is the route's timeout; a timeout given to `dispatch` (a test's) replaces it.
275
- `stdin` is bytes for the one profile write that uses `--file -`, or None."""
276
- return map_exit(run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin))
300
+ `stdin` is bytes for a call that uses `--file -`, or None. `json_stdout` is false when a
301
+ successful CLI prints text (a brief answer, including a late-answer notice)."""
302
+ result = run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin)
303
+ return map_exit(result) if json_stdout else _text_exit(result)
277
304
 
278
305
  def locked(self, work):
279
306
  """work() under the run's lock; 409 busy when another write to this run is in flight."""
@@ -305,6 +332,43 @@ def _change(ctx):
305
332
  return ctx.locked(lambda: ctx.call('control', action, path, *tail, '--actor', 'ui', '--json'))
306
333
 
307
334
 
335
+ def _answer_text(value):
336
+ """The answer string, or BadBody. 1 to MAX_ANSWER characters, no NUL, encodable as UTF-8."""
337
+ if not isinstance(value, str):
338
+ raise BadBody('answer must be a string')
339
+ if '\x00' in value:
340
+ raise BadBody('answer must not contain a NUL')
341
+ if not 1 <= len(value) <= MAX_ANSWER:
342
+ raise BadBody(f'answer must be 1 to {MAX_ANSWER} characters')
343
+ try:
344
+ return value.encode('utf-8')
345
+ except UnicodeEncodeError:
346
+ raise BadBody('answer must be valid text')
347
+
348
+
349
+ def _brief_answer(ctx):
350
+ """POST an answer: `forge brief answer <plan> <task> <qid> --file - --actor ui`, text on stdin.
351
+
352
+ A late answer is exit 0 with a notice on stdout, so it is a success and the page can show it.
353
+ """
354
+ ctx.route = 'brief'
355
+ task, qid = ctx.parts
356
+ try:
357
+ if not isinstance(ctx.body, dict):
358
+ raise BadBody('body must be a JSON object')
359
+ if not _QID.fullmatch(qid):
360
+ raise BadBody('qid must match ^q[0-9]+$')
361
+ _check_fields(ctx.body, ('answer',))
362
+ stdin = _answer_text(ctx.body.get('answer'))
363
+ except BadBody as exc:
364
+ return _invalid(str(exc))
365
+ path = ctx.locate(('plan',))
366
+ if path is None:
367
+ return 404, {'error': 'not found'}
368
+ return ctx.locked(lambda: ctx.call('brief', 'answer', path, task, qid, '--file', '-', '--actor', 'ui',
369
+ stdin=stdin, json_stdout=False))
370
+
371
+
308
372
  # ----------------------------------------------------------------- issues, delete and config routes
309
373
 
310
374
  def _invalid(detail):
@@ -839,6 +903,19 @@ def _project_memories(ctx):
839
903
  return (404, {'error': 'not found'}) if found is None else (200, found)
840
904
 
841
905
 
906
+ def _storage(ctx):
907
+ # The Disk screen (#139): forge_storage's report, measured in the background and cached per server
908
+ # (storage.CACHE_S); ?refresh=1 measures again.
909
+ from forge_ui import storage
910
+ ctx.route = 'storage'
911
+ try:
912
+ params = _query_params(ctx.query, ('refresh',))
913
+ refresh = _bit(params, 'refresh')
914
+ except BadBody as exc:
915
+ return _invalid(str(exc))
916
+ return 200, storage.screen(ctx.server).answer(refresh=refresh)
917
+
918
+
842
919
  def _worktrees(ctx):
843
920
  # The Worktrees screen (#125): git and the run dirs, read here, plus the history `forge dataset worktrees`
844
921
  # keeps, read through the CLI. Cached per server (worktrees.CACHE_S); ?refresh=1 reads everything again.
@@ -859,6 +936,8 @@ def _worktrees(ctx):
859
936
  ROUTES = [
860
937
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
861
938
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
939
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/tasks/([A-Za-z0-9][A-Za-z0-9._-]{0,127})/brief/([^/]+)'),
940
+ _brief_answer),
862
941
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_list),
863
942
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_file),
864
943
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues/dismiss'), _issues_dismiss),
@@ -869,6 +948,7 @@ ROUTES = [
869
948
  ('POST', re.compile(r'/api/config()'), _config_set),
870
949
  ('GET', re.compile(r'/api/models/reviewers()'), _reviewer_outcomes),
871
950
  ('GET', re.compile(r'/api/worktrees()'), _worktrees),
951
+ ('GET', re.compile(r'/api/storage()'), _storage),
872
952
  ('GET', re.compile(r'/api/projects()'), _projects),
873
953
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
874
954
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
@@ -877,12 +957,12 @@ ROUTES = [
877
957
 
878
958
 
879
959
  def match(method, path):
880
- """(handler, run key) for a route, or None."""
960
+ """(handler, match) for a route, or None. Group 1 of the match is the run key."""
881
961
  for verb, pattern, handler in ROUTES:
882
962
  if verb == method:
883
963
  found = pattern.fullmatch(path)
884
964
  if found:
885
- return handler, found.group(1)
965
+ return handler, found
886
966
  return None
887
967
 
888
968
 
@@ -895,7 +975,8 @@ def dispatch(server, cli, method, path, body, timeout=None, query=''):
895
975
  found = match(method, path)
896
976
  if found is None:
897
977
  return None
898
- handler, key = found
899
- ctx = Context(server, cli, key, body, timeout, query)
978
+ handler, matched = found
979
+ ctx = Context(server, cli, matched.group(1), body, timeout, query)
980
+ ctx.parts = matched.groups()[1:]
900
981
  status, obj = handler(ctx)
901
982
  return status, obj, ctx.route, ctx.key