@giamme/forge 0.12.0 → 0.12.1

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.
package/ui/docs/api.md CHANGED
@@ -13,6 +13,7 @@ forge_ui/diffs.py unified diffs: parsing, the ```diff fence of a review pr
13
13
  forge_ui/models.py per-run model facts (attempts and reviews) for the leaderboard, cached per run
14
14
  forge_ui/fractal.py Fractal child tasks under $XDG_STATE_HOME/forge/fractal, read through dir fds
15
15
  forge_ui/transcripts.py an agent CLI's `<role>.log` read as one conversation, whichever harness wrote it
16
+ forge_ui/checks.py the checks an agent ran, its running call and the environment problems it met, from a transcript
16
17
  forge_ui/server.py serves those dicts as JSON plus the static page, 127.0.0.1 only; authenticates writes
17
18
  forge_ui/control.py the write routes: each one is a forge CLI call (see Controls)
18
19
  forge_ui/static/ the page: index.html, app.js, style.css, graph.js and the scripts they load
@@ -66,6 +67,10 @@ written), and the reader must never raise because of one.
66
67
  | `tasks/<id>/qa.gate` | `threshold<TAB>decision<TAB>worst<TAB>n_confirmed<TAB>n_unlabelled<TAB>n_below` (`decision` is `accept` or `keep`, `-` for none) |
67
68
  | `tasks/<id>/known_issues.md` | the confirmed findings a threshold tolerated |
68
69
  | `tasks/<id>/dwarf.input`, `qa.input` | the prompts forge assembled; `<role>.delivered`, `<role>.resolved` the live dispatch files |
70
+ | `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) |
71
+ | `tasks/<id>/escalation.stop`, `split.suggested` | the retry policy stopped the task: `<attempts><TAB><model>`, and the split it suggests (free text) |
72
+ | `scheduler.live` | `{"pid": n}`: the scheduler running the plan; it is live while that process is |
73
+ | `drain`, `stop`, `max_parallel`, `infra.paused` | a live scheduler's controls (Controls below): a drain, a stop (`graceful` or `now`), a capacity, and its infrastructure pauses as `{"scopes": [{scope, class, harness, model, tasks, cycle, until, exhausted}]}` |
69
74
  | `tasks/<id>/attempts/<role>-<uuid>/` | one execution of the task: `task`, `dwarf` or `qa` |
70
75
  | `tasks/<id>/changes.diff` | `git diff --binary` of the task's work since its base, cumulative, rewritten every attempt; `changes.prev.diff` the previous attempt's; `committed.diff` base..the reviewed commit |
71
76
  | `tasks/<id>/drift.txt`, `conflict.files` | one path per line: files the diff changed without declaring them; files that conflicted on merge |
@@ -88,10 +93,11 @@ one of `task dwarf qa solo verification parallel` and `<uuid>` 32 lowercase hex
88
93
  |---|---|
89
94
  | `metrics.json` | `role`, `started` (monotonic), `wall_started` (epoch), `phase`, `phase_started` (monotonic), `elapsed_s` (seconds per phase, `total` once done), `exit_code` (`null` while in flight), `harness`, `prompt_bytes`, `input_tokens`, `cached_input_tokens`, `output_tokens`, `infra_class`, `shadow` |
90
95
  | `dataset.json` | may be absent: `parent` (the execution that started this one, e.g. `task-<uuid>`), `trigger`, `attempt_start` and `resume` (task executions) |
91
- | `<role>.resolved`, `.prompt`, `.last`, `.timedout` | copies made when it finished: the model resolution (`key=value`), the prompt, the final message, the timeout marker |
96
+ | `<role>.resolved`, `.prompt`, `.last`, `.timedout`, `.log`, `.clock` | copies made when it finished: the model resolution (`key=value`), the prompt, the final message, the timeout marker, the harness log and its clock |
92
97
 
93
- Only the transcript endpoint opens an execution's `.log` (a `dwarf`'s or `qa`'s, see
94
- ExecutionTranscript); no read opens a `.cmd`.
98
+ Only the transcript, checks and environment endpoints open an execution's `.log` and `.clock` (a
99
+ `dwarf`'s or `qa`'s, see ExecutionTranscript and Checks), and RunDetail reads the last 256 KB of a
100
+ running one's log for its `now`; no read opens a `.cmd`.
95
101
 
96
102
  **Task status** is `MERGED` if `tasks/<id>/merged` exists, otherwise the first word of
97
103
  `tasks/<id>/status`, otherwise `PENDING`.
@@ -166,6 +172,9 @@ def final_review_diff(path, name, source='plan') -> dict | None # a DiffDetai
166
172
  def files_detail(path, source='plan') -> dict | None # Files
167
173
  def run_findings(path, source='plan') -> dict | None # RunFindings
168
174
  def execution_transcript(path, name, source='plan') -> dict | None # an ExecutionTranscript
175
+ def execution_checks(path, name, source='plan') -> dict | None # ExecutionChecks
176
+ def task_checks(path, task_id, source='plan') -> dict | None # TaskChecks
177
+ def run_environment(path, source='plan') -> dict | None # RunEnvironment
169
178
  def fractal_detail(path, task_id, source='plan') -> dict | None # a TaskFractal
170
179
  def fractal_node(path, task_id, node, source='plan') -> dict | None # a FractalNodeDetail
171
180
  def fractal_node_diff(path, task_id, node, source='plan') -> dict | None # a DiffDetail
@@ -180,6 +189,7 @@ class Catalog:
180
189
  def final_review(self, key, name) -> dict | None
181
190
  def diff(self, key, task_id, which='current'), execution_diff(self, key, name),
182
191
  final_review_diff(self, key, name), files(self, key), findings(self, key), transcript(self, key, name),
192
+ execution_checks(self, key, name), task_checks(self, key, task_id), environment(self, key),
183
193
  fractal(self, key, task_id),
184
194
  fractal_node(self, key, task_id, node), fractal_node_diff(self, key, task_id, node),
185
195
  verification_log(self, key, lane=None, k=None, first=None) -> dict | None
@@ -229,6 +239,9 @@ its last 20,000 behind a leading `…`. Their `truncated` lists the field names
229
239
  | `GET /api/runs/<key>/files` | `200 Files` |
