levi-gear 0.1.0 → 0.2.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 (36) hide show
  1. package/README.md +13 -8
  2. package/agents/_team-protocol.md +12 -5
  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 +1 -1
  9. package/src/commands/list.js +2 -1
  10. package/src/lib/agents.js +9 -2
  11. package/src/lib/desired-state.js +23 -7
  12. package/src/lib/role-skills.js +23 -0
  13. package/src/lib/tools.js +6 -1
  14. package/src/lib/usecases.js +40 -1
  15. package/usecases/brainstorming/SKILL.md +8 -4
  16. package/usecases/code-review/SKILL.md +79 -0
  17. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  18. package/usecases/code-review/references/review-guide.md +70 -0
  19. package/usecases/code-review/references/security.md +119 -0
  20. package/usecases/create-feature/SKILL.md +94 -0
  21. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  22. package/usecases/create-feature/workflow.js +440 -0
  23. package/usecases/design/SKILL.md +61 -0
  24. package/usecases/design/references/svg-guide.md +14 -0
  25. package/usecases/design/scripts/check-svg.py +77 -0
  26. package/usecases/fix-bug/SKILL.md +96 -0
  27. package/usecases/fix-bug/workflow.js +298 -0
  28. package/usecases/generate-test-scenarios/SKILL.md +97 -0
  29. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  30. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  31. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  32. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  33. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  34. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  35. package/usecases/spec-writing/SKILL.md +59 -0
  36. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,96 @@
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. With a Workflow tool (Claude Code) it runs as `workflow.js`: 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. Without one, you run the same steps one by one.
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
+ - *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.
71
+ 7. **Act on the result.**
72
+ - `done`: go to step 8.
73
+ - `questions`: an agent found a point that is still open. Ask the user, append the answers to `confirmed.md`, and run step 6 again.
74
+ - `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.
75
+ - `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.
76
+ - `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.
77
+ - `stalled`: the rounds ran out (10 by default) and something still fails. Tell the user what failed last. If they want to go on, in the same session call the Workflow tool again with `resumeFromRunId` and a higher `maxRounds`. Tests and test cases still do not change.
78
+ 8. **Clean up.** Delete `docs/levi/<slug>/`, then `docs/levi` if it is empty. Keep everything else.
79
+ 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.
80
+
81
+ ## Workflow
82
+
83
+ 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`.
84
+
85
+ 1. **Baseline.** Record `git rev-parse HEAD` and the files `git status --porcelain` lists, so the review sees only this run's changes.
86
+ 2. **Two tracks at the same time**, neither reading the other's work:
87
+ - *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.
88
+ - *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`.
89
+ 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`.
90
+ 4. **Lock** the tests that cover the bug (`lock-tests.mjs lock docs/levi/<slug>/locked/tests ...`).
91
+ 5. **Rounds** (at most 10 unless raised), each starting with a fresh `levi-developer` call:
92
+ 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.
93
+ 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.
94
+ 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`. Critical or warning findings go back to the developer.
95
+ 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.
96
+ 5. The run is done when the review approves and every case passes.
@@ -0,0 +1,298 @@
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
+ // ---- Fix: fix, tests, review, E2E, until the review approves and every scenario passes ----
197
+
198
+ phase('Fix')
199
+ const gate = () =>
200
+ guard(
201
+ 'gate',
202
+ [
203
+ `1. Run \`${LOCK} verify ${LOCK_TESTS}\` and put the paths it lists under "restored" into restored (empty list when intact).`,
204
+ `2. Run \`${inv.testCommand}\` and record its exit code as testsExit.`,
205
+ inv.suiteCommand && inv.suiteCommand !== inv.testCommand
206
+ ? `3. Run \`${inv.suiteCommand}\` and record its exit code as suiteExit.`
207
+ : '3. There is no separate suite: set suiteExit to testsExit.',
208
+ '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.',
209
+ ].join('\n'),
210
+ GATE,
211
+ )
212
+
213
+ 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.`
214
+ let scenarios = null
215
+ let last = null
216
+ for (let round = 1; round <= MAX_ROUNDS; round++) {
217
+ log(`round ${round}`)
218
+ const fixed = await agent(
219
+ `${CONTEXT}\nInvestigation: ${INVESTIGATION}\n\n${todo}\n\n${RULES}\nWhen done, run \`${inv.testCommand}\`${inv.suiteCommand ? ` and \`${inv.suiteCommand}\`` : ''} and report the real result.`,
220
+ { label: `developer:fix-${round}`, phase: 'Fix', agentType: 'levi-developer', schema: FIXED },
221
+ )
222
+ if (!fixed || fixed.status === 'BLOCKED') return { status: 'blocked', stage: 'fix', detail: fixed ? fixed.blockers : ['the fix did not complete'] }
223
+
224
+ // Unit and feature tests must pass before the review.
225
+ const g = await gate()
226
+ if (!g) return { status: 'blocked', stage: 'tests', detail: 'the test run did not complete' }
227
+ if (g.restored.length || g.testsExit !== 0 || g.suiteExit !== 0) {
228
+ const tampered = g.restored.length ? `\nThese locked tests had been changed and were restored: ${g.restored.join(', ')}. Never touch them.` : ''
229
+ last = { stage: 'tests', failures: g.failures, restored: g.restored }
230
+ 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}`
231
+ continue
232
+ }
233
+
234
+ const review = await agent(
235
+ `${CONTEXT}\nInvestigation: ${INVESTIGATION}
236
+
237
+ 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'}.
238
+ The unit and feature tests pass. They are locked: do not propose changing them.
239
+ 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.
240
+ Follow ${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.
241
+ 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.`,
242
+ { label: `teamlead:review-${round}`, phase: 'Fix', agentType: 'levi-teamlead', schema: CODE_REVIEW },
243
+ )
244
+ if (!review) return { status: 'blocked', stage: 'review', detail: 'the review did not complete' }
245
+ const blocking = review.findings.filter((f) => f.severity !== 'suggestion')
246
+ if (!review.approved || blocking.length) {
247
+ last = { stage: 'review', findings: blocking }
248
+ 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')}`
249
+ continue
250
+ }
251
+
252
+ // The review approved: QA runs its scenarios end to end.
253
+ if (!scenarios) {
254
+ scenarios = await scenariosReady
255
+ if (!scenarios) return { status: 'blocked', stage: 'scenarios', detail: 'QA did not finish the scenarios' }
256
+ if (scenarios.stop === 'questions') return { status: 'questions', stage: 'scenarios', questions: scenarios.questions }
257
+ if (scenarios.stop) return { status: 'blocked', stage: 'scenarios', detail: scenarios.detail }
258
+ }
259
+ const e2e = (note) =>
260
+ agent(
261
+ `${CONTEXT}
262
+
263
+ 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 ${
264
+ 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'
265
+ }. Start the app with \`${inv.app.start}\` (${inv.app.url}; ${inv.app.notes}) and stop it when you are done.
266
+ Change no application code. Return the result of every case, by its ID.${note ? `\n\n${note}` : ''}`,
267
+ { label: `qa:e2e-${round}`, phase: 'Fix', agentType: 'levi-qa', schema: E2E },
268
+ )
269
+ // Changes to the test cases by anyone but QA are undone before QA runs them; QA's own results are kept after.
270
+ const restored = await restoreScenarios()
271
+ if (restored && restored.exitCode !== 0) log('the test cases had been changed outside QA and were restored')
272
+ const run = await e2e()
273
+ if (!run) return { status: 'blocked', stage: 'e2e', detail: 'the E2E run did not complete' }
274
+ await snapshotScenarios()
275
+ const failing = []
276
+ for (let n = 1; n <= scenarios.scenarioCount; n++) {
277
+ const id = `TC-${FEATURE_ID}-${String(n).padStart(3, '0')}`
278
+ const r = run.results.find((x) => x.id === id)
279
+ if (!r || r.result !== 'PASS') failing.push(`${id}: ${r ? r.evidence : 'not run'}`)
280
+ }
281
+ if (!failing.length) {
282
+ return {
283
+ status: 'done',
284
+ rounds: round,
285
+ rootCause: inv.rootCause,
286
+ tests: inv.bugTests,
287
+ wroteTests: inv.wroteTests,
288
+ testCommand: inv.testCommand,
289
+ scenarios: { files: SCENARIO_FILES, count: scenarios.scenarioCount },
290
+ review: review.summary,
291
+ suggestions: review.findings.filter((f) => f.severity === 'suggestion'),
292
+ }
293
+ }
294
+ last = { stage: 'e2e', failing }
295
+ 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')}`
296
+ }
297
+
298
+ return { status: 'stalled', rounds: MAX_ROUNDS, last }
@@ -0,0 +1,97 @@
1
+ ---
2
+ name: levi-generate-test-scenarios
3
+ description: Have QA generate screen-level test cases (test scenarios) from the feature specs already in the repository, using the spec as the only source. It covers the positive path of every user story, role permissions, screen flow edge cases, validation and error states, and background logic, and lists where the spec is unclear. Each feature gets docs/tests/<FeatureID>-<slug>.md and a matching .xlsx sheet that can be imported into Jira, TestRail, Notion or a spreadsheet. Specs are never created or changed; a missing spec or missing information is reported up front. Fits requests such as "generate test cases for F001", "write test scenarios from the spec", "sinh test case cho F001, F002", "viết kịch bản test từ spec".
4
+ argument-hint: "<feature IDs (for example F001 F002) or spec files and folders; empty for every feature>"
5
+ skill-for: qa
6
+ skill-when: you write or change test cases or test scenarios, or record their results
7
+ skill-guide: references/test-case-guide.md
8
+ ---
9
+
10
+ # Generate test scenarios
11
+
12
+ `levi-qa` writes the test cases; writing test cases is its job, and this skill's guide is how it does it in every usecase. You find the specs, ask the user what needs deciding, call QA once per feature for each pass, and report the result. You never write or edit a test case, a spec, or an output file yourself.
13
+
14
+ ## The rules that never bend
15
+
16
+ - **The spec is the only source.** Every case comes from what the spec says. Nothing is inferred from the code, the UI, the designs or outside knowledge, and no function is invented.
17
+ - **Specs are read-only.** Nothing under `docs/specs/` (or any spec the user points to) is created, edited or completed. A missing spec or a gap in one is reported to the user, not filled in.
18
+ - **Unclear stays unclear.** Where the spec is vague or silent, nobody decides: the point goes into the case's notes and into the "spec ambiguities" section.
19
+ - **Never overwrite silently.** An existing output file is replaced only when the user says so.
20
+
21
+ ## Files
22
+
23
+ | File | Owner | Purpose |
24
+ |---|---|---|
25
+ | `docs/tests/<base>.md` | QA | **Deliverable**: title and source spec, coverage summary, the test cases, spec ambiguities |
26
+ | `docs/tests/<base>.xlsx` | QA | **Deliverable**: one sheet, one row per case, columns `ID, Title, Category, Priority, Preconditions, Steps, Expected Result, Notes` |
27
+ | `docs/levi/test-cases/<FeatureID>-analysis.md` | QA | Scratch: spec items, coverage plan, ambiguities, readiness |
28
+ | `docs/levi/test-cases/<FeatureID>.json` | QA | Scratch: the cases the two deliverables are rendered from |
29
+ | `references/test-case-guide.md` | - | How QA analyzes the spec and writes the cases |
30
+ | `scripts/render-test-cases.mjs` | - | Checks the cases and renders both deliverables from them, so they always agree. The cases are also embedded in the `.md`, so QA can change them later |
31
+
32
+ ## Features, IDs and file names
33
+
34
+ A feature is one spec file, or one folder of spec files, under `docs/specs/` (searched recursively). When one file holds several features under headings that start with a feature code, each of those sections is a feature, and its source is that section plus the file's shared sections (roles, glossary, common rules).
35
+
36
+ | Item | Rule |
37
+ |---|---|
38
+ | Feature ID | The code the spec gives the feature, such as `F001` or `FEAT-12`: at the start of the file or folder name (`F001-login.md`), in the title (`# F001: Login`) or in a header field (`ID: F001`). Uppercase. A spec with no code uses its slug in uppercase, for example `EXPORT-ORDERS-CSV` |
39
+ | Feature slug | The file or folder name without extension and without the code, in kebab-case. When nothing is left, the title in ASCII kebab-case |
40
+ | Output `<base>` | `<FeatureID>-<slug>` when the spec has a code (`F001-login`); `<slug>-test-cases` when it has none (`export-orders-csv-test-cases`) |
41
+ | Case ID | `TC-<FeatureID>-<3 digits>`, for example `TC-F001-001` |
42
+
43
+ ## Steps
44
+
45
+ 1. **Intake.** From the request, take the feature codes (`F001`, `F002`, ...) and the spec files or folders it names. Anything else in it (a focus such as "only permissions") is passed to QA as written.
46
+ 2. **Find the specs.**
47
+ - Paths given: each file or folder is a feature. A path that does not exist is missing.
48
+ - Codes given: match each against `docs/specs/` by file and folder name, title and header fields, case-insensitively. No match: missing, reported as for example "No spec for F003 in docs/specs/".
49
+ - Neither given: list every feature in `docs/specs/`. If there is none, tell the user (`docs/specs/` is missing or empty) and stop.
50
+
51
+ Only the specs found this way are read. Work out each feature's ID, slug and output base.
52
+ 3. **Ask the user, all at once.** In one round (use the tool's structured question feature if it has one; if it limits the number of questions per call, make the calls back to back), ask only what applies:
53
+ - *No codes or paths were given:* list the features found and ask whether to generate for all of them or which ones. Do not generate for the whole project without this confirmation.
54
+ - *A code matches more than one spec:* which one.
55
+ - *`docs/tests/<base>.md` or `.xlsx` already exists:* replace it, or write a new version with a date suffix, `<base>-YYYYMMDD` (today's date; if that exists too, add `-2`, `-3`, ...).
56
+
57
+ In the same message, before the questions, tell the user every missing spec. If no feature is left to generate, say so and stop. Skip the questions when none applies.
58
+ 4. **Analyze.** Call `levi-qa` once per feature (in parallel when the tool allows), with this prompt filled in:
59
+
60
+ ```text
61
+ Analysis pass for feature <FeatureID>: <feature name or slug>.
62
+
63
+ Spec files (your only source): <paths, and the section when it is part of a file>
64
+ Write (yours as QA; create the folder if needed): docs/levi/test-cases/<FeatureID>-analysis.md
65
+ What the user asked: <the request, word for word>
66
+
67
+ Follow <this skill's folder>/references/test-case-guide.md, "The source rule" and "Analysis".
68
+ Read nothing but the spec files above and that guide. Do not change any spec. Write no other file.
69
+ ```
70
+
71
+ 5. **Report what is missing, up front.** Before any case is written, tell the user in one message, per feature: `Generate: no` with what the spec lacks (that feature is skipped), and for the others the Missing line and the number of ambiguities found. Then go on; this is information, not a question. If every feature is `Generate: no`, delete the scratch folder and stop.
72
+ 6. **Generate.** For every feature with `Generate: yes`, call `levi-qa` (in parallel when the tool allows):
73
+
74
+ ```text
75
+ Generation pass for feature <FeatureID>: <feature name or slug>.
76
+
77
+ Spec files (your only source): <paths, and the section when it is part of a file>
78
+ Your analysis: docs/levi/test-cases/<FeatureID>-analysis.md
79
+ Cases file: docs/levi/test-cases/<FeatureID>.json
80
+ Output base: docs/tests/<base>
81
+ Replace existing files: <yes, pass --force | no>
82
+
83
+ Follow <this skill's folder>/references/test-case-guide.md, "The source rule" and "Writing test cases".
84
+ Read nothing but the spec files, your analysis and that guide. Do not change any spec.
85
+ Report the case count and every ambiguity that remains.
86
+ ```
87
+
88
+ 7. **Verify.** For each feature, run `node <this skill's folder>/scripts/render-test-cases.mjs check docs/levi/test-cases/<FeatureID>.json` and check that `docs/tests/<base>.md` and `docs/tests/<base>.xlsx` exist. If the check fails or a file is missing, send QA the errors once to fix and render again. If it still fails, report the feature as not done, with the errors.
89
+ 8. **Clean up.** Delete `docs/levi/test-cases/`, and `docs/levi` if that is empty. Delete only after step 7.
90
+ 9. **Report.** A short summary, in the language of the request:
91
+ - per feature: the number of cases (by priority), the two file paths, and the spec it came from;
92
+ - features not generated: missing specs and specs that lacked what was needed;
93
+ - the spec ambiguities to clarify with QA and BA, one line each (feature, spec item, issue).
94
+
95
+ If QA was BLOCKED or needed context, say what it needs.
96
+
97
+ Without a parallel subagent feature, run the QA calls of steps 4 and 6 one after another; the steps are the same.