@sun-asterisk/sungen 3.2.17 → 3.2.18

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 (187) hide show
  1. package/dist/cli/commands/audit.d.ts.map +1 -1
  2. package/dist/cli/commands/audit.js +23 -0
  3. package/dist/cli/commands/audit.js.map +1 -1
  4. package/dist/cli/commands/delivery.d.ts.map +1 -1
  5. package/dist/cli/commands/delivery.js +209 -16
  6. package/dist/cli/commands/delivery.js.map +1 -1
  7. package/dist/cli/index.js +5 -0
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/dashboard/snapshot-builder.d.ts.map +1 -1
  10. package/dist/dashboard/snapshot-builder.js +8 -1
  11. package/dist/dashboard/snapshot-builder.js.map +1 -1
  12. package/dist/dashboard/templates/index.html +1 -1
  13. package/dist/exporters/api-environment.d.ts +11 -0
  14. package/dist/exporters/api-environment.d.ts.map +1 -0
  15. package/dist/exporters/api-environment.js +129 -0
  16. package/dist/exporters/api-environment.js.map +1 -0
  17. package/dist/exporters/feature-parser.d.ts +16 -1
  18. package/dist/exporters/feature-parser.d.ts.map +1 -1
  19. package/dist/exporters/feature-parser.js +21 -2
  20. package/dist/exporters/feature-parser.js.map +1 -1
  21. package/dist/exporters/matrix/build.d.ts +70 -0
  22. package/dist/exporters/matrix/build.d.ts.map +1 -0
  23. package/dist/exporters/matrix/build.js +516 -0
  24. package/dist/exporters/matrix/build.js.map +1 -0
  25. package/dist/exporters/matrix/export.d.ts +50 -0
  26. package/dist/exporters/matrix/export.d.ts.map +1 -0
  27. package/dist/exporters/matrix/export.js +152 -0
  28. package/dist/exporters/matrix/export.js.map +1 -0
  29. package/dist/exporters/matrix/fingerprint.d.ts +20 -0
  30. package/dist/exporters/matrix/fingerprint.d.ts.map +1 -0
  31. package/dist/exporters/matrix/fingerprint.js +83 -0
  32. package/dist/exporters/matrix/fingerprint.js.map +1 -0
  33. package/dist/exporters/matrix/gates.d.ts +21 -0
  34. package/dist/exporters/matrix/gates.d.ts.map +1 -0
  35. package/dist/exporters/matrix/gates.js +367 -0
  36. package/dist/exporters/matrix/gates.js.map +1 -0
  37. package/dist/exporters/matrix/map-loader.d.ts +22 -0
  38. package/dist/exporters/matrix/map-loader.d.ts.map +1 -0
  39. package/dist/exporters/matrix/map-loader.js +193 -0
  40. package/dist/exporters/matrix/map-loader.js.map +1 -0
  41. package/dist/exporters/matrix/render-csv.d.ts +9 -0
  42. package/dist/exporters/matrix/render-csv.d.ts.map +1 -0
  43. package/dist/exporters/matrix/render-csv.js +92 -0
  44. package/dist/exporters/matrix/render-csv.js.map +1 -0
  45. package/dist/exporters/matrix/render-xlsx.d.ts +41 -0
  46. package/dist/exporters/matrix/render-xlsx.d.ts.map +1 -0
  47. package/dist/exporters/matrix/render-xlsx.js +430 -0
  48. package/dist/exporters/matrix/render-xlsx.js.map +1 -0
  49. package/dist/exporters/matrix/types.d.ts +199 -0
  50. package/dist/exporters/matrix/types.d.ts.map +1 -0
  51. package/dist/exporters/matrix/types.js +15 -0
  52. package/dist/exporters/matrix/types.js.map +1 -0
  53. package/dist/exporters/matrix/wording.d.ts +61 -0
  54. package/dist/exporters/matrix/wording.d.ts.map +1 -0
  55. package/dist/exporters/matrix/wording.js +221 -0
  56. package/dist/exporters/matrix/wording.js.map +1 -0
  57. package/dist/exporters/scenario-merger.d.ts.map +1 -1
  58. package/dist/exporters/scenario-merger.js +2 -1
  59. package/dist/exporters/scenario-merger.js.map +1 -1
  60. package/dist/exporters/spec-parser.d.ts.map +1 -1
  61. package/dist/exporters/spec-parser.js +2 -1
  62. package/dist/exporters/spec-parser.js.map +1 -1
  63. package/dist/exporters/xlsx-report-builder.d.ts +1 -1
  64. package/dist/exporters/xlsx-report-builder.d.ts.map +1 -1
  65. package/dist/exporters/xlsx-report-builder.js +3 -3
  66. package/dist/exporters/xlsx-report-builder.js.map +1 -1
  67. package/dist/harness/audit.d.ts +10 -0
  68. package/dist/harness/audit.d.ts.map +1 -1
  69. package/dist/harness/audit.js +98 -16
  70. package/dist/harness/audit.js.map +1 -1
  71. package/dist/harness/blindspot.d.ts.map +1 -1
  72. package/dist/harness/blindspot.js +2 -1
  73. package/dist/harness/blindspot.js.map +1 -1
  74. package/dist/harness/capability-plan.d.ts +2 -0
  75. package/dist/harness/capability-plan.d.ts.map +1 -1
  76. package/dist/harness/capability-plan.js +17 -4
  77. package/dist/harness/capability-plan.js.map +1 -1
  78. package/dist/harness/feedback.d.ts.map +1 -1
  79. package/dist/harness/feedback.js +3 -2
  80. package/dist/harness/feedback.js.map +1 -1
  81. package/dist/harness/flow-check.d.ts.map +1 -1
  82. package/dist/harness/flow-check.js +2 -1
  83. package/dist/harness/flow-check.js.map +1 -1
  84. package/dist/harness/flow-plan.d.ts.map +1 -1
  85. package/dist/harness/flow-plan.js +3 -2
  86. package/dist/harness/flow-plan.js.map +1 -1
  87. package/dist/harness/intent.d.ts.map +1 -1
  88. package/dist/harness/intent.js +2 -1
  89. package/dist/harness/intent.js.map +1 -1
  90. package/dist/harness/journey.d.ts.map +1 -1
  91. package/dist/harness/journey.js +3 -2
  92. package/dist/harness/journey.js.map +1 -1
  93. package/dist/harness/ledger.d.ts.map +1 -1
  94. package/dist/harness/ledger.js +3 -2
  95. package/dist/harness/ledger.js.map +1 -1
  96. package/dist/harness/manifest.d.ts.map +1 -1
  97. package/dist/harness/manifest.js +4 -3
  98. package/dist/harness/manifest.js.map +1 -1
  99. package/dist/harness/parse.d.ts.map +1 -1
  100. package/dist/harness/parse.js +16 -3
  101. package/dist/harness/parse.js.map +1 -1
  102. package/dist/harness/quality-gates.d.ts.map +1 -1
  103. package/dist/harness/quality-gates.js +2 -1
  104. package/dist/harness/quality-gates.js.map +1 -1
  105. package/dist/harness/read-text.d.ts +22 -0
  106. package/dist/harness/read-text.d.ts.map +1 -0
  107. package/dist/harness/read-text.js +64 -0
  108. package/dist/harness/read-text.js.map +1 -0
  109. package/dist/harness/script-check.d.ts.map +1 -1
  110. package/dist/harness/script-check.js +3 -2
  111. package/dist/harness/script-check.js.map +1 -1
  112. package/dist/harness/sensors.d.ts +13 -1
  113. package/dist/harness/sensors.d.ts.map +1 -1
  114. package/dist/harness/sensors.js +63 -20
  115. package/dist/harness/sensors.js.map +1 -1
  116. package/dist/harness/spec-coverage.d.ts +5 -0
  117. package/dist/harness/spec-coverage.d.ts.map +1 -1
  118. package/dist/harness/spec-coverage.js +17 -7
  119. package/dist/harness/spec-coverage.js.map +1 -1
  120. package/dist/harness/trace.d.ts.map +1 -1
  121. package/dist/harness/trace.js +4 -3
  122. package/dist/harness/trace.js.map +1 -1
  123. package/dist/harness/viewpoint-baseline.d.ts +49 -0
  124. package/dist/harness/viewpoint-baseline.d.ts.map +1 -0
  125. package/dist/harness/viewpoint-baseline.js +141 -0
  126. package/dist/harness/viewpoint-baseline.js.map +1 -0
  127. package/dist/harness/viewpoint-ledger.d.ts.map +1 -1
  128. package/dist/harness/viewpoint-ledger.js +2 -1
  129. package/dist/harness/viewpoint-ledger.js.map +1 -1
  130. package/dist/orchestrator/assets-drift.d.ts +24 -0
  131. package/dist/orchestrator/assets-drift.d.ts.map +1 -0
  132. package/dist/orchestrator/assets-drift.js +80 -0
  133. package/dist/orchestrator/assets-drift.js.map +1 -0
  134. package/dist/orchestrator/templates/ai-src/commands/create-test.md +24 -0
  135. package/dist/orchestrator/templates/ai-src/commands/delivery.md +203 -120
  136. package/dist/orchestrator/templates/ai-src/config/claude.md +1 -1
  137. package/dist/orchestrator/templates/ai-src/config/copilot.md +1 -1
  138. package/dist/orchestrator/templates/ai-src/skills/sungen-delivery/SKILL.md +102 -6
  139. package/dist/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +1 -0
  140. package/dist/orchestrator/templates/ai-src/skills/sungen-tc-generation/SKILL.md +23 -0
  141. package/package.json +3 -3
  142. package/src/cli/commands/audit.ts +23 -1
  143. package/src/cli/commands/delivery.ts +240 -18
  144. package/src/cli/index.ts +6 -0
  145. package/src/dashboard/snapshot-builder.ts +8 -1
  146. package/src/dashboard/templates/index.html +1 -1
  147. package/src/exporters/api-environment.ts +97 -0
  148. package/src/exporters/feature-parser.ts +21 -2
  149. package/src/exporters/matrix/build.ts +551 -0
  150. package/src/exporters/matrix/export.ts +149 -0
  151. package/src/exporters/matrix/fingerprint.ts +49 -0
  152. package/src/exporters/matrix/gates.ts +400 -0
  153. package/src/exporters/matrix/map-loader.ts +163 -0
  154. package/src/exporters/matrix/render-csv.ts +94 -0
  155. package/src/exporters/matrix/render-xlsx.ts +420 -0
  156. package/src/exporters/matrix/types.ts +226 -0
  157. package/src/exporters/matrix/wording.ts +221 -0
  158. package/src/exporters/scenario-merger.ts +2 -1
  159. package/src/exporters/spec-parser.ts +2 -1
  160. package/src/exporters/xlsx-report-builder.ts +3 -2
  161. package/src/harness/audit.ts +104 -18
  162. package/src/harness/blindspot.ts +2 -1
  163. package/src/harness/capability-plan.ts +17 -4
  164. package/src/harness/feedback.ts +3 -2
  165. package/src/harness/flow-check.ts +2 -1
  166. package/src/harness/flow-plan.ts +3 -2
  167. package/src/harness/intent.ts +2 -1
  168. package/src/harness/journey.ts +3 -2
  169. package/src/harness/ledger.ts +3 -2
  170. package/src/harness/manifest.ts +4 -3
  171. package/src/harness/parse.ts +17 -3
  172. package/src/harness/quality-gates.ts +2 -1
  173. package/src/harness/read-text.ts +28 -0
  174. package/src/harness/script-check.ts +3 -2
  175. package/src/harness/sensors.ts +55 -8
  176. package/src/harness/spec-coverage.ts +22 -7
  177. package/src/harness/trace.ts +4 -3
  178. package/src/harness/viewpoint-baseline.ts +128 -0
  179. package/src/harness/viewpoint-ledger.ts +2 -1
  180. package/src/orchestrator/assets-drift.ts +64 -0
  181. package/src/orchestrator/templates/ai-src/commands/create-test.md +24 -0
  182. package/src/orchestrator/templates/ai-src/commands/delivery.md +203 -120
  183. package/src/orchestrator/templates/ai-src/config/claude.md +1 -1
  184. package/src/orchestrator/templates/ai-src/config/copilot.md +1 -1
  185. package/src/orchestrator/templates/ai-src/skills/sungen-delivery/SKILL.md +102 -6
  186. package/src/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +1 -0
  187. package/src/orchestrator/templates/ai-src/skills/sungen-tc-generation/SKILL.md +23 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Delivery Map loader — `qa/<kind>/<unit>/delivery/<unit>.map.yaml`.