230
240
  | `GET /api/runs/<key>/findings` | `200 RunFindings` |
231
241
  | `GET /api/runs/<key>/executions/<qa-or-dwarf>/transcript` | `200 ExecutionTranscript` |
242
+ | `GET /api/runs/<key>/executions/<qa-or-dwarf>/checks` | `200 ExecutionChecks`; another role is a 404 |
243
+ | `GET /api/runs/<key>/tasks/<id>/checks` | `200 TaskChecks`; `<id>` as for TaskDetail |
244
+ | `GET /api/runs/<key>/environment` | `200 RunEnvironment` |
232
245
  | `GET /api/runs/<key>/verification/log[/lines/<n>]` | `200 VerificationLog` of `verification.log`: its tail, or with `/lines/<n>` a range |
233
246
  | `GET /api/runs/<key>/verification/retry/log[/lines/<n>]` | `200 VerificationLog` of `verification.retry.log`, a single command's rerun |
234
247
  | `GET /api/runs/<key>/verification/lanes/<lane>/log[/lines/<n>]` | `200 VerificationLog` of `verification.lane.<lane>.log` |
@@ -372,6 +385,12 @@ Every RunSummary field, plus:
372
385
  "ended": 1760622300.0}]},
373
386
  "final_review": FinalReviewSummary,
374
387
  "final_reviews": [FinalReviewSummary, ...],
388
+ "scheduler": {"live": true, "drained": false, "stopping": null, "max_parallel": 3,
389
+ "pauses": [{"scope": "model:codex/gpt-6", "class": "rate_limit", "harness": "codex", "model": "gpt-6",
390
+ "tasks": ["perf"], "cycle": 1, "until": 1760622130.0, "exhausted": false}]},
391
+ "sweep": {"at": 1760622050.0, "severity": "P3", "plausible": false, "tasks": ["sweep-1"], "findings": 2, "fixed": 1,
392
+ "dropped": [{"task": "page", "severity": "P3", "location": "ui/page.html:3", "summary": "Old markup.",
393
+ "reason": "changed", "merged_since": ["graph"]}]},
375
394
  "deferrals": ["wave 2: docs deferred (file overlap with a task already in this wave)"],
376
395
  "findings_available": true,
377
396
  "warnings": ["tasks/graph/route.jsonl line 2: not JSON"],
@@ -448,6 +467,17 @@ Every RunSummary field, plus:
448
467
  epoch in the name), or `null`; `final_reviews` lists the newest 20, newest first. That newest
449
468
  review's `outdated` is its own. `final_review_outdated` stays the published review's flag, so
450
469
  the two differ when a newer review exists than the one `final-review` links to.
470
+ - `scheduler`: `live` is whether the pid in `scheduler.live` is a running process. Only then are the
471
+ rest read: `drained` (a `drain` file), `stopping` (`stop` holds `graceful` or `now`, else `null`),
472
+ `max_parallel` (the `max_parallel` file when it holds 1 to 64, else `null`) and `pauses` (the scopes of
473
+ `infra.paused`, `[]` without it); while no scheduler runs they are `false`, `null`, `null` and `[]`.
474
+ A solo run's `scheduler` is `null`.
475
+ - `sweep`: the run's finding sweep (`run --sweep`), `null` without `sweep/plan.json` (and for a solo
476
+ run). `tasks` are its fix tasks (tasks with a `sweep.json`), `findings` how many findings they took
477
+ and `fixed` how many of those their reviews marked fixed (a fix task counts once it merged).
478
+ `dropped` lists, from the plan, at most 200 findings the sweep left for `forge issues`, each with
479
+ its `reason` (`below-severity`, `dismissed`, `no-location`, `file-gone`, `changed`, `duplicate`,
480
+ `group-cap`, `over-max`, `no-model`) and, for `changed`, the tasks that `merged_since` the review.
451
481
  - `deferrals`: the non-empty lines of `deferrals.txt`, `[]` when it is missing.
452
482
  - `findings_available`: whether `scripts/forge-contract.py` could be loaded.
453
483
  - `fractal`: `null` without `fractal-selection.json`, else `{"enabled", "run", "available", "reason"}`
@@ -503,7 +533,14 @@ Every RunSummary field, plus:
503
533
  "findings": FindingsSummary,
504
534
  "gate": {"threshold": "P2", "decision": "keep", "worst": "P3", "n_confirmed": 1,
505
535
  "n_unlabelled": 0, "n_below": 1},
506
- "known_issues": true
536
+ "known_issues": true,
537
+ "now": {"role": "dwarf", "execution": "dwarf-…", "attempt": 2, "phase": "model", "phase_started": 1760621200.0,
538
+ "started": 1760621195.0, "last_output_at": 1760621410.2,
539
+ "call": {"kind": "command", "command": "npm test", "tool": null, "started": 1760621390.0, "check": "test"}},
540
+ "waiting": null,
541
+ "sweep": null,
542
+ "swept": [{"id": "S1", "severity": "P2", "confidence": "CONFIRMED", "task": "reader", "location": "ui/reader.py:12",
543
+ "summary": "Status is read twice.", "status": "fixed", "note": null, "by": "sweep-1"}]
507
544
  }
