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,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
+ }
@@ -0,0 +1,157 @@
1
+ // Writes a single-sheet .xlsx workbook with Node's standard library only (no dependencies).
2
+ //
3
+ // writeXlsx(file, { sheet, columns: [{ header, width }], rows: [[cell, ...], ...] })
4
+ //
5
+ // Every cell is written as text, so nothing is ever read as a number, a date or a formula. The header row is bold,
6
+ // frozen and filterable; cells wrap and align to the top, and line breaks inside a cell are kept.
7
+
8
+ import fs from 'node:fs';
9
+ import zlib from 'node:zlib';
10
+
11
+ const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
12
+ const REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
13
+ const PKG_REL = 'http://schemas.openxmlformats.org/package/2006/relationships';
14
+ const XML_HEAD = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
15
+ const INVALID_XML = /[^\t\n\r -퟿-�\u{10000}-\u{10FFFF}]/gu;
16
+
17
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
18
+ let c = n;
19
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
20
+ return c >>> 0;
21
+ });
22
+
23
+ function crc32(buf) {
24
+ let c = 0xffffffff;
25
+ for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
26
+ return (c ^ 0xffffffff) >>> 0;
27
+ }
28
+
29
+ function escapeXml(text) {
30
+ return String(text)
31
+ .replace(INVALID_XML, '')
32
+ .replace(/&/g, '&amp;')
33
+ .replace(/</g, '&lt;')
34
+ .replace(/>/g, '&gt;')
35
+ .replace(/"/g, '&quot;');
36
+ }
37
+
38
+ function columnName(index) {
39
+ let name = '';
40
+ for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) name = String.fromCharCode(65 + ((n - 1) % 26)) + name;
41
+ return name;
42
+ }
43
+
44
+ // A ZIP archive of deflated entries, as an .xlsx package expects.
45
+ function zip(entries) {
46
+ const locals = [];
47
+ const centrals = [];
48
+ let offset = 0;
49
+ for (const [name, text] of entries) {
50
+ const nameBuf = Buffer.from(name, 'utf8');
51
+ const data = Buffer.from(text, 'utf8');
52
+ const packed = zlib.deflateRawSync(data);
53
+ const crc = crc32(data);
54
+ const local = Buffer.alloc(30);
55
+ local.writeUInt32LE(0x04034b50, 0);
56
+ local.writeUInt16LE(20, 4);
57
+ local.writeUInt16LE(8, 8);
58
+ local.writeUInt16LE(33, 12); // DOS date 1980-01-01
59
+ local.writeUInt32LE(crc, 14);
60
+ local.writeUInt32LE(packed.length, 18);
61
+ local.writeUInt32LE(data.length, 22);
62
+ local.writeUInt16LE(nameBuf.length, 26);
63
+ const central = Buffer.alloc(46);
64
+ central.writeUInt32LE(0x02014b50, 0);
65
+ central.writeUInt16LE(20, 4);
66
+ central.writeUInt16LE(20, 6);
67
+ central.writeUInt16LE(8, 10);
68
+ central.writeUInt16LE(33, 14);
69
+ central.writeUInt32LE(crc, 16);
70
+ central.writeUInt32LE(packed.length, 20);
71
+ central.writeUInt32LE(data.length, 24);
72
+ central.writeUInt16LE(nameBuf.length, 28);
73
+ central.writeUInt32LE(offset, 42);
74
+ locals.push(local, nameBuf, packed);
75
+ centrals.push(central, nameBuf);
76
+ offset += local.length + nameBuf.length + packed.length;
77
+ }
78
+ const directory = Buffer.concat(centrals);
79
+ const end = Buffer.alloc(22);
80
+ end.writeUInt32LE(0x06054b50, 0);
81
+ end.writeUInt16LE(entries.length, 8);
82
+ end.writeUInt16LE(entries.length, 10);
83
+ end.writeUInt32LE(directory.length, 12);
84
+ end.writeUInt32LE(offset, 16);
85
+ return Buffer.concat([...locals, directory, end]);
86
+ }
87
+
88
+ function sheetXml(columns, rows) {
89
+ const lastCell = `${columnName(columns.length - 1)}${rows.length + 1}`;
90
+ const row = (cells, r, style) =>
91
+ `<row r="${r}">` +
92
+ cells
93
+ .map((cell, c) => `<c r="${columnName(c)}${r}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${escapeXml(cell ?? '')}</t></is></c>`)
94
+ .join('') +
95
+ '</row>';
96
+ return (
97
+ XML_HEAD +
98
+ `<worksheet xmlns="${MAIN}"><dimension ref="A1:${lastCell}"/>` +
99
+ '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>' +
100
+ '<sheetFormatPr defaultRowHeight="15"/><cols>' +
101
+ columns.map((col, i) => `<col min="${i + 1}" max="${i + 1}" width="${col.width}" customWidth="1"/>`).join('') +
102
+ '</cols><sheetData>' +
103
+ row(columns.map((col) => col.header), 1, 2) +
104
+ rows.map((cells, i) => row(cells, i + 2, 1)).join('') +
105
+ `</sheetData><autoFilter ref="A1:${lastCell}"/></worksheet>`
106
+ );
107
+ }
108
+
109
+ const STYLES =
110
+ XML_HEAD +
111
+ `<styleSheet xmlns="${MAIN}">` +
112
+ '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>' +
113
+ '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>' +
114
+ '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>' +
115
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
116
+ '<cellXfs count="3"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' +
117
+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>' +
118
+ '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf></cellXfs>' +
119
+ '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>';
120
+
121
+ export function writeXlsx(file, { sheet, columns, rows }) {
122
+ const lastCell = `${columnName(columns.length - 1)}${rows.length + 1}`;
123
+ const quotedSheet = `'${sheet.replace(/'/g, "''")}'`;
124
+ const filterRange = `${quotedSheet}!$A$1:$${lastCell.replace(/(\d+)$/, '$$$1')}`;
125
+ const entries = [
126
+ [
127
+ '[Content_Types].xml',
128
+ XML_HEAD +
129
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
130
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
131
+ '<Default Extension="xml" ContentType="application/xml"/>' +
132
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
133
+ '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' +
134
+ '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>',
135
+ ],
136
+ [
137
+ '_rels/.rels',
138
+ XML_HEAD +
139
+ `<Relationships xmlns="${PKG_REL}"><Relationship Id="rId1" Type="${REL}/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
140
+ ],
141
+ [
142
+ 'xl/workbook.xml',
143
+ XML_HEAD +
144
+ `<workbook xmlns="${MAIN}" xmlns:r="${REL}"><sheets><sheet name="${escapeXml(sheet)}" sheetId="1" r:id="rId1"/></sheets>` +
145
+ `<definedNames><definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">${escapeXml(filterRange)}</definedName></definedNames></workbook>`,
146
+ ],
147
+ [
148
+ 'xl/_rels/workbook.xml.rels',
149
+ XML_HEAD +
150
+ `<Relationships xmlns="${PKG_REL}"><Relationship Id="rId1" Type="${REL}/worksheet" Target="worksheets/sheet1.xml"/>` +
151
+ `<Relationship Id="rId2" Type="${REL}/styles" Target="styles.xml"/></Relationships>`,
152
+ ],
153
+ ['xl/worksheets/sheet1.xml', sheetXml(columns, rows)],
154
+ ['xl/styles.xml', STYLES],
155
+ ];
156
+ fs.writeFileSync(file, zip(entries));
157
+ }