levi-gear 0.1.0 → 0.3.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 (47) hide show
  1. package/README.md +13 -8
  2. package/agents/_team-protocol.md +15 -6
  3. package/agents/designer.md +2 -2
  4. package/agents/developer.md +1 -1
  5. package/agents/pm.md +4 -1
  6. package/agents/qa.md +1 -1
  7. package/agents/teamlead.md +1 -1
  8. package/package.json +4 -1
  9. package/src/commands/list.js +2 -1
  10. package/src/lib/agents.js +9 -2
  11. package/src/lib/desired-state.js +38 -11
  12. package/src/lib/role-skills.js +23 -0
  13. package/src/lib/tools.js +6 -1
  14. package/src/lib/usecases.js +44 -2
  15. package/src/runtime/codex-run-state.mjs +156 -0
  16. package/src/runtime/quota-check.mjs +195 -0
  17. package/usecases/_run-rules.md +38 -0
  18. package/usecases/brainstorming/SKILL.md +60 -14
  19. package/usecases/brainstorming/references/codex-runner.md +28 -0
  20. package/usecases/code-review/SKILL.md +86 -0
  21. package/usecases/code-review/references/codex-runner.md +5 -0
  22. package/usecases/code-review/references/large-changes.md +37 -0
  23. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  24. package/usecases/code-review/references/review-guide.md +72 -0
  25. package/usecases/code-review/references/security.md +119 -0
  26. package/usecases/create-feature/SKILL.md +97 -0
  27. package/usecases/create-feature/references/codex-runner.md +57 -0
  28. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  29. package/usecases/create-feature/workflow.js +532 -0
  30. package/usecases/design/SKILL.md +66 -0
  31. package/usecases/design/references/codex-runner.md +27 -0
  32. package/usecases/design/references/svg-guide.md +14 -0
  33. package/usecases/design/scripts/check-svg.py +77 -0
  34. package/usecases/fix-bug/SKILL.md +97 -0
  35. package/usecases/fix-bug/references/codex-runner.md +32 -0
  36. package/usecases/fix-bug/workflow.js +392 -0
  37. package/usecases/generate-test-scenarios/SKILL.md +102 -0
  38. package/usecases/generate-test-scenarios/references/codex-runner.md +32 -0
  39. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  40. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  41. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  42. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  43. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  44. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  45. package/usecases/spec-writing/SKILL.md +63 -0
  46. package/usecases/spec-writing/references/codex-runner.md +25 -0
  47. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,14 @@
