@orion-qa/orion 3.1.0 → 3.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 (113) hide show
  1. package/.claude/agents/automation-strategist.md +1 -0
  2. package/.claude/agents/change-agent.md +1 -0
  3. package/.claude/agents/codebase-analyst.md +2 -1
  4. package/.claude/agents/environment-discovery.md +1 -0
  5. package/.claude/agents/evidence-validator.md +1 -0
  6. package/.claude/agents/executor.md +1 -0
  7. package/.claude/agents/failure-analyst.md +2 -1
  8. package/.claude/agents/implementer.md +2 -1
  9. package/.claude/agents/requirement-analyst.md +1 -0
  10. package/.claude/agents/reviewer.md +1 -0
  11. package/.claude/agents/test-reporter.md +1 -0
  12. package/.claude/settings.json +17 -0
  13. package/.claude/skills/architecture-analysis/SKILL.md +1 -1
  14. package/.claude/skills/automation-implementation/SKILL.md +7 -5
  15. package/.claude/skills/automation-review/references/assertion-guard.md +1 -1
  16. package/.claude/skills/code-review/SKILL.md +2 -0
  17. package/.claude/skills/documentation/SKILL.md +1 -1
  18. package/.claude/skills/execution/SKILL.md +5 -4
  19. package/.claude/skills/orion/SKILL.md +12 -7
  20. package/.claude/skills/orion/references/assess-fix.md +5 -4
  21. package/.claude/skills/orion/references/batch.md +64 -0
  22. package/.claude/skills/orion/references/blockers.md +1 -1
  23. package/.claude/skills/orion/references/conversation.md +56 -25
  24. package/.claude/skills/orion/references/delivery-formats.md +23 -35
  25. package/.claude/skills/orion/references/doctor.md +1 -1
  26. package/.claude/skills/orion/references/greeting.md +23 -0
  27. package/.claude/skills/orion/references/hosts.md +3 -2
  28. package/.claude/skills/orion/references/modes.md +4 -2
  29. package/.claude/skills/orion/references/plain-language.md +57 -0
  30. package/.claude/skills/orion/references/project-context-files.md +2 -1
  31. package/.claude/skills/orion/references/recovery-loop.md +8 -0
  32. package/.claude/skills/orion/references/setup-card.md +18 -3
  33. package/.claude/skills/orion/references/status-lines.md +10 -4
  34. package/.claude/skills/orion/scripts/batch_detect.mjs +98 -0
  35. package/.claude/skills/orion/scripts/batch_state.mjs +179 -0
  36. package/.claude/skills/orion/scripts/browser_setup.mjs +12 -7
  37. package/.claude/skills/orion/scripts/cases_export.py +724 -0
  38. package/.claude/skills/orion/scripts/codemap.mjs +116 -0
  39. package/.claude/skills/orion/scripts/done_check.mjs +200 -0
  40. package/.claude/skills/orion/scripts/fix_plan.mjs +21 -0
  41. package/.claude/skills/orion/scripts/hooks/lean_guard.mjs +162 -0
  42. package/.claude/skills/orion/scripts/lib/table.mjs +116 -0
  43. package/.claude/skills/orion/scripts/quiet.mjs +160 -0
  44. package/.claude/skills/orion/scripts/report_check.mjs +6 -3
  45. package/.claude/skills/orion/scripts/report_make.mjs +186 -0
  46. package/.claude/skills/orion/scripts/results_parse.mjs +16 -3
  47. package/.claude/skills/orion/scripts/rules.mjs +92 -0
  48. package/.claude/skills/orion/scripts/run_state.mjs +67 -0
  49. package/.claude/skills/orion/scripts/suite_check.mjs +41 -2
  50. package/.claude/skills/orion/templates/project-context/assessment.md +2 -2
  51. package/.claude/skills/orion/templates/project-context/retry-policy.md +6 -0
  52. package/.claude/skills/orion/templates/project-context/test-design.md +6 -0
  53. package/.claude/skills/playwright/templates/dotnet/PageObjects/BasePage.cs +4 -0
  54. package/.claude/skills/playwright/templates/javascript/fixtures/index.js +4 -2
  55. package/.claude/skills/playwright/templates/javascript/fixtures/session.js +9 -6
  56. package/.claude/skills/playwright/templates/javascript/jsconfig.json +3 -2
  57. package/.claude/skills/playwright/templates/javascript/pageObjects/basePage.js +4 -0
  58. package/.claude/skills/playwright/templates/javascript/playwright.config.js +3 -0
  59. package/.claude/skills/playwright/templates/javascript/reporters/summaryReporter.js +15 -1
  60. package/.claude/skills/playwright/templates/javascript/src/config/env.js +29 -1
  61. package/.claude/skills/playwright/templates/project/fixtures/index.ts +4 -2
  62. package/.claude/skills/playwright/templates/project/fixtures/session.ts +7 -5
  63. package/.claude/skills/playwright/templates/project/pageObjects/basePage.ts +4 -0
  64. package/.claude/skills/playwright/templates/project/playwright.config.ts +3 -0
  65. package/.claude/skills/playwright/templates/project/reporters/summaryReporter.ts +15 -0
  66. package/.claude/skills/playwright/templates/project/src/config/env.ts +29 -1
  67. package/.claude/skills/playwright/templates/python/page_objects/base_page.py +3 -0
  68. package/.claude/skills/playwright/templates/python/src/config/env.py +34 -2
  69. package/.claude/skills/selenium/templates/csharp-nunit/PageObjects/BasePage.cs +4 -0
  70. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/pageObjects/BasePage.java +3 -0
  71. package/.claude/skills/selenium/templates/python-pytest/page_objects/base_page.py +3 -0
  72. package/.claude/skills/self-healing/SKILL.md +1 -1
  73. package/.claude/skills/test-reporting/references/tool-mapping.md +13 -9
  74. package/.claude/skills/ui-observation/SKILL.md +1 -0
  75. package/.claude-plugin/plugin.json +15 -2
  76. package/.codex/agents/automation-strategist.toml +1 -0
  77. package/.codex/agents/change-agent.toml +1 -0
  78. package/.codex/agents/codebase-analyst.toml +1 -0
  79. package/.codex/agents/environment-discovery.toml +1 -0
  80. package/.codex/agents/evidence-validator.toml +1 -0
  81. package/.codex/agents/executor.toml +1 -0
  82. package/.codex/agents/failure-analyst.toml +1 -0
  83. package/.codex/agents/implementer.toml +2 -1
  84. package/.codex/agents/requirement-analyst.toml +1 -0
  85. package/.codex/agents/reviewer.toml +1 -0
  86. package/.codex/agents/test-reporter.toml +1 -0
  87. package/.codex/hooks.json +15 -0
  88. package/.cursor/commands/orion.md +1 -1
  89. package/.cursor/hooks.json +10 -0
  90. package/.devin/hooks.v1.json +13 -0
  91. package/.gemini/agents/automation-strategist.md +1 -0
  92. package/.gemini/agents/change-agent.md +1 -0
  93. package/.gemini/agents/codebase-analyst.md +1 -0
  94. package/.gemini/agents/environment-discovery.md +1 -0
  95. package/.gemini/agents/evidence-validator.md +1 -0
  96. package/.gemini/agents/executor.md +1 -0
  97. package/.gemini/agents/failure-analyst.md +1 -0
  98. package/.gemini/agents/implementer.md +2 -1
  99. package/.gemini/agents/requirement-analyst.md +1 -0
  100. package/.gemini/agents/reviewer.md +1 -0
  101. package/.gemini/agents/test-reporter.md +1 -0
  102. package/.gemini/commands/orion.toml +2 -2
  103. package/.github/hooks/orion-lean.json +13 -0
  104. package/.github/prompts/orion.prompt.md +2 -2
  105. package/.windsurf/workflows/orion.md +2 -2
  106. package/AGENTS.md +7 -7
  107. package/README.md +55 -160
  108. package/assets/run-flow.svg +1 -1
  109. package/bin/orion.mjs +7 -7
  110. package/hosts/gemini-extension/gemini-extension.json +1 -1
  111. package/hosts/gemini-extension/hooks/hooks.json +16 -0
  112. package/hosts/gemini-extension/policies/platform.toml +5 -0
  113. package/package.json +5 -1