508
545
  ```
509
546
 
@@ -547,6 +584,28 @@ Every RunSummary field, plus:
547
584
  - `gate`: the parsed `qa.gate` (`n_*` integers, `-` is `null`), or `null` when missing or
548
585
  malformed (malformed is warned).
549
586
  - `known_issues`: whether `known_issues.md` is a non-empty file.
587
+ - `now`: `null` unless the task is `RUNNING`. Then where it is: the newest running non-shadow `dwarf`
588
+ or `qa` execution (`role`, `execution`, `attempt`, `phase`, `phase_started`, `started`), else the
589
+ running task execution, and, for an agent, `last_output_at` (its log's mtime) and `call`: the call
590
+ it is making, read from the last 256 KB of `tasks/<id>/<role>.log` (the run dir's for a solo run),
591
+ or `null` while it thinks or writes. `call.kind` is `command`, `tool` or `edit`; `command` keeps
592
+ 400 characters; `check` is the command's kind as Checks below tells it (`null` for none);
593
+ `started` comes from the harness's own times, from `<role>.clock`, or, when the call is the log's
594
+ last line, the log's mtime. Every value but the call is `null` when unknown.
595
+ - `waiting`: why a task that is not running waits, as far as the run dir says, or `null`:
596
+ `{"kind": "escalation", "attempts", "model", "split"}` when `escalation.stop` exists (whether or
597
+ not a scheduler runs); else, while `scheduler.live` is true, for a `PENDING` or `INFRA` task:
598
+ `infra` (a pause in `scheduler.pauses` holds it: scope `all`, or its id in `tasks`; the pause's
599
+ keys plus `kind`), then for a `PENDING` task `deps` (`on`: its deps not merged, `stopped`: those
600
+ in a stopped status such as `FAIL`), `stopping` (`mode`), `drained`, `overlap` (`on`: running
601
+ tasks whose files overlap its own, as forge-schedule.py tells overlap), `slot` (`running`,
602
+ `max_parallel`: the run is at its capacity) or `next` (nothing holds it).
603
+ - `sweep`: `null` unless the task is a finding sweep's fix task (it has a `sweep.json`). Then `file`
604
+ and `findings`, each `{id, severity, confidence, task, location, summary, status, note}`: `task` is
605
+ the task the finding came from, `status` what the fix task's review said of it (`fixed`,
606
+ `not-fixed`, or `unreported` when it merged without a line for it; read from `sweep.outcome.json`)
607
+ and `null` until the fix task merged, `note` the review's words on it.
608
+ - `swept`: this task's findings a fix task took, the same objects plus `by` (the fix task); `[]`.
550
609
  - Text fields are `null` when the file is missing.
551
610
 
552
611
  A solo run's one task uses this same shape. `id` is `solo` and `title` is the goal, or
@@ -558,7 +617,8 @@ in `attempts.tsv`, or `null`. `escalations`, `route` and `shadow` are empty. `ve
558
617
  `qa_tail` come from `qa.last`, and `prompt` comes from `prompt.md`. `deps` and `files` are
559
618
  `[]`; `difficulty`, `accepted_by`, `approach` and `retry_findings` are `null`; `accepted` is
560
619
  false; `accepted_attempt` and `accepted_over` are `null`; `explored` is false; `clef` is
561
- `{first_pass: null, retry_pass: {}}`. `request` on the detail is `request.md`.
620
+ `{first_pass: null, retry_pass: {}}`; `waiting` and `sweep` are `null`, `swept` is `[]`. `request` on
621
+ the detail is `request.md`.
562
622
 
563
623
  ## Execution
564
624
 