1
+ # SVG guide
2
+
3
+ How `levi-designer` draws SVG designs, in the `design` usecase and in every usecase that has it draw. The prompt names what to draw, the references and the output folder. These rules add to the ones in your own definition.
4
+
5
+ ## Rules
6
+
7
+ - **Valid and self-contained.** `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 W H" width="W" height="H">`, with a `<title>` as the first child and a `<desc>` saying what the screen is. No `<image>`, no raster data, no external files, fonts, links or scripts, no `<foreignObject>`, no animation. Photos and illustrations are drawn as simple shapes or as a labeled placeholder rectangle.
8
+ - **One artboard per file.** One screen, state or breakpoint per file, drawn on an artboard with a background rect. Name files after what they show: `<screen>.svg`, `<screen>-<state>.svg`, `<screen>-<breakpoint>.svg`, in kebab-case.
9
+ - **Size.** Use the size of the reference when there is one (its aspect ratio is kept). Otherwise: mobile 390×844, tablet 768×1024, desktop 1440×900.
10
+ - **Tokens.** Define colors, type sizes, radii and shadows once per file in a `<style>` block as classes with literal values (`.text-primary{fill:#1F2937}`), and use the classes. Do not use CSS variables: many renderers ignore them. Reuse the same values in every file of the folder, and the project's tokens when it has them.
11
+ - **Structure.** Group by what things are, with kebab-case `id`s: `header`, `nav`, `card-order`, `button-primary`, `input-email`. Repeated parts (icons, buttons) are defined once in `<defs>` and drawn with `<use>`. Ids are unique in the file.
12
+ - **Text.** Real `<text>` elements, not outlines, so the content stays readable and searchable. Use a system font stack (`font-family="Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"`), never a font loaded from a URL. Text that wraps is split into `<tspan>` lines that fit their container.
13
+ - **Content.** Texts, labels, numbers and data come from the request or the references, exactly as given. Anything else is a placeholder, written like `[Product name]` or `Lorem ipsum`, never made-up facts, names or figures.
14
+ - **Accessibility.** Text contrast WCAG 2.1 AA (4.5:1, or 3:1 for large text), touch targets at least 44px, visible focus in focus states, meaning never by color alone. A recreate reference that breaks one of these is reproduced as it is and the problem is named in the report.
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env python3
2
+ """Check SVG design files against the levi-design rules.
3
+
4
+ Usage: check-svg.py <file.svg|folder> [...]
5
+
6
+ Prints one line per problem and exits 1 when any file has one. Standard library only.
7
+ """
8
+ import re
9
+ import sys
10
+ import xml.etree.ElementTree as ET
11
+ from pathlib import Path
12
+
13
+ SVG = "{http://www.w3.org/2000/svg}"
14
+ XLINK_HREF = "{http://www.w3.org/1999/xlink}href"
15
+ FORBIDDEN = {"script", "foreignObject", "iframe", "audio", "video", "animate", "animateTransform", "set"}
16
+
17
+
18
+ def local(tag):
19
+ return tag.split("}", 1)[-1] if isinstance(tag, str) else ""
20
+
21
+
22
+ def check(path):
23
+ problems = []
24
+ try:
25
+ root = ET.parse(path).getroot()
26
+ except ET.ParseError as e:
27
+ return [f"not well-formed XML: {e}"]
28
+
29
+ if root.tag != SVG + "svg":
30
+ problems.append("root element is not <svg xmlns=\"http://www.w3.org/2000/svg\">")
31
+ if not root.get("viewBox"):
32
+ problems.append("<svg> has no viewBox")
33
+ if not any(local(c.tag) == "title" for c in root):
34
+ problems.append("<svg> has no <title> as a direct child")
35
+
36
+ ids = set()
37
+ for el in root.iter():
38
+ name = local(el.tag)
39
+ if name in FORBIDDEN:
40
+ problems.append(f"<{name}> is not allowed")
41
+ if name == "image":
42
+ problems.append("<image> is not allowed: draw it as vector shapes or a labeled placeholder")
43
+ href = el.get("href") or el.get(XLINK_HREF) or ""
44
+ if href and not href.startswith("#"):
45
+ problems.append(f"<{name}> references something outside the file: {href[:60]}")
46
+ if any(a.startswith("on") for a in el.attrib):
47
+ problems.append(f"<{name}> has an event handler attribute")
48
+ i = el.get("id")
49
+ if i:
50
+ if i in ids:
51
+ problems.append(f"duplicate id \"{i}\"")
52
+ ids.add(i)
53
+ if name == "style" and el.text and re.search(r"@import|url\(\s*['\"]?(https?:|//|data:)", el.text):
54
+ problems.append("<style> loads an external resource")
55
+ return problems
56
+
57
+
58
+ def main(args):
59
+ files = []
60
+ for a in args:
61
+ p = Path(a)
62
+ files += sorted(p.rglob("*.svg")) if p.is_dir() else [p]
63
+ if not files:
64
+ print("no SVG files given", file=sys.stderr)
65
+ return 2
66
+ bad = 0
67
+ for f in files:
68
+ problems = check(f)
69
+ for msg in problems:
70
+ print(f"{f}: {msg}")
71
+ bad += bool(problems)
72
+ print(f"{len(files)} file(s) checked, {bad} with problems")
73
+ return 1 if bad else 0
74
+
75
+
76
+ if __name__ == "__main__":
77
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,97 @@
1
+ ---
2
+ name: levi-fix-bug
3
+ description: Fix a bug in code that is already merged into the base branch. The developer lists what is unclear in the report and the user confirms it; then, as a Workflow of independent subagents, the developer investigates and fixes it test first (writing unit and feature tests only when the existing ones do not cover the bug) while QA writes the bug's test cases; the teamlead reviews every fix once the tests pass, and after its approval QA runs the test cases end to end in a headless browser and sends the failing ones back to the developer. Tests and test cases are never changed to make them pass. A problem in work that is not merged yet is a revision of that work, not a bug. Fits requests such as "fix this bug", "X is broken", "X shows the wrong value", "sửa bug X", "lỗi X".
4
+ argument-hint: "<what goes wrong, how to reproduce it, and screenshots or logs if you have them>"
5
+ requires: create-feature, code-review, generate-test-scenarios
6
+ ---
7
+
8
+ # Fix a bug
9
+
10
+ Fix a bug with the team: `levi-developer` clarifies, investigates and fixes, `levi-teamlead` reviews, `levi-qa` writes the scenarios and tests the fix end to end. You run them, relay their questions to the user, and never investigate, fix, review or test yourself.
11
+
12
+ **What counts as a bug.** A bug is a defect in feature code that is already merged into the base branch. When the code at fault is still on a branch that is not merged, or not committed (for example the output of `create-feature` the user is checking), a request to change it is a revision of that work, not a bug. This usecase does not handle revisions: it says so and stops.
13
+
14
+ The work has two halves:
15
+
16
+ - **Clarify** (steps 1 to 5), here in the conversation, because it needs the user. The developer lists what is unclear and the user confirms it.
17
+ - **Fix** (step 6), without the user. Claude Code runs `workflow.js`; Codex uses the durable runner in [`references/codex-runner.md`](references/codex-runner.md). Every agent call is a fresh subagent that sees only the files it is given, and the developer and QA work at the same time without reading each other's work.
18
+
19
+ ## The rules that never bend
20
+
21
+ - **Test first.** Before the fix, there are unit and feature tests that fail because of the bug: existing ones when they already cover it, otherwise new ones the developer writes. The fix is done when they pass, together with the whole suite.
22
+ - **Tests are locked, test cases are QA's.** The tests that cover the bug are locked before the fix: nobody may edit, delete, skip or weaken them afterwards, and when one fails, the code is fixed. The lock is the `lock-tests.mjs` script of `create-feature`: it hashes the files, checks them after every round and restores any that changed. The test cases belong to QA: QA writes, changes and runs them with the test case guide of `generate-test-scenarios`, and a change by anyone else is undone with the same script before QA runs them. QA never changes an expected result to match what the code does.
23
+ - **No guessing.** The expected behavior comes from the spec, the designs and the points the user confirmed. What none of them settles is asked, not assumed.
24
+ - **Nothing is committed.** The changes stay in the working tree for the user to review.
25
+
26
+ ## Files
27
+
28
+ | File | Owner | Purpose |
29
+ |---|---|---|
30
+ | `docs/specs/<spec>.md`, `docs/designs/<design>/` | PM, Designer | The spec and designs of the feature, when there are. Read-only |
31
+ | Unit and feature tests, in the framework's folders | Developer | **Deliverable.** The tests that cover the bug. Locked before the fix |
32
+ | `docs/tests/bugs/<slug>.md`, `docs/tests/bugs/<slug>.xlsx` | QA | **Deliverable.** The test cases of the bug with their PASS or FAIL result, in the format of `generate-test-scenarios`. Only QA changes them |
33
+ | Application code | Developer | **Deliverable.** The fix |
34
+ | `docs/levi/<slug>/report.md` | Workflow | Scratch: the bug report as the user gave it. Deleted at the end |
35
+ | `docs/levi/<slug>/confirmed.md` | Workflow | Scratch: the developer's questions and the user's answers, word for word. Deleted at the end |
36
+ | `docs/levi/<slug>/investigation.md` | Developer | Scratch: root cause, tests that cover the bug, fix plan. Deleted at the end |
37
+ | `docs/levi/<slug>/review.md` | Teamlead | Scratch: review findings. Deleted at the end |
38
+ | `docs/levi/<slug>/locked/` | Workflow | Scratch: copies and hashes of the locked tests, and of the test cases as QA last wrote them. Deleted at the end |
39
+ | `docs/levi/<slug>/test-cases.json` | QA | Scratch: the data the test cases are rendered from. Deleted at the end |
40
+
41
+ `<slug>` is a short kebab-case name for the bug, in English (for example `cart-total-rounding`). `levi-create-feature/`, `levi-design/`, `levi-code-review/` and `levi-generate-test-scenarios/` are installed next to this skill's folder. The test cases use the feature ID `BUG-<SLUG>` (the slug in uppercase), so their IDs are `TC-BUG-<SLUG>-001` and up.
42
+
43
+ ## Steps
44
+
45
+ 1. **Intake.** The request is the bug report: what goes wrong, where, how to reproduce it, what was expected, with any screenshots, logs or videos. If it is empty, ask what is broken and stop. Derive the slug.
46
+ 2. **Merge check.** Find the base branch: the target of `git symbolic-ref --short refs/remotes/origin/HEAD` when it exists, otherwise `main` or `master`; use `origin/<branch>` when that ref exists, else the local branch. All code is merged when `git status --porcelain` lists nothing and `git merge-base --is-ancestor HEAD <base>` exits 0. Otherwise the workflow checks the lines at the root cause once the developer has found it.
47
+ - If the user clearly points at work that is not merged (a change still on its branch, the output of a usecase they are reviewing), tell them it is a revision of that work, not a bug, and stop.
48
+ 3. **Write down the report.** Write `docs/levi/<slug>/report.md`: the report exactly as the user wrote it, the path of every attachment, and for an image that exists only in the conversation, a plain description of what it shows (texts exactly, values, states), without opinions. For a video, extract key frames into `docs/levi/<slug>/frames/` as step 3 of `levi-design/SKILL.md` describes, and list them.
49
+ 4. **Spec and designs.** List `docs/specs/` and `docs/designs/` and match them against the feature where the bug happens, or use what the user pointed to. One clear match is used; two or more plausible ones, ask the user which (or "none"). With none, the expected behavior comes from the report and the confirmed points alone.
50
+ 5. **Clarify with the developer.** Call `levi-developer` with `report.md`, the spec, the designs and `confirmed.md` (when it exists). It reads them and the project, changes nothing, and returns:
51
+ - every point that is unclear and would change the fix or its tests: the expected behavior, the steps, the data, the environment, the scope (which cases are part of the bug). Each comes with two to four options, the most likely first;
52
+ - whether it looks like a bug: the behavior differs from what the spec, the designs and the report expect, or the code does exactly what the spec says.
53
+
54
+ Ask the user all the points in one round (use the tool's structured question feature if it has one). Append the questions and answers to `confirmed.md`, word for word. Do not answer for the user, and do not take an option as the answer unless the user picks it. Then call `levi-developer` again, fresh, with the updated `confirmed.md`. Stop when it has no more points; at most three rounds. If it then says the code works as the spec states, tell the user, quoting the spec: changing that behavior is a change to the feature, not a bug fix. Stop there.
55
+ 6. **Fix.** Delete `docs/levi/<slug>/locked/` if an earlier run left it.
56
+ - *With a Workflow tool (Claude Code):* call it with `scriptPath` set to `workflow.js` in this skill's folder, and `args`:
57
+
58
+ ```json
59
+ {
60
+ "slug": "<slug>",
61
+ "spec": "docs/specs/<spec>.md (omit when there is none)",
62
+ "designs": "docs/designs/<design>/ (omit when there is none)",
63
+ "base": "<base branch ref from step 2>",
64
+ "allMerged": true,
65
+ "skillDir": "<this skill's folder, relative to the project root>"
66
+ }
67
+ ```
68
+
69
+ Set `allMerged` to false when step 2 found unmerged work.
70
+ - *On Codex:* follow [`references/codex-runner.md`](references/codex-runner.md), which persists `docs/levi/<slug>/run.json`, then run the steps under [Workflow](#workflow) through that runner.
71
+ - *Other tools without a Workflow tool:* run the steps under [Workflow](#workflow) below yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
72
+ 7. **Act on the result.**
73
+ - `done`: go to step 8.
74
+ - `questions`: an agent found a point that is still open. Ask the user, append the answers to `confirmed.md`, and run step 6 again.
75
+ - `not_a_bug`: the developer found that the code does what the spec and the confirmed points expect. Tell the user why, clean up (step 8) and stop.
76
+ - `unmerged`: the root cause is in code that is not merged into the base branch. Tell the user it is a revision of unmerged work, not a bug, with the root cause and its locations. Clean up and stop. The code was not changed.
77
+ - `blocked`: something outside the code stops the work (the app cannot start, a service or credential is missing, no test could be made to fail on the bug). Tell the user the stage, the detail and what they need to provide. Keep `docs/levi/<slug>/` and run step 6 again when they say to.
78
+ - `stalled`: the rounds ran out (10 by default) and something still fails. Tell the user what failed last. On Claude Code, continue in the same session with `resumeFromRunId` and a higher `maxRounds`; on Codex, keep `run.json` and resume the active `build` stage when the user asks to continue. Tests and test cases still do not change.
79
+ 8. **Clean up.** Delete `docs/levi/<slug>/`, then `docs/levi` if it is empty. Keep everything else.
80
+ 9. **Report.** Tell the user: the root cause and where it was; the tests that cover the bug (written now, or existing ones) and the command that runs them; the test case files with their result (for example `4/4 PASS`); how many rounds it took; the review outcome and the suggestions left open; the files changed (from `git status`); and that nothing was committed.
81
+
82
+ ## Workflow
83
+
84
+ The steps `workflow.js` runs, and the ones you run when there is no Workflow tool. Give every call the paths of `report.md`, `confirmed.md`, the spec, the designs and `docs/levi/<slug>/`. When a call returns points only the user can settle, stop with `questions`. When a call is BLOCKED, stop with `blocked`.
85
+
86
+ 1. **Baseline.** Record `git rev-parse HEAD` and the files `git status --porcelain` lists, so the review sees only this run's changes.
87
+ 2. **Two tracks at the same time**, neither reading the other's work:
88
+ - *QA.* `levi-qa` writes the test cases from the report, the confirmed points, the spec and the designs, without reading code, following `levi-generate-test-scenarios/references/test-case-guide.md`, with the cases file `docs/levi/<slug>/test-cases.json` and the output base `docs/tests/bugs/<slug>`: case 1 follows the steps of the report, the next ones cover nearby cases the same bug could break. The files are snapshotted at once (`lock-tests.mjs lock docs/levi/<slug>/locked/scenarios ...`). QA then waits for the review to approve.
89
+ - *Developer, test first.* `levi-developer` finds the root cause (file, line range, other places with the same cause) and writes `investigation.md`. If existing unit and feature tests already cover the bug and fail because of it, it uses them; otherwise it writes the missing ones, from the spec and the confirmed points. The tests are run: some must fail on the current code. If none fails, the developer tries again (at most 3 times). If the code turns out to do what is expected, stop with `not_a_bug`.
90
+ 3. **Merge check**, unless all code is merged: for each root-cause location, `git blame --porcelain -L <from>,<to> -- <file>`, then `git merge-base --is-ancestor <commit> <base>` for each commit. An uncommitted line (all-zero commit), an untracked file or a commit that is not an ancestor of the base means the code is not merged: stop with `unmerged`.
91
+ 4. **Lock** the tests that cover the bug (`lock-tests.mjs lock docs/levi/<slug>/locked/tests ...`).
92
+ 5. **Rounds** (at most 10 unless raised), each starting with a fresh `levi-developer` call:
93
+ 1. *Fix.* The developer fixes the code: first as planned in `investigation.md`, later what the last round sent back. It fixes the cause, not the symptom.
94
+ 2. *Tests.* `lock-tests.mjs verify` on the tests (any changed test is restored and the developer is told), then the bug's tests, then the whole suite. A failure goes back to the developer.
95
+ 3. *Review.* Once the tests pass, a fresh `levi-teamlead` call reviews the change since the baseline: the root cause fixed everywhere, what the spec, designs and confirmed points expect, nothing else broken, security, performance, fit, following `levi-code-review/references/review-guide.md` and its checklists. It writes `review.md`. A change of more than 100 reviewable files is reviewed in slices by several fresh `levi-teamlead` calls and merged by a lead call, as `levi-code-review/references/large-changes.md` says. Critical or warning findings go back to the developer.
96
+ 4. *E2E.* Once the review approves, `lock-tests.mjs verify` on the test cases undoes any change made outside QA. Then `levi-qa` runs every case in a headless browser (the project's E2E runner such as Playwright, or a browser tool; through the API or CLI when there is no UI) and records PASS or FAIL as its test case guide says; the snapshot is then taken again. Failing cases go back to the developer, and the next round runs tests, review and E2E again.
97
+ 5. The run is done when the review approves and every case passes.
@@ -0,0 +1,32 @@
1
+ # Codex runner
2
+
3
+ Use this durable runner on Codex instead of the Claude-only `workflow.js`. Run every command below from the project root. After clarification is complete, first inspect `docs/levi/<slug>/run.json`. If absent, initialize it:
4
+
5
+ ```bash
6
+ node <this skill folder>/scripts/codex-run-state.mjs init docs/levi/<slug> fix-bug <slug> baseline tests merge-check lock build
7
+ ```
8
+
9
+ For each current stage, call `begin` before dispatching the named Levi agent and `complete` only after its artifacts exist. `status` is the source of truth after an interruption; completed stages are never repeated. Use `wait` for questions that need the user, `block` for an external dependency, and `resume` after it is resolved. Do not use the Claude-only `resumeFromRunId`.
10
+
11
+ ```bash
12
+ node <this skill folder>/scripts/codex-run-state.mjs begin docs/levi/<slug> <stage>
13
+ node <this skill folder>/scripts/codex-run-state.mjs complete docs/levi/<slug> <stage> <artifact>...
14
+ node <this skill folder>/scripts/codex-run-state.mjs wait docs/levi/<slug> <stage> "<questions>"
15
+ node <this skill folder>/scripts/codex-run-state.mjs block docs/levi/<slug> <stage> "<blocker>"
16
+ node <this skill folder>/scripts/codex-run-state.mjs resume docs/levi/<slug>
17
+ ```
18
+
19
+ For a valid terminal result that does not build a fix, use `finish` before cleanup:
20
+
21
+ ```bash
22
+ node <this skill folder>/scripts/codex-run-state.mjs finish docs/levi/<slug> tests
23
+ node <this skill folder>/scripts/codex-run-state.mjs finish docs/levi/<slug> merge-check
24
+ ```
25
+
26
+ - `baseline`: record the baseline commit and dirty paths for the later review.
27
+ - `tests`: QA writes and PM-approved scenarios while the developer investigates and produces a failing test. Both tracks are separate; complete only with `investigation.md`, `test-cases.json`, and the rendered scenario files. When the code already does what is expected, use `finish` at this stage and report `not_a_bug`; do not build a change.
28
+ - `merge-check`: run the existing blame/ancestor check when the initial check did not prove all code merged. For unmerged root-cause code, use `finish` at this stage, report `unmerged`, and do not fix it.
29
+ - `lock`: lock the developer tests and QA cases with the existing lock script. Require both lock manifests.
30
+ - `build`: run the existing code → test gate → teamlead review → QA E2E loop (a review of more than 100 reviewable files follows `levi-code-review/references/large-changes.md`: split, parallel slice reviews, one merge). Keep the stage active across all rounds. Complete only after approved review and all cases PASS.
31
+
32
+ Use installed named roles for every subagent call. The coordinator owns the checkpoint and stages; subagents only read/write their assigned artifacts. Keep dependent work sequential and use parallel calls only for the independent QA and investigation tracks.
@@ -0,0 +1,392 @@
1
+ export const meta = {
2
+ name: 'levi-fix-bug',
3
+ description: 'Fix a bug with TDD: the developer investigates and fixes it while QA writes the scenarios; the teamlead reviews every fix, then QA runs the scenarios end to end until they all pass',
4
+ whenToUse: 'Started by the levi-fix-bug skill once the open points of the bug report are confirmed with the user',
5
+ phases: [
6
+ { title: 'Investigate', detail: 'the developer finds the root cause and makes tests fail on the bug; QA writes the scenarios at the same time' },
7
+ { title: 'Fix', detail: 'fix, unit and feature tests, teamlead review, E2E; repeat until the review approves and every scenario passes' },
8
+ ],
9
+ }
10
+
11
+ // args: { slug, spec?, designs?, base, allMerged?, featureId?, testBase?, skillDir, maxRounds? } — see the skill's SKILL.md.
12
+ const A = args || {}
13
+ const absent = ['slug', 'base', 'skillDir'].filter((k) => !A[k])
14
+ if (absent.length) return { status: 'error', message: `missing args: ${absent.join(', ')}` }
15
+
16
+ const WORK = `docs/levi/${A.slug}`
17
+ const REPORT = `${WORK}/report.md`
18
+ const CONFIRMED = `${WORK}/confirmed.md`
19
+ const INVESTIGATION = `${WORK}/investigation.md`
20
+ const REVIEW = `${WORK}/review.md`
21
+ // QA's test cases of the bug, written and run with the test case guide of levi-generate-test-scenarios.
22
+ const FEATURE_ID = A.featureId || `BUG-${A.slug.toUpperCase()}`
23
+ const TEST_BASE = A.testBase || `docs/tests/bugs/${A.slug}`
24
+ const SCENARIOS = `${TEST_BASE}.md`
25
+ const SCENARIO_FILES = [SCENARIOS, `${TEST_BASE}.xlsx`]
26
+ const CASES = `${WORK}/test-cases.json`
27
+ const TEST_GUIDE = `${A.skillDir}/../levi-generate-test-scenarios/references/test-case-guide.md`
28
+ const LOCK = `node ${A.skillDir}/../levi-create-feature/scripts/lock-tests.mjs`
29
+ const REVIEW_GUIDE = `${A.skillDir}/../levi-code-review/references/review-guide.md`
30
+ const LOCK_TESTS = `${WORK}/locked/tests`
31
+ // Only QA changes its test cases: a snapshot taken after each QA step restores changes made by anyone else.
32
+ const LOCK_SCENARIOS = `${WORK}/locked/scenarios`
33
+ const MAX_RED = 3
34
+ const MAX_ROUNDS = A.maxRounds || 10
35
+
36
+ const CONTEXT = [
37
+ `Bug report, as the user gave it: ${REPORT}`,
38
+ `Points confirmed with the user (they override any guess): ${CONFIRMED}`,
39
+ `Spec: ${A.spec || 'none; the expected behavior is what the report and the confirmed points say'}`,
40
+ `Designs: ${A.designs || 'none'}`,
41
+ `Work folder: ${WORK}`,
42
+ ].join('\n')
43
+
44
+ // ---- schemas ----
45
+
46
+ const STATUS = { type: 'string', enum: ['DONE', 'DONE_WITH_CONCERNS', 'BLOCKED', 'NEEDS_CONTEXT'] }
47
+ const QUESTIONS = {
48
+ type: 'array',
49
+ items: { type: 'string' },
50
+ description: 'Points only the user can settle, that the report, the confirmed points and the spec leave open. Empty when none.',
51
+ }
52
+ const STRINGS = { type: 'array', items: { type: 'string' } }
53
+ const obj = (properties) => ({ type: 'object', properties, required: Object.keys(properties) })
54
+
55
+ const INVESTIGATE = obj({
56
+ status: STATUS,
57
+ summary: { type: 'string' },
58
+ isBug: { type: 'boolean', description: 'false when the code does what the spec and the confirmed points expect' },
59
+ rootCause: { type: 'string' },
60
+ locations: {
61
+ type: 'array',
62
+ description: 'The lines at the root cause, in the current working tree',
63
+ items: obj({ file: { type: 'string' }, from: { type: 'integer' }, to: { type: 'integer' } }),
64
+ },
65
+ bugTests: { ...STRINGS, description: 'Test files that fail now because of the bug: the ones you wrote, or existing ones that already cover it' },
66
+ wroteTests: { type: 'boolean', description: 'false when existing tests already covered the bug and none were written' },
67
+ testCommand: { type: 'string', description: 'Shell command that runs the unit and feature tests covering the bug' },
68
+ suiteCommand: { type: 'string', description: 'Shell command that runs the whole test suite; empty when the project has none' },
69
+ app: obj({ start: { type: 'string' }, url: { type: 'string' }, notes: { type: 'string' } }),
70
+ hasUi: { type: 'boolean' },
71
+ questions: QUESTIONS,
72
+ })
73
+ const WRITTEN = obj({ status: STATUS, summary: { type: 'string' }, scenarioCount: { type: 'integer' }, questions: QUESTIONS })
74
+ const RUN = obj({ exitCode: { type: 'integer' }, summary: { type: 'string' } })
75
+ const GATE = obj({ restored: STRINGS, testsExit: { type: 'integer' }, suiteExit: { type: 'integer' }, failures: { type: 'string' } })
76
+ const BASE = obj({ head: { type: 'string' }, dirty: STRINGS })
77
+ const MERGED = obj({ unmerged: { ...STRINGS, description: 'Locations with lines not merged into the base branch, with the reason' } })
78
+ const FIXED = obj({ status: STATUS, summary: { type: 'string' }, files: STRINGS, blockers: STRINGS })
79
+ const CODE_REVIEW = obj({
80
+ approved: { type: 'boolean' },
81
+ summary: { type: 'string' },
82
+ findings: {
83
+ type: 'array',
84
+ items: obj({ severity: { type: 'string', enum: ['critical', 'warning', 'suggestion'] }, file: { type: 'string' }, problem: { type: 'string' }, fix: { type: 'string' } }),
85
+ },
86
+ })
87
+ const E2E = obj({
88
+ status: STATUS,
89
+ summary: { type: 'string' },
90
+ results: { type: 'array', items: obj({ id: { type: 'string' }, result: { type: 'string', enum: ['PASS', 'FAIL'] }, evidence: { type: 'string' } }) },
91
+ })
92
+
93
+ // ---- helpers ----
94
+
95
+ // Mechanical steps (git, the lock script, running tests) go to a plain agent that only runs commands.
96
+ const guard = (label, prompt, schema) =>
97
+ agent(`${prompt}\n\nRun the commands from the project root. Do not create, edit or delete any file yourself, and do not try to fix anything. Report only what you observed.`, {
98
+ label,
99
+ schema,
100
+ effort: 'low',
101
+ })
102
+
103
+ const questionsOf = (r) => (r && r.questions) || []
104
+
105
+ const snapshotScenarios = () => guard('qa-snapshot', `Run \`${LOCK} lock ${LOCK_SCENARIOS} ${SCENARIO_FILES.join(' ')}\` and return its exit code, and its output as summary.`, RUN)
106
+ const restoreScenarios = () => guard('qa-restore', `Run \`${LOCK} verify ${LOCK_SCENARIOS}\` and return its exit code, and its output as summary.`, RUN)
107
+
108
+ // ---- QA writes the test cases, apart from the developer ----
109
+
110
+ async function qaScenarios() {
111
+ const written = await agent(
112
+ `${CONTEXT}
113
+
114
+ Write the test cases of this bug, following your test case guide, ${TEST_GUIDE} ("The source rule" and "Writing test cases").
115
+
116
+ Sources (your only ones): the report, the confirmed points, the spec and the designs above. Do not read the application code or anything the developer writes.
117
+ Feature ID: ${FEATURE_ID}
118
+ Cases file: ${CASES}
119
+ Output base: ${TEST_BASE}. If its files exist from an earlier run, they are yours: get the cases back as the guide's "Changing test cases" says and bring them in line with the sources.
120
+
121
+ On top of the guide:
122
+ - Case 1 follows the steps of the report. The next ones cover the nearby cases the same bug could break (other inputs, states, roles).
123
+ - Expected results come from the spec and the confirmed points, never from a guess. Put every point they leave open into questions as well.
124
+ - Each case can be run end to end, in a browser for UI and otherwise through the API or the CLI, by someone who has only the rendered file and the running app.
125
+ - Do not record results: you record them later, when you run the cases.
126
+
127
+ Return the number of cases as scenarioCount.`,
128
+ { label: 'qa:scenarios', phase: 'Investigate', agentType: 'levi-qa', schema: WRITTEN },
129
+ )
130
+ if (!written || written.status === 'BLOCKED') return { stop: 'blocked', detail: written ? written.summary : 'QA did not write the scenarios' }
131
+ if (questionsOf(written).length) return { stop: 'questions', questions: written.questions }
132
+ const locked = await snapshotScenarios()
133
+ if (!locked || locked.exitCode !== 0) return { stop: 'blocked', detail: locked ? locked.summary : 'the scenarios could not be locked' }
134
+ return { scenarioCount: written.scenarioCount }
135
+ }
136
+
137
+ // ---- the developer investigates and writes the failing tests (TDD red) ----
138
+
139
+ async function investigate() {
140
+ let found = await agent(
141
+ `${CONTEXT}
142
+
143
+ Investigate this bug, test first. Do not fix it yet.
144
+
145
+ 1. Find the root cause in the code: file, function, line range, and why. Look for other places with the same cause. If the code already does what the spec and the confirmed points expect, it is not a bug: say so (isBug=false) and stop.
146
+ 2. Look at the existing unit and feature tests. If some already cover this bug, they fail now because of it, and they follow the spec and the confirmed points, use them and write nothing (wroteTests=false). Otherwise write the missing unit tests (at the root cause) and feature tests (at the behavior the user saw), with the project's framework and conventions: the reported case and the nearby cases the same cause breaks. Every assertion comes from the spec and the confirmed points.
147
+ 3. Run them: they must fail now, because of the bug, not because of a typo or a wrong setup.
148
+
149
+ Write ${INVESTIGATION}: expected against actual, the root cause with its locations, other places with the same cause, the tests that cover the bug, and how you will fix it.
150
+ Return also the command that runs the tests covering the bug, the command for the whole suite, and how to start the app for end-to-end tests. After this step the tests that cover the bug are locked: the fix must pass them and nobody may change them.`,
151
+ { label: 'developer:investigate', phase: 'Investigate', agentType: 'levi-developer', schema: INVESTIGATE },
152
+ )
153
+ for (let i = 1; ; i++) {
154
+ if (!found || found.status === 'BLOCKED') return { stop: 'blocked', detail: found ? found.summary : 'the developer did not finish the investigation' }
155
+ if (questionsOf(found).length) return { stop: 'questions', questions: found.questions }
156
+ if (!found.isBug) return { stop: 'not_a_bug', reason: found.summary }
157
+ if (!found.bugTests.length) return { stop: 'blocked', detail: 'the investigation names no test that covers the bug' }
158
+ const red = await guard(`red-run-${i}`, `Run \`${found.testCommand}\`. The bug is not fixed yet, so some of these tests must fail. Return the exit code, and in summary each failing test with the first line of its error. At most 60 lines.`, RUN)
159
+ if (red && red.exitCode !== 0) return { ...found, red: red.summary }
160
+ if (i >= MAX_RED) return { stop: 'blocked', detail: `after ${MAX_RED} tries, no test fails on the buggy code` }
161
+ found = await agent(
162
+ `${CONTEXT}\n\nThe tests you named (${found.bugTests.join(', ')}) all pass with \`${found.testCommand}\` on the buggy code, so they do not catch the bug. Write or correct the tests so that they fail because of this bug, then return your investigation again, updating ${INVESTIGATION}. Do not fix the bug yet.`,
163
+ { label: `developer:red-${i}`, phase: 'Investigate', agentType: 'levi-developer', schema: INVESTIGATE },
164
+ )
165
+ }
166
+ }
167
+
168
+ // ---- run both at the same time ----
169
+
170
+ phase('Investigate')
171
+ const base = await guard('baseline', 'Run `git rev-parse HEAD` (use "none" when the repository has no commit yet) and `git status --porcelain`. Return the commit as head and the paths listed by git status as dirty.', BASE)
172
+ const scenariosReady = qaScenarios()
173
+ const inv = await investigate()
174
+ if (inv.stop === 'questions') return { status: 'questions', stage: 'investigation', questions: inv.questions }
175
+ if (inv.stop === 'not_a_bug') return { status: 'not_a_bug', reason: inv.reason }
176
+ if (inv.stop) return { status: 'blocked', stage: 'investigation', detail: inv.detail }
177
+
178
+ // A bug is a defect in code already merged into the base branch. A defect in work that is not merged
179
+ // yet (a branch under review, uncommitted changes) is a revision of that work, not a bug.
180
+ if (!A.allMerged) {
181
+ if (!inv.locations.length) return { status: 'blocked', stage: 'merge check', detail: 'the investigation gives no location for the root cause' }
182
+ const merged = await guard(
183
+ 'merged-check',
184
+ `Check whether the code at these locations is merged into \`${A.base}\`:\n${inv.locations.map((l) => `- ${l.file} lines ${l.from}-${l.to}`).join('\n')}\nFor each location, run \`git blame --porcelain -L <from>,<to> -- <file>\` and collect the commit of every line. A line whose commit is all zeros is uncommitted, so not merged. For every other commit, run \`git merge-base --is-ancestor <commit> ${A.base}\`: exit 0 means merged, 1 means not merged. A file git does not track is not merged. List in unmerged every location with at least one line that is not merged, and why.`,
185
+ MERGED,
186
+ )
187
+ if (!merged) return { status: 'blocked', stage: 'merge check', detail: 'the check against the base branch did not complete' }
188
+ if (merged.unmerged.length) return { status: 'unmerged', rootCause: inv.rootCause, unmerged: merged.unmerged }
189
+ }
190
+
191
+ const lockedTests = await guard('lock-tests', `Run \`${LOCK} lock ${LOCK_TESTS} ${inv.bugTests.join(' ')}\` and return its exit code, and its output as summary.`, RUN)
192
+ if (!lockedTests || lockedTests.exitCode !== 0) return { status: 'blocked', stage: 'lock', detail: lockedTests ? lockedTests.summary : 'the tests could not be locked' }
193
+
194
+ const RULES = `The test cases in ${SCENARIO_FILES.join(' and ')} belong to QA: do not edit them; a change by anyone else is undone. Locked files: the tests ${inv.bugTests.join(', ')}. They are the definition of done. Never edit, delete, rename, skip or weaken any of them, and never change test configuration to leave them out. A locked file you change is restored automatically and your work is wasted. When a test fails, the code is wrong: fix the code, at the root cause, without special-casing test inputs.`
195
+
196
+ const REVIEW_PHASE = 'Fix'
197
+ // ---- review of the change: one teamlead, or slices merged by a lead when the change is large ----
198
+ // levi-code-review/references/large-changes.md explains why: one reviewer skims a big change and finds problems a few at a time.
199
+
200
+ const LARGE_CHANGE = 100 // reviewable files; more than this is reviewed in slices
201
+ const LARGE_GUIDE = `${A.skillDir}/../levi-code-review/references/large-changes.md`
202
+ const FINDING = CODE_REVIEW.properties.findings.items
203
+ const CHANGED = obj({ files: { type: 'array', items: obj({ path: { type: 'string' }, lines: { type: 'integer' } }) } })
204
+ const SLICES = obj({ slices: { type: 'array', items: obj({ title: { type: 'string' }, files: STRINGS, shares: { type: 'string' } }) } })
205
+ const SLICE_REVIEW = obj({ summary: { type: 'string' }, findings: { type: 'array', items: FINDING }, crossSlice: STRINGS, notChecked: STRINGS })
206
+
207
+ // What is wrong with a split: a slice over the limit, a file in no slice, a file in two slices or not in the change.
208
+ const splitProblems = (slices, paths) => {
209
+ const placed = slices.flatMap((s) => s.files)
210
+ return [
211
+ ...slices.filter((s) => s.files.length > LARGE_CHANGE).map((s) => `slice "${s.title}" has ${s.files.length} files, more than ${LARGE_CHANGE}`),
212
+ ...paths.filter((p) => !placed.includes(p)).map((p) => `${p} is in no slice`),
213
+ ...placed.filter((p, i) => placed.indexOf(p) !== i || !paths.includes(p)).map((p) => `${p} is in two slices or not part of the change`),
214
+ ]
215
+ }
216
+
217
+ async function splitChange(round, files) {
218
+ const paths = files.map((f) => f.path)
219
+ const ask = (note) =>
220
+ agent(
221
+ `${CONTEXT}
222
+
223
+ This change is too large for one reviewer (${paths.length} reviewable files). Split it into slices that are reviewed at the same time, as the "Steps" of ${LARGE_GUIDE} say: at most ${LARGE_CHANGE} files per slice and as few slices as that allows, grouped by what belongs together (a module or feature with its tests, callers, schema and migrations; never by alphabet), every file in exactly one slice. For each slice return a title, its files, and one line on what it shares with the other slices (an interface, a schema, a config). Change nothing and write no file.
224
+ The files, with their changed lines:
225
+ ${files.map((f) => `${f.path} (${f.lines})`).join('\n')}${note}`,
226
+ { label: `teamlead:split-${round}`, phase: REVIEW_PHASE, agentType: 'levi-teamlead', schema: SLICES },
227
+ )
228
+ let split = await ask('')
229
+ let problems = split ? splitProblems(split.slices, paths) : ['no split was returned']
230
+ if (problems.length) {
231
+ split = await ask(`\n\nYour previous split was not valid: ${problems.slice(0, 20).join('; ')}. Return the whole corrected split.`)
232
+ problems = split ? splitProblems(split.slices, paths) : ['no split was returned']
233
+ }
234
+ if (!problems.length) return split.slices
235
+ log(`the lead's split was not usable (${problems[0]}); cutting the file list by path`)
236
+ const sorted = [...paths].sort()
237
+ return Array.from({ length: Math.ceil(sorted.length / LARGE_CHANGE) }, (_, i) => ({
238
+ title: `Files ${i * LARGE_CHANGE + 1}-${Math.min((i + 1) * LARGE_CHANGE, sorted.length)} by path`,
239
+ files: sorted.slice(i * LARGE_CHANGE, (i + 1) * LARGE_CHANGE),
240
+ shares: 'unknown: read the other slices as needed',
241
+ }))
242
+ }
243
+
244
+ // `brief` says what the review is for and what to check; `output` says where the review goes and what blocks.
245
+ async function reviewChange(round, brief, output) {
246
+ const changed = await guard(
247
+ `changed-files-${round}`,
248
+ `List the reviewable files of the change: every file that differs from commit ${base.head} (git diff --name-only ${base.head}) and every untracked file (git status --porcelain), leaving out files that were already modified before the run (${base.dirty.join(', ') || 'none'}), generated files, lock files, vendored code and build output. Give each path with its number of changed lines (git diff --numstat ${base.head}; the line count for an untracked file).`,
249
+ CHANGED,
250
+ )
251
+ if (!changed) return null
252
+ const prompt = `${CONTEXT}\n\n${brief}\nFollow ${REVIEW_GUIDE} and the two checklists next to it (security by OWASP Top 10, performance and correctness), but write the findings where and how this prompt says.`
253
+ if (changed.files.length <= LARGE_CHANGE) {
254
+ return agent(`${prompt}\n${output}`, { label: `teamlead:review-${round}`, phase: REVIEW_PHASE, agentType: 'levi-teamlead', schema: CODE_REVIEW })
255
+ }
256
+
257
+ log(`round ${round}: ${changed.files.length} reviewable files, so the review is split into slices (${LARGE_GUIDE})`)
258
+ const slices = await splitChange(round, changed.files)
259
+ const others = (i) => slices.map((s, j) => (j === i ? null : `- ${s.title} (${s.files.length} files): shares ${s.shares}`)).filter(Boolean).join('\n')
260
+ const reviewSlice = (s, i) =>
261
+ agent(
262
+ `${prompt}
263
+
264
+ This change is large (${changed.files.length} reviewable files), so ${slices.length} reviewers each review one slice at the same time, and a lead merges their reports. You review slice ${i + 1}: ${s.title}. It shares: ${s.shares}.
265
+ Your files, to review in full:
266
+ ${s.files.join('\n')}
267
+ The other slices:
268
+ ${others(i)}
269
+ Report every finding you can make a case for in your files, in one pass, whatever the severity: nothing is held for a later round, because the author fixes the whole list at once. When a change in your files breaks or relies on code in another slice, report it on your file and name the other location; what only another slice's reviewer can settle goes in crossSlice. Do not write ${REVIEW} or any other file and change nothing: your reply is the review of this slice. Give no verdict for the whole change. Findings carry the same fields as in a full review.`,
270
+ { label: `teamlead:review-${round}-slice-${i + 1}`, phase: REVIEW_PHASE, agentType: 'levi-teamlead', schema: SLICE_REVIEW },
271
+ )
272
+ const reports = [...(await parallel(slices.map((s, i) => () => reviewSlice(s, i))))]
273
+ const failed = slices.map((_, i) => i).filter((i) => !reports[i])
274
+ if (failed.length) {
275
+ const again = await parallel(failed.map((i) => () => reviewSlice(slices[i], i)))
276
+ failed.forEach((i, k) => (reports[i] = again[k]))
277
+ }
278
+ if (reports.some((r) => !r)) return null
279
+
280
+ return agent(
281
+ `${prompt}
282
+
283
+ You are the lead teamlead. ${slices.length} reviewers reviewed this large change in slices; ${LARGE_GUIDE} ("Steps", the merge) says how to combine them. Their reports:
284
+ ${JSON.stringify(slices.map((s, i) => ({ slice: s.title, files: s.files.length, report: reports[i] })))}
285
+ Merge them into the one review: join findings that have one cause (list every location), give equal problems equal severity, settle each crossSlice item by reading the code on both sides, re-read the location of every critical finding before you keep it, keep every valid finding and add nothing else. Do not approve while any slice lists something in notChecked that matters to the verdict.
286
+ ${output}`,
287
+ { label: `teamlead:review-${round}-merge`, phase: REVIEW_PHASE, agentType: 'levi-teamlead', schema: CODE_REVIEW },
288
+ )
289
+ }
290
+
291
+ // ---- Fix: fix, tests, review, E2E, until the review approves and every scenario passes ----
292
+
293
+ phase('Fix')
294
+ const gate = () =>
295
+ guard(
296
+ 'gate',
297
+ [
298
+ `1. Run \`${LOCK} verify ${LOCK_TESTS}\` and put the paths it lists under "restored" into restored (empty list when intact).`,
299
+ `2. Run \`${inv.testCommand}\` and record its exit code as testsExit.`,
300
+ inv.suiteCommand && inv.suiteCommand !== inv.testCommand
301
+ ? `3. Run \`${inv.suiteCommand}\` and record its exit code as suiteExit.`
302
+ : '3. There is no separate suite: set suiteExit to testsExit.',
303
+ 'In failures, summarize every failing or erroring test: file, test name, and the first lines of the error. At most 80 lines. Empty when everything passed.',
304
+ ].join('\n'),
305
+ GATE,
306
+ )
307
+
308
+ let todo = `Fix the bug as planned in ${INVESTIGATION}. Fix the cause, not the symptom, everywhere it occurs, and keep the change as small as the fix allows.`
309
+ let scenarios = null
310
+ let last = null
311
+ for (let round = 1; round <= MAX_ROUNDS; round++) {
312
+ log(`round ${round}`)
313
+ const fixed = await agent(
314
+ `${CONTEXT}\nInvestigation: ${INVESTIGATION}\n\n${todo}\n\n${RULES}\nWhen done, run \`${inv.testCommand}\`${inv.suiteCommand ? ` and \`${inv.suiteCommand}\`` : ''} and report the real result.`,
315
+ { label: `developer:fix-${round}`, phase: 'Fix', agentType: 'levi-developer', schema: FIXED },
316
+ )
317
+ if (!fixed || fixed.status === 'BLOCKED') return { status: 'blocked', stage: 'fix', detail: fixed ? fixed.blockers : ['the fix did not complete'] }
318
+
319
+ // Unit and feature tests must pass before the review.
320
+ const g = await gate()
321
+ if (!g) return { status: 'blocked', stage: 'tests', detail: 'the test run did not complete' }
322
+ if (g.restored.length || g.testsExit !== 0 || g.suiteExit !== 0) {
323
+ const tampered = g.restored.length ? `\nThese locked tests had been changed and were restored: ${g.restored.join(', ')}. Never touch them.` : ''
324
+ last = { stage: 'tests', failures: g.failures, restored: g.restored }
325
+ todo = `The unit and feature tests do not pass yet. Fix the code so that they do:\n${g.failures || 'the test run failed'}${tampered}`
326
+ continue
327
+ }
328
+
329
+ const review = await reviewChange(
330
+ round,
331
+ `Investigation: ${INVESTIGATION}
332
+
333
+ Review the developer's fix of this bug. The change is everything that differs from commit ${base.head} (git diff and untracked files), leaving out files that were already modified before the run: ${base.dirty.join(', ') || 'none'}.
334
+ The unit and feature tests pass. They are locked: do not propose changing them.
335
+ Check that the fix removes the root cause rather than the symptom, everywhere it occurs; that it does what the spec, the designs and the confirmed points expect; that it breaks nothing else; and its security (input validation, authorization, secrets), performance and fit with the architecture and conventions.`,
336
+ `Write ${REVIEW}: findings graded critical / warning / suggestion, each with the file, the problem and a concrete fix. Approve only when no critical or warning finding remains; suggestions alone do not block.`,
337
+ )
338
+ if (!review) return { status: 'blocked', stage: 'review', detail: 'the review did not complete' }
339
+ const blocking = review.findings.filter((f) => f.severity !== 'suggestion')
340
+ if (!review.approved || blocking.length) {
341
+ last = { stage: 'review', findings: blocking }
342
+ todo = `The teamlead's review (${REVIEW}) asks for these changes. Make them:\n${blocking.map((f) => `- [${f.severity}] ${f.file}: ${f.problem} Fix: ${f.fix}`).join('\n')}`
343
+ continue
344
+ }
345
+
346
+ // The review approved: QA runs its scenarios end to end.
347
+ if (!scenarios) {
348
+ scenarios = await scenariosReady
349
+ if (!scenarios) return { status: 'blocked', stage: 'scenarios', detail: 'QA did not finish the scenarios' }
350
+ if (scenarios.stop === 'questions') return { status: 'questions', stage: 'scenarios', questions: scenarios.questions }
351
+ if (scenarios.stop) return { status: 'blocked', stage: 'scenarios', detail: scenarios.detail }
352
+ }
353
+ const e2e = (note) =>
354
+ agent(
355
+ `${CONTEXT}
356
+
357
+ The fix of this bug was approved in review. Run every test case in ${SCENARIOS} (there are ${scenarios.scenarioCount}) against the running app and record the results, following your test case guide, ${TEST_GUIDE} ("Recording results"), with the cases file ${CASES} and the output base ${TEST_BASE}. Run them ${
358
+ inv.hasUi ? "in a headless browser: the project's E2E runner (such as Playwright) or a browser tool you have" : 'through its API or CLI'
359
+ }. Start the app with \`${inv.app.start}\` (${inv.app.url}; ${inv.app.notes}) and stop it when you are done.
360
+ Change no application code. Return the result of every case, by its ID.${note ? `\n\n${note}` : ''}`,
361
+ { label: `qa:e2e-${round}`, phase: 'Fix', agentType: 'levi-qa', schema: E2E },
362
+ )
363
+ // Changes to the test cases by anyone but QA are undone before QA runs them; QA's own results are kept after.
364
+ const restored = await restoreScenarios()
365
+ if (restored && restored.exitCode !== 0) log('the test cases had been changed outside QA and were restored')
366
+ const run = await e2e()
367
+ if (!run) return { status: 'blocked', stage: 'e2e', detail: 'the E2E run did not complete' }
368
+ await snapshotScenarios()
369
+ const failing = []
370
+ for (let n = 1; n <= scenarios.scenarioCount; n++) {
371
+ const id = `TC-${FEATURE_ID}-${String(n).padStart(3, '0')}`
372
+ const r = run.results.find((x) => x.id === id)
373
+ if (!r || r.result !== 'PASS') failing.push(`${id}: ${r ? r.evidence : 'not run'}`)
374
+ }
375
+ if (!failing.length) {
376
+ return {
377
+ status: 'done',
378
+ rounds: round,
379
+ rootCause: inv.rootCause,
380
+ tests: inv.bugTests,
381
+ wroteTests: inv.wroteTests,
382
+ testCommand: inv.testCommand,
383
+ scenarios: { files: SCENARIO_FILES, count: scenarios.scenarioCount },
384
+ review: review.summary,
385
+ suggestions: review.findings.filter((f) => f.severity === 'suggestion'),
386
+ }
387
+ }
388
+ last = { stage: 'e2e', failing }
389
+ todo = `QA ran the test cases in ${SCENARIOS} end to end after the review, and these failed. Fix the code so that they pass:\n${failing.join('\n')}`
390
+ }
391
+
392
+ return { status: 'stalled', rounds: MAX_ROUNDS, last }