3
+ *
4
+ * Structural validation only (shape, required fields, enum values, duplicate ids).
5
+ * Semantic validation against the .feature is the gates' job (gates.ts) — the loader
6
+ * never reads the feature.
7
+ */
8
+
9
+ import * as fs from 'fs';
10
+ import * as path from 'path';
11
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
12
+ import { DeliveryMap, MapCategory, MapDisposition, MapGroup, RequirementOverride, RequirementStatus, ReviewState } from './types';
13
+
14
+ const CATEGORIES: MapCategory[] = ['normal', 'abnormal', 'security', 'nfr'];
15
+ const REVIEW_STATES: ReviewState[] = ['proposed', 'approved'];
16
+ const DISPOSITIONS = ['excluded', 'blocked', 'covered_elsewhere', 'accepted_risk'];
17
+ const REQUIREMENT_STATUSES: RequirementStatus[] =
18
+ ['covered', 'partially_covered', 'covered_elsewhere', 'planned', 'gap', 'not_applicable'];
19
+
20
+ export interface MapLoadResult {
21
+ map: DeliveryMap | null;
22
+ /** Structural problems — any entry blocks the matrix path (fix the file first). */
23
+ errors: string[];
24
+ }
25
+
26
+ /** Path of the map file for a unit directory (qa/<kind>/<screen>) + feature basename. */
27
+ export function mapFilePath(unitDir: string, featureBaseName: string): string {
28
+ return path.join(unitDir, 'delivery', `${featureBaseName}.map.yaml`);
29
+ }
30
+
31
+ export function loadDeliveryMap(file: string): MapLoadResult {
32
+ if (!fs.existsSync(file)) return { map: null, errors: [] };
33
+ const errors: string[] = [];
34
+ let raw: unknown;
35
+ try {
36
+ raw = parseYaml(fs.readFileSync(file, 'utf-8'));
37
+ } catch (e) {
38
+ return { map: null, errors: [`map YAML does not parse: ${e instanceof Error ? e.message : e}`] };
39
+ }
40
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
41
+ return { map: null, errors: ['map root must be a YAML mapping'] };
42
+ }
43
+ const doc = raw as Record<string, unknown>;
44
+
45
+ const groups: MapGroup[] = [];
46
+ const seenIds = new Set<string>();
47
+ const rawGroups = doc.groups;
48
+ if (!Array.isArray(rawGroups) || rawGroups.length === 0) {
49
+ errors.push('map has no `groups` list');
50
+ } else {
51
+ rawGroups.forEach((g, i) => {
52
+ if (!g || typeof g !== 'object') { errors.push(`groups[${i}] is not a mapping`); return; }
53
+ const grp = g as Record<string, unknown>;
54
+ const where = `groups[${i}]${typeof grp.id === 'string' ? ` (${grp.id})` : ''}`;
55
+ for (const field of ['id', 'target', 'intent', 'oracle'] as const) {
56
+ if (typeof grp[field] !== 'string' || !(grp[field] as string).trim()) {
57
+ errors.push(`${where}: missing/empty \`${field}\``);
58
+ }
59
+ }
60
+ if (!CATEGORIES.includes(grp.category as MapCategory)) {
61
+ errors.push(`${where}: \`category\` must be one of ${CATEGORIES.join(' | ')}`);
62
+ }
63
+ const review = (grp.review ?? 'proposed') as ReviewState;
64
+ if (!REVIEW_STATES.includes(review)) {
65
+ errors.push(`${where}: \`review\` must be proposed | approved`);
66
+ }
67
+ const variants = grp.variants;
68
+ if (!Array.isArray(variants) || variants.length === 0 || variants.some((v) => typeof v !== 'string' || !v.trim())) {
69
+ errors.push(`${where}: \`variants\` must be a non-empty list of VP refs`);
70
+ }
71
+ const id = String(grp.id ?? '');
72
+ if (id) {
73
+ if (seenIds.has(id)) errors.push(`duplicate group id \`${id}\``);
74
+ seenIds.add(id);
75
+ }
76
+ groups.push({
77
+ id,
78
+ target: String(grp.target ?? ''),
79
+ intent: String(grp.intent ?? ''),
80
+ oracle: String(grp.oracle ?? ''),
81
+ ...(grp.dimensions !== undefined ? { dimensions: String(grp.dimensions) } : {}),
82
+ category: grp.category as MapCategory,
83
+ review,
84
+ variants: Array.isArray(variants) ? variants.map(String) : [],
85
+ });
86
+ });
87
+ }
88
+
89
+ const dispositions: Record<string, MapDisposition> = {};
90
+ if (doc.dispositions !== undefined) {
91
+ if (!doc.dispositions || typeof doc.dispositions !== 'object' || Array.isArray(doc.dispositions)) {
92
+ errors.push('`dispositions` must be a mapping of VP-id → { as, reason }');
93
+ } else {
94
+ for (const [vpId, d] of Object.entries(doc.dispositions as Record<string, unknown>)) {
95
+ const dd = (d && typeof d === 'object' ? d : {}) as Record<string, unknown>;
96
+ if (!DISPOSITIONS.includes(String(dd.as))) {
97
+ errors.push(`dispositions.${vpId}: \`as\` must be one of ${DISPOSITIONS.join(' | ')}`);
98
+ }
99
+ dispositions[vpId] = { as: dd.as as MapDisposition['as'], reason: dd.reason ? String(dd.reason) : undefined };
100
+ }
101
+ }
102
+ }
103
+
104
+ const requirements: Record<string, RequirementOverride> = {};
105
+ if (doc.requirements !== undefined) {
106
+ if (!doc.requirements || typeof doc.requirements !== 'object' || Array.isArray(doc.requirements)) {
107
+ errors.push('`requirements` must be a mapping of requirement-id → { status, note }');
108
+ } else {
109
+ for (const [reqId, r] of Object.entries(doc.requirements as Record<string, unknown>)) {
110
+ const rr = (r && typeof r === 'object' ? r : {}) as Record<string, unknown>;
111
+ if (!REQUIREMENT_STATUSES.includes(String(rr.status) as RequirementStatus)) {
112
+ errors.push(`requirements.${reqId}: \`status\` must be one of ${REQUIREMENT_STATUSES.join(' | ')}`);
113
+ }
114
+ requirements[reqId] = { status: rr.status as RequirementStatus, note: rr.note ? String(rr.note) : undefined };
115
+ }
116
+ }
117
+ }
118
+
119
+ const fingerprints: Record<string, string> = {};
120
+ if (doc.fingerprints && typeof doc.fingerprints === 'object' && !Array.isArray(doc.fingerprints)) {
121
+ for (const [k, v] of Object.entries(doc.fingerprints as Record<string, unknown>)) {
122
+ fingerprints[k] = String(v);
123
+ }
124
+ }
125
+
126
+ const map: DeliveryMap = {
127
+ version: Number(doc.version ?? 1),
128
+ unit: String(doc.unit ?? ''),
129
+ formNo: doc.form_no !== undefined ? String(doc.form_no) : undefined,
130
+ groups,
131
+ dispositions,
132
+ requirements,
133
+ fingerprints,
134
+ };
135
+ return { map: errors.length > 0 ? null : map, errors };
136
+ }
137
+
138
+ /**
139
+ * Write the map back (used by `--approve` to flip review states + stamp fingerprints).
140
+ * Field order is kept stable so approve-diffs stay minimal and reviewable.
141
+ */
142
+ export function writeDeliveryMap(file: string, map: DeliveryMap): void {
143
+ const doc: Record<string, unknown> = {
144
+ version: map.version,
145
+ unit: map.unit,
146
+ ...(map.formNo !== undefined ? { form_no: map.formNo } : {}),
147
+ groups: map.groups.map((g) => ({
148
+ id: g.id,
149
+ target: g.target,
150
+ intent: g.intent,
151
+ oracle: g.oracle,
152
+ ...(g.dimensions !== undefined ? { dimensions: g.dimensions } : {}),
153
+ category: g.category,
154
+ review: g.review,
155
+ variants: g.variants,
156
+ })),
157
+ ...(Object.keys(map.dispositions).length > 0 ? { dispositions: map.dispositions } : {}),
158
+ ...(Object.keys(map.requirements).length > 0 ? { requirements: map.requirements } : {}),
159
+ ...(Object.keys(map.fingerprints).length > 0 ? { fingerprints: map.fingerprints } : {}),
160
+ };
161
+ fs.mkdirSync(path.dirname(file), { recursive: true });
162
+ fs.writeFileSync(file, stringifyYaml(doc, { lineWidth: 0 }), 'utf-8');
163
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Flat CSV rendering of the matrix — same model as the workbook, one row per
3
+ * delivery item (`Level: item`) followed by its variant rows (`Level: variant`;
4
+ * every item has them — the variant row carries the source scenario id, data,
5
+ * and result), so downstream pipelines can re-derive both views from one file.
6
+ */
7
+
8
+ import { variantState } from './build';
9
+ import { coverageSummary, itemModeLabel, itemResultLabel } from './render-xlsx';
10
+ import { MatrixModel } from './types';
11
+
12
+ const HEADERS = [
13
+ 'Level', 'ID', 'Target', 'Test Intent / Condition', 'Category', 'Priority',
14
+ 'Precondition', 'Coverage / Test Data', 'Action / Trigger', 'Expected Result',
15
+ 'Mode', 'Trace', 'Result', 'Executed Date', 'Note / Evidence', 'Defect ID',
16
+ ];
17
+
18
+ function esc(value: string): string {
19
+ if (/[",\n]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
20
+ return value;
21
+ }
22
+
23
+ function isoDate(startTime: string | undefined): string {
24
+ if (!startTime) return '';
25
+ const d = new Date(startTime);
26
+ if (isNaN(d.getTime())) return '';
27
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
28
+ }
29
+
30
+ export function renderMatrixCsv(model: MatrixModel): string {
31
+ const BOM = '\ufeff'; // Excel compatibility (Vietnamese/Japanese content)
32
+ const lines: string[] = [];
33
+ lines.push(`# Test Case & Coverage Matrix — ${model.unit}`);
34
+ lines.push(`# delivery items: ${model.manifest.itemCount} · coverage variants: ${model.manifest.variantCount} · state: ${model.manifest.approvalState}`);
35
+ lines.push(HEADERS.map(esc).join(','));
36
+
37
+ for (const item of model.items) {
38
+ lines.push([
39
+ 'item',
40
+ item.id,
41
+ item.target,
42
+ item.intent,
43
+ item.category,
44
+ item.priority,
45
+ item.precondition.join('\n'),
46
+ coverageSummary(item),
47
+ // Shared leading steps only; each variant row carries its remaining steps.
48
+ item.trigger.join('\n'),
49
+ item.oracle,
50
+ itemModeLabel(item),
51
+ item.traces.join(' '),
52
+ itemResultLabel(item),
53
+ '',
54
+ item.review === 'proposed' ? 'REVIEW REQUIRED' : '',
55
+ '',
56
+ ].map(esc).join(','));
57
+
58
+ for (const v of item.variants) {
59
+ const expected = v.verification.length > 0
60
+ ? `${v.oracle.join('\n')}\nVerification method: ${v.verification.join(' ')}`
61
+ : v.oracle.join('\n');
62
+ lines.push([
63
+ 'variant',
64
+ v.ref,
65
+ '',
66
+ v.condition,
67
+ '', '',
68
+ // Precondition DELTA — variant-specific setup only (review GAP-03).
69
+ (item.preconditionDeltas[v.ref] ?? []).join('\n'),
70
+ v.data.join('\n'),
71
+ // Steps after the parent's shared prefix only.
72
+ (item.triggerDeltas[v.ref] ?? []).join('\n'),
73
+ expected,
74
+ v.mode === 'manual' ? 'Manual' : 'Auto',
75
+ v.traces.join(' '),
76
+ variantState(v),
77
+ isoDate(v.result?.startTime),
78
+ v.result?.error ? String(v.result.error).slice(0, 200) : '',
79
+ '',
80
+ ].map(esc).join(','));
81
+ }
82
+ }
83
+
84
+ // Requirement coverage appendix — keeps the CSV self-contained for pipelines.
85
+ if (model.requirements.length > 0) {
86
+ lines.push('');
87
+ lines.push('# Requirement coverage');
88
+ lines.push(['Requirement', 'Status', 'Delivery items', 'Variants', 'Note'].join(','));
89
+ for (const r of model.requirements) {
90
+ lines.push([r.id, r.status, r.items.join(' '), String(r.variantCount), r.note].map(esc).join(','));
91
+ }
92
+ }
93
+ return BOM + lines.join('\n') + '\n';
94
+ }
@@ -0,0 +1,420 @@
1
+ /**
2
+ * Render the Test Case & Coverage Matrix workbook.
3
+ *
4
+ * Sheets:
5
+ * 1. Testcases — one parent row per delivery item; EVERY item (including
6
+ * single-variant ones) carries variant sub-rows on Excel outline level 1 —
7
+ * the sub-row is where source traceability (VP-id), test data, and the
8
+ * manual result/evidence entry live (review B-05/B-06). Collapse outline
9
+ * level 1 for the customer/review view; expand to execute.
10
+ * 2. Coverage — requirement coverage (id ↔ items ↔ status), the target ×
11
+ * category grid (explicit `—` gaps), dispositions, and the manifest.
12
+ *
13
+ * Manual-execution support: variant Result cells carry a dropdown
14
+ * (Passed/Failed/Blocked/Pending/N/A) and the parent Result is a live Excel
15
+ * formula derived from its children — a parent can never contradict its
16
+ * variants, even after QA edits results by hand (review B-06).
17
+ *
18
+ * Every sheet keeps the company ISO masthead. A draft matrix (unapproved
19
+ * groups / review findings) carries a red DRAFT banner.
20
+ */
21
+
22
+ import * as ExcelJS from 'exceljs';
23
+ import {
24
+ renderReportHeaderBand,
25
+ allBordersBlack,
26
+ ARIAL_FONT,
27
+ BLACK,
28
+ LAVENDER,
29
+ } from '../xlsx-report-builder';
30
+ import { variantState } from './build';
31
+ import { DeliveryItem, MatrixModel, MapCategory } from './types';
32
+
33
+ const CATEGORY_ORDER: MapCategory[] = ['normal', 'abnormal', 'security', 'nfr'];
34
+ const SOFT_BLUE = { argb: 'FFDCE6F1' };
35
+ const DRAFT_RED = { argb: 'FFC00000' };
36
+ const GAP_FILL = { argb: 'FFFCE4EC' };
37
+ const RESULT_STATES = 'Passed,Failed,Blocked,Pending,N/A';
38
+
39
+ function headerCell(c: ExcelJS.Cell, label: string): void {
40
+ c.value = label;
41
+ c.font = { bold: true, size: 10, color: BLACK, name: ARIAL_FONT };
42
+ c.fill = { type: 'pattern', pattern: 'solid', fgColor: LAVENDER };
43
+ c.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
44
+ c.border = allBordersBlack;
45
+ }
46
+
47
+ function dataCell(c: ExcelJS.Cell, value: ExcelJS.CellValue, opts?: { bold?: boolean; fill?: { argb: string }; center?: boolean; color?: { argb: string } }): void {
48
+ // An empty value stays a genuinely blank cell — never an empty shared string,
49
+ // which some renderers display as its string-table index (review M-03).
50
+ if (value !== '' && value !== undefined && value !== null) c.value = value;
51
+ c.font = { bold: opts?.bold ?? false, size: 10, name: ARIAL_FONT, ...(opts?.color ? { color: opts.color } : {}) };
52
+ c.alignment = { horizontal: opts?.center ? 'center' : 'left', vertical: 'top', wrapText: true };
53
+ c.border = allBordersBlack;
54
+ if (opts?.fill) c.fill = { type: 'pattern', pattern: 'solid', fgColor: opts.fill };
55
+ }
56
+
57
+ /** Mode is a coverage dimension: mixed items show both counts. */
58
+ export function itemModeLabel(item: DeliveryItem): string {
59
+ if (item.mode === 'mixed') {
60
+ const auto = item.variants.filter((v) => v.mode === 'auto').length;
61
+ return `Auto ${auto} · Manual ${item.variants.length - auto}`;
62
+ }
63
+ return item.mode === 'manual' ? 'Manual' : 'Auto';
64
+ }
65
+
66
+ /**
67
+ * Parent roll-up label. It must NEVER be exactly one of the variant state words
68
+ * (`Passed`/`Failed`/`Blocked`/`Pending`/`N/A`) — the summary band counts the
69
+ * Result column with exact-match COUNTIF over parent AND child rows, so a parent
70
+ * reading plain "Pending" was counted as an extra pending variant (109 instead
71
+ * of 77 on st-login).
72
+ */
73
+ export function itemResultLabel(item: DeliveryItem): string {
74
+ const { passed, failed, blocked, na } = item.resultCounts;
75
+ const eff = item.variants.length - na;
76
+ const suffix = na > 0 ? ` · ${na} N/A` : '';
77
+ if (item.result === 'na') return 'All N/A';
78
+ if (item.result === 'failed') return `${passed}/${eff} Passed · ${failed} Failed${suffix}`;
79
+ if (item.result === 'blocked') return `${passed}/${eff} Passed · ${blocked} Blocked${suffix}`;
80
+ return `${passed}/${eff} Passed${suffix}`;
81
+ }
82
+
83
+ /** ISO date (2026-08-04) — unambiguous across locales (review §9). */
84
+ function isoDate(startTime: string | undefined): string {
85
+ if (!startTime) return '';
86
+ const d = new Date(startTime);
87
+ if (isNaN(d.getTime())) return '';
88
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
89
+ }
90
+
91
+ function numbered(lines: string[], start = 1): string {
92
+ if (lines.length === 0) return '';
93
+ if (lines.length === 1 && start === 1) return lines[0];
94
+ return lines.map((l, i) => `${start + i}. ${l}`).join('\n');
95
+ }
96
+
97
+ /**
98
+ * Compact coverage summary for the parent row. A declared `dimensions:` digest
99
+ * wins ("15 variants — required ×3 · format ×9 …"); otherwise a single variant
100
+ * shows its condition and a group falls back to its variant REFS. Concatenating
101
+ * every variant's full title turned this cell into an 800-character paragraph.
102
+ */
103
+ export function coverageSummary(item: DeliveryItem): string {
104
+ const n = item.variants.length;
105
+ const head = `${n} variant${n === 1 ? '' : 's'}:`;
106
+ if (item.dimensions) return `${head} ${item.dimensions}`;
107
+ if (n === 1) return `${head} ${item.variants[0].condition}`;
108
+ return `${head} ${item.variants.map((v) => v.ref).join(' · ')}`;
109
+ }
110
+
111
+ /** Expected cell = observable outcomes; the HOW moves under a separate heading. */
112
+ function expectedWithVerification(oracle: string[], verification: string[]): string {
113
+ const expected = numbered(oracle);
114
+ if (verification.length === 0) return expected;
115
+ return `${expected}\nVerification method: ${verification.join(' ')}`;
116
+ }
117
+
118
+ /** Red DRAFT banner on row 5 when the matrix is not approved for official delivery. */
119
+ function draftBanner(ws: ExcelJS.Worksheet, model: MatrixModel): void {
120
+ if (model.manifest.approvalState !== 'draft') return;
121
+ ws.mergeCells('B5:H5');
122
+ const c = ws.getCell('B5');
123
+ c.value = 'DRAFT — NOT APPROVED FOR OFFICIAL DELIVERY (review-required findings or proposed groups remain)';
124
+ c.font = { bold: true, size: 11, name: ARIAL_FONT, color: { argb: 'FFFFFFFF' } };
125
+ c.fill = { type: 'pattern', pattern: 'solid', fgColor: DRAFT_RED };
126
+ c.alignment = { horizontal: 'center', vertical: 'middle' };
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Sheet 1 — Testcases (the matrix)
131
+ // ---------------------------------------------------------------------------
132
+
133
+ const MATRIX_HEADERS = [
134
+ 'ID', 'Target', 'Test Intent / Condition', 'Category', 'Priority', 'Precondition',
135
+ 'Coverage / Test Data', 'Action / Trigger', 'Expected Result', 'Mode', 'Trace',
136
+ 'Result', 'Executed Date', 'Executor', 'Note / Evidence', 'Defect ID',
137
+ ];
138
+ const RESULT_COL = 13; // column M
139
+
140
+ function addMatrixSheet(wb: ExcelJS.Workbook, model: MatrixModel, sungenVersion?: string): void {
141
+ const ws = wb.addWorksheet('Testcases');
142
+ ws.properties.outlineLevelRow = 1;
143
+
144
+ ws.columns = [
145
+ { width: 3 }, // A margin
146
+ { width: 22 }, // B ID
147
+ { width: 18 }, // C Target
148
+ { width: 42 }, // D Intent / Condition
149
+ { width: 11 }, // E Category
150
+ { width: 9 }, // F Priority
151
+ { width: 26 }, // G Precondition
152
+ { width: 34 }, // H Coverage / Data
153
+ { width: 34 }, // I Trigger
154
+ { width: 42 }, // J Expected
155
+ { width: 11 }, // K Mode
156
+ { width: 13 }, // L Trace
157
+ { width: 22 }, // M Result
158
+ { width: 12 }, // N Executed
159
+ { width: 13 }, // O Executor
160
+ { width: 22 }, // P Note / Evidence
161
+ { width: 12 }, // Q Defect ID
162
+ ];
163
+
164
+ renderReportHeaderBand(wb, ws, `${model.unit.toUpperCase()} TEST CASE & COVERAGE MATRIX`, sungenVersion, model.formNo);
165
+ draftBanner(ws, model);
166
+
167
+ // Summary band (row 6) — items vs variants stay separate metrics by design (I8).
168
+ // The execution counters are LIVE formulas over the variant Result cells, so
169
+ // hand-entered results update the totals (review GAP-06). Variant cells hold the
170
+ // exact state words and parent cells NEVER do (itemResultLabel + the roll-up
171
+ // formula always compose a "n/m Passed …" label), so exact-match COUNTIF over
172
+ // the whole column counts variants only.
173
+ const sum = (k: 'passed' | 'failed' | 'blocked' | 'notRun' | 'na'): number =>
174
+ model.items.reduce((a, i) => a + i.resultCounts[k], 0);
175
+ const passed = sum('passed');
176
+ const failed = sum('failed');
177
+ const blocked = sum('blocked');
178
+ const notRun = sum('notRun');
179
+ const na = sum('na');
180
+ const RANGE = 'M9:M10000';
181
+ const band = ws.getRow(6);
182
+ const bandCells: Array<[string, ExcelJS.CellValue]> = [
183
+ ['items', `Delivery items: ${model.manifest.itemCount}`],
184
+ ['variants', `Coverage variants: ${model.manifest.variantCount}`],
185
+ ['passed', { formula: `"Passed: "&COUNTIF(${RANGE},"Passed")`, result: `Passed: ${passed}` } as ExcelJS.CellValue],
186
+ ['failed', { formula: `"Failed: "&COUNTIF(${RANGE},"Failed")`, result: `Failed: ${failed}` } as ExcelJS.CellValue],
187
+ ['blocked', { formula: `"Blocked: "&COUNTIF(${RANGE},"Blocked")`, result: `Blocked: ${blocked}` } as ExcelJS.CellValue],
188
+ ['pending', { formula: `"Pending: "&COUNTIF(${RANGE},"Pending")`, result: `Pending: ${notRun}` } as ExcelJS.CellValue],
189
+ ['na', { formula: `"N/A: "&COUNTIF(${RANGE},"N/A")`, result: `N/A: ${na}` } as ExcelJS.CellValue],
190
+ ];
191
+ bandCells.forEach(([, v], i) => {
192
+ const c = band.getCell(2 + i);
193
+ dataCell(c, v, { bold: true, fill: SOFT_BLUE, center: true });
194
+ });
195
+
196
+ const HEADER_ROW = 8;
197
+ const hr = ws.getRow(HEADER_ROW);
198
+ hr.height = 28;
199
+ MATRIX_HEADERS.forEach((label, i) => headerCell(hr.getCell(2 + i), label));
200
+
201
+ let rowIdx = HEADER_ROW + 1;
202
+ for (const item of model.items) {
203
+ const parentRowIdx = rowIdx++;
204
+
205
+ // --- Variant sub-rows FIRST (to know their cell range for the parent formula).
206
+ // Every item gets sub-rows — the sub-row is where the source scenario id, the
207
+ // resolved data, and the manual result/evidence entry live (review B-05).
208
+ const firstChild = rowIdx;
209
+ // Delta-only sub-rows (review GAP-01): content identical across the whole
210
+ // item lives ONCE on the parent — a child repeats only what distinguishes it.
211
+ // The child's Expected Result is always kept: it is the precise source
212
+ // oracle (the semantic anchor), not a repetition of the parent's summary.
213
+ for (const v of item.variants) {
214
+ const vr = ws.getRow(rowIdx++);
215
+ vr.outlineLevel = 1;
216
+ const vValues: ExcelJS.CellValue[] = [
217
+ v.ref,
218
+ '',
219
+ v.condition,
220
+ '', '',
221
+ numbered(item.preconditionDeltas[v.ref] ?? []),
222
+ numbered(v.data),
223
+ // Only the steps after the parent's shared prefix, numbered so the
224
+ // parent's steps + these read as one continuous procedure.
225
+ numbered(item.triggerDeltas[v.ref] ?? [], item.trigger.length + 1),
226
+ expectedWithVerification(v.oracle, v.verification),
227
+ v.mode === 'manual' ? `Manual${v.manualReason ? ` (${v.manualReason})` : ''}` : 'Auto',
228
+ v.traces.join(', '),
229
+ variantState(v),
230
+ isoDate(v.result?.startTime),
231
+ '',
232
+ v.result?.error ? String(v.result.error).slice(0, 200) : '',
233
+ '',
234
+ ];
235
+ vValues.forEach((val, i) => dataCell(vr.getCell(2 + i), val, { center: i === 9 }));
236
+ // Manual-execution entry: constrain the Result cell to the known states.
237
+ vr.getCell(2 + 11).dataValidation = {
238
+ type: 'list', allowBlank: true, formulae: [`"${RESULT_STATES}"`],
239
+ };
240
+ }
241
+ const lastChild = rowIdx - 1;
242
+
243
+ // --- Parent row: only values that are genuinely COMMON to the whole item
244
+ // (review M-04); everything variant-specific stays on the sub-rows.
245
+ const pr = ws.getRow(parentRowIdx);
246
+ const coverage = coverageSummary(item);
247
+
248
+ // Live roll-up derived from the child Result cells — precedence
249
+ // failed → blocked → pending → partial → passed. N/A variants leave the
250
+ // denominator (review GAP-06): eff = n − COUNTIF(N/A); all-N/A → "N/A".
251
+ const rng = `M${firstChild}:M${lastChild}`;
252
+ const n = item.variants.length;
253
+ const EFF = `(${n}-COUNTIF(${rng},"N/A"))`;
254
+ const NA = `IF(COUNTIF(${rng},"N/A")>0," · "&COUNTIF(${rng},"N/A")&" N/A","")`;
255
+ // Mirrors itemResultLabel exactly — and never yields a bare state word.
256
+ const rollUpFormula =
257
+ `IF(COUNTIF(${rng},"Failed")>0,COUNTIF(${rng},"Passed")&"/"&${EFF}&" Passed · "&COUNTIF(${rng},"Failed")&" Failed"&${NA},` +
258
+ `IF(COUNTIF(${rng},"Blocked")>0,COUNTIF(${rng},"Passed")&"/"&${EFF}&" Passed · "&COUNTIF(${rng},"Blocked")&" Blocked"&${NA},` +
259
+ `IF(${EFF}=0,"All N/A",` +
260
+ `COUNTIF(${rng},"Passed")&"/"&${EFF}&" Passed"&${NA})))`;
261
+
262
+ const values: ExcelJS.CellValue[] = [
263
+ item.id,
264
+ item.target,
265
+ item.intent,
266
+ item.category,
267
+ item.priority,
268
+ numbered(item.precondition),
269
+ coverage,
270
+ // The shared leading steps; each variant's remaining steps sit on its sub-row.
271
+ numbered(item.trigger),
272
+ item.oracle,
273
+ itemModeLabel(item),
274
+ item.traces.join(', '),
275
+ { formula: rollUpFormula, result: itemResultLabel(item) } as ExcelJS.CellValue,
276
+ '',
277
+ '',
278
+ item.review === 'proposed' ? 'REVIEW REQUIRED' : '',
279
+ '',
280
+ ];
281
+ values.forEach((v, i) => dataCell(pr.getCell(2 + i), v, {
282
+ bold: true,
283
+ fill: SOFT_BLUE,
284
+ center: i === 3 || i === 4 || i === 9,
285
+ ...(i === 14 && item.review === 'proposed' ? { color: DRAFT_RED } : {}),
286
+ }));
287
+ }
288
+
289
+ ws.autoFilter = { from: { row: HEADER_ROW, column: 2 }, to: { row: rowIdx - 1, column: 17 } };
290
+ // Freeze the header band AND the ID + Target columns (review §9).
291
+ ws.views = [{ state: 'frozen', xSplit: 3, ySplit: HEADER_ROW }];
292
+ // Print: landscape, fit width only (never squash all rows into one page),
293
+ // repeat the masthead + header rows on every page (review GAP-08).
294
+ ws.pageSetup = {
295
+ orientation: 'landscape',
296
+ fitToPage: true,
297
+ fitToWidth: 1,
298
+ fitToHeight: 0,
299
+ printTitlesRow: '1:8',
300
+ };
301
+ }
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Sheet 2 — Coverage (requirements + overview grid + dispositions + manifest)
305
+ // ---------------------------------------------------------------------------
306
+
307
+ function addCoverageSheet(wb: ExcelJS.Workbook, model: MatrixModel, sungenVersion?: string): void {
308
+ const ws = wb.addWorksheet('Coverage');
309
+ ws.columns = [
310
+ { width: 3 }, { width: 22 }, { width: 18 }, { width: 16 }, { width: 16 }, { width: 16 },
311
+ { width: 16 }, { width: 44 },
312
+ ];
313
+ renderReportHeaderBand(wb, ws, `${model.unit.toUpperCase()} COVERAGE OVERVIEW`, sungenVersion, model.formNo);
314
+ draftBanner(ws, model);
315
+
316
+ let rowIdx = 7;
317
+
318
+ // --- Requirement coverage (review §6): every requirement id gets ONE explicit status.
319
+ if (model.requirements.length > 0) {
320
+ dataCell(ws.getRow(rowIdx).getCell(2), 'Requirement coverage — every id has an explicit status', { bold: true });
321
+ rowIdx += 1;
322
+ const rh = ws.getRow(rowIdx);
323
+ ws.mergeCells(rowIdx, 4, rowIdx, 6);
324
+ headerCell(rh.getCell(2), 'Requirement');
325
+ headerCell(rh.getCell(3), 'Status');
326
+ headerCell(rh.getCell(4), 'Delivery items');
327
+ headerCell(rh.getCell(7), 'Variants');
328
+ headerCell(rh.getCell(8), 'Note');
329
+ rowIdx += 1;
330
+ for (const r of model.requirements) {
331
+ const row = ws.getRow(rowIdx++);
332
+ dataCell(row.getCell(2), r.id, { bold: true });
333
+ dataCell(row.getCell(3), r.status, {
334
+ center: true,
335
+ ...(r.status === 'gap' ? { fill: GAP_FILL, bold: true } : {}),
336
+ });
337
+ ws.mergeCells(rowIdx - 1, 4, rowIdx - 1, 6);
338
+ dataCell(row.getCell(4), r.items.join(', '));
339
+ dataCell(row.getCell(7), r.variantCount > 0 ? String(r.variantCount) : '', { center: true });
340
+ dataCell(row.getCell(8), r.note);
341
+ }
342
+ rowIdx += 1;
343
+ }
344
+
345
+ // --- Target × category grid ---
346
+ dataCell(ws.getRow(rowIdx).getCell(2), 'Coverage matrix — delivery items (coverage variants) per target × category', { bold: true });
347
+ rowIdx += 1;
348
+ const gridHeader = ws.getRow(rowIdx++);
349
+ headerCell(gridHeader.getCell(2), 'Target');
350
+ CATEGORY_ORDER.forEach((cat, i) => headerCell(gridHeader.getCell(3 + i), cat));
351
+ headerCell(gridHeader.getCell(3 + CATEGORY_ORDER.length), 'Total');
352
+
353
+ const targets = Array.from(new Set(model.items.map((i) => i.target)));
354
+ for (const target of targets) {
355
+ const row = ws.getRow(rowIdx++);
356
+ dataCell(row.getCell(2), target, { bold: true });
357
+ let totalItems = 0;
358
+ let totalVariants = 0;
359
+ CATEGORY_ORDER.forEach((cat, i) => {
360
+ const cell = row.getCell(3 + i);
361
+ const items = model.items.filter((it) => it.target === target && it.category === cat);
362
+ const variants = items.reduce((a, it) => a + it.variants.length, 0);
363
+ totalItems += items.length;
364
+ totalVariants += variants;
365
+ // `—` is an explicit statement: this target × category cell has NO coverage.
366
+ dataCell(cell, items.length === 0 ? '—' : `${items.length} (${variants})`, {
367
+ center: true,
368
+ ...(items.length === 0 ? { fill: GAP_FILL } : {}),
369
+ });
370
+ });
371
+ dataCell(row.getCell(3 + CATEGORY_ORDER.length), `${totalItems} (${totalVariants})`, { center: true, bold: true });
372
+ }
373
+
374
+ // --- Dispositions ---
375
+ if (model.dispositions.length > 0) {
376
+ rowIdx += 1;
377
+ dataCell(ws.getRow(rowIdx).getCell(2), 'Not in the matrix (explicit dispositions)', { bold: true });
378
+ rowIdx += 1;
379
+ const dh = ws.getRow(rowIdx++);
380
+ ['Source', 'Disposition', 'Reason', 'Title'].forEach((l, i) => headerCell(dh.getCell(2 + i), l));
381
+ for (const d of model.dispositions) {
382
+ const row = ws.getRow(rowIdx++);
383
+ dataCell(row.getCell(2), d.vpId);
384
+ dataCell(row.getCell(3), d.as, { center: true });
385
+ dataCell(row.getCell(4), d.reason);
386
+ dataCell(row.getCell(5), d.title);
387
+ }
388
+ }
389
+
390
+ // --- Manifest ---
391
+ rowIdx += 1;
392
+ dataCell(ws.getRow(rowIdx).getCell(2), 'Generation manifest', { bold: true });
393
+ rowIdx += 1;
394
+ const m = model.manifest;
395
+ const manifestRows: Array<[string, string]> = [
396
+ ['Unit', m.unit],
397
+ ['Approval state', m.approvalState],
398
+ ['Delivery items', String(m.itemCount)],
399
+ ['Coverage variants', String(m.variantCount)],
400
+ ['Source fingerprint', m.sourceFingerprint],
401
+ ['Map fingerprint', m.mapFingerprint],
402
+ ['Transformer version', m.transformerVersion],
403
+ ['Max variants / item (warn)', String(m.thresholds.maxVariantsPerItem)],
404
+ ];
405
+ for (const [k, v] of manifestRows) {
406
+ const row = ws.getRow(rowIdx++);
407
+ dataCell(row.getCell(2), k, { bold: true, fill: SOFT_BLUE });
408
+ ws.mergeCells(rowIdx - 1, 3, rowIdx - 1, 7);
409
+ dataCell(row.getCell(3), v);
410
+ }
411
+ }
412
+
413
+ // ---------------------------------------------------------------------------
414
+
415
+ export function renderMatrixXlsx(model: MatrixModel, sungenVersion?: string): ExcelJS.Workbook {
416
+ const wb = new ExcelJS.Workbook();
417
+ addMatrixSheet(wb, model, sungenVersion);
418
+ addCoverageSheet(wb, model, sungenVersion);
419
+ return wb;
420
+ }