@@ -829,12 +889,90 @@ or `input` when there are none), `tool` (`tool`, `input`, `output`), `result` (`
829
889
  with `same: true` when the last message said it; `tokens`), `error` (`text`), `text` (`text`,
830
890
  `stream: "stderr"` for lines between JSON events) and `gap` (`count` events left out). Any event
831
891
  may have `t` (epoch seconds), `id` (the harness's call id), `error` (`true` for a failed call or a
832
- non-zero exit, `false` for a call answered without one) and `running: true` (a call not finished yet). `tokens` are the run's totals
892
+ non-zero exit, `false` for a call answered without one) and `running: true` (a call not finished yet); an
893
+ answered `command`, `edit` or `tool` may have `ended` (epoch seconds). Times are the harness's own when
894
+ its lines carry them (claude's and opencode's), else read from `<role>.clock` beside the log: a line
895
+ is timed by the first sample that saw the log reach its end, to within the clock's second (codex and
896
+ grok write no times; a run from before the clock has none). `tokens` are the run's totals
833
897
  (`input` counts cached input too). A message, a reasoning or a result keeps 20,000 characters, a
834
898
  command, an input or an output its first two thirds and last third of 8,000 around `… n
835
899
  characters …` (`<key>_cut` holds n). A log over 32 MB is read from its end; past 5,000 events or
836
900
  4,000,000 characters the middle is left out (a `gap` event, `truncated: true`). Parses are kept by
837
- the log's `(path, size, mtime_ns)` and the session file's.
901
+ the log's `(path, size, mtime_ns)`, its clock's and the session file's.
902
+
903
+ ## Checks (`forge_ui/checks.py`)
904
+
905
+ The checks an agent ran are the `command` events of its transcript that are tests, type checks,
906
+ lints or builds. A command is split on `&&`, `||`, `;`, `|` and newlines; each part loses its
907
+ environment assignments and wrappers (`env`, `timeout 600`, `uv run`, `npx`, `poetry run`, a
908
+ `sh -c '…'` around it, …) and a `cd` part is left out. `kind` is the first of `test`, `typecheck`,
909
+ `lint`, `build` that some part is (pytest and `python -m unittest`, `npm test`, `node --test`, jest,
910
+ vitest, mocha, `go test`, `cargo test`, a `test`/`check` shell script; tsc, mypy, pyright, `bash -n`,
911
+ `cargo check`, `go vet`; eslint, ruff, flake8, shellcheck, `cargo clippy`, a formatter with
912
+ `--check`; `npm run build`, `cargo build`, plain `make`, …).
913
+
914
+ ExecutionChecks (a `dwarf` or `qa` execution):
915
+
916
+ ```json
917
+ {"run": "3f9a0c1d2e4b", "execution": "dwarf-…", "role": "dwarf", "state": "done", "attempt": 1, "spec": "luna",
918
+ "harness": "codex", "source": "log", "truncated": false, "last_output_at": null,
919
+ "owner": {"kind": "task", "id": "api"},
920
+ "checks": [{"index": 4, "command": "npm test", "kind": "test", "exit": 1, "failed": true, "running": false,
921
+ "started": 1760620100.0, "ended": 1760620232.0, "duration_s": 132.0,
922
+ "counts": {"passed": 41, "failed": 3, "skipped": 0}, "tail": "…last lines…"}],
923
+ "call": null,
924
+ "environment": [{"index": 2, "command": "npm run db:up", "problem": "docker-pools",
925
+ "label": "Docker ran out of network address pools", "line": "Error response from daemon: …"}],
926
+ "criteria": [{"command": "npm test", "kind": "test", "status": "ran", "by": {"index": 4}}],
927
+ "warnings": []}
928
+ ```
929
+
930
+ - `index` is the event's place in the ExecutionTranscript (the conversation view's `ev-<index>`);
931
+ `command` keeps 1,000 characters. `failed` is a failed call or a non-zero exit; `duration_s` is
932
+ `ended` minus `started` when both are known. `counts` is what the output's summary says:
933
+ `{passed, failed, skipped}` (pytest, unittest, forge's `tests/run_tests.py`, `node --test`, jest,
934
+ vitest, mocha, Playwright, cargo, `go test -v`) or `{errors, warnings}` (tsc, mypy, eslint, ruff,
935
+ pyright), else `null`. `tail` is a failed check's last 6 non-empty output lines, else `null`.
936
+ - `call` is the call not answered yet (`{index, kind, command, tool, started, check}`; the newest
937
+ when several run at once), or `null`. `last_output_at` is the log's mtime while it runs, else `null`.
938
+ - `environment`: each problem a failed command met that is not only a reader (`rg`, `grep`, `cat`,
939
+ `git`, `ls`, …): `docker-daemon`, `docker-pools`, `container`, `port` (EADDRINUSE), `sandbox`
940
+ (EPERM, `Operation not permitted`), `refused` (ECONNREFUSED), `network` (DNS, unreachable), `disk`
941
+ (ENOSPC) and `missing-tool` (`command not found`), with `label` and the first line that shows it
942
+ (240 characters).
943
+ - `criteria`: the check commands the owner task's `prompt.md` names under an `## Acceptance
944
+ criteria` heading (in code spans, or a fenced block's lines), each once, against this execution's
945
+ checks: `status` is `ran` (a check had every word of it), `similar` (one by the same program, of
946
+ the same kind) or `missing`; `by` names the matching check. `[]` for a final review or a shadow.
947
+
948
+ TaskChecks:
949
+
950
+ ```json
951
+ {"run": "3f9a0c1d2e4b", "task": "api",
952
+ "criteria": [{"command": "npm test", "kind": "test"}, {"command": "npx tsc --noEmit", "kind": "typecheck"}],
953
+ "attempts": [{"attempt": 1, "running": false, "executions": [ExecutionChecks without run/owner/criteria/warnings, ...],
954
+ "criteria": [{"command": "npm test", "kind": "test", "status": "ran",
955
+ "by": {"execution": "qa-…", "role": "qa", "index": 1}},
956
+ {"command": "npx tsc --noEmit", "kind": "typecheck", "status": "missing", "by": null}]}],
957
+ "truncated": [], "warnings": []}
958
+ ```
959
+
960
+ Every non-shadow `dwarf` and `qa` execution of the task, by attempt; an attempt's `criteria` hold
961
+ against the checks of all its agents, and `running` is whether one of them runs.
962
+
963
+ RunEnvironment: the environment problems of every task's agents, each once, in the order above:
964
+
965
+ ```json
966
+ {"run": "3f9a0c1d2e4b",
967
+ "problems": [{"problem": "docker-pools", "label": "Docker ran out of network address pools",
968
+ "tasks": ["schema", "api"], "count": 2,
969
+ "hits": [{"task": "schema", "attempt": 1, "role": "dwarf", "execution": "dwarf-…", "index": 0,
970
+ "command": "npm run db:up", "line": "Error response from daemon: …"}]}],
971
+ "warnings": []}
972
+ ```
973
+
974
+ `tasks` in plan order, `count` every failed command that met it, `hits` the first 50. A finished
975
+ execution's problems are kept by its log's and clock's signature.
838
976
 
839
977
  ## VerificationLog
840
978
 
@@ -1019,8 +1157,8 @@ difficulty paths deps model` each), `decomposition_history` (its newest 20, each
1019
1157
 
1020
1158
  - It holds `style.css` (with the labels' face, `D-DINCondensed-Bold.woff2`, inlined as a `data:`
1021
1159
  URL) and the classic scripts the run view uses (`theme.js icons.js datatable.js shell.js
1022
- runmodel.js cloudmodel.js graph.js gantt.js panel.js diffview.js convo.js files.js map3d.js search.js
1023
- app.js`), inline; the import map; a `<script type="application/json" id="forge-snapshot">` with
1160
+ runmodel.js cloudmodel.js graph.js gantt.js verifyview.js checksview.js panel.js diffview.js convo.js files.js
1161
+ map3d.js search.js app.js`), inline; the import map; a `<script type="application/json" id="forge-snapshot">` with
1024
1162
  `{meta, api}`; and a `<script type="text/plain" id="forge-stage">` holding `iso.js`,
1025
1163
  `cloud3d.js`, `findings3d.js`, `stagectl.js` and `scene3d.js` bundled into one module (each
1026
1164
  module in its own scope, relative imports bound to the earlier ones' exports, `createStage`
@@ -1029,13 +1167,14 @@ difficulty paths deps model` each), `decomposition_history` (its newest 20, each
1029
1167
  it (server.api_get): `/api/runs` (this run only), the RunDetail, every TaskDetail, every
1030
1168
  ExecutionDetail the RunDetail names, every FinalReviewDetail, Files, RunFindings, and the
1031
1169
  Fractal trees and nodes. With `texts=1` also every diff the page can open (each task's diff and its `sources`,
1032
- each final review's, each Fractal node's), every `dwarf` and `qa` ExecutionTranscript (at most 2 MB each),
1170
+ each final review's, each Fractal node's), every `dwarf` and `qa` ExecutionTranscript (at most 2 MB each)
1171
+ and ExecutionChecks, every TaskChecks, the RunEnvironment,
1033
1172
  and the VerificationLog tail of `verification.log`, of each lane's log and of each lane run's log
1034
1173
  (under their tail paths; line ranges are not stored, so the page shows the tail).
1035
1174
  - `texts=0` (the default) nulls these keys wherever they hold a string, list or object: `prompt
1036
1175
  last request log_tail dwarf_tail qa_tail qa_last qa_input tasks_summary known_issues texts text
1037
- planning_last approach retry_findings dwarf_input error last_line message excerpt tail lines`, and stores no
1038
- diff and no transcript. A finding keeps its `summary`, a failing test its `name`.
1176
+ planning_last approach retry_findings dwarf_input error last_line message excerpt tail lines call split`,
1177
+ 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`.
1039
1178
  - `paths=0` (the default) makes every string that is a whole absolute path (but `/api/…`, `url`s
1040
1179
  and `command`s) its last component, and replaces the run dir, the repo and the home dir inside other
