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,102 @@
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
+ | `docs/levi/test-cases/selection.md` | Workflow | Scratch: the confirmed feature list, output bases and overwrite choices for a resumable Codex run |
30
+ | `references/test-case-guide.md` | - | How QA analyzes the spec and writes the cases |
31
+ | `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 |
32
+
33
+ ## Features, IDs and file names
34
+
35
+ 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).
36
+
37
+ | Item | Rule |
38
+ |---|---|
39
+ | 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` |
40
+ | 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 |
41
+ | Output `<base>` | `<FeatureID>-<slug>` when the spec has a code (`F001-login`); `<slug>-test-cases` when it has none (`export-orders-csv-test-cases`) |
42
+ | Case ID | `TC-<FeatureID>-<3 digits>`, for example `TC-F001-001` |
43
+
44
+ ## Codex runner
45
+
46
+ On Codex, use [`references/codex-runner.md`](references/codex-runner.md). It checkpoints selection, per-feature QA work and verification in `docs/levi/test-cases/run.json` so a stopped run does not silently regenerate finished outputs.
47
+
48
+ ## Steps
49
+
50
+ 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.
51
+ 2. **Find the specs.**
52
+ - Paths given: each file or folder is a feature. A path that does not exist is missing.
53
+ - 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/".
54
+ - Neither given: list every feature in `docs/specs/`. If there is none, tell the user (`docs/specs/` is missing or empty) and stop.
55
+
56
+ Only the specs found this way are read. Work out each feature's ID, slug and output base.
57
+ 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:
58
+ - *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.
59
+ - *A code matches more than one spec:* which one.
60
+ - *`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`, ...).
61
+
62
+ 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.
63
+ 4. **Analyze.** Call `levi-qa` once per feature (in parallel when the tool allows), with this prompt filled in:
64
+
65
+ ```text
66
+ Analysis pass for feature <FeatureID>: <feature name or slug>.
67
+
68
+ Spec files (your only source): <paths, and the section when it is part of a file>
69
+ Write (yours as QA; create the folder if needed): docs/levi/test-cases/<FeatureID>-analysis.md
70
+ What the user asked: <the request, word for word>
71
+
72
+ Follow <this skill's folder>/references/test-case-guide.md, "The source rule" and "Analysis".
73
+ Read nothing but the spec files above and that guide. Do not change any spec. Write no other file.
74
+ ```
75
+
76
+ 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.
77
+ 6. **Generate.** For every feature with `Generate: yes`, call `levi-qa` (in parallel when the tool allows):
78
+
79
+ ```text
80
+ Generation pass for feature <FeatureID>: <feature name or slug>.
81
+
82
+ Spec files (your only source): <paths, and the section when it is part of a file>
83
+ Your analysis: docs/levi/test-cases/<FeatureID>-analysis.md
84
+ Cases file: docs/levi/test-cases/<FeatureID>.json
85
+ Output base: docs/tests/<base>
86
+ Replace existing files: <yes, pass --force | no>
87
+
88
+ Follow <this skill's folder>/references/test-case-guide.md, "The source rule" and "Writing test cases".
89
+ Read nothing but the spec files, your analysis and that guide. Do not change any spec.
90
+ Report the case count and every ambiguity that remains.
91
+ ```
92
+
93
+ 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.
94
+ 8. **Clean up.** Delete `docs/levi/test-cases/`, and `docs/levi` if that is empty. Delete only after step 7.
95
+ 9. **Report.** A short summary, in the language of the request:
96
+ - per feature: the number of cases (by priority), the two file paths, and the spec it came from;
97
+ - features not generated: missing specs and specs that lacked what was needed;
98
+ - the spec ambiguities to clarify with QA and BA, one line each (feature, spec item, issue).
99
+
100
+ If QA was BLOCKED or needed context, say what it needs.
101
+
102
+ Without a parallel subagent feature, run the QA calls of steps 4 and 6 one after another; the steps are the same.
@@ -0,0 +1,32 @@
1
+ # Codex runner
2
+
3
+ Run from the project root with one durable state per invocation:
4
+
5
+ ```bash
6
+ node <this skill folder>/scripts/codex-run-state.mjs status docs/levi/test-cases
7
+ node <this skill folder>/scripts/codex-run-state.mjs init docs/levi/test-cases generate-test-scenarios test-cases select analyze report generate verify
8
+ ```
9
+
10
+ ```bash
11
+ node <this skill folder>/scripts/codex-run-state.mjs begin docs/levi/test-cases <stage>
12
+ node <this skill folder>/scripts/codex-run-state.mjs complete docs/levi/test-cases <stage> <artifact>...
13
+ node <this skill folder>/scripts/codex-run-state.mjs wait docs/levi/test-cases <stage> "<questions>"
14
+ node <this skill folder>/scripts/codex-run-state.mjs block docs/levi/test-cases <stage> "<blocker>"
15
+ node <this skill folder>/scripts/codex-run-state.mjs resume docs/levi/test-cases
16
+ ```
17
+
18
+ When a valid branch ends before the last stage, use `finish` rather than pretending later stages completed:
19
+
20
+ ```bash
21
+ node <this skill folder>/scripts/codex-run-state.mjs finish docs/levi/test-cases report
22
+ ```
23
+
24
+ Use `status` before continuing a stopped run. Begin the current stage, complete it only after its outputs exist, and use `wait`, `block`, and `resume` for user choices and dependencies. Record the selected feature list and output bases in `docs/levi/test-cases/selection.md`, then pass that file to `complete` for `select`. Do not regenerate a feature whose verify stage completed.
25
+
26
+ - `select`: find requested specs, report missing ones, and preserve required choices (all features, ambiguous codes, overwrite/versioned output) with `wait`. Complete when exact features and output bases are fixed in `selection.md`.
27
+ - `analyze`: dispatch one `levi-qa` agent per selected feature only. They may run in parallel because each owns `docs/levi/test-cases/<FeatureID>-analysis.md`. Complete only when every selected analysis exists.
28
+ - `report`: report `Generate: no` and ambiguities before any writing. If every selected feature is skipped, use `finish docs/levi/test-cases report` and clean up; otherwise continue.
29
+ - `generate`: dispatch QA only for features marked `Generate: yes`. Complete only when each `json` case source and both requested output files exist.
30
+ - `verify`: run `render-test-cases.mjs check` for every generated feature. QA may repair each failing feature once; a remaining failure marks this stage `block` with its errors. Complete only after all selected outputs validate, then cleanup removes the scratch state.
31
+
32
+ Only `levi-qa` writes analysis, case sources and deliverables. The coordinator does not edit those files.
@@ -0,0 +1,171 @@
1
+ # Test case guide
2
+
3
+ How `levi-qa` writes, changes and runs test cases (also called test scenarios), in the `generate-test-scenarios` usecase and in every other one: whichever workflow asks you for test cases, this is how you do it.
4
+
5
+ The prompt gives you:
6
+
7
+ - the **sources**: the files the cases come from (a spec, and sometimes designs, a bug report or the points the user confirmed);
8
+ - the **feature ID** (`F001`, `EXPORT-ORDERS-CSV`, ...), which every case ID carries;
9
+ - the **cases file**: a JSON scratch file the cases are written in;
10
+ - the **output base**: the path, without extension, of the two files rendered from it (`docs/tests/F001-login` gives `docs/tests/F001-login.md` and `.xlsx`).
11
+
12
+ When the prompt leaves the feature ID or the output base out, derive them as the "Features, IDs and file names" table in `SKILL.md` says. When it leaves the cases file out, use `docs/levi/<slug>/test-cases.json` in the work folder. These files are yours as QA; create their folders as needed. Paths in this guide are relative to the skill folder, the parent of `references/`.
13
+
14
+ ## The source rule
15
+
16
+ - **The sources are the only source.** Read only the sources the prompt names, and this guide. Do not read application code, tests, or anything else the prompt does not name, and do not use what similar products usually do. A case, a step or an expected result that no source supports does not get written.
17
+ - **Never touch a source.** Specs and the other sources are read-only, even for a typo. What is wrong or missing in them goes into the ambiguities.
18
+ - **Do not decide for the spec.** When a source is unclear, silent or contradicts itself on a point a case needs, do not pick an answer. If the case can still be run and checked without that point, write it without it and say so in its notes; if a step or the expected result depends on it (an unstated limit, count or message), leave the case out. Record the point as an ambiguity either way, and, when the prompt asks for questions, list it there too.
19
+ - **Test data is not invention.** A concrete input that illustrates a rule the source states (an email without `@` for "email must be valid") is test data, and allowed. A value that settles what the source leaves open (whether a limit is inclusive, how many attempts lock an account) is not: that is an ambiguity.
20
+ - **Write in the language of the spec** (or of the sources, when there is no spec). Titles, preconditions, steps, expected results, notes, ambiguities and the section labels follow it. Field names, IDs, categories and priorities stay as defined below.
21
+
22
+ ## References
23
+
24
+ Every case names the items it comes from. Use the source's own IDs when it has them (`US-1`, `AC-3`, `BR-2`). When an item has no ID, name its place: the section heading plus the item's position, counting list items, table rows or sentences of a paragraph, for example `Validation rules #2` or `Screen flow #3`; for a bug report, `Report` or `Confirmed #2`. Use the same reference everywhere for the same item. An ambiguity that spans several items lists them comma-separated, for example `V-1, V-3`.
25
+
26
+ ## Coverage areas
27
+
28
+ | Area | What to cover | Category |
29
+ |---|---|---|
30
+ | Positive path | Each user story done the way the spec describes it, at least one case per story | Functional |
31
+ | Permissions | Each role the spec allows can do the action; each role the spec forbids, or that is not among the allowed ones when the spec lists them, is refused in the way the spec says | Security |
32
+ | Screen flow edge cases | Navigation the spec describes: back, cancel, leaving and returning, the transitions between screens and states | Functional or UX |
33
+ | Validation and error states | Required fields, formats, lengths, boundary values (at the limit, just below, just above), each error state and message | Functional |
34
+ | Background logic | Each trigger the spec gives for background processing, and the outcome it says is observable | Functional |
35
+
36
+ - Cover only the areas the sources give material for. When a gap matters (for example a form with no validation rules), it is an ambiguity.
37
+ - Use **UX** for what the spec says about feedback, messages, loading and empty states; **Performance** and **Accessibility** only for requirements the spec states, such as a time limit or a screen reader label.
38
+ - Boundary values come from the spec's numbers. If the spec gives a limit without saying whether it is inclusive, that is an ambiguity.
39
+ - The prompt can add what must be covered, for example every acceptance criterion, or the steps of a bug report as the first case.
40
+
41
+ ## Analysis
42
+
43
+ Only when the prompt asks for an analysis pass. Read the sources and write the analysis file you are given, in this format:
44
+
45
+ ```markdown
46
+ # <FeatureID>: <feature name>
47
+
48
+ ## Spec items
49
+ | Ref | Kind | Summary |
50
+ |---|---|---|
51
+ | US-1 | story | <one line> |
52
+
53
+ ## Coverage plan
54
+ | Area | Spec items | Planned cases |
55
+ |---|---|---|
56
+ | Positive path | US-1 | <what each case checks, one line each> |
57
+
58
+ ## Ambiguities
59
+ | # | Spec item | Issue |
60
+ |---|---|---|
61
+ | 1 | AC-3 | <what is unclear, silent or contradictory, and what a case needs to know> |
62
+
63
+ ## Readiness
64
+ Generate: yes | no
65
+ Missing: <what the spec lacks; "none">
66
+ ```
67
+
68
+ - **Kind** is one of `story`, `screen-flow`, `permission`, `background`, `validation`, `error-state` or `other`. List every item of these kinds the spec contains.
69
+ - **Generate** is `no` only when the spec gives nothing that can be tested: no story, no flow, no rule with an observable outcome. A spec that only lacks some areas is still `yes`; the gaps are listed under Missing and as ambiguities.
70
+
71
+ ## Writing test cases
72
+
73
+ Plan the coverage (in your head, or from your analysis when there is one), write the cases file as JSON, check it and render it.
74
+
75
+ ### Fields
76
+
77
+ | Field | Rule |
78
+ |---|---|
79
+ | `id` | `TC-<FeatureID>-<3 digits>`, numbered from 001 in order, no gaps |
80
+ | `title` | Short, says exactly what is checked |
81
+ | `category` | `Functional`, `UX`, `Security`, `Performance` or `Accessibility` |
82
+ | `priority` | `P0`: blocks the main flow, or security. `P1`: important function. `P2`: minor or cosmetic |
83
+ | `preconditions` | Data state, user role and the starting screen. Line breaks are allowed |
84
+ | `steps` | One action per step, in order, without numbers (the script numbers them) |
85
+ | `expected` | A concrete, observable result, worded as the source words it, checkable yes or no |
86
+ | `refs` | The items the case traces to |
87
+ | `positive` | `true` for a case that completes a user story as described, `false` otherwise |
88
+ | `notes` | Optional: what QA must confirm, and the ambiguity the case depends on |
89
+ | `status`, `evidence` | Only once the case has been run, see [Recording results](#recording-results) |
90
+
91
+ ### JSON format
92
+
93
+ ```json
94
+ {
95
+ "featureId": "F001",
96
+ "featureName": "<feature name as the spec gives it>",
97
+ "spec": ["docs/specs/F001-login.md"],
98
+ "labels": {
99
+ "title": "Test cases",
100
+ "source": "Spec",
101
+ "total": "Total",
102
+ "result": "Result",
103
+ "coverage": "Coverage",
104
+ "category": "Category",
105
+ "priority": "Priority",
106
+ "preconditions": "Preconditions",
107
+ "steps": "Steps",
108
+ "expected": "Expected Result",
109
+ "notes": "Notes",
110
+ "status": "Status",
111
+ "evidence": "Evidence",
112
+ "cases": "Test cases",
113
+ "ambiguities": "Spec ambiguities",
114
+ "item": "Spec item",
115
+ "issue": "Issue",
116
+ "affected": "Affected cases",
117
+ "none": "None.",
118
+ "specRef": "Spec"
119
+ },
120
+ "stories": [{ "ref": "US-1", "title": "<story in one line>" }],
121
+ "cases": [
122
+ {
123
+ "id": "TC-F001-001",
124
+ "title": "<title>",
125
+ "category": "Functional",
126
+ "priority": "P0",
127
+ "preconditions": "<preconditions>",
128
+ "steps": ["<action>", "<action>"],
129
+ "expected": "<expected result>",
130
+ "refs": ["US-1", "AC-1"],
131
+ "positive": true,
132
+ "notes": "<optional>"
133
+ }
134
+ ],
135
+ "ambiguities": [{ "ref": "AC-3", "issue": "<what is unclear>", "cases": ["TC-F001-004"] }]
136
+ }
137
+ ```
138
+
139
+ - `spec` lists every source file the cases come from.
140
+ - `labels` holds the headings and field names of the Markdown file and the `Spec:` prefix of the notes. Translate them all into the spec's language; leave out only those you keep in English. The column headers of the `.xlsx` file always stay in English, so that importers recognize them.
141
+ - `stories` lists every user story of the spec. Leave it empty only when the sources have none; when a spec has none, say so as an ambiguity.
142
+ - `ambiguities` carries every ambiguity that still stands. `cases` lists the cases that depend on it, or is empty.
143
+
144
+ ### Check and render
145
+
146
+ 1. `node scripts/render-test-cases.mjs check <cases file>` (the script is in the skill folder). Fix every error it prints and run it again until it passes. It checks the ID format and order, the field values, duplicate cases, that every story has a positive case, and that ambiguities point to real cases.
147
+ 2. Check what the script cannot, and fix what fails:
148
+ - every case traces to a source item that says what the case expects; nothing is invented;
149
+ - each step is a single action;
150
+ - each expected result can be observed and checked yes or no;
151
+ - no two cases check the same thing with different words;
152
+ - every area you planned has its cases, and everything the prompt said must be covered is.
153
+ 3. `node scripts/render-test-cases.mjs render <cases file> <output base>`. It writes `<output base>.md` and `<output base>.xlsx`, and refuses to replace them: add `--force` only when they are already yours (written by you earlier in this run, or a set you are changing) or the prompt says to replace them. Never write or edit those two files by hand.
154
+
155
+ ## Changing test cases
156
+
157
+ The rendered files belong to QA, and only QA changes them, always through the cases file:
158
+
159
+ 1. When you do not have the cases file of this run, get it back from the rendered Markdown: `node scripts/render-test-cases.mjs extract <output base>.md <cases file>` (the data is embedded at the end of the file, in a comment that viewers do not show).
160
+ 2. Change the cases in the JSON: fix what a review found, cover a changed source, add or remove cases. Keep the numbering from 001 with no gaps.
161
+ 3. Check and render again, with `--force`.
162
+
163
+ Never change an expected result to match what the product does. When you think the source is wrong, it is an ambiguity or a question, not a change to the case.
164
+
165
+ ## Recording results
166
+
167
+ When you run the cases (end to end, in a headless browser through the project's E2E runner or a browser tool, or through the API or CLI when there is no UI):
168
+
169
+ 1. Follow each case's preconditions and steps as written, and compare with its expected result.
170
+ 2. In the cases file, give each case you ran `"status": "PASS"` or `"status": "FAIL"`, and `"evidence"`: what you observed (for FAIL, the actual result against the expected one, and the error). A case you could not run is FAIL, with the reason: untested is not passed.
171
+ 3. Check and render again, with `--force`. The Markdown then shows the result of each case and the total, and the `.xlsx` gets `Status` and `Evidence` columns.
@@ -0,0 +1,76 @@
1
+ // Renders a test cases document as Markdown. The document itself is embedded at the end, in an HTML comment that
2
+ // Markdown viewers do not show, so the cases can be read back and changed later (see extractDocument).
3
+
4
+ import { CATEGORIES, PRIORITIES, hasResults, notesCell } from './test-case-fields.mjs';
5
+
6
+ const DATA_OPEN = '<!-- levi-test-cases ';
7
+ const DATA_CLOSE = ' -->';
8
+ const DATA = /<!-- levi-test-cases (\{[\s\S]*\}) -->/;
9
+
10
+ // Angle brackets are escaped so they are not read as HTML, a line break becomes <br>, and a table cell also
11
+ // escapes its pipes.
12
+ const inline = (text) =>
13
+ String(text).trim().replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r?\n/g, '<br>');
14
+ const cell = (text) => inline(text).replace(/\|/g, '\\|');
15
+
16
+ function coverage(doc, labels) {
17
+ const count = (category, priority) =>
18
+ doc.cases.filter((tc) => (!category || tc.category === category) && (!priority || tc.priority === priority)).length;
19
+ return [
20
+ `| ${labels.category} | ${PRIORITIES.join(' | ')} | ${labels.total} |`,
21
+ `|---|${PRIORITIES.map(() => '---:').join('|')}|---:|`,
22
+ ...CATEGORIES.map((c) => `| ${c} | ${PRIORITIES.map((p) => count(c, p)).join(' | ')} | ${count(c)} |`),
23
+ `| **${labels.total}** | ${PRIORITIES.map((p) => `**${count(null, p)}**`).join(' | ')} | **${doc.cases.length}** |`,
24
+ ];
25
+ }
26
+
27
+ function testCase(tc, labels, withResults) {
28
+ const lines = [
29
+ `### ${tc.id}: ${inline(tc.title)}`,
30
+ '',
31
+ `- **${labels.category}:** ${tc.category}`,
32
+ `- **${labels.priority}:** ${tc.priority}`,
33
+ `- **${labels.preconditions}:** ${inline(tc.preconditions)}`,
34
+ `- **${labels.steps}:**`,
35
+ ...tc.steps.map((step, i) => ` ${i + 1}. ${inline(step)}`),
36
+ `- **${labels.expected}:** ${inline(tc.expected)}`,
37
+ `- **${labels.notes}:** ${inline(notesCell(tc, labels))}`,
38
+ ];
39
+ if (withResults) lines.push(`- **${labels.status}:** ${tc.status ?? '-'}`, `- **${labels.evidence}:** ${inline(tc.evidence ?? '-')}`);
40
+ return lines;
41
+ }
42
+
43
+ export function renderMarkdown(doc, labels) {
44
+ const withResults = hasResults(doc);
45
+ const passed = doc.cases.filter((tc) => tc.status === 'PASS').length;
46
+ const out = [
47
+ `# ${doc.featureId}: ${inline(doc.featureName)} - ${labels.title}`,
48
+ '',
49
+ `- **${labels.source}:** ${doc.spec.map((p) => `\`${p}\``).join(', ')}`,
50
+ `- **${labels.total}:** ${doc.cases.length}`,
51
+ ...(withResults ? [`- **${labels.result}:** ${passed}/${doc.cases.length} PASS`] : []),
52
+ '',
53
+ `## ${labels.coverage}`,
54
+ '',
55
+ ...coverage(doc, labels),
56
+ '',
57
+ `## ${labels.cases}`,
58
+ ];
59
+ for (const tc of doc.cases) out.push('', ...testCase(tc, labels, withResults));
60
+ out.push('', `## ${labels.ambiguities}`, '');
61
+ const ambiguities = doc.ambiguities ?? [];
62
+ if (!ambiguities.length) out.push(labels.none);
63
+ else {
64
+ out.push(`| # | ${labels.item} | ${labels.issue} | ${labels.affected} |`, '|---|---|---|---|');
65
+ ambiguities.forEach((a, i) => out.push(`| ${i + 1} | ${cell(a.ref)} | ${cell(a.issue)} | ${(a.cases ?? []).join(', ') || '-'} |`));
66
+ }
67
+ // "--" cannot appear inside an HTML comment; inside JSON strings it is written as "--", which parses back the same.
68
+ out.push('', DATA_OPEN + JSON.stringify(doc).replace(/--/g, '-\\u002d') + DATA_CLOSE);
69
+ return out.join('\n') + '\n';
70
+ }
71
+
72
+ export function extractDocument(markdown) {
73
+ const match = DATA.exec(markdown);
74
+ if (!match) throw new Error('no embedded test cases found; the file was not written by render-test-cases.mjs');
75
+ return JSON.parse(match[1]);
76
+ }
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ // Checks test cases and renders them as Markdown and Excel, so that both files always agree.
3
+ //
4
+ // node render-test-cases.mjs check <cases.json> validate only
5
+ // node render-test-cases.mjs render <cases.json> <out-base> [--force] validate, then write <out-base>.md and .xlsx
6
+ // node render-test-cases.mjs extract <out-base>.md <cases.json> read the cases back from a rendered file
7
+ //
8
+ // The JSON format is described in ../references/test-case-guide.md. Every command prints JSON and exits 1 on an
9
+ // error. `render` refuses to replace an existing file unless --force is given; `extract` never overwrites the JSON.
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { validate } from './validate-test-cases.mjs';
14
+ import { CATEGORIES, PRIORITIES, DEFAULT_LABELS, columns, hasResults, rowCells } from './test-case-fields.mjs';
15
+ import { renderMarkdown, extractDocument } from './render-test-cases-markdown.mjs';
16
+ import { writeXlsx } from './write-xlsx.mjs';
17
+
18
+ function render(doc, base, force) {
19
+ const files = [`${base}.md`, `${base}.xlsx`];
20
+ const existing = files.filter((f) => fs.existsSync(f));
21
+ if (existing.length && !force) return { ok: false, errors: existing.map((f) => `already exists: ${f} (pass --force to replace it)`) };
22
+ const labels = { ...DEFAULT_LABELS, ...doc.labels };
23
+ const withResults = hasResults(doc);
24
+ fs.mkdirSync(path.dirname(base), { recursive: true });
25
+ fs.writeFileSync(files[0], renderMarkdown(doc, labels));
26
+ writeXlsx(files[1], { sheet: 'Test cases', columns: columns(doc), rows: doc.cases.map((tc) => rowCells(tc, labels, withResults)) });
27
+ const tally = (key, values) => Object.fromEntries(values.map((v) => [v, doc.cases.filter((tc) => tc[key] === v).length]));
28
+ return {
29
+ ok: true,
30
+ written: files,
31
+ cases: doc.cases.length,
32
+ byCategory: tally('category', CATEGORIES),
33
+ byPriority: tally('priority', PRIORITIES),
34
+ ...(withResults ? { results: tally('status', ['PASS', 'FAIL']) } : {}),
35
+ ambiguities: (doc.ambiguities ?? []).length,
36
+ };
37
+ }
38
+
39
+ function extract(markdownFile, output) {
40
+ if (fs.existsSync(output)) return { ok: false, errors: [`already exists: ${output}`] };
41
+ const doc = extractDocument(fs.readFileSync(markdownFile, 'utf8'));
42
+ fs.mkdirSync(path.dirname(output), { recursive: true });
43
+ fs.writeFileSync(output, JSON.stringify(doc, null, 2) + '\n');
44
+ return { ok: true, written: [output], cases: doc.cases.length };
45
+ }
46
+
47
+ const [cmd, input, target, flag] = process.argv.slice(2);
48
+ try {
49
+ let result;
50
+ if (cmd === 'check' && input) result = { ok: true, ...validate(JSON.parse(fs.readFileSync(input, 'utf8'))) };
51
+ else if (cmd === 'render' && input && target) {
52
+ const doc = JSON.parse(fs.readFileSync(input, 'utf8'));
53
+ const { errors, warnings } = validate(doc);
54
+ result = errors.length ? { ok: false, errors, warnings } : { ...render(doc, target, flag === '--force'), warnings };
55
+ } else if (cmd === 'extract' && input && target) result = extract(input, target);
56
+ else {
57
+ console.error('usage: render-test-cases.mjs check <cases.json> | render <cases.json> <out-base> [--force] | extract <file.md> <cases.json>');
58
+ process.exitCode = 2;
59
+ }
60
+ if (result) {
61
+ if (result.errors?.length) result.ok = false;
62
+ console.log(JSON.stringify(result, null, 2));
63
+ if (!result.ok) process.exitCode = 1;
64
+ }
65
+ } catch (err) {
66
+ console.log(JSON.stringify({ ok: false, errors: [err.message] }, null, 2));
67
+ process.exitCode = 1;
68
+ }
@@ -0,0 +1,63 @@
1
+ // The fields of a test case and how they become the cells of a row. Shared by the validator and both renderers.
2
+
3
+ export const CATEGORIES = ['Functional', 'UX', 'Security', 'Performance', 'Accessibility'];
4
+ export const PRIORITIES = ['P0', 'P1', 'P2'];
5
+ export const RESULTS = ['PASS', 'FAIL'];
6
+
7
+ export const DEFAULT_LABELS = {
8
+ title: 'Test cases',
9
+ source: 'Spec',
10
+ total: 'Total',
11
+ result: 'Result',
12
+ coverage: 'Coverage',
13
+ category: 'Category',
14
+ priority: 'Priority',
15
+ preconditions: 'Preconditions',
16
+ steps: 'Steps',
17
+ expected: 'Expected Result',
18
+ notes: 'Notes',
19
+ status: 'Status',
20
+ evidence: 'Evidence',
21
+ cases: 'Test cases',
22
+ ambiguities: 'Spec ambiguities',
23
+ item: 'Spec item',
24
+ issue: 'Issue',
25
+ affected: 'Affected cases',
26
+ none: 'None.',
27
+ specRef: 'Spec',
28
+ };
29
+
30
+ const COLUMNS = [
31
+ { header: 'ID', width: 16 },
32
+ { header: 'Title', width: 40 },
33
+ { header: 'Category', width: 14 },
34
+ { header: 'Priority', width: 10 },
35
+ { header: 'Preconditions', width: 40 },
36
+ { header: 'Steps', width: 60 },
37
+ { header: 'Expected Result', width: 50 },
38
+ { header: 'Notes', width: 40 },
39
+ ];
40
+ const RESULT_COLUMNS = [
41
+ { header: 'Status', width: 10 },
42
+ { header: 'Evidence', width: 50 },
43
+ ];
44
+
45
+ // Results appear (Status and Evidence) once at least one case has been run.
46
+ export const hasResults = (doc) => (doc.cases || []).some((tc) => tc.status !== undefined);
47
+
48
+ export const columns = (doc) => (hasResults(doc) ? [...COLUMNS, ...RESULT_COLUMNS] : COLUMNS);
49
+
50
+ export function notesCell(tc, labels) {
51
+ const refs = Array.isArray(tc.refs) ? tc.refs : [];
52
+ const ref = `${labels.specRef}: ${refs.join(', ')}`;
53
+ return typeof tc.notes === 'string' && tc.notes.trim() ? `${ref}\n${tc.notes.trim()}` : ref;
54
+ }
55
+
56
+ export const numberedSteps = (tc) =>
57
+ (Array.isArray(tc.steps) ? tc.steps : []).map((step, i) => `${i + 1}. ${String(step).trim()}`).join('\n');
58
+
59
+ export function rowCells(tc, labels, withResults) {
60
+ const cells = [tc.id, tc.title, tc.category, tc.priority, tc.preconditions, numberedSteps(tc), tc.expected, notesCell(tc, labels)];
61
+ if (withResults) cells.push(tc.status ?? '-', tc.evidence ?? '-');
62
+ return cells.map((cell) => String(cell ?? '').trim());
63
+ }
@@ -0,0 +1,69 @@
1
+ // Checks a test cases document (the JSON format in ../references/test-case-guide.md) before it is rendered.
2
+
3
+ import { CATEGORIES, PRIORITIES, RESULTS, DEFAULT_LABELS, rowCells } from './test-case-fields.mjs';
4
+
5
+ const XLSX_CELL_LIMIT = 32767;
6
+ const isText = (value) => typeof value === 'string' && value.trim() !== '';
7
+
8
+ function checkCase(tc, i, doc, errors) {
9
+ const expectedId = `TC-${doc.featureId}-${String(i + 1).padStart(3, '0')}`;
10
+ const at = `case ${i + 1} (${tc.id ?? 'no id'})`;
11
+ if (tc.id !== expectedId) errors.push(`${at}: id must be ${expectedId} (numbered from 001, in order, no gaps)`);
12
+ for (const field of ['title', 'preconditions', 'expected']) if (!isText(tc[field])) errors.push(`${at}: ${field} is missing`);
13
+ if (!CATEGORIES.includes(tc.category)) errors.push(`${at}: category must be one of ${CATEGORIES.join(', ')}`);
14
+ if (!PRIORITIES.includes(tc.priority)) errors.push(`${at}: priority must be one of ${PRIORITIES.join(', ')}`);
15
+ if (typeof tc.positive !== 'boolean') errors.push(`${at}: positive must be true or false`);
16
+ if (!Array.isArray(tc.refs) || !tc.refs.length || !tc.refs.every(isText)) errors.push(`${at}: refs must name the spec items it traces to`);
17
+ if (tc.notes !== undefined && typeof tc.notes !== 'string') errors.push(`${at}: notes must be text`);
18
+ if (!Array.isArray(tc.steps) || !tc.steps.length) errors.push(`${at}: steps is empty`);
19
+ else
20
+ tc.steps.forEach((step, s) => {
21
+ if (!isText(step)) errors.push(`${at}: step ${s + 1} is empty`);
22
+ else if (/[\r\n]/.test(step)) errors.push(`${at}: step ${s + 1} spans several lines; split it, one action per step`);
23
+ else if (/^\s*\d+[.)]\s/.test(step)) errors.push(`${at}: step ${s + 1} is numbered; leave numbering to the script`);
24
+ });
25
+ if (tc.status !== undefined && !RESULTS.includes(tc.status)) errors.push(`${at}: status must be PASS or FAIL (leave it out when not run)`);
26
+ if (tc.status !== undefined && !isText(tc.evidence)) errors.push(`${at}: a run case needs evidence of what was observed`);
27
+ if (tc.status === undefined && tc.evidence !== undefined) errors.push(`${at}: evidence without a status`);
28
+ for (const cell of rowCells(tc, DEFAULT_LABELS, true))
29
+ if (cell.length > XLSX_CELL_LIMIT) errors.push(`${at}: a field is longer than ${XLSX_CELL_LIMIT} characters`);
30
+ }
31
+
32
+ export function validate(doc) {
33
+ const errors = [];
34
+ const warnings = [];
35
+ if (!/^[A-Z0-9]+(-[A-Z0-9]+)*$/.test(doc.featureId ?? '')) errors.push('featureId must be uppercase letters, digits and hyphens');
36
+ if (!isText(doc.featureName)) errors.push('featureName is missing');
37
+ if (!Array.isArray(doc.spec) || !doc.spec.length || !doc.spec.every(isText)) errors.push('spec must list the source file paths');
38
+ const cases = Array.isArray(doc.cases) ? doc.cases : [];
39
+ if (!cases.length) errors.push('cases is empty');
40
+
41
+ const titles = new Map();
42
+ const bodies = new Map();
43
+ cases.forEach((tc, i) => {
44
+ checkCase(tc, i, doc, errors);
45
+ const title = String(tc.title ?? '').trim().toLowerCase();
46
+ const body = JSON.stringify([tc.preconditions, tc.steps, tc.expected]);
47
+ if (title && titles.has(title)) errors.push(`case ${i + 1} (${tc.id}): same title as ${titles.get(title)}`);
48
+ if (bodies.has(body)) errors.push(`case ${i + 1} (${tc.id}): same preconditions, steps and expected result as ${bodies.get(body)}`);
49
+ titles.set(title, tc.id);
50
+ bodies.set(body, tc.id);
51
+ });
52
+
53
+ const stories = Array.isArray(doc.stories) ? doc.stories : [];
54
+ if (!stories.length) warnings.push('stories is empty: no user story coverage was checked');
55
+ for (const story of stories) {
56
+ if (!isText(story?.ref)) errors.push('every story needs a ref');
57
+ else if (!cases.some((tc) => tc.positive === true && tc.refs?.includes(story.ref)))
58
+ errors.push(`story ${story.ref} has no positive case (a case with positive: true whose refs include it)`);
59
+ }
60
+
61
+ const ids = new Set(cases.map((tc) => tc.id));
62
+ (Array.isArray(doc.ambiguities) ? doc.ambiguities : []).forEach((a, i) => {
63
+ if (!isText(a?.ref) || !isText(a?.issue)) errors.push(`ambiguity ${i + 1}: ref and issue are required`);
64
+ for (const id of a?.cases ?? []) if (!ids.has(id)) errors.push(`ambiguity ${i + 1}: unknown case ${id}`);
65
+ });
66
+ if (doc.labels !== undefined && (typeof doc.labels !== 'object' || Object.values(doc.labels).some((v) => !isText(v))))
67
+ errors.push('labels must map label names to text');
68
+ return { errors, warnings };
69
+ }