@@ -0,0 +1,724 @@
1
+ #!/usr/bin/env python3
2
+ """Export accepted test cases in the format the person asks for, all from the same accepted design.
3
+
4
+ Standard library only (nothing to install). In: one or more platform CSVs (one per story, or one with a Story column),
5
+ optionally the acceptance criteria. Out: one file in the asked format (Gherkin: one file per story).
6
+
7
+ Formats (--format, or taken from the --out extension):
8
+ xlsx Excel workbook: Summary (one row per story) · Test cases (grouped by story, header frozen, filters, priority
9
+ colours, Review drop-down Approve/Change/Drop + Reviewer Comment) · Traceability (AC → cases, covered yes/no) · About
10
+ csv the platform CSV (UTF-8 with BOM, CRLF), plus Story, Tracker Key, Review, Reviewer Comment; Excel and Sheets open it
11
+ md Markdown: a summary table, then each story with its cases in full (review in an editor, a wiki or a PR)
12
+ html one review page: summary, filter box, each case as a card with its steps; prints cleanly (and is the PDF's source)
13
+ pdf the html page printed by the installed Chrome or Edge (headless), else LibreOffice; exit 3 if neither is there
14
+ docx Word document: a heading per story and one table per case (Word, Google Docs, LibreOffice)
15
+ feature Gherkin, scenarios only (no step code), one file per story when there are several
16
+ json the cases as a list of objects (for scripts and other tools)
17
+ testrail · xray · zephyr · azure each tool's CSV import layout (delivery-formats.md; try one case first)
18
+
19
+ Usage:
20
+ python3 cases_export.py --out <file> [--format <fmt>] --label "<AI-generated line naming the approver>" [--ac <ac.csv>]
21
+ [--link "https://<site>.atlassian.net/browse/{key}"] [--titles "PR-1=Sign in,PR-2=…"] <cases.csv>...
22
+ cases.csv: Test Case ID, Title, Preconditions, Steps, Expected Result, Priority, Refs, Test Data, Type, Technique,
23
+ App check, Postconditions; optional Story, Story Title, Automated Test, Last Run, Tracker Key, Review,
24
+ Reviewer Comment. Story falls back to the first word of Refs, then the file name.
25
+ ac.csv: Story, AC, Criterion (the acceptance criteria's own text).
26
+ A reviewed file comes back with tm.py: xlsx-to-csv <file> --sheet "Test cases" (Excel); a csv is read as it is.
27
+ Exit 0 written · 2 bad input · 3 no PDF printer (deliver the html and say "print it to PDF").
28
+ """
29
+ import argparse
30
+ import csv
31
+ import datetime
32
+ import html
33
+ import io
34
+ import json
35
+ import os
36
+ import re
37
+ import shutil
38
+ import subprocess
39
+ import sys
40
+ import tempfile
41
+ import zipfile
42
+ from xml.sax.saxutils import escape
43
+
44
+ COLUMNS = [ # (header, width, source column names in the CSV)
45
+ ("Story", 11, ["Story"]),
46
+ ("AC", 9, []),
47
+ ("Test Case ID", 10, ["Test Case ID", "ID"]),
48
+ ("Title", 38, ["Title"]),
49
+ ("Type", 11, ["Type"]),
50
+ ("Priority", 10, ["Priority"]),
51
+ ("Preconditions", 30, ["Preconditions"]),
52
+ ("Steps", 48, ["Steps"]),
53
+ ("Expected Result", 40, ["Expected Result", "Expected"]),
54
+ ("Test Data", 24, ["Test Data"]),
55
+ ("Automated Test", 30, ["Automated Test"]),
56
+ ("Last Run", 16, ["Last Run"]),
57
+ ("Tracker Key", 12, ["Tracker Key"]),
58
+ ("Review", 11, ["Review"]),
59
+ ("Reviewer Comment", 34, ["Reviewer Comment"]),
60
+ ]
61
+ OPTIONAL = [("Postconditions", 26, ["Postconditions"]), ("Technique", 18, ["Technique"]), ("App check", 12, ["App check"])]
62
+ READER_HIDDEN = {"Technique", "App check"} # design-internal: kept in csv and json, left out of what people read
63
+ SHOW_IF_SET = {"Test Data", "Preconditions", "Automated Test", "Last Run", "Tracker Key"}
64
+ REVIEW = ["Approve", "Change", "Drop"]
65
+ TYPES = ["positive", "negative", "boundary", "edge"]
66
+ PRIORITIES = ["High", "Medium", "Low"]
67
+
68
+ # Style indexes (cellXfs order in styles())
69
+ S_BODY, S_HEADER, S_TITLE, S_BOLD, S_HIGH, S_MED, S_LOW, S_STORY, S_REVIEW, S_LINK, S_NOTE, S_YES, S_NO, S_NUM = range(14)
70
+
71
+
72
+ def styles():
73
+ """The workbook's styles part: fonts, fills, borders and the cell formats indexed by the S_* constants."""
74
+ fonts = ['<font><sz val="11"/><name val="Calibri"/></font>',
75
+ '<font><b/><sz val="11"/><color rgb="FFFFFFFF"/><name val="Calibri"/></font>',
76
+ '<font><b/><sz val="15"/><color rgb="FF1F3864"/><name val="Calibri"/></font>',
77
+ '<font><b/><sz val="11"/><name val="Calibri"/></font>',
78
+ '<font><u/><sz val="11"/><color rgb="FF0563C1"/><name val="Calibri"/></font>',
79
+ '<font><i/><sz val="10"/><color rgb="FF595959"/><name val="Calibri"/></font>']
80
+ def fill(rgb):
81
+ return f'<fill><patternFill patternType="solid"><fgColor rgb="FF{rgb}"/><bgColor indexed="64"/></patternFill></fill>'
82
+ fills = ['<fill><patternFill patternType="none"/></fill>', '<fill><patternFill patternType="gray125"/></fill>',
83
+ fill("1F3864"), fill("F8CBAD"), fill("FFE699"), fill("C6EFCE"), fill("DDEBF7"), fill("FFF2CC")]
84
+ side = '<{0} style="thin"><color rgb="FFBFBFBF"/></{0}>'
85
+ borders = ['<border><left/><right/><top/><bottom/><diagonal/></border>',
86
+ '<border>' + "".join(side.format(s) for s in ("left", "right", "top", "bottom")) + '<diagonal/></border>']
87
+ wrap = '<alignment wrapText="1" vertical="top"/>'
88
+ def xf(font=0, fill_=0, border=1, align=wrap):
89
+ return (f'<xf numFmtId="0" fontId="{font}" fillId="{fill_}" borderId="{border}" xfId="0" applyFont="1" '
90
+ f'applyFill="1" applyBorder="1" applyAlignment="1">{align}</xf>')
91
+ xfs = [xf(), xf(1, 2, 1, '<alignment wrapText="1" vertical="center"/>'), xf(2, 0, 0, '<alignment vertical="center"/>'),
92
+ xf(3, 0, 0, '<alignment vertical="top"/>'), xf(3, 3), xf(3, 4), xf(3, 5), xf(3, 6), xf(0, 7), xf(4, 0, 1),
93
+ xf(5, 0, 0, '<alignment wrapText="1" vertical="top"/>'), xf(3, 5), xf(3, 3),
94
+ xf(0, 0, 1, '<alignment horizontal="center" vertical="top"/>')]
95
+ return ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
96
+ '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
97
+ f'<fonts count="{len(fonts)}">{"".join(fonts)}</fonts><fills count="{len(fills)}">{"".join(fills)}</fills>'
98
+ f'<borders count="{len(borders)}">{"".join(borders)}</borders>'
99
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
100
+ f'<cellXfs count="{len(xfs)}">{"".join(xfs)}</cellXfs>'
101
+ '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>')
102
+
103
+
104
+ def plural(n, one, many=None):
105
+ """1 case, 2 cases."""
106
+ return f"{n} {one if n == 1 else (many or one + 's')}"
107
+
108
+
109
+ def col_letter(i):
110
+ """1 → A, 27 → AA."""
111
+ s = ""
112
+ while i:
113
+ i, r = divmod(i - 1, 26)
114
+ s = chr(65 + r) + s
115
+ return s
116
+
117
+
118
+ CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
119
+
120
+
121
+ def cell(ref, value, style=S_BODY):
122
+ """One cell: a number, a HYPERLINK formula (value given as ("link", url, text)), or inline text."""
123
+ if isinstance(value, tuple) and value[0] == "link":
124
+ _, url, text = value
125
+ f = 'HYPERLINK("{}","{}")'.format(url.replace('"', '""'), text.replace('"', '""'))
126
+ return f'<c r="{ref}" s="{S_LINK}" t="str"><f>{escape(f)}</f><v>{escape(text)}</v></c>'
127
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
128
+ return f'<c r="{ref}" s="{style}"><v>{value}</v></c>'
129
+ text = CONTROL.sub("", str(value if value is not None else ""))
130
+ if text == "":
131
+ return f'<c r="{ref}" s="{style}"/>'
132
+ return f'<c r="{ref}" s="{style}" t="inlineStr"><is><t xml:space="preserve">{escape(text)}</t></is></c>'
133
+
134
+
135
+ def sheet(rows, widths, freeze=None, autofilter=None, merges=(), validations=(), heights=None):
136
+ """A worksheet part. rows: list of lists of (value, style); freeze: (cols, rows) frozen; validations: (range, list)."""
137
+ out = ['<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
138
+ '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
139
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
140
+ '<sheetPr><pageSetUpPr fitToPage="1"/></sheetPr>']
141
+ if freeze:
142
+ xs, ys = freeze
143
+ tl = f"{col_letter(xs + 1)}{ys + 1}"
144
+ attrs = (f' xSplit="{xs}"' if xs else "") + (f' ySplit="{ys}"' if ys else "")
145
+ pane = "bottomRight" if xs and ys else ("bottomLeft" if ys else "topRight")
146
+ out.append(f'<sheetViews><sheetView workbookViewId="0"><pane{attrs} topLeftCell="{tl}" activePane="{pane}" '
147
+ f'state="frozen"/><selection pane="{pane}" activeCell="{tl}" sqref="{tl}"/></sheetView></sheetViews>')
148
+ else:
149
+ out.append('<sheetViews><sheetView workbookViewId="0"/></sheetViews>')
150
+ out.append('<sheetFormatPr defaultRowHeight="15"/><cols>')
151
+ out += [f'<col min="{i}" max="{i}" width="{w}" customWidth="1"/>' for i, w in enumerate(widths, 1)]
152
+ out.append('</cols><sheetData>')
153
+ for r, row in enumerate(rows, 1):
154
+ h = (heights or {}).get(r)
155
+ out.append(f'<row r="{r}"' + (f' ht="{h}" customHeight="1"' if h else "") + '>')
156
+ out += [cell(f"{col_letter(c)}{r}", v, s) for c, (v, s) in enumerate(row, 1)]
157
+ out.append('</row>')
158
+ out.append('</sheetData>')
159
+ if autofilter:
160
+ out.append(f'<autoFilter ref="{autofilter}"/>')
161
+ if merges:
162
+ out.append(f'<mergeCells count="{len(merges)}">' + "".join(f'<mergeCell ref="{m}"/>' for m in merges) + '</mergeCells>')
163
+ if validations:
164
+ out.append(f'<dataValidations count="{len(validations)}">')
165
+ for rng, items in validations:
166
+ out.append(f'<dataValidation type="list" allowBlank="1" showErrorMessage="1" sqref="{rng}">'
167
+ f'<formula1>"{escape(",".join(items))}"</formula1></dataValidation>')
168
+ out.append('</dataValidations>')
169
+ out.append('<pageMargins left="0.5" right="0.5" top="0.6" bottom="0.6" header="0.3" footer="0.3"/>'
170
+ '<pageSetup orientation="landscape" fitToWidth="1" fitToHeight="0"/></worksheet>')
171
+ return "".join(out)
172
+
173
+
174
+ def pick(row, names):
175
+ """The first non-empty value among the given column names (case-insensitive)."""
176
+ low = {k.strip().lower(): v for k, v in row.items() if k}
177
+ for n in names:
178
+ v = low.get(n.lower())
179
+ if v not in (None, ""):
180
+ return v.strip()
181
+ return ""
182
+
183
+
184
+ def norm_priority(p):
185
+ """high / P1 / 1 → High, and so on; anything else is kept as written."""
186
+ t = p.strip().lower()
187
+ return {"high": "High", "p1": "High", "1": "High", "critical": "High", "medium": "Medium", "p2": "Medium",
188
+ "2": "Medium", "low": "Low", "p3": "Low", "3": "Low"}.get(t, p.strip())
189
+
190
+
191
+ def ac_ids(refs):
192
+ """AC-1, AC-2 from a Refs cell such as "PR-1 AC-1 AC-3"."""
193
+ return re.findall(r"\bAC-\d+\b", refs or "", re.I)
194
+
195
+
196
+ def tc_sort(case_id):
197
+ """TS-2 before TS-10."""
198
+ m = re.search(r"(\d+)$", case_id or "")
199
+ return (re.sub(r"\d+$", "", case_id or ""), int(m.group(1)) if m else 0)
200
+
201
+
202
+ def load(paths):
203
+ """Read the case CSVs into dicts, each with its story."""
204
+ cases = []
205
+ for p in paths:
206
+ with open(p, encoding="utf-8-sig", newline="") as f:
207
+ for row in csv.DictReader(f):
208
+ row = {k: (v[1:] if isinstance(v, str) and v.startswith("'") and FORMULA.match(v[1:]) else v) for k, v in row.items()}
209
+ if not any((v or "").strip() for v in row.values()):
210
+ continue
211
+ refs = pick(row, ["Refs", "Requirement"])
212
+ story = pick(row, ["Story"]) or (refs.split()[0] if refs and not refs.upper().startswith("AC-") else "") \
213
+ or re.sub(r"-test-cases$", "", os.path.splitext(os.path.basename(p))[0])
214
+ case = {h: pick(row, src) for h, _, src in COLUMNS + OPTIONAL if src}
215
+ case["Story"] = story
216
+ case["AC"] = ", ".join(ac_ids(refs)) or pick(row, ["AC"])
217
+ case["Priority"] = norm_priority(case["Priority"])
218
+ case["Story Title"] = pick(row, ["Story Title"])
219
+ cases.append(case)
220
+ return cases
221
+
222
+
223
+ def build(cases, label, ac_rows, link, titles):
224
+ """The workbook parts: name → XML text."""
225
+ stories = sorted({c["Story"] for c in cases}, key=tc_sort)
226
+ for c in cases:
227
+ titles.setdefault(c["Story"], c["Story Title"])
228
+ cases.sort(key=lambda c: (stories.index(c["Story"]), tc_sort(c["Test Case ID"])))
229
+ extra = [o for o in OPTIONAL if o[0] not in READER_HIDDEN and any(c.get(o[0]) for c in cases)]
230
+ cols = [x for x in COLUMNS[:10] + extra + COLUMNS[10:] if x[0] not in SHOW_IF_SET or any(c.get(x[0]) for c in cases)]
231
+ story_cell = (lambda k: ("link", link.replace("{key}", k), k)) if link else (lambda k: k)
232
+
233
+ # Test cases
234
+ rows = [[(h, S_HEADER) for h, _, _ in cols]]
235
+ pstyle = {"High": S_HIGH, "Medium": S_MED, "Low": S_LOW}
236
+ for c in cases:
237
+ r = []
238
+ for h, _, _ in cols:
239
+ v = c.get(h, "")
240
+ if h == "Story":
241
+ r.append((story_cell(v) if v else "", S_STORY))
242
+ elif h == "Priority":
243
+ r.append((v, pstyle.get(v, S_BODY)))
244
+ elif h in ("Review", "Reviewer Comment"):
245
+ r.append((v, S_REVIEW))
246
+ elif h == "Tracker Key" and v and link and re.match(r"^[A-Z][A-Z0-9]+-\d+$", v):
247
+ r.append((("link", link.replace("{key}", v), v), S_LINK))
248
+ else:
249
+ r.append((v, S_BODY))
250
+ rows.append(r)
251
+ last = f"{col_letter(len(cols))}{len(rows)}"
252
+ idx = {h: i + 1 for i, (h, _, _) in enumerate(cols)}
253
+ n = max(len(rows), 2)
254
+ val = [(f"{col_letter(idx['Review'])}2:{col_letter(idx['Review'])}{n + 200}", REVIEW),
255
+ (f"{col_letter(idx['Priority'])}2:{col_letter(idx['Priority'])}{n + 200}", PRIORITIES),
256
+ (f"{col_letter(idx['Type'])}2:{col_letter(idx['Type'])}{n + 200}", TYPES)]
257
+ ws_cases = sheet(rows, [w for _, w, _ in cols], freeze=(3, 1), autofilter=f"A1:{last}", validations=val,
258
+ heights={1: 30})
259
+
260
+ # Traceability
261
+ acs = {}
262
+ for a in ac_rows:
263
+ acs.setdefault((a["Story"], a["AC"]), a.get("Criterion", ""))
264
+ for c in cases:
265
+ for a in ac_ids(c["AC"]):
266
+ acs.setdefault((c["Story"], a.upper()), "")
267
+ tr = [[("Story", S_HEADER), ("AC", S_HEADER), ("Acceptance criterion", S_HEADER), ("Test cases", S_HEADER),
268
+ ("Covered", S_HEADER)]]
269
+ for (s, a) in sorted(acs, key=lambda k: (stories.index(k[0]) if k[0] in stories else 999, tc_sort(k[1]))):
270
+ ids = [c["Test Case ID"] for c in cases if c["Story"] == s and a.upper() in [x.upper() for x in ac_ids(c["AC"])]]
271
+ tr.append([(story_cell(s), S_STORY), (a, S_BODY), (acs[(s, a)], S_BODY), (", ".join(ids), S_BODY),
272
+ ("Yes" if ids else "No", S_YES if ids else S_NO)])
273
+ no_ac = [c["Test Case ID"] for c in cases if not c["AC"]]
274
+ if no_ac:
275
+ tr.append([("", S_BODY), ("—", S_BODY), ("not linked to an acceptance criterion", S_BODY), (", ".join(no_ac), S_BODY), ("", S_BODY)])
276
+ ws_trace = sheet(tr, [11, 9, 60, 30, 10], freeze=(0, 1), autofilter=f"A1:E{len(tr)}", heights={1: 24})
277
+
278
+ # Summary
279
+ today = datetime.date.today().isoformat()
280
+ sm = [[(f"Test cases · {', '.join(stories)}", S_TITLE)], [(f"{plural(len(cases), 'test case')} for {plural(len(stories), 'story', 'stories')} · {today}", S_NOTE)],
281
+ [(label, S_NOTE)], [("", S_NOTE)]]
282
+ head = ["Story", "Title", "Cases", "High", "Medium", "Low", "Positive", "Negative", "Boundary / edge", "Automated",
283
+ "Last run", "Approved", "To change", "To drop", "Not reviewed"]
284
+ sm.append([(h, S_HEADER) for h in head])
285
+ for s in stories:
286
+ cs = [c for c in cases if c["Story"] == s]
287
+ def cnt(f):
288
+ return sum(1 for c in cs if f(c))
289
+ runs = sorted({c["Last Run"] for c in cs if c["Last Run"]})
290
+ sm.append([(story_cell(s), S_STORY), (titles.get(s, ""), S_BODY), (len(cs), S_NUM),
291
+ (cnt(lambda c: c["Priority"] == "High"), S_NUM), (cnt(lambda c: c["Priority"] == "Medium"), S_NUM),
292
+ (cnt(lambda c: c["Priority"] == "Low"), S_NUM),
293
+ (cnt(lambda c: c["Type"].lower() == "positive"), S_NUM), (cnt(lambda c: c["Type"].lower() == "negative"), S_NUM),
294
+ (cnt(lambda c: c["Type"].lower() in ("boundary", "edge")), S_NUM), (cnt(lambda c: c["Automated Test"]), S_NUM),
295
+ ("; ".join(runs), S_BODY), (cnt(lambda c: c["Review"].lower() == "approve"), S_NUM),
296
+ (cnt(lambda c: c["Review"].lower() == "change"), S_NUM), (cnt(lambda c: c["Review"].lower() == "drop"), S_NUM),
297
+ (cnt(lambda c: not c["Review"]), S_NUM)])
298
+ sm += [[("", S_NOTE)], [("How to review", S_BOLD)],
299
+ [("1. Open the Test cases sheet. Filter by Story, Priority or Type with the arrows in the header.", S_NOTE)],
300
+ [("2. For each case pick Approve, Change or Drop in the yellow Review column; say what to change in Reviewer Comment.", S_NOTE)],
301
+ [("3. Save and send the file back (or say \"reviewed\" if it stayed in the workspace): changes are shown before anything is written.", S_NOTE)],
302
+ [("Nothing in this file is sent to Jira or another tool until you approve that write in the chat.", S_NOTE)]]
303
+ ws_sum = sheet(sm, [12, 40, 8, 8, 9, 8, 9, 10, 10, 11, 18, 10, 10, 9, 12], merges=["A1:H1", "A2:O2", "A3:O3"] +
304
+ [f"A{i}:O{i}" for i in range(len(sm) - 4, len(sm) + 1)], heights={1: 26})
305
+
306
+ # About
307
+ ab = [[("About this workbook", S_TITLE)], [(label, S_BODY)],
308
+ [(f"Generated {today} from the accepted test design. Test data is synthetic; no secrets or personal data.", S_BODY)],
309
+ [("Read it back after a review: python3 .claude/skills/requirement-analysis/scripts/tm.py xlsx-to-csv <file> --sheet \"Test cases\"", S_BODY)]]
310
+ ws_about = sheet(ab, [120])
311
+
312
+ names = ["Summary", "Test cases", "Traceability", "About"]
313
+ parts = {f"xl/worksheets/sheet{i}.xml": x for i, x in enumerate([ws_sum, ws_cases, ws_trace, ws_about], 1)}
314
+ defined = (f'<definedNames><definedName name="_xlnm._FilterDatabase" localSheetId="1" hidden="1">\'Test cases\'!$A$1:'
315
+ f'${col_letter(len(cols))}${len(rows)}</definedName><definedName name="_xlnm._FilterDatabase" localSheetId="2" '
316
+ f'hidden="1">Traceability!$A$1:$E${len(tr)}</definedName></definedNames>')
317
+ parts["xl/workbook.xml"] = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
318
+ '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
319
+ 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
320
+ '<bookViews><workbookView activeTab="0"/></bookViews><sheets>' +
321
+ "".join(f'<sheet name="{n}" sheetId="{i}" r:id="rId{i}"/>' for i, n in enumerate(names, 1)) +
322
+ '</sheets>' + defined + '<calcPr calcId="191029" fullCalcOnLoad="1"/></workbook>')
323
+ parts["xl/_rels/workbook.xml.rels"] = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
324
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
325
+ "".join(f'<Relationship Id="rId{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{i}.xml"/>' for i in range(1, 5)) +
326
+ '<Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')
327
+ parts["xl/styles.xml"] = styles()
328
+ parts["_rels/.rels"] = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
329
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
330
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
331
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/></Relationships>')
332
+ parts["docProps/core.xml"] = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
333
+ '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" '
334
+ 'xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" '
335
+ 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
336
+ f'<dc:title>Test cases {escape(", ".join(stories))}</dc:title><dc:creator>AI test-automation agents</dc:creator>'
337
+ f'<dc:description>{escape(label)}</dc:description></cp:coreProperties>')
338
+ parts["[Content_Types].xml"] = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
339
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
340
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
341
+ '<Default Extension="xml" ContentType="application/xml"/>'
342
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
343
+ "".join(f'<Override PartName="/xl/worksheets/sheet{i}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' for i in range(1, 5)) +
344
+ '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
345
+ '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>')
346
+ return parts, len(cases), stories
347
+
348
+
349
+ def steps_of(text):
350
+ """Numbered or line-separated steps → a list of step texts."""
351
+ lines = [l.strip() for l in (text or "").replace("\r", "").split("\n") if l.strip()]
352
+ if len(lines) == 1:
353
+ parts = re.split(r"\s*(?:^|\s)\d+[.)]\s+", " " + lines[0])
354
+ lines = [x.strip() for x in parts if x.strip()] or lines
355
+ return [re.sub(r"^\d+[.)]\s*", "", l) for l in lines]
356
+
357
+
358
+ def lines_of(text):
359
+ """Preconditions or data → separate lines (split on line breaks or ';')."""
360
+ return [x.strip() for x in re.split(r"[\n;]", text or "") if x.strip()]
361
+
362
+
363
+ def ordered(cases):
364
+ """Stories in key order, cases in ID order within each."""
365
+ stories = sorted({c["Story"] for c in cases}, key=tc_sort)
366
+ cases.sort(key=lambda c: (stories.index(c["Story"]), tc_sort(c["Test Case ID"])))
367
+ return stories
368
+
369
+
370
+ def write_xlsx(out, cases, label, ac_rows, link, titles):
371
+ parts, n, stories = build(cases, label, ac_rows, link, titles)
372
+ with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
373
+ for name in ["[Content_Types].xml", "_rels/.rels", "docProps/core.xml", "xl/workbook.xml", "xl/_rels/workbook.xml.rels",
374
+ "xl/styles.xml"] + [f"xl/worksheets/sheet{i}.xml" for i in range(1, 5)]:
375
+ z.writestr(name, parts[name])
376
+ return [out], "sheets Summary · Test cases · Traceability · About"
377
+
378
+
379
+ FORMULA = re.compile(r"^(?:[=@\t\r]|[+-](?!\s|$))")
380
+
381
+
382
+ def safe_cell(value):
383
+ """A cell a spreadsheet reads as text, never as a formula: case text can come from a story or a tracker (untrusted),
384
+ and `=HYPERLINK(…)` or `+cmd|…` would run when the file is opened. A leading ' is the spreadsheet's own "this is
385
+ text" mark; the importer here drops it again on the way back (load)."""
386
+ s = "" if value is None else str(value)
387
+ return "'" + s if FORMULA.match(s) else s
388
+
389
+
390
+ def csv_text(header, rows):
391
+ """CSV the way Excel and the importers read it: UTF-8 with BOM, CRLF, quoted where needed, no live formulas."""
392
+ buf = io.StringIO()
393
+ w = csv.writer(buf, lineterminator="\r\n")
394
+ w.writerow(header)
395
+ w.writerows([[safe_cell(v) for v in r] for r in rows])
396
+ return "\ufeff" + buf.getvalue()
397
+
398
+
399
+ PLATFORM = ["Test Case ID", "Title", "Preconditions", "Steps", "Expected Result", "Priority", "Refs", "Test Data", "Type",
400
+ "Technique", "App check", "Postconditions", "Story", "Automated Test", "Last Run", "Tracker Key", "Review",
401
+ "Reviewer Comment"]
402
+
403
+
404
+ def refs(c):
405
+ return " ".join([c["Story"]] + [a.strip() for a in c["AC"].split(",") if a.strip()])
406
+
407
+
408
+ def write_csv(out, cases, *_):
409
+ ordered(cases)
410
+ rows = [[refs(c) if h == "Refs" else c.get(h, "") for h in PLATFORM] for c in cases]
411
+ open(out, "w", encoding="utf-8", newline="").write(csv_text(PLATFORM, rows))
412
+ return [out], "platform CSV (the importer reads it back unchanged)"
413
+
414
+
415
+ def md_cell(t):
416
+ return (t or "").replace("|", "\\|").replace("\n", "<br>")
417
+
418
+
419
+ def write_md(out, cases, label, ac_rows, link, titles):
420
+ stories = ordered(cases)
421
+ o = [f"_{label}_", "", f"# Test cases: {', '.join(stories)}", "",
422
+ "| Story | Title | Cases | High | Medium | Low | Automated |", "|---|---|---|---|---|---|---|"]
423
+ for s in stories:
424
+ cs = [c for c in cases if c["Story"] == s]
425
+ key = f"[{s}]({link.replace('{key}', s)})" if link else s
426
+ o.append(f"| {key} | {md_cell(titles.get(s) or cs[0]['Story Title'])} | {len(cs)} | "
427
+ + " | ".join(str(sum(c["Priority"] == p for c in cs)) for p in PRIORITIES)
428
+ + f" | {sum(bool(c['Automated Test']) for c in cs)} |")
429
+ acs = {(a["Story"], a["AC"]): a["Criterion"] for a in ac_rows}
430
+ for s in stories:
431
+ cs = [c for c in cases if c["Story"] == s]
432
+ o += ["", f"## {s}" + (f": {titles.get(s) or cs[0]['Story Title']}" if (titles.get(s) or cs[0]["Story Title"]) else ""), "",
433
+ "| ID | What it checks | Type | Priority | AC | Expected result |", "|---|---|---|---|---|---|"]
434
+ o += [f"| {c['Test Case ID']} | {md_cell(c['Title'])} | {c['Type']} | {c['Priority']} | {c['AC']} | {md_cell(c['Expected Result'])} |" for c in cs]
435
+ for c in cs:
436
+ o += ["", f"### {c['Test Case ID']} · {c['Title']}",
437
+ f"**Type** {c['Type'] or '—'} · **Priority** {c['Priority'] or '—'} · **Covers** "
438
+ + (", ".join(f"{a}" + (f" ({acs[(s, a)]})" if acs.get((s, a)) else "") for a in ac_ids(c["AC"])) or "—")]
439
+ if c["Preconditions"]:
440
+ o += ["", "**Preconditions**"] + [f"- {x}" for x in lines_of(c["Preconditions"])]
441
+ o += ["", "**Steps**"] + [f"{i}. {x}" for i, x in enumerate(steps_of(c["Steps"]), 1)]
442
+ o += ["", f"**Expected** {c['Expected Result']}"]
443
+ for h in ("Test Data", "Postconditions", "Automated Test", "Last Run", "Tracker Key", "Review", "Reviewer Comment"):
444
+ if c.get(h):
445
+ o.append(f"**{h}** {c[h]} ")
446
+ open(out, "w", encoding="utf-8").write("\n".join(o) + "\n")
447
+ return [out], f"{len(stories)} stor{'y' if len(stories) == 1 else 'ies'}, summary then each case in full"
448
+
449
+
450
+ CSS = """
451
+ :root{--ink:#1d2433;--muted:#5b6475;--line:#d9dee7;--bg:#fff;--card:#f7f9fc;--head:#1f3864;--hi:#f8cbad;--me:#ffe699;--lo:#c6efce}
452
+ @media (prefers-color-scheme:dark){:root{--ink:#e6e9ef;--muted:#a3abba;--line:#394152;--bg:#151a23;--card:#1d2330;--head:#9fb7e8;--hi:#6b3a2a;--me:#6b5a1f;--lo:#2c5a37}}
453
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
454
+ main{max-width:1100px;margin:auto;padding:24px 16px 64px}h1{font-size:26px;margin:0 0 4px;color:var(--head)}h2{margin:36px 0 8px;color:var(--head)}
455
+ .label{color:var(--muted);font-style:italic;font-size:13px}table{border-collapse:collapse;width:100%;margin:10px 0}
456
+ th,td{border:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top}th{background:var(--card)}
457
+ .p-High{background:var(--hi)}.p-Medium{background:var(--me)}.p-Low{background:var(--lo)}
458
+ .case{border:1px solid var(--line);border-radius:8px;background:var(--card);margin:12px 0;padding:12px 16px;break-inside:avoid}
459
+ .case h3{margin:0 0 6px;font-size:16px}.meta span{display:inline-block;margin-right:10px;padding:1px 8px;border-radius:10px;font-size:12px;border:1px solid var(--line)}
460
+ .case ol{margin:4px 0 8px 20px;padding:0}.k{font-weight:600}#q{width:100%;padding:8px 10px;font-size:15px;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--ink)}
461
+ a{color:inherit}@media print{#q{display:none}.case{background:none}body{font-size:12px}}
462
+ """
463
+
464
+
465
+ def write_html(out, cases, label, ac_rows, link, titles):
466
+ stories = ordered(cases)
467
+ e = html.escape
468
+ acs = {(a["Story"], a["AC"]): a["Criterion"] for a in ac_rows}
469
+ def key(s):
470
+ return f'<a href="{e(link.replace("{key}", s))}">{e(s)}</a>' if link else e(s)
471
+ o = [f"<!doctype html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'>"
472
+ f"<title>Test cases {e(', '.join(stories))}</title><style>{CSS}</style></head><body><main>",
473
+ f"<h1>Test cases: {e(', '.join(stories))}</h1><p class='label'>{e(label)}</p>",
474
+ "<table><tr><th>Story</th><th>Title</th><th>Cases</th><th>High</th><th>Medium</th><th>Low</th><th>Automated</th></tr>"]
475
+ for s in stories:
476
+ cs = [c for c in cases if c["Story"] == s]
477
+ o.append(f"<tr><td>{key(s)}</td><td>{e(titles.get(s) or cs[0]['Story Title'])}</td><td>{len(cs)}</td>"
478
+ + "".join(f"<td>{sum(c['Priority'] == p for c in cs)}</td>" for p in PRIORITIES)
479
+ + f"<td>{sum(bool(c['Automated Test']) for c in cs)}</td></tr>")
480
+ o.append("</table><input id='q' placeholder='Filter: an ID, a word, High, negative…' oninput=\"for(const c of document.querySelectorAll('.case'))c.style.display=c.textContent.toLowerCase().includes(this.value.toLowerCase())?'':'none'\">")
481
+ for s in stories:
482
+ cs = [c for c in cases if c["Story"] == s]
483
+ t = titles.get(s) or cs[0]["Story Title"]
484
+ o.append(f"<h2>{key(s)}{(': ' + e(t)) if t else ''}</h2>")
485
+ for c in cs:
486
+ cov = ", ".join(e(a) + (f" ({e(acs[(s, a)])})" if acs.get((s, a)) else "") for a in ac_ids(c["AC"])) or "—"
487
+ o.append(f"<section class='case'><h3>{e(c['Test Case ID'])} · {e(c['Title'])}</h3><div class='meta'>"
488
+ f"<span class='p-{e(c['Priority'])}'>{e(c['Priority'] or '—')}</span><span>{e(c['Type'] or '—')}</span><span>covers {cov}</span></div>")
489
+ if c["Preconditions"]:
490
+ o.append("<p><span class='k'>Preconditions</span> " + e("; ".join(lines_of(c["Preconditions"]))) + "</p>")
491
+ o.append("<ol>" + "".join(f"<li>{e(x)}</li>" for x in steps_of(c["Steps"])) + "</ol>")
492
+ o.append(f"<p><span class='k'>Expected</span> {e(c['Expected Result'])}</p>")
493
+ extra = [(h, c.get(h)) for h in ("Test Data", "Postconditions", "Automated Test", "Last Run", "Tracker Key", "Review", "Reviewer Comment") if c.get(h)]
494
+ if extra:
495
+ o.append("<p>" + " · ".join(f"<span class='k'>{e(h)}</span> {e(v)}" for h, v in extra) + "</p>")
496
+ o.append("</section>")
497
+ o.append("</main></body></html>")
498
+ open(out, "w", encoding="utf-8").write("\n".join(o))
499
+ return [out], "one page: summary, filter box, a card per case"
500
+
501
+
502
+ def write_pdf(out, cases, label, ac_rows, link, titles):
503
+ tmp = tempfile.mkdtemp()
504
+ src = os.path.join(tmp, "cases.html")
505
+ write_html(src, cases, label, ac_rows, link, titles)
506
+ for b in ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "msedge", "microsoft-edge",
507
+ r"C:\Program Files\Google\Chrome\Application\chrome.exe", r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
508
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"):
509
+ exe = shutil.which(b) or (b if os.path.isfile(b) else None)
510
+ if exe:
511
+ r = subprocess.run([exe, "--headless", "--no-sandbox", "--disable-gpu", "--no-pdf-header-footer",
512
+ f"--print-to-pdf={os.path.abspath(out)}", "file://" + src], capture_output=True, timeout=120)
513
+ if r.returncode == 0 and os.path.isfile(out):
514
+ return [out], f"printed by {os.path.basename(exe)}"
515
+ office = shutil.which("soffice") or shutil.which("libreoffice")
516
+ if office:
517
+ subprocess.run([office, "--headless", "--convert-to", "pdf", "--outdir", tmp, src], capture_output=True, timeout=180)
518
+ if os.path.isfile(os.path.join(tmp, "cases.pdf")):
519
+ shutil.move(os.path.join(tmp, "cases.pdf"), out)
520
+ return [out], "printed by LibreOffice"
521
+ raise SystemExit(3)
522
+
523
+
524
+ def docx_par(text, style=None, bold=False):
525
+ rpr = "<w:rPr><w:b/></w:rPr>" if bold else ""
526
+ ppr = f'<w:pPr><w:pStyle w:val="{style}"/></w:pPr>' if style else ""
527
+ runs = []
528
+ for i, line in enumerate((text or "").split("\n")):
529
+ if i:
530
+ runs.append("<w:r><w:br/></w:r>")
531
+ runs.append(f'<w:r>{rpr}<w:t xml:space="preserve">{escape(CONTROL.sub("", line))}</w:t></w:r>')
532
+ return f"<w:p>{ppr}{''.join(runs)}</w:p>"
533
+
534
+
535
+ def docx_table(rows):
536
+ b = "".join(f'<w:{s} w:val="single" w:sz="4" w:color="BFBFBF"/>' for s in ("top", "left", "bottom", "right", "insideH", "insideV"))
537
+ o = [f'<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="pct"/><w:tblBorders>{b}</w:tblBorders></w:tblPr><w:tblGrid><w:gridCol w:w="2200"/><w:gridCol w:w="7400"/></w:tblGrid>']
538
+ for k, v in rows:
539
+ o.append(f'<w:tr><w:tc><w:tcPr><w:tcW w:w="2200" w:type="dxa"/><w:shd w:val="clear" w:color="auto" w:fill="DDEBF7"/></w:tcPr>{docx_par(k, bold=True)}</w:tc>'
540
+ f'<w:tc><w:tcPr><w:tcW w:w="7400" w:type="dxa"/></w:tcPr>{docx_par(v)}</w:tc></w:tr>')
541
+ return "".join(o) + "</w:tbl>"
542
+
543
+
544
+ def write_docx(out, cases, label, ac_rows, link, titles):
545
+ stories = ordered(cases)
546
+ acs = {(a["Story"], a["AC"]): a["Criterion"] for a in ac_rows}
547
+ body = [docx_par(f"Test cases: {', '.join(stories)}", "Title"), docx_par(label)]
548
+ for s in stories:
549
+ cs = [c for c in cases if c["Story"] == s]
550
+ t = titles.get(s) or cs[0]["Story Title"]
551
+ body.append(docx_par(f"{s}{': ' + t if t else ''} ({plural(len(cs), 'case')})", "Heading1"))
552
+ if link:
553
+ body.append(docx_par(link.replace("{key}", s)))
554
+ for c in cs:
555
+ body.append(docx_par(f"{c['Test Case ID']} · {c['Title']}", "Heading2"))
556
+ rows = [("Priority · Type", f"{c['Priority'] or '—'} · {c['Type'] or '—'}"),
557
+ ("Covers", ", ".join(a + (f" ({acs[(s, a)]})" if acs.get((s, a)) else "") for a in ac_ids(c["AC"])) or "—")]
558
+ if c["Preconditions"]:
559
+ rows.append(("Preconditions", "\n".join(lines_of(c["Preconditions"]))))
560
+ rows += [("Steps", "\n".join(f"{i}. {x}" for i, x in enumerate(steps_of(c["Steps"]), 1))), ("Expected", c["Expected Result"])]
561
+ rows += [(h, c[h]) for h in ("Test Data", "Postconditions", "Automated Test", "Last Run", "Tracker Key", "Review", "Reviewer Comment") if c.get(h)]
562
+ body.append(docx_table(rows))
563
+ body.append(docx_par(""))
564
+ W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
565
+ doc = (f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document {W}><w:body>{"".join(body)}'
566
+ '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1000" w:right="1000" w:bottom="1000" w:left="1000" w:header="500" w:footer="500" w:gutter="0"/></w:sectPr></w:body></w:document>')
567
+ def st(i, name, size, color, extra=""):
568
+ return (f'<w:style w:type="paragraph" w:styleId="{i}"><w:name w:val="{name}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/>'
569
+ f'<w:pPr><w:spacing w:before="240" w:after="80"/>{extra}</w:pPr><w:rPr><w:b/><w:color w:val="{color}"/><w:sz w:val="{size}"/></w:rPr></w:style>')
570
+ styles_xml = (f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles {W}>'
571
+ '<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:cs="Calibri"/><w:sz w:val="21"/></w:rPr></w:rPrDefault>'
572
+ '<w:pPrDefault><w:pPr><w:spacing w:after="60"/></w:pPr></w:pPrDefault></w:docDefaults>'
573
+ '<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>'
574
+ + st("Title", "Title", 36, "1F3864") + st("Heading1", "heading 1", 30, "1F3864", '<w:keepNext/><w:outlineLvl w:val="0"/>')
575
+ + st("Heading2", "heading 2", 24, "2F5597", '<w:keepNext/><w:outlineLvl w:val="1"/>') + '</w:styles>')
576
+ with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
577
+ z.writestr("[Content_Types].xml", '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
578
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>'
579
+ '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
580
+ '<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>')
581
+ z.writestr("_rels/.rels", '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
582
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')
583
+ z.writestr("word/_rels/document.xml.rels", '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
584
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')
585
+ z.writestr("word/document.xml", doc)
586
+ z.writestr("word/styles.xml", styles_xml)
587
+ return [out], "a heading per story, a table per case"
588
+
589
+
590
+ def write_feature(out, cases, label, ac_rows, link, titles):
591
+ stories = ordered(cases)
592
+ base, ext = os.path.splitext(out)
593
+ written = []
594
+ for s in stories:
595
+ cs = [c for c in cases if c["Story"] == s]
596
+ path = out if len(stories) == 1 else f"{base}-{s}{ext or '.feature'}"
597
+ t = titles.get(s) or cs[0]["Story Title"] or s
598
+ o = [f"# {label} Scenarios only, no step definitions.", f"@{s}", f"Feature: {t}"]
599
+ for c in cs:
600
+ tags = [c["Test Case ID"]] + ac_ids(c["AC"]) + ([{"High": "P1", "Medium": "P2", "Low": "P3"}[c["Priority"]]] if c["Priority"] in PRIORITIES else []) + ([c["Type"].lower()] if c["Type"] else [])
601
+ o += ["", " " + " ".join("@" + re.sub(r"\s+", "-", x) for x in tags), f" Scenario: {c['Title']}"]
602
+ pre = lines_of(c["Preconditions"])
603
+ o += [f" {'Given' if i == 0 else 'And'} {x}" for i, x in enumerate(pre)]
604
+ o += [f" {'When' if i == 0 else 'And'} {x}" for i, x in enumerate(steps_of(c["Steps"]))]
605
+ o += [f" {'Then' if i == 0 else 'And'} {x}" for i, x in enumerate(lines_of(c["Expected Result"]) or ["—"])]
606
+ open(path, "w", encoding="utf-8").write("\n".join(o) + "\n")
607
+ written.append(path)
608
+ return written, "one Feature per story"
609
+
610
+
611
+ def write_json(out, cases, label, ac_rows, link, titles):
612
+ stories = ordered(cases)
613
+ data = {"label": label, "stories": [{"key": s, "title": titles.get(s, ""), "link": link.replace("{key}", s) if link else "",
614
+ "acceptance_criteria": [{"id": a["AC"], "text": a["Criterion"]} for a in ac_rows if a["Story"] == s],
615
+ "test_cases": [{"id": c["Test Case ID"], "title": c["Title"], "type": c["Type"], "priority": c["Priority"],
616
+ "covers": ac_ids(c["AC"]), "preconditions": lines_of(c["Preconditions"]),
617
+ "steps": steps_of(c["Steps"]), "expected": c["Expected Result"], "test_data": c["Test Data"],
618
+ "automated_test": c["Automated Test"], "last_run": c["Last Run"], "tracker_key": c["Tracker Key"],
619
+ "review": c["Review"], "reviewer_comment": c["Reviewer Comment"]}
620
+ for c in cases if c["Story"] == s]} for s in stories]}
621
+ open(out, "w", encoding="utf-8").write(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
622
+ return [out], "stories → acceptance criteria and test cases"
623
+
624
+
625
+ def write_tool(tool):
626
+ """The tool import CSV layouts from delivery-formats.md (vendor docs, 2026-10-16)."""
627
+ def w(out, cases, label, *_):
628
+ ordered(cases)
629
+ rows = []
630
+ if tool == "testrail":
631
+ head = ["Title", "Preconditions", "Priority", "References", "Custom ID", "Step", "Expected Result"]
632
+ for c in cases:
633
+ st = steps_of(c["Steps"]) or [""]
634
+ for i, x in enumerate(st):
635
+ exp = c["Expected Result"] if i == len(st) - 1 else ""
636
+ rows.append([c["Title"], c["Preconditions"], c["Priority"], refs(c), c["Test Case ID"], x, exp] if i == 0 else ["", "", "", "", "", x, exp])
637
+ elif tool == "xray":
638
+ head = ["Issue Id", "Summary", "Test Type", "Priority", "Labels", "Action", "Data", "Result"]
639
+ for n, c in enumerate(cases, 1):
640
+ st = steps_of(c["Steps"]) or [""]
641
+ labels = " ".join([c["Story"], c["Test Case ID"]] + ([c["Type"]] if c["Type"] else []))
642
+ for i, x in enumerate(st):
643
+ exp = c["Expected Result"] if i == len(st) - 1 else ""
644
+ rows.append([n, f"[{c['Story']}] {c['Title']}", "Manual", c["Priority"], labels, x, c["Test Data"] if i == 0 else "", exp] if i == 0 else [n, "", "", "", "", x, "", exp])
645
+ elif tool == "zephyr":
646
+ head = ["Name", "Objective", "Precondition", "Priority", "Labels", "Test Script (Plain Text)"]
647
+ for c in cases:
648
+ script = "\n".join(f"{i}. {x}" for i, x in enumerate(steps_of(c["Steps"]), 1)) + f"\nExpected: {c['Expected Result']}"
649
+ rows.append([f"[{c['Story']}] {c['Title']}", f"Covers {refs(c)}", c["Preconditions"], c["Priority"],
650
+ " ".join([c["Story"], c["Test Case ID"]] + ([c["Type"]] if c["Type"] else [])), script])
651
+ else:
652
+ head = ["ID", "Work Item Type", "Title", "Test Step", "Step Action", "Step Expected", "Area Path", "Assigned To", "State"]
653
+ for c in cases:
654
+ st = steps_of(c["Steps"]) or [""]
655
+ for i, x in enumerate(st, 1):
656
+ exp = c["Expected Result"] if i == len(st) else ""
657
+ rows.append(["", "Test Case", f"[{c['Story']}] {c['Title']}"[:128], i, x, exp, "", "", "Design"] if i == 1 else ["", "", "", i, x, exp, "", "", ""])
658
+ open(out, "w", encoding="utf-8", newline="").write(csv_text(head, rows))
659
+ return [out], f"{tool} import layout; try one case first (label: in your message, not in the file)"
660
+ return w
661
+
662
+
663
+ FORMATS = {"xlsx": write_xlsx, "csv": write_csv, "md": write_md, "html": write_html, "pdf": write_pdf, "docx": write_docx,
664
+ "feature": write_feature, "json": write_json, "testrail": write_tool("testrail"), "xray": write_tool("xray"),
665
+ "zephyr": write_tool("zephyr"), "azure": write_tool("azure")}
666
+ EXT = {".xlsx": "xlsx", ".csv": "csv", ".md": "md", ".html": "html", ".htm": "html", ".pdf": "pdf", ".docx": "docx",
667
+ ".feature": "feature", ".json": "json"}
668
+
669
+
670
+ def main():
671
+ """Parse arguments, read the cases, write the asked format."""
672
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
673
+ ap.add_argument("csv", nargs="+")
674
+ ap.add_argument("--out", required=True)
675
+ ap.add_argument("--format", choices=sorted(FORMATS))
676
+ ap.add_argument("--label", required=True, help="the AI-generated line, naming the approver (AGENTS rule 10)")
677
+ ap.add_argument("--ac", help="CSV with Story, AC, Criterion")
678
+ ap.add_argument("--link", help='story link pattern, e.g. "https://x.atlassian.net/browse/{key}"')
679
+ ap.add_argument("--titles", default="", help='story titles, "PR-1=Sign in,PR-2=Reports"')
680
+ a = ap.parse_args()
681
+ fmt = a.format or EXT.get(os.path.splitext(a.out)[1].lower())
682
+ if not fmt:
683
+ print(f"cases_export: say --format ({', '.join(sorted(FORMATS))}); the extension of {a.out} doesn't name one", file=sys.stderr)
684
+ return 2
685
+ for p in a.csv + ([a.ac] if a.ac else []):
686
+ if not os.path.isfile(p):
687
+ print(f"cases_export: no such file: {p}", file=sys.stderr)
688
+ return 2
689
+ if a.link and "{key}" not in a.link:
690
+ print("cases_export: --link needs {key} where the story key goes", file=sys.stderr)
691
+ return 2
692
+ cases = load(a.csv)
693
+ if not cases:
694
+ print("cases_export: no test cases in the input", file=sys.stderr)
695
+ return 2
696
+ missing = [c.get("Test Case ID") or "?" for c in cases if not (c.get("Test Case ID") and c.get("Title"))]
697
+ if missing:
698
+ print(f"cases_export: rows without an ID or title: {', '.join(missing)}", file=sys.stderr)
699
+ return 2
700
+ ac_rows = []
701
+ if a.ac:
702
+ with open(a.ac, encoding="utf-8-sig", newline="") as f:
703
+ ac_rows = [{"Story": pick(r, ["Story"]), "AC": pick(r, ["AC"]).upper(), "Criterion": pick(r, ["Criterion", "Text"])}
704
+ for r in csv.DictReader(f)]
705
+ titles = dict(t.split("=", 1) for t in a.titles.split(",") if "=" in t)
706
+ for c in cases:
707
+ if c["Story Title"]:
708
+ titles.setdefault(c["Story"], c["Story Title"])
709
+ os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
710
+ try:
711
+ files, note = FORMATS[fmt](a.out, cases, a.label, ac_rows, a.link, titles)
712
+ except SystemExit as e:
713
+ if e.code == 3:
714
+ print("cases_export: no Chrome, Edge or LibreOffice to print the PDF; deliver the html (\"open it and print to PDF\")", file=sys.stderr)
715
+ return 3
716
+ raise
717
+ stories = sorted({c["Story"] for c in cases}, key=tc_sort)
718
+ print(f"{', '.join(files)}: {len(cases)} test cases, {len(stories)} stor{'y' if len(stories) == 1 else 'ies'} "
719
+ f"({', '.join(stories)}); {fmt}: {note}")
720
+ return 0
721
+
722
+
723
+ if __name__ == "__main__":
724
+ sys.exit(main())