1041
1180
  strings with their last component (`~` for home).
@@ -1292,8 +1431,9 @@ Plain scripts unless noted; each defines one global and none parses API text as
1292
1431
  | `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 |
1293
1432
  | `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 |
1294
1433
  | `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 |
1434
+ | `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 |
1295
1435
  | `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}` |
1296
- | `convo.js` | `ForgeConvo` | `render(host, {run, spec: {task, exec}, brief, live, fetchJSON, rerender, diffHash, closeHref})`: an ExecutionTranscript as a timeline, with search, the errors and, while the execution runs, a read of its log every 2.5 s |
1436
+ | `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 |
1297
1437
  | `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 |
1298
1438
  | `cloudmodel.js` | `ForgeCloudModel` | pure: projects, per-run facts, the cloud's filters, its five layouts (anchors from every run, dragged runs kept), label picking, layout files. Also a CommonJS module |
1299
1439
  | `cloudui.js` | `ForgeCloudUI` | `create(root, ctx)`: the cloud's filter panel, layout and shape switches, position tools, legend and run card; a list of the same runs without 3D |
@@ -1310,7 +1450,7 @@ Routes (the URL hash): `#/` the map of every run; `#/cloud`, `#/cloud/runs/<key>
1310
1450
  selected), `#/cloud/projects/<id>` (a project in focus), `#/cloud/models/<alias>` (the cloud
1311
1451
  filtered to that model); `#/models` the leaderboard; `#/runs/<key>`; `…/tasks/<id>`;
1312
1452
  `…/tasks/<id>/executions/<name>`; `…/executions/<name>` (an execution that belongs to no
1313
- task); `…/final-review[/<name>]`; `…/verification`; `…/integration`; `…/tasks/<id>/fractal/<node>`;
1453
+ task); an agent's conversation, `…/executions/<name>/conversation[/event/<n>]` after either; `…/final-review[/<name>]`; `…/verification`; `…/integration`; `…/tasks/<id>/fractal/<node>`;
1314
1454
  and the diff viewer: `…/tasks/<id>/diff[/<source>][/file/<path>]` (`source` is `current`, `prev`,
1315
1455
  `committed`, `existing` or an execution), `…/final-review/<name>/diff[/file/<path>]`,
1316
1456
  `…/tasks/<id>/fractal/<node>/diff[/file/<path>]` (`path` percent-encoded whole).
@@ -0,0 +1,331 @@
1
+ """The checks an agent ran, read from its transcript (transcripts.py): each test, type check, lint or build command
2
+ with its exit, how long it took and the counts it printed; the call it is running now; the commands its brief's
3
+ acceptance criteria name that it never ran; and the environment problems its failed commands met (Docker, a
4
+ sandbox's EPERM, a port in use, …), which forge-ui groups across a run's tasks.
5
+
6
+ Nothing here opens a file: it reads the events transcripts.transcript() answers and the brief's text.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ KINDS = ('test', 'typecheck', 'lint', 'build')
13
+ COMMAND_CAP = 1000 # characters of a command kept in a check
14
+ LINE_CAP = 240 # of an environment problem's line
15
+ TAIL_LINES = 6 # of a failed check's output, its last non-empty lines
16
+ _ANSI = re.compile(r'\x1b\[[0-9;?]*[ -/]*[@-~]')
17
+
18
+ # ---------- what a command is ----------
19
+
20
+ _SPLIT = re.compile(r'\s*(?:&&|\|\||;|\||\n)\s*')
21
+ _WRAPPED = re.compile(r'''^(?:/\S+/)?(?:ba|z)?sh\s+-l?c\s+(['"])(.*)\1$''', re.S)
22
+ _PREFIX = re.compile(r'''^(?:[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*)\s+|env\s+|command\s+|exec\s+|time\s+|nice\s+(?:-n\s*-?\d+\s+)?
23
+ |timeout\s+(?:-\S+\s+)*\d+(?:\.\d+)?[smhd]?\s+|gtimeout\s+(?:-\S+\s+)*\d+[smhd]?\s+|xvfb-run\s+(?:-\S+\s+)*
24
+ |uv\s+run\s+(?:--?[A-Za-z-]+(?:[= ](?!-)\S+)?\s+)*|poetry\s+run\s+|pipenv\s+run\s+|hatch\s+run\s+|pdm\s+run\s+|rye\s+run\s+
25
+ |npx\s+(?:--yes\s+|-y\s+)?|pnpm\s+(?:exec|dlx)\s+|yarn\s+dlx\s+|bunx\s+|bundle\s+exec\s+|dotenv\s+(?:-\S+\s+)*--\s+)''', re.X)
26
+ _PY = r'(?:python(?:\d+(?:\.\d+)?)?|py)'
27
+ _PKG = r'(?:npm|pnpm|yarn|bun)'
28
+ # (kind, pattern), tried in this order on each part of a command
29
+ _PATTERNS = tuple((kind, re.compile(pattern)) for kind, pattern in (
30
+ ('test', _PY + r'\s+-m\s+(?:pytest|unittest|nose2?|tox|nox|green)\b'),
31
+ ('test', r'(?:pytest|py\.test|tox|nox|nose2?|ward)\b'),
32
+ ('test', _PY + r'\s+(?:-\S+\s+)*(?:\S*/)?(?:test_\S*|\S*_tests?|run_?tests|runtests|tests)\.py\b'),
33
+ ('test', _PKG + r'\s+(?:run(?:-script)?\s+)?(?:test|tests|t)(?:[:\-]\S*)?(?:\s|$)'),
34
+ ('test', r'node\s+(?:--\S+\s+)*--test\b'),
35
+ ('test', r'(?:jest|vitest|mocha|ava|tap|jasmine|karma|cypress\s+run|playwright\s+test|deno\s+test|bun\s+test)\b'),
36
+ ('test', r'go\s+test\b|cargo\s+(?:test|nextest)\b|(?:make|just|task)\s+(?:-\S+\s+)*(?:test|tests|check|test-\S+|check-\S+)\b'),
37
+ ('test', r'(?:\./)?(?:\S*/)?(?:test|tests|check|run-tests|run_tests)\.sh\b|(?:ba|z)?sh\s+(?:\S*/)?\S*(?:test|check)\S*\.sh\b'),
38
+ ('test', r'(?:rspec|rake\s+test|phpunit|vendor/bin/phpunit|dotnet\s+test|mvn\s+(?:-\S+\s+)*(?:test|verify)\b|'
39
+ r'(?:\./)?gradlew?\s+(?:-\S+\s+)*(?:test|check)\b|swift\s+test|ctest|mix\s+test|stack\s+test|cabal\s+test)'),
40
+ ('typecheck', r'(?:tsc|vue-tsc|mypy|dmypy|pyright|basedpyright|pyre|pytype|flow)\b|' + _PY + r'\s+-m\s+(?:mypy|pyright|py_compile|compileall)\b'),
41
+ ('typecheck', _PKG + r'\s+(?:run\s+)?(?:typecheck|type-check|types|tsc|check-types|check:types)\b'),
42
+ ('typecheck', r'cargo\s+check\b|go\s+vet\b|node\s+--check\b|(?:ba|z)?sh\s+-n\b'),
43
+ ('lint', r'(?:eslint|ruff|flake8|pylint|pycodestyle|pyflakes|golangci-lint|shellcheck|stylelint|biome|rubocop|hadolint|'
44
+ r'markdownlint|yamllint|actionlint|oxlint|swiftlint|ktlint|tflint|deno\s+lint|cargo\s+clippy)\b'),
45
+ ('lint', _PY + r'\s+-m\s+(?:ruff|flake8|pylint|pycodestyle)\b|' + _PKG + r'\s+(?:run\s+)?lint\S*'),
46
+ ('lint', r'(?:prettier|black|isort|gofmt|rustfmt|cargo\s+fmt|ruff\s+format)\b.*(?:--check|--diff|\s-l\b|\s-d\b)'),
47
+ ('build', _PKG + r'\s+(?:run\s+)?build\S*|(?:cargo|go|swift|dotnet|zig)\s+build\b|(?:\./)?gradlew?\s+(?:-\S+\s+)*build\b|'
48
+ r'mvn\s+(?:-\S+\s+)*(?:package|install|compile)\b|(?:vite|webpack|next|tsup|esbuild|rollup|parcel)\s+build\b|'
49
+ r'make(?:\s+-j\s*\d*)?(?:\s+(?:all|build))?$|docker\s+(?:compose\s+)?build\b'),
50
+ ))
51
+ # programs that only read: a failed one says nothing about the environment
52
+ _READERS = frozenset(('rg', 'grep', 'egrep', 'fgrep', 'cat', 'sed', 'awk', 'head', 'tail', 'less', 'more', 'ls', 'find', 'fd',
53
+ 'wc', 'nl', 'file', 'stat', 'tree', 'jq', 'diff', 'cmp', 'echo', 'printf', 'test', '[', 'which', 'type',
54
+ 'git', 'pwd', 'cd', 'true', 'false', 'basename', 'dirname', 'realpath', 'readlink', 'sort', 'uniq', 'cut'))
55
+
56
+
57
+ def parts(command):
58
+ """The commands a shell line runs, each without its env assignments and wrappers (`timeout 600`, `uv run`,
59
+ `npx`, …); `cd` steps are left out."""
60
+ out = []
61
+ for part in _SPLIT.split(command or ''):
62
+ part = part.strip().strip('()').strip()
63
+ inner = _WRAPPED.match(part)
64
+ if inner:
65
+ out.extend(parts(inner.group(2)))
66
+ continue
67
+ while True:
68
+ m = _PREFIX.match(part)
69
+ if not m or not m.group(0):
70
+ break
71
+ part = part[m.end():]
72
+ if part and not re.match(r'(?:cd|pushd|popd|export|set|source|\.)\b', part):
73
+ out.append(part)
74
+ return out
75
+
76
+
77
+ def classify(command):
78
+ """test, typecheck, lint or build when some part of the command is one (the first of those, in that order),
79
+ else None."""
80
+ found = set()
81
+ for part in parts(command):
82
+ for kind, pattern in _PATTERNS:
83
+ if pattern.match(part):
84
+ found.add(kind)
85
+ break
86
+ return next((kind for kind in KINDS if kind in found), None)
87
+
88
+
89
+ def _readonly(command):
90
+ programs = [part.split()[0].rsplit('/', 1)[-1] for part in parts(command) if part.split()]
91
+ return bool(programs) and all(program in _READERS for program in programs)
92
+
93
+
94
+ # ---------- what it printed ----------
95
+
96
+ _WORDS = {'passed': 'passed', 'passing': 'passed', 'pass': 'passed', 'xpassed': 'passed', 'ok': None,
97
+ 'failed': 'failed', 'failing': 'failed', 'fail': 'failed', 'error': 'failed', 'errors': 'failed',
98
+ 'skipped': 'skipped', 'pending': 'skipped', 'todo': 'skipped', 'xfailed': 'skipped', 'skip': 'skipped'}
99
+ _COUNTED = re.compile(r'(\d+)\s+(passed|failed|skipped|errors?|xfailed|xpassed|pending|todo)\b')
100
+ _SUMMARY = re.compile(r'^.*\b\d+\s+(?:passed|failed)\b.*$', re.M)
101
+
102
+
103
+ def _ints(**values):
104
+ return {key: int(value) for key, value in values.items() if value is not None}
105
+
106
+
107
+ def counts(output, kind=None):
108
+ """What a check's output says it found: {passed, failed, skipped} for tests, {errors, warnings} for type
109
+ checks and linters, or None. Read from the end of the output, where the summaries are."""
110
+ text = _ANSI.sub('', output or '')[-8000:]
111
+ if not text.strip():
112
+ return None
113
+ if kind in ('lint', 'typecheck'):
114
+ return _problems(text) or _tests(text)
115
+ return _tests(text) or _problems(text)
116
+
117
+
118
+ def _tests(text):
119
+ # cargo test: one line per test binary, summed
120
+ rows = re.findall(r'test result: \w+\. (\d+) passed; (\d+) failed; (\d+) ignored', text)
121
+ if rows:
122
+ return {key: sum(int(row[i]) for row in rows) for i, key in enumerate(('passed', 'failed', 'skipped'))}
123
+ # forge's tests/run_tests.py: "1639 tests in 312 classes: …; 75 skipped", then "OK" or "FAILED: 2 failures, 1 errors in …"
124
+ m = None
125
+ for m in re.finditer(r'^(\d+) tests in \d+ classes: .*; (\d+) skipped\s*\n(?:FAILED: (\d+) failures, (\d+) errors|OK)', text, re.M):
126
+ pass
127
+ if m:
128
+ total, skipped = int(m.group(1)), int(m.group(2))
129
+ failed = int(m.group(3) or 0) + int(m.group(4) or 0)
130
+ return {'passed': max(0, total - failed - skipped), 'failed': failed, 'skipped': skipped}
131
+ # unittest: "Ran 12 tests in 0.3s" then "OK (skipped=2)" or "FAILED (failures=1, errors=2)"
132
+ ran = list(re.finditer(r'^Ran (\d+) tests? in [\d.]+s\s*\n+\s*(OK|FAILED)\b(?: \(([^)]*)\))?', text, re.M))
133
+ if ran:
134
+ m = ran[-1]
135
+ detail = {key: int(value) for key, value in re.findall(r'(\w+)=(\d+)', m.group(3) or '')}
136
+ failed = detail.get('failures', 0) + detail.get('errors', 0) + detail.get('unexpected_successes', 0)
137
+ skipped = detail.get('skipped', 0) + detail.get('expected_failures', 0)
138
+ return {'passed': max(0, int(m.group(1)) - failed - skipped), 'failed': failed, 'skipped': skipped}
139
+ # node --test: "# pass 5", "# fail 1" (tap) or "ℹ pass 5" (spec)
140
+ node = dict(re.findall(r'^[#ℹ]\s+(pass|fail|skipped|todo|cancelled)\s+(\d+)\s*$', text, re.M))
141
+ if 'pass' in node:
142
+ n = lambda key: int(node.get(key, 0))
143
+ return {'passed': n('pass'), 'failed': n('fail') + n('cancelled'), 'skipped': n('skipped') + n('todo')}
144
+ # mocha: "5 passing (20ms)", "1 failing", "2 pending", each on its own line
145
+ mocha = dict((word, int(n)) for n, word in re.findall(r'^\s*(\d+) (passing|failing|pending)\b', text, re.M))
146
+ if 'passing' in mocha or 'failing' in mocha:
147
+ return {'passed': mocha.get('passing', 0), 'failed': mocha.get('failing', 0), 'skipped': mocha.get('pending', 0)}
148
+ # playwright: one line per outcome, the count first (" 1 failed", " 5 passed (10.2s)")
149
+ found = {}
150
+ for n, word in re.findall(r'^\s*(\d+) (passed|failed|flaky|skipped|did not run|interrupted)\b', '\n'.join(text.splitlines()[-40:]), re.M):
151
+ key = {'flaky': 'passed', 'did not run': 'skipped', 'interrupted': 'failed'}.get(word, word)
152
+ found[key] = found.get(key, 0) + int(n)
153
+ if found:
154
+ return {key: found.get(key, 0) for key in ('passed', 'failed', 'skipped')}
155
+ # pytest, jest ("Tests: 1 failed, 5 passed, 6 total"), vitest ("Tests 1 failed | 5 passed (6)"): the last line that
156
+ # counts passes or failures
157
+ lines = _SUMMARY.findall(text)
158
+ if lines:
159
+ found = {}
160
+ for n, word in _COUNTED.findall(lines[-1]):
161
+ key = _WORDS.get(word)
162
+ if key:
163
+ found[key] = found.get(key, 0) + int(n)
164
+ if found:
165
+ return {key: found.get(key, 0) for key in ('passed', 'failed', 'skipped')}
166
+ # go test: one line per test with -v, else one per package
167
+ go = re.findall(r'^\s*--- (PASS|FAIL|SKIP):', text, re.M)
168
+ if go:
169
+ return {'passed': go.count('PASS'), 'failed': go.count('FAIL'), 'skipped': go.count('SKIP')}
170
+ return None
171
+
172
+
173
+ def _problems(text):
174
+ m = None
175
+ for m in re.finditer(r'✖ (\d+) problems? \((\d+) errors?, (\d+) warnings?\)', text): # eslint
176
+ pass
177
+ if m:
178
+ return _ints(errors=m.group(2), warnings=m.group(3))
179
+ m = re.search(r'(\d+) errors?, (\d+) warnings?, \d+ (?:informations|notes)\s*$', text, re.M) # pyright
180
+ if m:
181
+ return _ints(errors=m.group(1), warnings=m.group(2))
182
+ found = re.findall(r'^Found (\d+) errors?\b', text, re.M) # tsc, mypy, ruff
183
+ if found:
184
+ return {'errors': int(found[-1])}
185
+ if re.search(r'^(?:Success: no issues found|All checks passed!|0 errors, 0 warnings)', text, re.M):
186
+ return {'errors': 0}
187
+ return None
188
+
189
+
190
+ def _tail(output):
191
+ lines = [line.rstrip() for line in _ANSI.sub('', output or '').splitlines() if line.strip()]
192
+ return '\n'.join(lines[-TAIL_LINES:]) or None
193
+
194
+
195
+ # ---------- environment problems ----------
196
+
197
+ # (id, label, pattern), in the order a banner lists them
198
+ ENVIRONMENT = tuple((key, label, re.compile(pattern, re.I | re.M)) for key, label, pattern in (
199
+ ('docker-daemon', 'Docker is not running', r'Cannot connect to the Docker daemon|Is the docker daemon running|'
200
+ r'docker daemon is not running|error during connect:.*docker'),
201
+ ('docker-pools', 'Docker ran out of network address pools', r'all predefined address pools have been fully subnetted|'
202
+ r'could not find an available, non-overlapping IPv4 address pool'),
203
+ ('container', 'A container is missing or its name is taken', r'No such container|container name "[^"]*" is already in use|'
204
+ r'Conflict\. The container name'),
205
+ ('port', 'A port is already in use', r'EADDRINUSE|address already in use|port is already allocated'),
206
+ ('sandbox', 'The sandbox refused an operation (EPERM)', r'\bEPERM\b|Operation not permitted|PermissionError: \[Errno 1\]'),
207
+ ('refused', 'A local service refused the connection', r'ECONNREFUSED|Connection refused|could not connect to server'),
208
+ ('network', 'No network or DNS', r'Could not resolve host|getaddrinfo (?:ENOTFOUND|EAI_AGAIN)|Temporary failure in name '
209
+ r'resolution|Network is unreachable|ENETUNREACH|nodename nor servname provided'),
210
+ ('disk', 'The disk is full', r'ENOSPC|No space left on device'),
211
+ ('missing-tool', 'A command is not installed', r'command not found|^\S+: not found$|is not recognized as an internal or external command'),
212
+ ))
213
+ LABELS = {key: label for key, label, _ in ENVIRONMENT}
214
+
215
+
216
+ def environment(output):
217
+ """[(id, the first line that shows it)] for each environment problem in a failed command's output."""
218
+ text = _ANSI.sub('', output or '')
219
+ found = []
220
+ for key, _, pattern in ENVIRONMENT:
221
+ m = pattern.search(text)
222
+ if m:
223
+ start = text.rfind('\n', 0, m.start()) + 1
224
+ end = text.find('\n', m.end())
225
+ line = text[start:end if end >= 0 else len(text)].strip()
226
+ found.append((key, line[:LINE_CAP]))
227
+ return found
228
+
229
+
230
+ # ---------- one transcript ----------
231
+
232
+ def _failed(ev):
233
+ return bool(ev.get('error')) or ev.get('exit') not in (None, 0)
234
+
235
+
236
+ def _command(text):
237
+ text = text or ''
238
+ return text if len(text) <= COMMAND_CAP else text[:COMMAND_CAP] + '…'
239
+
240
+
241
+ def analyze(events):
242
+ """{checks, call, environment} of one transcript's events.
243
+
244
+ checks: [{index, command, kind, exit, failed, running, started, ended, duration_s, counts, tail}], in order; index
245
+ is the event's place in the transcript (the conversation view's `ev-<index>`).
246
+ call: the call not answered yet ({index, kind: command|tool, command, tool, check, started}), the newest when
247
+ several run at once, or None.
248
+ environment: [{index, command, problem, label, line}] for each problem a failed command met.
249
+ """
250
+ checks, problems, call = [], [], None
251
+ for index, ev in enumerate(events):
252
+ kind = ev.get('kind')
253
+ if kind not in ('command', 'tool', 'edit'):
254
+ continue
255
+ if ev.get('running'):
256
+ call = dict(index=index, kind=kind, command=_command(ev.get('command')) if kind == 'command' else None,
257
+ tool=ev.get('tool') or None, started=ev.get('t'),
258
+ check=classify(ev.get('command')) if kind == 'command' else None)
259
+ if kind != 'command':
260
+ continue
261
+ command, check = ev.get('command') or '', classify(ev.get('command'))
262
+ failed = not ev.get('running') and _failed(ev)
263
+ if check:
264
+ started, ended = ev.get('t'), ev.get('ended')
265
+ checks.append(dict(index=index, command=_command(command), kind=check, exit=ev.get('exit'), failed=failed,
266
+ running=bool(ev.get('running')), started=started, ended=ended,
267
+ duration_s=round(ended - started, 3) if started is not None and ended is not None else None,
268
+ counts=counts(ev.get('output'), check), tail=_tail(ev.get('output')) if failed else None))
269
+ if failed and not _readonly(command):
270
+ for key, line in environment(ev.get('output')):
271
+ problems.append(dict(index=index, command=_command(command), problem=key, label=LABELS[key], line=line))
272
+ return dict(checks=checks, call=call, environment=problems)
273
+
274
+
275
+ # ---------- the brief's acceptance criteria ----------
276
+
277
+ _HEADING = re.compile(r'^(#{1,6})\s+acceptance criteria\s*:?\s*$', re.I)
278
+ _ANY_HEADING = re.compile(r'^(#{1,6})\s')
279
+ _FENCE = re.compile(r'^\s*(```|~~~)')
280
+ _CODE = re.compile(r'(`+)(.+?)\1')
281
+
282
+
283
+ def criteria(brief):
284
+ """The check commands an `## Acceptance criteria` section of a brief names: in `code` spans or in its fenced
285
+ blocks, each once, in order: [{command, kind}]."""
286
+ found, seen, level, fenced = [], set(), None, False
287
+ for line in (brief or '').splitlines():
288
+ if _FENCE.match(line):
289
+ fenced = not fenced
290
+ continue
291
+ heading = None if fenced else _ANY_HEADING.match(line)
292
+ if heading and level is not None and len(heading.group(1)) <= level:
293
+ level = None
294
+ if not fenced and _HEADING.match(line):
295
+ level = len(_HEADING.match(line).group(1))
296
+ continue
297
+ if level is None:
298
+ continue
299
+ candidates = [line.strip().lstrip('$ ').strip()] if fenced else [m.group(2).strip() for m in _CODE.finditer(line)]
300
+ for text in candidates:
301
+ kind = classify(text)
302
+ if kind and text not in seen:
303
+ seen.add(text)
304
+ found.append(dict(command=text, kind=kind))
305
+ return found
306
+
307
+
308
+ def _tokens(command):
309
+ out = []
310
+ for part in parts(command):
311
+ out.extend(re.sub(r'^python(?:\d+(?:\.\d+)?)?$', 'python', word.strip('\'"')) for word in part.split())
312
+ return out
313
+
314
+
315
+ def coverage(wanted, ran):
316
+ """Each wanted check against the commands that ran: `ran` when one has every word of it, `similar` when one is
317
+ the same kind of check by the same program (the whole suite where one module was asked, say), else `missing`.
318
+ ran = [(command, info)]; the matching run's info rides along as `by`."""
319
+ out = []
320
+ runs = [(set(_tokens(command)), (_tokens(command) or [None])[0], classify(command), info) for command, info in ran]
321
+ for item in wanted:
322
+ words = _tokens(item['command'])
323
+ status, by = 'missing', None
324
+ for tokens, program, kind, info in runs:
325
+ if words and set(words) <= tokens:
326
+ status, by = 'ran', info
327
+ break
328
+ if status == 'missing' and words and program == words[0] and kind == item['kind']:
329
+ status, by = 'similar', info
330
+ out.append(dict(item, status=status, by=by))
331
+ return out