qualiow-exploratory-testing 1.3.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/.claude-plugin/marketplace.json +26 -0
  2. package/.claude-plugin/plugin.json +22 -0
  3. package/.env.example +27 -0
  4. package/CHANGELOG.md +259 -0
  5. package/README.md +472 -204
  6. package/agents/qa-diff-indexer-agent.md +81 -0
  7. package/agents/qa-gather-agent.md +41 -0
  8. package/agents/qa-page-mapper-agent.md +74 -0
  9. package/agents/qa-reporting-agent.md +103 -0
  10. package/{scripts → bin}/doctor-mobile.sh +57 -18
  11. package/bin/mcli +15 -9
  12. package/bin/mobile-cli.mjs +574 -286
  13. package/bin/qualiow +30 -0
  14. package/{scripts → bin}/setup-mobile.sh +56 -19
  15. package/bin/wadb +10 -4
  16. package/bin/wk-ios +29 -17
  17. package/bin/wkeval.mjs +7 -1
  18. package/data/domains/_default.yml +1 -1
  19. package/data/knowledge/changelog.yml +30 -12
  20. package/data/knowledge/manifest.yml +355 -127
  21. package/data/knowledge/releases/v0.1.0/entries/technique-business-logic-race-conditions.yml +1 -1
  22. package/data/knowledge/releases/v0.1.0/release.yml +8 -1
  23. package/data/knowledge/releases/v0.6.0/entries/technique-async-callback-contracts.yml +98 -0
  24. package/data/knowledge/releases/v0.6.0/entries/technique-exactly-once-verification.yml +116 -0
  25. package/data/knowledge/releases/v0.6.0/release.yml +30 -0
  26. package/data/security/SECURITY-POLICY.md +273 -0
  27. package/data/targets/_default.yml +1 -1
  28. package/data/targets/_example-api-only.yml +80 -0
  29. package/data/targets/_example-mobile-emulation.yml +2 -2
  30. package/data/targets/_example-native-mobile.yml +2 -2
  31. package/data/targets/_example-sim-android-chrome.yml +1 -1
  32. package/data/targets/_example-sim-ios-safari.yml +1 -1
  33. package/data/templates/api-probe-matrix.md +3 -3
  34. package/data/templates/bug-report.md +29 -151
  35. package/data/templates/coverage-map.md +9 -6
  36. package/data/templates/expected-behaviour.md +3 -2
  37. package/data/templates/session-charter.md +3 -0
  38. package/data/templates/session-report.md +57 -80
  39. package/dist/cli/index.js +2286 -701
  40. package/dist/index.d.ts +637 -81
  41. package/dist/index.js +2058 -228
  42. package/docs/BACKEND-VERIFICATION.md +39 -9
  43. package/docs/GETTING-STARTED.md +300 -121
  44. package/docs/MOBILE-SETUP.md +149 -18
  45. package/hooks/hooks.json +27 -0
  46. package/hooks/scripts/read-guard.mjs +95 -0
  47. package/hooks/scripts/secret-patterns.d.mts +8 -0
  48. package/hooks/scripts/secret-patterns.mjs +136 -0
  49. package/hooks/scripts/write-guard.mjs +87 -0
  50. package/package.json +33 -18
  51. package/skills/qa-explore/SKILL.md +32 -25
  52. package/skills/qa-explore/phases/00-setup.md +76 -42
  53. package/skills/qa-explore/phases/01-auth.md +32 -15
  54. package/skills/qa-explore/phases/02-charter.md +16 -5
  55. package/skills/qa-explore/phases/03-discovery.md +93 -27
  56. package/skills/qa-explore/phases/04-journeys.md +2 -2
  57. package/skills/qa-explore/phases/05-features.md +39 -24
  58. package/skills/qa-explore/phases/06-edge-cases.md +24 -13
  59. package/skills/qa-explore/phases/07-reporting.md +102 -142
  60. package/skills/qa-explore/references/context-integration.md +1 -1
  61. package/skills/qa-explore/references/delegation-rules.md +82 -0
  62. package/skills/qa-explore/references/output-contract.md +192 -0
  63. package/skills/qa-explore/references/paths.md +108 -0
  64. package/skills/qa-explore/references/playwright-agents-integration.md +61 -84
  65. package/skills/qa-explore/references/security-rules.md +70 -25
  66. package/skills/qa-explore/references/session-rules.md +2 -1
  67. package/skills/qa-explore/references/severity-guide.md +31 -4
  68. package/skills/qa-explore-cleanup/SKILL.md +51 -15
  69. package/skills/qa-explore-feedback/SKILL.md +23 -5
  70. package/skills/qa-explore-mobile/SKILL.md +86 -64
  71. package/skills/qa-explore-mobile/phases/00-setup.md +71 -62
  72. package/skills/qa-explore-mobile/phases/01-auth.md +28 -31
  73. package/skills/qa-explore-mobile/phases/02-charter.md +8 -4
  74. package/skills/qa-explore-mobile/phases/03-discovery.md +17 -11
  75. package/skills/qa-explore-mobile/phases/04-journeys.md +6 -6
  76. package/skills/qa-explore-mobile/phases/05-features.md +9 -9
  77. package/skills/qa-explore-mobile/phases/06-edge-cases.md +35 -40
  78. package/skills/qa-explore-mobile/phases/07-reporting.md +108 -60
  79. package/skills/qa-explore-mobile/references/mobile-edges.md +26 -26
  80. package/skills/qa-explore-quick/SKILL.md +71 -26
  81. package/skills/qa-explore-report/SKILL.md +65 -35
  82. package/skills/qa-gather/SKILL.md +44 -8
  83. package/skills/qa-knowledge-add/SKILL.md +25 -9
  84. package/skills/qa-knowledge-list/SKILL.md +37 -40
  85. package/skills/qa-target-setup/SKILL.md +63 -41
  86. package/skills/qa-verify-backend/SKILL.md +31 -19
  87. package/skills/qa-verify-backend/phases/00-setup.md +57 -12
  88. package/skills/qa-verify-backend/phases/01-ac-decomposition.md +2 -2
  89. package/skills/qa-verify-backend/phases/02-static-review.md +11 -0
  90. package/skills/qa-verify-backend/phases/03-live-verification.md +5 -3
  91. package/skills/qa-verify-backend/phases/03b-api-verification.md +24 -9
  92. package/skills/qa-verify-backend/phases/04-e2e-trigger.md +18 -2
  93. package/skills/qa-verify-backend/phases/05-reporting.md +72 -12
  94. package/skills/qa-verify-backend/references/api-probes.md +28 -1
  95. package/skills/qa-verify-backend/references/payload-verification.md +1 -1
  96. package/skills/qa-verify-backend/references/release-readiness.md +1 -1
  97. package/skills/qa-verify-backend/references/safety-rules.md +13 -8
  98. package/data/domains/_default.md +0 -181
  99. package/data/domains/ecommerce.md +0 -192
  100. package/data/domains/fintech.md +0 -200
  101. package/data/domains/identity.md +0 -88
  102. package/data/domains/marketing.md +0 -194
  103. package/data/domains/saas.md +0 -197
  104. package/dist/cli/index.d.ts +0 -1
  105. package/dist/cli/index.js.map +0 -1
  106. package/dist/index.js.map +0 -1
package/dist/index.js CHANGED
@@ -17,42 +17,43 @@ var AuthConfigSchema = z.object({
17
17
  credentials: z.object({
18
18
  username: z.string(),
19
19
  password: z.string()
20
- }).optional(),
20
+ }).strict().optional(),
21
21
  token: z.string().optional(),
22
22
  identity_provider: z.string().optional(),
23
23
  // Staging builds sometimes accept a fixed OTP — recorded so the auth phase can
24
24
  // use it instead of waiting for a real code. Never a real credential.
25
25
  static_otp: z.string().optional(),
26
- test_email_pattern: z.string().optional()
27
- });
26
+ test_email_pattern: z.string().optional(),
27
+ notes: z.string().optional()
28
+ }).strict();
28
29
  var BrowserConfigSchema = z.object({
29
30
  headless: z.boolean(),
30
31
  viewport: z.object({
31
32
  width: z.number().int().positive(),
32
33
  height: z.number().int().positive()
33
- }),
34
+ }).strict(),
34
35
  // Optional engine selection + Playwright device descriptor for mobile-web
35
36
  // emulation targets (e.g. engine: webkit, device: "iPhone 15").
36
37
  engine: z.enum(["chromium", "webkit", "firefox"]).optional(),
37
38
  channel: z.string().optional(),
38
39
  device: z.string().optional()
39
- });
40
+ }).strict();
40
41
  var ScopeConfigSchema = z.object({
41
42
  start_pages: z.array(z.string()).optional(),
42
43
  max_depth: z.number().int().min(0),
43
44
  include_patterns: z.array(z.string()).optional(),
44
45
  exclude_patterns: z.array(z.string()).optional()
45
- });
46
+ }).strict();
46
47
  var SafetyConfigSchema = z.object({
47
48
  read_only: z.boolean(),
48
49
  no_form_submit: z.boolean(),
49
50
  no_file_upload: z.boolean().optional(),
50
51
  no_delete_actions: z.boolean().optional()
51
- });
52
+ }).strict();
52
53
  var EnvironmentConfigSchema = z.object({
53
54
  kind: z.enum(["dev", "ephemeral", "staging", "production"]),
54
55
  destroyed_automatically: z.boolean().optional()
55
- });
56
+ }).strict();
56
57
  var BackendConfigSchema = z.object({
57
58
  provider: z.enum(["aws"]).optional(),
58
59
  aws_profile_env: z.string().optional(),
@@ -65,13 +66,17 @@ var BackendConfigSchema = z.object({
65
66
  // Free-form logical name -> deployed resource name (config_table, dlq, ...).
66
67
  resources: z.record(z.string(), z.string()).optional(),
67
68
  notes: z.string().optional()
68
- });
69
+ }).strict();
69
70
  var ApiSurfaceConfigSchema = z.object({
70
71
  // Defaults to the target's base_url when omitted.
71
72
  base_url: z.string().optional(),
72
- auth: z.enum(["session-cookie", "bearer-env", "none"]).optional(),
73
- // NAME of the env var holding a bearer token, for `auth: bearer-env`.
73
+ auth: z.enum(["session-cookie", "bearer-env", "api-key-env", "none"]).optional(),
74
+ // NAME of the env var holding the credential, for `auth: bearer-env` (a bearer
75
+ // token) or `auth: api-key-env` (a static API key sent in its own header).
74
76
  token_env: z.string().optional(),
77
+ // Header carrying the credential for `auth: api-key-env`. Defaults to
78
+ // `X-Api-Key`. The VALUE always comes from `token_env`, never from here.
79
+ header_name: z.string().optional(),
75
80
  // Persistent browser profile directory holding the authenticated session,
76
81
  // e.g. `.auth/my-service-dev-profile`. Gitignored.
77
82
  browser_profile: z.string().optional(),
@@ -81,19 +86,23 @@ var ApiSurfaceConfigSchema = z.object({
81
86
  endpoints: z.record(z.string(), z.string()).optional(),
82
87
  // The ONLY endpoints the read-only API lane may call without asking.
83
88
  probe_allowlist: z.array(z.string()).optional(),
89
+ // The ONLY endpoints phase 4 may call through the real write path, and only in
90
+ // a dev or ephemeral environment. Empty or absent means the API lane is
91
+ // read-only here and every state-changing AC needs a different channel.
92
+ write_allowlist: z.array(z.string()).optional(),
84
93
  // Other target ids to run the same matrix against, for parity comparison.
85
94
  parity_targets: z.array(z.string()).optional(),
86
95
  // Flag name -> where its deployed value is declared for this environment.
87
96
  // A flag can select between two implementations inside one identical build.
88
97
  feature_flags: z.record(z.string(), z.string()).optional(),
89
98
  notes: z.string().optional()
90
- });
99
+ }).strict();
91
100
  var SourceBranchConfigSchema = z.object({
92
101
  repo_path: z.string(),
93
102
  branch: z.string(),
94
103
  base_branch: z.string().optional(),
95
104
  components: z.record(z.string(), z.string()).optional()
96
- });
105
+ }).strict();
97
106
  var WebTargetConfigSchema = z.object({
98
107
  id: z.string().min(1),
99
108
  name: z.string().min(1),
@@ -112,7 +121,7 @@ var WebTargetConfigSchema = z.object({
112
121
  api: ApiSurfaceConfigSchema.optional(),
113
122
  source: SourceBranchConfigSchema.optional(),
114
123
  notes: z.string().optional()
115
- });
124
+ }).strict();
116
125
  var MobileDeviceConfigSchema = z.object({
117
126
  name: z.string().optional(),
118
127
  // iOS simulator name (portable across machines)
@@ -122,7 +131,7 @@ var MobileDeviceConfigSchema = z.object({
122
131
  // Android AVD name
123
132
  serial: z.string().optional()
124
133
  // Android serial once booted (e.g. emulator-5554)
125
- });
134
+ }).strict();
126
135
  var MobileAppConfigSchema = z.object({
127
136
  bundle_id: z.string().optional(),
128
137
  // iOS bundle id (or browser bundle in web mode)
@@ -132,21 +141,21 @@ var MobileAppConfigSchema = z.object({
132
141
  // iOS .app artifact(s) — native mode
133
142
  apk_paths: z.array(z.string()).optional()
134
143
  // Android APK(s) — native mode
135
- });
144
+ }).strict();
136
145
  var MobileWebConfigSchema = z.object({
137
146
  base_url: z.string().url(),
138
147
  start_url: z.string().url().optional()
139
- });
148
+ }).strict();
140
149
  var SourceRepoConfigSchema = z.object({
141
150
  path: z.string(),
142
151
  build_commands: z.record(z.string(), z.string()).optional()
143
- });
152
+ }).strict();
144
153
  var MobileScopeConfigSchema = z.object({
145
154
  start_screen: z.string().optional(),
146
155
  start_url: z.string().optional(),
147
156
  include_patterns: z.array(z.string()).optional(),
148
157
  exclude_patterns: z.array(z.string()).optional()
149
- });
158
+ }).strict();
150
159
  var MobileTargetConfigSchema = z.object({
151
160
  id: z.string().min(1),
152
161
  name: z.string().min(1),
@@ -162,15 +171,22 @@ var MobileTargetConfigSchema = z.object({
162
171
  safety: SafetyConfigSchema.optional(),
163
172
  source_repo: SourceRepoConfigSchema.optional(),
164
173
  notes: z.string().optional()
165
- });
166
- var TargetConfigSchema = z.custom().superRefine((data, ctx) => {
167
- const isMobile = typeof data === "object" && data !== null && "platform" in data;
174
+ }).strict();
175
+ var TargetConfigSchema = z.unknown().transform((data, ctx) => {
176
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
177
+ ctx.addIssue({ code: "custom", message: "Expected a target config object" });
178
+ return z.NEVER;
179
+ }
180
+ const isMobile = "platform" in data;
168
181
  const branch = isMobile ? MobileTargetConfigSchema : WebTargetConfigSchema;
169
182
  const result = branch.safeParse(data);
170
183
  if (!result.success) {
171
- for (const issue of result.error.issues)
184
+ for (const issue of result.error.issues) {
172
185
  ctx.addIssue(issue);
186
+ }
187
+ return z.NEVER;
173
188
  }
189
+ return result.data;
174
190
  });
175
191
 
176
192
  // src/schemas/knowledge-entry.schema.ts
@@ -215,7 +231,10 @@ var KnowledgeManifestEntrySchema = z3.object({
215
231
  var LoadingStrategySchema = z3.object({
216
232
  always: z3.array(z3.string()),
217
233
  by_domain: z3.record(z3.string(), z3.array(z3.string())),
218
- by_tag: z3.record(z3.string(), z3.array(z3.string()))
234
+ by_tag: z3.record(z3.string(), z3.array(z3.string())),
235
+ /** Per-skill selection used by `qualiow kb digest --for <skill>`. Optional so
236
+ * a manifest written before this key still validates. */
237
+ by_skill: z3.record(z3.string(), z3.array(z3.string())).optional()
219
238
  });
220
239
  var KnowledgeManifestSchema = z3.object({
221
240
  version: z3.string().min(1),
@@ -228,22 +247,28 @@ var KnowledgeManifestSchema = z3.object({
228
247
 
229
248
  // src/schemas/domain-config.schema.ts
230
249
  import { z as z4 } from "zod";
250
+ var RiskRankingSchema = z4.object({
251
+ p0: z4.array(z4.string()).min(1),
252
+ p1: z4.array(z4.string()).min(1),
253
+ p2: z4.array(z4.string()).min(1),
254
+ p3: z4.array(z4.string()).min(1)
255
+ }).strict();
231
256
  var JourneySchema = z4.object({
232
- id: z4.string().min(1),
233
257
  name: z4.string().min(1),
234
- description: z4.string().min(1),
235
- steps: z4.array(z4.string()).min(1),
236
- risk: z4.enum(["high", "medium", "low"])
237
- });
258
+ steps: z4.array(z4.string()).min(1)
259
+ }).strict();
238
260
  var DomainConfigSchema = z4.object({
239
261
  id: z4.string().min(1),
240
262
  name: z4.string().min(1),
241
- risk_ranking: z4.array(z4.string()).min(1),
263
+ risk_ranking: RiskRankingSchema,
242
264
  completeness_checklist: z4.array(z4.string()).min(1),
243
265
  data_integrity_checks: z4.array(z4.string()).min(1),
244
266
  journeys: z4.array(JourneySchema).min(1),
245
- guidance: z4.array(z4.string()).min(1)
246
- });
267
+ must_test_patterns: z4.record(z4.string(), z4.array(z4.string())),
268
+ common_bugs: z4.array(z4.string()).min(1),
269
+ compliance: z4.array(z4.string()).min(1),
270
+ guidance: z4.string().min(1)
271
+ }).strict();
247
272
 
248
273
  // src/schemas/session-metrics.schema.ts
249
274
  import { z as z5 } from "zod";
@@ -260,35 +285,138 @@ var SessionMetricsSchema = z5.object({
260
285
  duration_min: z5.number().min(0),
261
286
  bugs_found: z5.number().int().min(0),
262
287
  severity_counts: SeverityCountsSchema,
263
- pages_explored: z5.number().int().min(0)
288
+ pages_explored: z5.number().int().min(0),
289
+ // Optional context.
290
+ kind: z5.enum(["explore", "quick", "mobile", "backend"]).optional(),
291
+ domain: z5.string().optional(),
292
+ started_at: z5.string().optional(),
293
+ completed_at: z5.string().optional(),
294
+ phases_completed: z5.number().int().min(0).optional(),
295
+ total_phases: z5.number().int().min(0).optional(),
296
+ coverage: z5.record(z5.string(), z5.unknown()).optional(),
297
+ evidence: z5.record(z5.string(), z5.unknown()).optional(),
298
+ areas_not_tested: z5.array(z5.string()).optional(),
299
+ blocked_by: z5.string().nullable().optional()
264
300
  });
265
301
 
302
+ // src/schemas/knowledge-release.schema.ts
303
+ import { z as z6 } from "zod";
304
+ var KnowledgeReleaseSchema = z6.object({
305
+ version: z6.string().min(1),
306
+ date: z6.string().min(1),
307
+ author: z6.string().min(1),
308
+ status: z6.enum(["active", "deprecated"]),
309
+ notes: z6.string().min(1),
310
+ entry_count: z6.number().int().min(0),
311
+ entries: z6.array(z6.string().min(1)).min(1)
312
+ }).strict().refine((r) => r.entry_count === r.entries.length, {
313
+ message: "entry_count must equal the number of listed entries",
314
+ path: ["entry_count"]
315
+ });
316
+
317
+ // src/schemas/knowledge-changelog.schema.ts
318
+ import { z as z7 } from "zod";
319
+ var ChangelogEntrySchema = z7.object({
320
+ id: z7.string().min(1),
321
+ type: z7.enum(["heuristic", "technique", "checklist", "reference"]),
322
+ name: z7.string().min(1),
323
+ description: z7.string().min(1)
324
+ }).strict();
325
+ var ChangelogReleaseSchema = z7.object({
326
+ version: z7.string().min(1),
327
+ date: z7.string().min(1),
328
+ summary: z7.string().min(1),
329
+ entries_added: z7.array(ChangelogEntrySchema),
330
+ entries_modified: z7.array(z7.string()).default([]),
331
+ entries_removed: z7.array(z7.string()).default([]),
332
+ origin: z7.string().optional()
333
+ }).strict();
334
+ var KnowledgeChangelogSchema = z7.object({
335
+ releases: z7.array(ChangelogReleaseSchema).min(1)
336
+ }).strict();
337
+
266
338
  // src/utils/redact.ts
267
- var REDACTION_PATTERNS = [
339
+ var EMAIL_ALLOW = /(?:@|\.)(?:example\.(?:com|org|net)|localhost)$/i;
340
+ function luhnValid(digits) {
341
+ let sum = 0;
342
+ let alt = false;
343
+ for (let i = digits.length - 1; i >= 0; i--) {
344
+ let d = digits.charCodeAt(i) - 48;
345
+ if (d < 0 || d > 9) return false;
346
+ if (alt) {
347
+ d *= 2;
348
+ if (d > 9) d -= 9;
349
+ }
350
+ sum += d;
351
+ alt = !alt;
352
+ }
353
+ return sum % 10 === 0;
354
+ }
355
+ var RULES = [
356
+ {
357
+ name: "Private key",
358
+ pattern: /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/g,
359
+ replacement: "[PRIVATE_KEY_REDACTED]"
360
+ },
361
+ {
362
+ name: "JWT",
363
+ pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,
364
+ replacement: "[JWT_REDACTED]"
365
+ },
366
+ {
367
+ name: "Authorization header",
368
+ pattern: /(authorization)(\s*[:=]\s*)(\S[^\n\r]*)/gi,
369
+ replace: (m, k, sep, value) => /_REDACTED\]/.test(value) ? m : `${k}${sep}[REDACTED]`
370
+ },
371
+ {
372
+ name: "Cookie header",
373
+ pattern: /^(set-cookie|cookie)(\s*:\s*).+$/gim,
374
+ replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
375
+ },
376
+ {
377
+ name: "AWS access key id",
378
+ pattern: /\b(?:AKIA|ASIA|AROA|AIDA)[0-9A-Z]{16}\b/g,
379
+ replacement: "[AWS_KEY_REDACTED]"
380
+ },
381
+ {
382
+ name: "AWS secret access key",
383
+ pattern: /(aws_secret_access_key)(\s*[:=]\s*)\S+/gi,
384
+ replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
385
+ },
386
+ {
387
+ name: "OpenAI-style key",
388
+ pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,
389
+ replacement: "[SK_KEY_REDACTED]"
390
+ },
391
+ {
392
+ name: "GitHub token",
393
+ pattern: /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g,
394
+ replacement: "[GITHUB_TOKEN_REDACTED]"
395
+ },
268
396
  {
269
- name: "JWT token",
270
- pattern: /Bearer\s+eyJ[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/g,
271
- replacement: "Bearer [JWT_REDACTED]"
397
+ name: "Slack token",
398
+ pattern: /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g,
399
+ replacement: "[SLACK_TOKEN_REDACTED]"
272
400
  },
273
401
  {
274
402
  name: "API key",
275
- pattern: /api[_\-]?key[=:\s]+[A-Za-z0-9\-_]{16,}/gi,
276
- replacement: "api_key=[API_KEY_REDACTED]"
403
+ pattern: /(x-api-key|api[_-]?key)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
404
+ replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
277
405
  },
278
406
  {
279
407
  name: "Password",
280
- pattern: /password[=:\s]+[^\s,}"']+/gi,
281
- replacement: "password=[REDACTED]"
408
+ pattern: /(password|passwd|pwd)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
409
+ replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
282
410
  },
283
411
  {
284
412
  name: "Token",
285
- pattern: /token[=:\s]+[A-Za-z0-9\-_]{16,}/gi,
286
- replacement: "token=[TOKEN_REDACTED]"
413
+ pattern: /(access[_-]?token|refresh[_-]?token|token)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
414
+ replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
287
415
  },
288
416
  {
289
417
  name: "Secret",
290
- pattern: /secret[=:\s]+[^\s,}"']+/gi,
291
- replacement: "secret=[REDACTED]"
418
+ pattern: /([a-z_]*secret)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
419
+ replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
292
420
  },
293
421
  {
294
422
  name: "SSN",
@@ -297,44 +425,146 @@ var REDACTION_PATTERNS = [
297
425
  },
298
426
  {
299
427
  name: "Credit card number",
300
- pattern: /\b\d{13,19}\b/g,
301
- replacement: "[CARD_NUMBER_REDACTED]"
428
+ pattern: /\b\d(?:[ -]?\d){12,18}\b/g,
429
+ replace: (match) => {
430
+ const digits = match.replace(/\D/g, "");
431
+ if (digits.length < 13 || digits.length > 19) return match;
432
+ if (!/^[3-6]/.test(digits)) return match;
433
+ return luhnValid(digits) ? "[CARD_NUMBER_REDACTED]" : match;
434
+ }
302
435
  }
303
436
  ];
304
- function redact(text) {
305
- const redactions = [];
437
+ function redact(text, opts = {}) {
438
+ const redactions = /* @__PURE__ */ new Set();
306
439
  let result = text;
307
- for (const { name, pattern, replacement } of REDACTION_PATTERNS) {
308
- pattern.lastIndex = 0;
309
- if (pattern.test(result)) {
310
- redactions.push(name);
311
- pattern.lastIndex = 0;
312
- result = result.replace(pattern, replacement);
313
- }
440
+ const rules = RULES.slice();
441
+ if (opts.emails !== false) {
442
+ rules.push({
443
+ name: "Email",
444
+ pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
445
+ replace: (match) => EMAIL_ALLOW.test(match) ? match : "[EMAIL_REDACTED]"
446
+ });
447
+ }
448
+ for (const rule of rules) {
449
+ rule.pattern.lastIndex = 0;
450
+ let fired = false;
451
+ result = result.replace(rule.pattern, (...args) => {
452
+ const match = args[0];
453
+ const groups = args.slice(1, -2);
454
+ const out = rule.replace ? rule.replace(match, ...groups) : rule.replacement;
455
+ if (out !== match) fired = true;
456
+ return out;
457
+ });
458
+ if (fired) redactions.add(rule.name);
314
459
  }
315
- return { text: result, redactions };
460
+ return { text: result, redactions: [...redactions] };
316
461
  }
317
462
  function containsSecrets(text) {
318
- for (const { pattern } of REDACTION_PATTERNS) {
319
- pattern.lastIndex = 0;
320
- if (pattern.test(text)) {
321
- return true;
322
- }
323
- }
324
- return false;
463
+ return redact(text).redactions.length > 0;
325
464
  }
465
+ var REDACTION_CATEGORIES = RULES.map((r) => r.name).concat("Email");
326
466
 
327
467
  // src/utils/validate.ts
328
- import { readFileSync } from "fs";
329
- import { resolve, join } from "path";
330
- import { parse as parseYaml } from "yaml";
468
+ import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
469
+ import { resolve, join as join2, basename as basename2 } from "path";
470
+ import { parse as parseYaml2 } from "yaml";
331
471
  import { ZodError } from "zod";
472
+
473
+ // src/utils/kb-sync.ts
474
+ import { readFileSync, writeFileSync, existsSync, readdirSync } from "fs";
475
+ import { join, relative, basename } from "path";
476
+ import { parse as parseYaml, parseDocument } from "yaml";
332
477
  import { globSync } from "glob";
478
+ var TYPE_TO_STAT = {
479
+ heuristic: "heuristics",
480
+ technique: "techniques",
481
+ checklist: "checklists",
482
+ reference: "references"
483
+ };
484
+ function listReleaseDirs(knowledgeDir) {
485
+ const releasesDir = join(knowledgeDir, "releases");
486
+ if (!existsSync(releasesDir)) return [];
487
+ return readdirSync(releasesDir, { withFileTypes: true }).filter((d) => d.isDirectory() && /^v\d+\.\d+\.\d+$/.test(d.name)).map((d) => d.name).sort(compareVersions);
488
+ }
489
+ function compareVersions(a, b) {
490
+ const pa = a.replace(/^v/, "").split(".").map(Number);
491
+ const pb = b.replace(/^v/, "").split(".").map(Number);
492
+ for (let i = 0; i < 3; i++) {
493
+ if (pa[i] !== pb[i]) return pa[i] - pb[i];
494
+ }
495
+ return 0;
496
+ }
497
+ function buildManifestRegistry(dataDir) {
498
+ const knowledgeDir = join(dataDir, "knowledge");
499
+ const registry = [];
500
+ for (const rel of listReleaseDirs(knowledgeDir)) {
501
+ const files = globSync(join(knowledgeDir, "releases", rel, "entries", "*.yml")).sort();
502
+ for (const file of files) {
503
+ const entry = parseYaml(readFileSync(file, "utf-8"));
504
+ registry.push({
505
+ id: entry.id,
506
+ file: relative(knowledgeDir, file).split("\\").join("/"),
507
+ type: entry.type,
508
+ priority: entry.priority,
509
+ tags: entry.tags,
510
+ domains: entry.domains
511
+ });
512
+ }
513
+ }
514
+ return registry;
515
+ }
516
+ function computeStats(dataDir, registry) {
517
+ const stats = {
518
+ total_entries: registry.length,
519
+ heuristics: 0,
520
+ techniques: 0,
521
+ checklists: 0,
522
+ references: 0,
523
+ domain_profiles: 0,
524
+ custom_entries: 0
525
+ };
526
+ for (const e of registry) {
527
+ const key = TYPE_TO_STAT[e.type];
528
+ if (key) stats[key]++;
529
+ }
530
+ const domainsDir = join(dataDir, "domains");
531
+ if (existsSync(domainsDir)) {
532
+ stats.domain_profiles = readdirSync(domainsDir).filter(
533
+ (f) => f.endsWith(".yml")
534
+ ).length;
535
+ }
536
+ const customDir = join(dataDir, "knowledge", "custom");
537
+ if (existsSync(customDir)) {
538
+ stats.custom_entries = readdirSync(customDir).filter(
539
+ (f) => f.endsWith(".yml")
540
+ ).length;
541
+ }
542
+ return stats;
543
+ }
544
+ function syncKnowledgeManifest(dataDir, opts = {}) {
545
+ const manifestPath = join(dataDir, "knowledge", "manifest.yml");
546
+ const raw = readFileSync(manifestPath, "utf-8");
547
+ const doc = parseDocument(raw);
548
+ const registry = buildManifestRegistry(dataDir);
549
+ const stats = computeStats(dataDir, registry);
550
+ const current = parseYaml(raw);
551
+ const inSync = JSON.stringify(current.entries) === JSON.stringify(registry) && JSON.stringify(current.stats) === JSON.stringify(stats);
552
+ if (!opts.check && !inSync) {
553
+ doc.set("stats", stats);
554
+ doc.set("entries", registry);
555
+ doc.set("last_updated", (/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
556
+ writeFileSync(manifestPath, doc.toString(), "utf-8");
557
+ }
558
+ return { changed: !inSync, stats, entryCount: registry.length };
559
+ }
560
+
561
+ // src/utils/validate.ts
562
+ import { globSync as globSync2 } from "glob";
333
563
  function validateYamlFile(filePath, schema) {
334
564
  const absPath = resolve(filePath);
335
565
  try {
336
- const raw = readFileSync(absPath, "utf-8");
337
- const data = parseYaml(raw);
566
+ const raw = readFileSync2(absPath, "utf-8");
567
+ const data = parseYaml2(raw);
338
568
  schema.parse(data);
339
569
  return { file: absPath, valid: true };
340
570
  } catch (err) {
@@ -360,68 +590,447 @@ function validateYamlFile(filePath, schema) {
360
590
  };
361
591
  }
362
592
  }
593
+ function validateWithId(filePath, schema) {
594
+ const result = validateYamlFile(filePath, schema);
595
+ if (!result.valid) return result;
596
+ try {
597
+ const data = parseYaml2(readFileSync2(filePath, "utf-8"));
598
+ const stem = basename2(filePath, ".yml");
599
+ if (data.id !== stem) {
600
+ return {
601
+ file: resolve(filePath),
602
+ valid: false,
603
+ errors: [
604
+ {
605
+ path: "id",
606
+ message: `id "${data.id}" must equal the file name "${stem}"`
607
+ }
608
+ ]
609
+ };
610
+ }
611
+ } catch {
612
+ }
613
+ return result;
614
+ }
363
615
  function validateTargetConfig(filePath) {
364
- return validateYamlFile(filePath, TargetConfigSchema);
616
+ return validateWithId(filePath, TargetConfigSchema);
365
617
  }
366
618
  function validateKnowledgeEntry(filePath) {
367
619
  return validateYamlFile(filePath, KnowledgeEntrySchema);
368
620
  }
369
621
  function validateDomainConfig(filePath) {
370
- return validateYamlFile(filePath, DomainConfigSchema);
622
+ return validateWithId(filePath, DomainConfigSchema);
623
+ }
624
+ function validateKnowledgeBase(dataDir) {
625
+ const results = [];
626
+ const knowledgeDir = resolve(dataDir, "knowledge");
627
+ const manifestPath = join2(knowledgeDir, "manifest.yml");
628
+ const changelogPath = join2(knowledgeDir, "changelog.yml");
629
+ results.push(validateYamlFile(manifestPath, KnowledgeManifestSchema));
630
+ results.push(validateYamlFile(changelogPath, KnowledgeChangelogSchema));
631
+ const releaseDirs = listReleaseDirs(knowledgeDir);
632
+ for (const rel of releaseDirs) {
633
+ const releasePath = join2(knowledgeDir, "releases", rel, "release.yml");
634
+ const schemaResult = validateYamlFile(releasePath, KnowledgeReleaseSchema);
635
+ const errors = schemaResult.errors ?? [];
636
+ if (schemaResult.valid || errors.length === 0) {
637
+ try {
638
+ const release = parseYaml2(readFileSync2(releasePath, "utf-8"));
639
+ if (`v${release.version}` !== rel) {
640
+ errors.push({
641
+ path: "version",
642
+ message: `version "${release.version}" does not match directory "${rel}"`
643
+ });
644
+ }
645
+ const entryDir = join2(knowledgeDir, "releases", rel, "entries");
646
+ const filesOnDisk = existsSync2(entryDir) ? globSync2(join2(entryDir, "*.yml")).map((f) => basename2(f, ".yml")) : [];
647
+ for (const id of release.entries) {
648
+ if (!filesOnDisk.includes(id)) {
649
+ errors.push({ path: "entries", message: `declared entry "${id}" has no file` });
650
+ }
651
+ }
652
+ for (const id of filesOnDisk) {
653
+ if (!release.entries.includes(id)) {
654
+ errors.push({ path: "entries", message: `entry file "${id}" is not declared` });
655
+ }
656
+ }
657
+ } catch {
658
+ }
659
+ }
660
+ results.push(
661
+ errors.length ? { file: resolve(releasePath), valid: false, errors } : { file: resolve(releasePath), valid: true }
662
+ );
663
+ }
664
+ const crossErrors = [];
665
+ try {
666
+ const manifest = parseYaml2(readFileSync2(manifestPath, "utf-8"));
667
+ const registry = buildManifestRegistry(dataDir);
668
+ const stats = computeStats(dataDir, registry);
669
+ const registryIds = new Set(registry.map((e) => e.id));
670
+ if (JSON.stringify(manifest.entries) !== JSON.stringify(registry)) {
671
+ crossErrors.push({
672
+ path: "entries",
673
+ message: "registry is out of sync with the entry files (run `qualiow kb sync`)"
674
+ });
675
+ }
676
+ if (JSON.stringify(manifest.stats) !== JSON.stringify(stats)) {
677
+ crossErrors.push({
678
+ path: "stats",
679
+ message: `stats out of sync (expected total_entries ${stats.total_entries})`
680
+ });
681
+ }
682
+ const activeExpected = [...listReleaseDirs(knowledgeDir)].sort();
683
+ if (JSON.stringify([...manifest.active_releases].sort()) !== JSON.stringify(activeExpected)) {
684
+ crossErrors.push({ path: "active_releases", message: "does not match the release directories" });
685
+ }
686
+ const ls = manifest.loading_strategy;
687
+ const allRefs = [
688
+ ...ls.always,
689
+ ...Object.values(ls.by_domain).flat(),
690
+ ...Object.values(ls.by_tag).flat(),
691
+ ...Object.values(ls.by_skill ?? {}).flat()
692
+ ];
693
+ for (const id of allRefs) {
694
+ if (!registryIds.has(id)) {
695
+ crossErrors.push({ path: "loading_strategy", message: `references unknown entry "${id}"` });
696
+ }
697
+ }
698
+ const changelog = parseYaml2(readFileSync2(changelogPath, "utf-8"));
699
+ for (const r of changelog.releases) {
700
+ for (const e of r.entries_added) {
701
+ if (!registryIds.has(e.id)) {
702
+ crossErrors.push({ path: "changelog", message: `entry "${e.id}" is not in the registry` });
703
+ }
704
+ }
705
+ }
706
+ } catch (err) {
707
+ crossErrors.push({
708
+ path: "",
709
+ message: err instanceof Error ? err.message : "cross-check failed"
710
+ });
711
+ }
712
+ results.push(
713
+ crossErrors.length ? { file: join2(knowledgeDir, "(cross-check)"), valid: false, errors: crossErrors } : { file: join2(knowledgeDir, "(cross-check)"), valid: true }
714
+ );
715
+ return results;
371
716
  }
372
- function validateAllConfigs(dataDir) {
717
+ function validateAllConfigs(dataDir, opts = {}) {
373
718
  const results = [];
374
719
  const absDir = resolve(dataDir);
375
- const targetFiles = globSync(join(absDir, "targets", "*.yml"));
376
- for (const file of targetFiles) {
720
+ for (const file of globSync2(join2(absDir, "targets", "*.yml"))) {
377
721
  results.push(validateTargetConfig(file));
378
722
  }
379
- const entryFiles = globSync(
380
- join(absDir, "knowledge", "releases", "**", "entries", "*.yml")
381
- );
382
- for (const file of entryFiles) {
723
+ if (opts.cwd) {
724
+ const projectTarget = join2(opts.cwd, "qa", "target.yml");
725
+ if (existsSync2(projectTarget)) {
726
+ results.push(validateYamlFile(projectTarget, TargetConfigSchema));
727
+ }
728
+ }
729
+ for (const file of globSync2(join2(absDir, "domains", "*.yml"))) {
730
+ results.push(validateDomainConfig(file));
731
+ }
732
+ for (const file of globSync2(
733
+ join2(absDir, "knowledge", "releases", "**", "entries", "*.yml")
734
+ )) {
383
735
  results.push(validateKnowledgeEntry(file));
384
736
  }
737
+ if (existsSync2(join2(absDir, "knowledge", "manifest.yml"))) {
738
+ results.push(...validateKnowledgeBase(absDir));
739
+ }
385
740
  return results;
386
741
  }
387
742
 
388
743
  // src/utils/metrics.ts
389
- import { readFileSync as readFileSync2, appendFileSync, existsSync, mkdirSync } from "fs";
390
- import { join as join2, dirname } from "path";
744
+ import { readFileSync as readFileSync3, appendFileSync, existsSync as existsSync3, mkdirSync } from "fs";
745
+ import { join as join3, dirname } from "path";
391
746
  var METRICS_FILENAME = "metrics.jsonl";
392
747
  function appendSessionMetrics(outputDir, metrics) {
393
748
  SessionMetricsSchema.parse(metrics);
394
- const filePath = join2(outputDir, METRICS_FILENAME);
749
+ const filePath = join3(outputDir, METRICS_FILENAME);
395
750
  const dir = dirname(filePath);
396
- if (!existsSync(dir)) {
751
+ if (!existsSync3(dir)) {
397
752
  mkdirSync(dir, { recursive: true });
398
753
  }
399
754
  const line = JSON.stringify(metrics) + "\n";
400
755
  appendFileSync(filePath, line, "utf-8");
401
756
  }
402
757
  function readAllMetrics(outputDir) {
403
- const filePath = join2(outputDir, METRICS_FILENAME);
404
- if (!existsSync(filePath)) {
758
+ const filePath = join3(outputDir, METRICS_FILENAME);
759
+ if (!existsSync3(filePath)) {
405
760
  return [];
406
761
  }
407
- const content = readFileSync2(filePath, "utf-8").trim();
762
+ const content = readFileSync3(filePath, "utf-8").trim();
408
763
  if (!content) {
409
764
  return [];
410
765
  }
411
766
  const lines = content.split("\n");
412
767
  const results = [];
413
768
  for (const line of lines) {
414
- if (line.trim()) {
415
- const parsed = JSON.parse(line);
416
- results.push(SessionMetricsSchema.parse(parsed));
769
+ if (!line.trim()) continue;
770
+ let parsed;
771
+ try {
772
+ parsed = JSON.parse(line);
773
+ } catch {
774
+ continue;
417
775
  }
776
+ const result = SessionMetricsSchema.safeParse(parsed);
777
+ if (result.success) results.push(result.data);
418
778
  }
419
779
  return results;
420
780
  }
781
+ function appendSessionMetricsDeduped(outputDir, metrics) {
782
+ const existing = readAllMetrics(outputDir);
783
+ if (existing.some((m) => m.session_id === metrics.session_id)) {
784
+ return false;
785
+ }
786
+ appendSessionMetrics(outputDir, metrics);
787
+ return true;
788
+ }
789
+
790
+ // src/utils/session-dir.ts
791
+ var SESSION_KINDS = ["explore", "quick", "mobile", "backend"];
792
+ var SESSION_DIR_RE = /^(\d{4}-\d{2}-\d{2}-\d{4})-(explore|quick|mobile|backend)-([a-z0-9][a-z0-9-]*)$/;
793
+ function slugify(input) {
794
+ let s = (input ?? "").trim();
795
+ try {
796
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) {
797
+ s = new URL(s).hostname;
798
+ }
799
+ } catch {
800
+ }
801
+ s = s.toLowerCase().replace(/^_+/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/g, "");
802
+ return s || "session";
803
+ }
804
+ function pad(n) {
805
+ return String(n).padStart(2, "0");
806
+ }
807
+ function sessionTimestamp(date = /* @__PURE__ */ new Date()) {
808
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}`;
809
+ }
810
+ function sessionDirName(kind, target, date = /* @__PURE__ */ new Date()) {
811
+ return `${sessionTimestamp(date)}-${kind}-${slugify(target)}`;
812
+ }
813
+ function parseSessionDirName(name) {
814
+ const m = SESSION_DIR_RE.exec(name);
815
+ if (!m) return null;
816
+ return { timestamp: m[1], kind: m[2], slug: m[3] };
817
+ }
818
+
819
+ // src/utils/markdown-table.ts
820
+ function splitRow(line) {
821
+ const cells = line.split("|").map((c) => c.trim());
822
+ if (cells.length && cells[0] === "") cells.shift();
823
+ if (cells.length && cells[cells.length - 1] === "") cells.pop();
824
+ return cells;
825
+ }
826
+ function isSeparator(line) {
827
+ return /^\s*\|?\s*:?-{2,}/.test(line) && /-\s*\|/.test(line + "|");
828
+ }
829
+ function parseMarkdownTable(md, opts = {}) {
830
+ const lines = md.split("\n");
831
+ let start = 0;
832
+ if (opts.headingPrefix) {
833
+ const prefix = opts.headingPrefix.toLowerCase();
834
+ let found = -1;
835
+ for (let i = 0; i < lines.length; i++) {
836
+ const h = lines[i].match(/^#{1,6}\s+(.*)$/);
837
+ if (h && h[1].trim().toLowerCase().startsWith(prefix)) {
838
+ found = i + 1;
839
+ break;
840
+ }
841
+ }
842
+ if (found === -1) return null;
843
+ start = found;
844
+ }
845
+ let headerIdx = -1;
846
+ for (let i = start; i < lines.length - 1; i++) {
847
+ const line = lines[i];
848
+ if (line.includes("|") && isSeparator(lines[i + 1])) {
849
+ headerIdx = i;
850
+ break;
851
+ }
852
+ if (opts.headingPrefix && /^#{1,6}\s/.test(line) && i > start) {
853
+ return null;
854
+ }
855
+ }
856
+ if (headerIdx === -1) return null;
857
+ const headers = splitRow(lines[headerIdx]);
858
+ const keys = headers.map((h) => h.toLowerCase());
859
+ const rows = [];
860
+ for (let i = headerIdx + 2; i < lines.length; i++) {
861
+ const line = lines[i];
862
+ if (!line.includes("|")) break;
863
+ if (isSeparator(line)) continue;
864
+ const cells = splitRow(line);
865
+ if (cells.every((c) => c === "")) continue;
866
+ const row = {};
867
+ keys.forEach((k, idx) => {
868
+ row[k] = cells[idx] ?? "";
869
+ });
870
+ rows.push(row);
871
+ }
872
+ return { headers, rows };
873
+ }
874
+
875
+ // src/utils/confidentiality.ts
876
+ var CONFIDENTIALITY_LINES = [
877
+ "CONFIDENTIAL: This report may contain internal URLs, security vulnerabilities,",
878
+ "and application details. Do not share outside your organization without review."
879
+ ];
880
+ var CONFIDENTIALITY_HEADER_MD = CONFIDENTIALITY_LINES.map(
881
+ (l) => `> ${l}`
882
+ ).join("\n");
883
+ var CONFIDENTIALITY_NOTICE = CONFIDENTIALITY_LINES.join(" ");
884
+ function hasConfidentialityHeader(text) {
885
+ return /CONFIDENTIAL:\s*This report may contain internal URLs/i.test(
886
+ text.slice(0, 400)
887
+ );
888
+ }
889
+
890
+ // src/utils/index-files.ts
891
+ var INDEX_COLUMNS = [
892
+ "Date",
893
+ "Kind",
894
+ "Target",
895
+ "Bugs",
896
+ "Duration",
897
+ "Status",
898
+ "Report"
899
+ ];
900
+ var ALL_BUGS_COLUMNS = [
901
+ "ID",
902
+ "Session",
903
+ "Title",
904
+ "Severity",
905
+ "Status",
906
+ "Report"
907
+ ];
908
+ function table(title, note, columns) {
909
+ const header = `| ${columns.join(" | ")} |`;
910
+ const sep = `|${columns.map(() => "---").join("|")}|`;
911
+ return `# ${title}
912
+
913
+ ${note}
914
+
915
+ ${header}
916
+ ${sep}
917
+ `;
918
+ }
919
+ var INDEX_MD_HEADER = table(
920
+ "Exploratory Testing Sessions",
921
+ "_Index of exploratory testing sessions. Newest last._",
922
+ INDEX_COLUMNS
923
+ );
924
+ var ALL_BUGS_MD_HEADER = table(
925
+ "All Bugs Found",
926
+ "_Consolidated index across all exploratory testing sessions._",
927
+ ALL_BUGS_COLUMNS
928
+ );
929
+
930
+ // src/utils/gitignore.ts
931
+ var QUALIOW_GITIGNORE_HEADER = "# Qualiow";
932
+ var QUALIOW_GITIGNORE_ENTRIES = [
933
+ ".auth/",
934
+ ".env",
935
+ "qa/.env",
936
+ "output/sessions/*/",
937
+ "!output/sessions/INDEX.md",
938
+ "output/context/*.md",
939
+ "data/targets/local-*.yml",
940
+ ".playwright-cli/",
941
+ "*.trace.zip",
942
+ "*.webm"
943
+ ];
944
+ function mergeGitignore(existing) {
945
+ const existingLines = new Set(
946
+ existing.split("\n").map((l) => l.replace(/\s+$/, ""))
947
+ );
948
+ const missing = QUALIOW_GITIGNORE_ENTRIES.filter(
949
+ (e) => !existingLines.has(e)
950
+ );
951
+ if (missing.length === 0) return null;
952
+ const block = [];
953
+ if (!existingLines.has(QUALIOW_GITIGNORE_HEADER)) {
954
+ block.push(QUALIOW_GITIGNORE_HEADER);
955
+ }
956
+ block.push(...missing);
957
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
958
+ const leadingBlank = existing.length > 0 ? "\n" : "";
959
+ return existing + prefix + leadingBlank + block.join("\n") + "\n";
960
+ }
961
+
962
+ // src/utils/paths.ts
963
+ import { fileURLToPath } from "url";
964
+ import { dirname as dirname2, resolve as resolve2, join as join4, basename as basename3 } from "path";
965
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
966
+ var HERE = dirname2(fileURLToPath(import.meta.url));
967
+ function getPackageRoot() {
968
+ let current = HERE;
969
+ for (let i = 0; i < 10; i++) {
970
+ if (existsSync4(join4(current, "data")) && existsSync4(join4(current, "package.json"))) {
971
+ return current;
972
+ }
973
+ const parent = dirname2(current);
974
+ if (parent === current) break;
975
+ current = parent;
976
+ }
977
+ return resolve2(HERE, "..", "..");
978
+ }
979
+ function getPackageVersion(pkgRoot = getPackageRoot()) {
980
+ try {
981
+ const pkg = JSON.parse(
982
+ readFileSync4(join4(pkgRoot, "package.json"), "utf-8")
983
+ );
984
+ return pkg.version ?? "0.0.0";
985
+ } catch {
986
+ return "0.0.0";
987
+ }
988
+ }
989
+ function resolveSkillsSource(pkgRoot) {
990
+ const shipped = join4(pkgRoot, "skills");
991
+ if (existsSync4(shipped)) return shipped;
992
+ const canonical = join4(pkgRoot, ".claude", "skills");
993
+ if (existsSync4(canonical)) return canonical;
994
+ return null;
995
+ }
996
+ function resolveTargetPath(cwd, name, pkgRoot = getPackageRoot()) {
997
+ if (name) {
998
+ const candidates = [
999
+ resolve2(cwd, "data", "targets", `${name}.yml`),
1000
+ resolve2(pkgRoot, "data", "targets", `${name}.yml`)
1001
+ ];
1002
+ return candidates.find((p) => existsSync4(p)) ?? candidates[0];
1003
+ }
1004
+ const projectLocal = resolve2(cwd, "qa", "target.yml");
1005
+ if (existsSync4(projectLocal)) return projectLocal;
1006
+ const cwdDefault = resolve2(cwd, "data", "targets", "_default.yml");
1007
+ if (existsSync4(cwdDefault)) return cwdDefault;
1008
+ return resolve2(pkgRoot, "data", "targets", "_default.yml");
1009
+ }
1010
+ function resolveDataDir(cwd, explicit, pkgRoot = getPackageRoot()) {
1011
+ if (explicit) return resolve2(cwd, explicit);
1012
+ const projectLocal = resolve2(cwd, "data");
1013
+ if (existsSync4(join4(projectLocal, "knowledge", "manifest.yml"))) {
1014
+ return projectLocal;
1015
+ }
1016
+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
1017
+ if (pluginRoot) {
1018
+ const pluginData = resolve2(pluginRoot, "data");
1019
+ if (existsSync4(pluginData)) return pluginData;
1020
+ }
1021
+ return resolve2(pkgRoot, "data");
1022
+ }
1023
+ function resolveDomainPath(dataDir, id) {
1024
+ const direct = join4(dataDir, "domains", `${id}.yml`);
1025
+ if (existsSync4(direct)) return direct;
1026
+ const underscored = join4(dataDir, "domains", `_${id}.yml`);
1027
+ if (existsSync4(underscored)) return underscored;
1028
+ return direct;
1029
+ }
421
1030
 
422
1031
  // src/utils/parse-session.ts
423
- import { readFileSync as readFileSync3, readdirSync, existsSync as existsSync2 } from "fs";
424
- import { join as join3, basename } from "path";
1032
+ import { readFileSync as readFileSync5, readdirSync as readdirSync2, existsSync as existsSync5 } from "fs";
1033
+ import { join as join5, basename as basename4 } from "path";
425
1034
  var SEVERITY_ORDER = {
426
1035
  critical: 0,
427
1036
  high: 1,
@@ -475,33 +1084,48 @@ function extractNumberedList(text) {
475
1084
  }
476
1085
  return steps;
477
1086
  }
1087
+ function cleanValue(v) {
1088
+ return v.trim().replace(/^`|`$/g, "").trim();
1089
+ }
478
1090
  function extractEvidence(content) {
479
- const screenshots = [];
480
- const console_errors = [];
1091
+ const evidence = {
1092
+ screenshots: [],
1093
+ videos: [],
1094
+ logs: [],
1095
+ console_errors: [],
1096
+ network_failures: []
1097
+ };
481
1098
  const evidenceText = extractSection(content, "Evidence");
482
- if (!evidenceText) {
483
- return { screenshots, console_errors };
484
- }
1099
+ if (!evidenceText) return evidence;
485
1100
  for (const line of evidenceText.split("\n")) {
486
1101
  const trimmed = line.replace(/^[-*]\s*/, "").trim();
487
- if (/screenshot/i.test(trimmed)) {
488
- const pathMatch = trimmed.match(/:\s*(.+)/);
489
- if (pathMatch) {
490
- screenshots.push(pathMatch[1].trim());
491
- }
492
- }
493
- if (/console\s*(error|log)/i.test(trimmed)) {
494
- const msgMatch = trimmed.match(/:\s*(.+)/);
495
- if (msgMatch && !/none/i.test(msgMatch[1])) {
496
- console_errors.push(msgMatch[1].trim());
497
- }
1102
+ const value = () => {
1103
+ const m = trimmed.match(/:\s*(.+)/);
1104
+ return m ? cleanValue(m[1]) : "";
1105
+ };
1106
+ const nonEmpty = (v) => v && !/^none\b/i.test(v);
1107
+ if (/^screenshot/i.test(trimmed)) {
1108
+ const v = value();
1109
+ if (nonEmpty(v)) evidence.screenshots.push(v);
1110
+ } else if (/^video/i.test(trimmed)) {
1111
+ const v = value();
1112
+ if (nonEmpty(v)) evidence.videos.push(v);
1113
+ } else if (/^log\b/i.test(trimmed)) {
1114
+ const v = value();
1115
+ if (nonEmpty(v)) evidence.logs.push(v);
1116
+ } else if (/console\s*(error|log)/i.test(trimmed)) {
1117
+ const v = value();
1118
+ if (nonEmpty(v)) evidence.console_errors.push(v);
1119
+ } else if (/network\s*(failure|error|request)/i.test(trimmed)) {
1120
+ const v = value();
1121
+ if (nonEmpty(v)) evidence.network_failures.push(v);
498
1122
  }
499
1123
  }
500
- return { screenshots, console_errors };
1124
+ return evidence;
501
1125
  }
502
1126
  async function parseBugReport(filePath) {
503
- const content = readFileSync3(filePath, "utf-8");
504
- const filename = basename(filePath, ".md");
1127
+ const content = readFileSync5(filePath, "utf-8");
1128
+ const filename = basename4(filePath, ".md");
505
1129
  const id = filename;
506
1130
  let title = "";
507
1131
  let component = "";
@@ -514,6 +1138,10 @@ async function parseBugReport(filePath) {
514
1138
  component = componentMatch[1];
515
1139
  title = title.replace(/^\[[^\]]+\]\s*/, "").trim();
516
1140
  }
1141
+ const componentField = content.match(/\*\*Component:\*\*\s*(.+)/i);
1142
+ if (componentField) {
1143
+ component = cleanValue(componentField[1]);
1144
+ }
517
1145
  if (!component) {
518
1146
  const categoryMatch = content.match(/\|\s*Category\s*\|\s*(.+?)\s*\|/i);
519
1147
  if (categoryMatch) {
@@ -528,8 +1156,14 @@ async function parseBugReport(filePath) {
528
1156
  let url = "";
529
1157
  const urlMatch = content.match(/\*\*URL:\*\*\s*(.+)/i) ?? content.match(/URL:\s*(https?:\/\/[^\s]+)/i);
530
1158
  if (urlMatch) {
531
- url = urlMatch[1].trim();
1159
+ url = cleanValue(urlMatch[1]);
532
1160
  }
1161
+ const priority = cleanValue(content.match(/\*\*Priority:\*\*\s*(.+)/i)?.[1] ?? "");
1162
+ const environment = cleanValue(content.match(/\*\*Environment:\*\*\s*(.+)/i)?.[1] ?? "");
1163
+ const reproduction_rate = cleanValue(
1164
+ content.match(/\*\*Reproduction rate:\*\*\s*(.+)/i)?.[1] ?? ""
1165
+ );
1166
+ const summary = extractSection(content, "Summary").replace(/^>\s*/gm, "").trim();
533
1167
  const expected = extractSection(content, "Expected").replace(/^_.*_\n?/, "").replace(/^>\s*/gm, "").trim();
534
1168
  const actual = extractSection(content, "Actual").replace(/^_.*_\n?/, "").replace(/^>\s*/gm, "").trim();
535
1169
  const stepsSection = extractSection(content, "Steps to Reproduce");
@@ -540,8 +1174,12 @@ async function parseBugReport(filePath) {
540
1174
  id,
541
1175
  title,
542
1176
  severity,
1177
+ priority,
543
1178
  component,
544
1179
  url,
1180
+ environment,
1181
+ reproduction_rate,
1182
+ summary,
545
1183
  expected,
546
1184
  actual,
547
1185
  steps,
@@ -550,33 +1188,33 @@ async function parseBugReport(filePath) {
550
1188
  };
551
1189
  }
552
1190
  async function parseSession(sessionDir) {
553
- const id = basename(sessionDir);
1191
+ const id = basename4(sessionDir);
554
1192
  let charter;
555
- const charterPath = join3(sessionDir, "charter.md");
556
- if (existsSync2(charterPath)) {
557
- charter = readFileSync3(charterPath, "utf-8");
1193
+ const charterPath = join5(sessionDir, "charter.md");
1194
+ if (existsSync5(charterPath)) {
1195
+ charter = readFileSync5(charterPath, "utf-8");
558
1196
  }
559
1197
  let report;
560
- const reportPath = join3(sessionDir, "session-report.md");
561
- if (existsSync2(reportPath)) {
562
- report = readFileSync3(reportPath, "utf-8");
1198
+ const reportPath = join5(sessionDir, "session-report.md");
1199
+ if (existsSync5(reportPath)) {
1200
+ report = readFileSync5(reportPath, "utf-8");
563
1201
  }
564
1202
  const phases = [];
565
- if (existsSync2(sessionDir)) {
566
- const files = readdirSync(sessionDir);
1203
+ if (existsSync5(sessionDir)) {
1204
+ const files = readdirSync2(sessionDir);
567
1205
  const phaseFiles = files.filter((f) => /^phase-\d+/i.test(f)).sort();
568
1206
  for (const file of phaseFiles) {
569
- const content = readFileSync3(join3(sessionDir, file), "utf-8");
1207
+ const content = readFileSync5(join5(sessionDir, file), "utf-8");
570
1208
  const name = file.replace(/\.md$/, "");
571
1209
  phases.push({ name, content });
572
1210
  }
573
1211
  }
574
- const bugsDir = join3(sessionDir, "bugs");
1212
+ const bugsDir = join5(sessionDir, "bugs");
575
1213
  const bugs = [];
576
- if (existsSync2(bugsDir)) {
577
- const bugFiles = readdirSync(bugsDir).filter((f) => /^BUG-.*\.md$/i.test(f)).sort();
1214
+ if (existsSync5(bugsDir)) {
1215
+ const bugFiles = readdirSync2(bugsDir).filter((f) => /^BUG-.*\.md$/i.test(f)).sort();
578
1216
  for (const file of bugFiles) {
579
- const bug = await parseBugReport(join3(bugsDir, file));
1217
+ const bug = await parseBugReport(join5(bugsDir, file));
580
1218
  bugs.push(bug);
581
1219
  }
582
1220
  }
@@ -592,6 +1230,39 @@ async function parseSession(sessionDir) {
592
1230
 
593
1231
  // src/formatters/html-report.ts
594
1232
  import Handlebars from "handlebars";
1233
+
1234
+ // src/formatters/common.ts
1235
+ function redactString(s) {
1236
+ return s ? redact(s).text : s;
1237
+ }
1238
+ function redactBug(bug) {
1239
+ return {
1240
+ ...bug,
1241
+ title: redactString(bug.title),
1242
+ url: redactString(bug.url),
1243
+ environment: redactString(bug.environment),
1244
+ summary: redactString(bug.summary),
1245
+ expected: redactString(bug.expected),
1246
+ actual: redactString(bug.actual),
1247
+ steps: bug.steps.map(redactString),
1248
+ business_impact: redactString(bug.business_impact),
1249
+ evidence: {
1250
+ screenshots: bug.evidence.screenshots.map(redactString),
1251
+ videos: bug.evidence.videos.map(redactString),
1252
+ logs: bug.evidence.logs.map(redactString),
1253
+ console_errors: bug.evidence.console_errors.map(redactString),
1254
+ network_failures: bug.evidence.network_failures.map(redactString)
1255
+ }
1256
+ };
1257
+ }
1258
+ async function loadSessionForOutput(sessionDir) {
1259
+ const session = await parseSession(sessionDir);
1260
+ const report = session.report ? redact(session.report).text : "";
1261
+ return {
1262
+ session: { ...session, bugs: session.bugs.map(redactBug), report },
1263
+ report
1264
+ };
1265
+ }
595
1266
  function extractReportMeta(report, sessionId) {
596
1267
  const meta = {
597
1268
  target: sessionId,
@@ -606,40 +1277,34 @@ function extractReportMeta(report, sessionId) {
606
1277
  if (durationMatch) meta.duration = durationMatch[1].trim();
607
1278
  const targetMatch = report.match(/\*\*Application:\*\*\s*(.+)/i) ?? report.match(/\*\*Target:\*\*\s*(.+)/i) ?? report.match(/\|\s*Target\s*\|\s*(.+?)\s*\|/i);
608
1279
  if (targetMatch) meta.target = targetMatch[1].trim();
609
- const summaryMatch = report.match(/##\s+Executive Summary\s*\n+([\s\S]*?)(?=\n##\s|\n---)/i);
1280
+ const summaryMatch = report.match(
1281
+ /##\s+Executive Summary\s*\n+([\s\S]*?)(?=\n##\s|\n---|$)/i
1282
+ );
610
1283
  if (summaryMatch) meta.summary = summaryMatch[1].trim();
611
1284
  return meta;
612
1285
  }
613
1286
  function extractCoverage(report) {
614
- const entries = [];
615
- const tableMatch = report.match(
616
- /\|\s*Area\s*\|\s*Status\s*\|[\s\S]*?\n((?:\|.+\|.+\n?)+)/i
617
- );
618
- if (!tableMatch) return entries;
619
- const rows = tableMatch[1].split("\n").filter((r) => r.trim().startsWith("|"));
620
- for (const row of rows) {
621
- const cells = row.split("|").map((c) => c.trim()).filter(Boolean);
622
- if (cells.length >= 2 && !cells[0].startsWith("---")) {
623
- entries.push({
624
- area: cells[0] || "",
625
- status: cells[1] || "",
626
- bugsFound: cells[3] || "0",
627
- notes: cells[4] || ""
628
- });
629
- }
630
- }
631
- return entries;
1287
+ const table2 = parseMarkdownTable(report, { headingPrefix: "Coverage" });
1288
+ if (!table2) return [];
1289
+ return table2.rows.map((row) => ({
1290
+ area: row["area"] ?? "",
1291
+ risk: row["risk"] ?? "",
1292
+ status: row["status"] ?? row["tested?"] ?? row["tested"] ?? "",
1293
+ bugsFound: row["bugs"] ?? row["bugs found"] ?? row["findings"] ?? "0",
1294
+ notes: row["notes"] ?? ""
1295
+ }));
632
1296
  }
633
1297
  function extractListSection(report, heading) {
634
1298
  const items = [];
635
- const regex = new RegExp(`##\\s+${heading}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|\\n---|$)`, "i");
1299
+ const regex = new RegExp(
1300
+ `##\\s+${heading}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|\\n---|$)`,
1301
+ "i"
1302
+ );
636
1303
  const match = report.match(regex);
637
1304
  if (!match) return items;
638
1305
  for (const line of match[1].split("\n")) {
639
1306
  const itemMatch = line.match(/^[-*]\s+(?:\[.\]\s+)?(.+)/);
640
- if (itemMatch) {
641
- items.push(itemMatch[1].trim());
642
- }
1307
+ if (itemMatch) items.push(itemMatch[1].trim());
643
1308
  const numberedMatch = line.match(/^\d+\.\s+\*\*(.+?)\*\*\s*(.+)?/);
644
1309
  if (numberedMatch) {
645
1310
  const text = numberedMatch[2] ? `${numberedMatch[1]} ${numberedMatch[2]}` : numberedMatch[1];
@@ -648,11 +1313,15 @@ function extractListSection(report, heading) {
648
1313
  }
649
1314
  return items;
650
1315
  }
1316
+
1317
+ // src/formatters/html-report.ts
651
1318
  var HTML_TEMPLATE = `<!DOCTYPE html>
652
1319
  <html lang="en">
653
1320
  <head>
654
1321
  <meta charset="UTF-8">
655
1322
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1323
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:">
1324
+ <meta name="robots" content="noindex, nofollow">
656
1325
  <title>Qualiow Report \u2014 {{meta.target}}</title>
657
1326
  <style>
658
1327
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -846,6 +1515,18 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
846
1515
  margin-bottom: 0.35rem;
847
1516
  }
848
1517
 
1518
+ /* Confidentiality banner */
1519
+ .confidential {
1520
+ background: #2a1a1a;
1521
+ border: 1px solid #663333;
1522
+ color: #e0b0b0;
1523
+ border-radius: 6px;
1524
+ padding: 0.6rem 1rem;
1525
+ font-size: 0.8rem;
1526
+ margin-bottom: 1.5rem;
1527
+ letter-spacing: 0.02em;
1528
+ }
1529
+
849
1530
  /* Footer */
850
1531
  .footer {
851
1532
  margin-top: 3rem;
@@ -892,6 +1573,8 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
892
1573
  <body>
893
1574
  <div class="container">
894
1575
 
1576
+ <div class="confidential">{{confidentialityNotice}}</div>
1577
+
895
1578
  <div class="header">
896
1579
  <h1>Exploratory Testing Report</h1>
897
1580
  <div class="meta">
@@ -1012,7 +1695,7 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
1012
1695
  {{/if}}
1013
1696
 
1014
1697
  <div class="footer">
1015
- Generated by Qualiow Exploratory Testing
1698
+ Generated by Qualiow Exploratory Testing \xB7 CONFIDENTIAL \u2014 internal use only
1016
1699
  </div>
1017
1700
 
1018
1701
  </div>
@@ -1020,8 +1703,7 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
1020
1703
  </html>`;
1021
1704
  var compiledTemplate = Handlebars.compile(HTML_TEMPLATE);
1022
1705
  async function generateHtmlReport(sessionDir) {
1023
- const session = await parseSession(sessionDir);
1024
- const report = session.report ?? "";
1706
+ const { session, report } = await loadSessionForOutput(sessionDir);
1025
1707
  const meta = extractReportMeta(report, session.id);
1026
1708
  const coverage = extractCoverage(report);
1027
1709
  const observations = extractListSection(report, "Observations");
@@ -1037,6 +1719,7 @@ async function generateHtmlReport(sessionDir) {
1037
1719
  }));
1038
1720
  const html = compiledTemplate({
1039
1721
  meta,
1722
+ confidentialityNotice: CONFIDENTIALITY_NOTICE,
1040
1723
  totalBugs: session.bugs.length,
1041
1724
  criticalCount: counts.critical,
1042
1725
  highCount: counts.high,
@@ -1066,8 +1749,7 @@ function summarizeBusinessImpact(impact) {
1066
1749
  function extractTarget(report, sessionId) {
1067
1750
  const match = report.match(/\*\*Application:\*\*\s*(.+)/i) ?? report.match(/\*\*Target:\*\*\s*(.+)/i) ?? report.match(/\|\s*Target\s*\|\s*(.+?)\s*\|/i);
1068
1751
  if (match) return match[1].trim();
1069
- const parts = sessionId.split("-");
1070
- return parts[parts.length - 1] || sessionId;
1752
+ return parseSessionDirName(sessionId)?.slug ?? sessionId;
1071
1753
  }
1072
1754
  function extractDate(report) {
1073
1755
  const match = report.match(/\*\*Date:\*\*\s*(\d{4}-\d{2}-\d{2})/i) ?? report.match(/\|\s*Date\s*\|\s*(\d{4}-\d{2}-\d{2})\s*\|/i);
@@ -1081,64 +1763,33 @@ function extractPagesExplored(report) {
1081
1763
  const match = report.match(/Pages\s+Explored\s*\|\s*(\d+)/i);
1082
1764
  return match ? parseInt(match[1], 10) : 0;
1083
1765
  }
1084
- function extractCoverage2(report) {
1085
- const entries = [];
1086
- const tableMatch = report.match(
1087
- /\|\s*Area\s*\|\s*Status\s*\|[\s\S]*?\n((?:\|.+\|.+\n?)+)/i
1088
- );
1089
- if (!tableMatch) return entries;
1090
- const rows = tableMatch[1].split("\n").filter((r) => r.trim().startsWith("|"));
1091
- for (const row of rows) {
1092
- const cells = row.split("|").map((c) => c.trim()).filter(Boolean);
1093
- if (cells.length >= 2 && !cells[0].startsWith("---")) {
1094
- entries.push({
1095
- area: cells[0] || "",
1096
- status: cells[1] || "",
1097
- bugs_found: parseInt(cells[3] || "0", 10) || 0,
1098
- notes: cells[4] || ""
1099
- });
1100
- }
1101
- }
1102
- return entries;
1103
- }
1104
- function extractListSection2(report, heading) {
1105
- const items = [];
1106
- const regex = new RegExp(`##\\s+${heading}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|\\n---|$)`, "i");
1107
- const match = report.match(regex);
1108
- if (!match) return items;
1109
- for (const line of match[1].split("\n")) {
1110
- const itemMatch = line.match(/^[-*]\s+(?:\[.\]\s+)?(.+)/);
1111
- if (itemMatch) {
1112
- items.push(itemMatch[1].trim());
1113
- }
1114
- const numberedMatch = line.match(/^\d+\.\s+\*\*(.+?)\*\*\s*(.+)?/);
1115
- if (numberedMatch) {
1116
- const text = numberedMatch[2] ? `${numberedMatch[1]} ${numberedMatch[2]}` : numberedMatch[1];
1117
- items.push(text.replace(/\s*--\s*/, " -- "));
1118
- }
1119
- }
1120
- return items;
1121
- }
1122
1766
  async function generateJsonReport(sessionDir) {
1123
- const session = await parseSession(sessionDir);
1124
- const report = session.report ?? "";
1125
- const target = extractTarget(report, session.id);
1126
- const date = extractDate(report);
1127
- const duration_min = extractDuration(report);
1128
- const pages_explored = extractPagesExplored(report);
1767
+ const { session, report } = await loadSessionForOutput(sessionDir);
1129
1768
  const counts = { critical: 0, high: 0, medium: 0, low: 0 };
1130
1769
  for (const bug of session.bugs) {
1131
1770
  counts[bug.severity]++;
1132
1771
  }
1133
- const coverage = extractCoverage2(report);
1134
- const observations = extractListSection2(report, "Observations");
1135
- const recommendations = extractListSection2(report, "Recommendations");
1772
+ const coverage = extractCoverage(report).map((c) => ({
1773
+ area: c.area,
1774
+ risk: c.risk,
1775
+ status: c.status,
1776
+ bugs_found: parseInt(c.bugsFound, 10) || 0,
1777
+ notes: c.notes
1778
+ }));
1136
1779
  return {
1780
+ meta: {
1781
+ classification: "CONFIDENTIAL",
1782
+ notice: CONFIDENTIALITY_NOTICE,
1783
+ generated_by: `qualiow-exploratory-testing ${getPackageVersion()}`,
1784
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
1785
+ redacted: true
1786
+ },
1137
1787
  session: {
1138
1788
  id: session.id,
1139
- target,
1140
- date,
1141
- duration_min
1789
+ kind: parseSessionDirName(session.id)?.kind ?? null,
1790
+ target: extractTarget(report, session.id),
1791
+ date: extractDate(report),
1792
+ duration_min: extractDuration(report)
1142
1793
  },
1143
1794
  summary: {
1144
1795
  total_bugs: session.bugs.length,
@@ -1146,21 +1797,25 @@ async function generateJsonReport(sessionDir) {
1146
1797
  high: counts.high,
1147
1798
  medium: counts.medium,
1148
1799
  low: counts.low,
1149
- pages_explored
1800
+ pages_explored: extractPagesExplored(report)
1150
1801
  },
1151
1802
  bugs: session.bugs.map((bug) => ({
1152
1803
  id: bug.id,
1153
1804
  title: bug.title,
1154
1805
  severity: bug.severity,
1806
+ priority: bug.priority,
1155
1807
  component: bug.component,
1156
1808
  url: bug.url,
1809
+ environment: bug.environment,
1810
+ reproduction_rate: bug.reproduction_rate,
1811
+ summary: bug.summary,
1157
1812
  business_impact: bug.business_impact,
1158
1813
  steps: bug.steps,
1159
1814
  evidence: bug.evidence
1160
1815
  })),
1161
1816
  coverage,
1162
- observations,
1163
- recommendations
1817
+ observations: extractListSection(report, "Observations"),
1818
+ recommendations: extractListSection(report, "Recommendations")
1164
1819
  };
1165
1820
  }
1166
1821
 
@@ -1173,53 +1828,49 @@ var SEVERITY_TO_JIRA_PRIORITY = {
1173
1828
  };
1174
1829
  function csvEscape(value) {
1175
1830
  if (!value) return '""';
1176
- const escaped = value.replace(/"/g, '""');
1177
- return `"${escaped}"`;
1831
+ let v = value;
1832
+ if (/^[=+\-@\t\r]/.test(v)) v = `'${v}`;
1833
+ return `"${v.replace(/"/g, '""')}"`;
1178
1834
  }
1179
1835
  function formatDescription(bug) {
1180
1836
  const parts = [];
1837
+ if (bug.summary) {
1838
+ parts.push(bug.summary, "");
1839
+ }
1181
1840
  if (bug.steps.length > 0) {
1182
1841
  parts.push("h3. Steps to Reproduce");
1183
- for (const step of bug.steps) {
1184
- parts.push(`# ${step}`);
1185
- }
1842
+ for (const step of bug.steps) parts.push(`# ${step}`);
1186
1843
  parts.push("");
1187
1844
  }
1188
1845
  if (bug.expected) {
1189
- parts.push(`h3. Expected Behavior`);
1190
- parts.push(bug.expected);
1191
- parts.push("");
1846
+ parts.push("h3. Expected Behavior", bug.expected, "");
1192
1847
  }
1193
1848
  if (bug.actual) {
1194
- parts.push(`h3. Actual Behavior`);
1195
- parts.push(bug.actual);
1196
- parts.push("");
1849
+ parts.push("h3. Actual Behavior", bug.actual, "");
1197
1850
  }
1198
1851
  if (bug.business_impact) {
1199
- parts.push("h3. Business Impact");
1200
- parts.push(bug.business_impact);
1201
- parts.push("");
1852
+ parts.push("h3. Business Impact", bug.business_impact, "");
1853
+ }
1854
+ if (bug.environment) {
1855
+ parts.push("h3. Environment", bug.environment, "");
1202
1856
  }
1203
1857
  if (bug.url) {
1204
- parts.push(`h3. URL`);
1205
- parts.push(bug.url);
1858
+ parts.push("h3. URL", bug.url, "");
1206
1859
  }
1860
+ parts.push(`_${CONFIDENTIALITY_NOTICE}_`);
1207
1861
  return parts.join("\n");
1208
1862
  }
1209
- function extractDomain(sessionId) {
1210
- return "general";
1211
- }
1212
1863
  async function generateJiraExport(sessionDir) {
1213
- const session = await parseSession(sessionDir);
1864
+ const { session } = await loadSessionForOutput(sessionDir);
1214
1865
  const headers = ["Summary", "Priority", "Description", "Component", "Labels"];
1215
1866
  const rows = [headers.join(",")];
1216
- const domain = extractDomain(session.id);
1867
+ const kind = parseSessionDirName(session.id)?.kind ?? "";
1217
1868
  for (const bug of session.bugs) {
1218
1869
  const summary = `${bug.id}: ${bug.title}`;
1219
1870
  const priority = SEVERITY_TO_JIRA_PRIORITY[bug.severity] ?? "Major";
1220
1871
  const description = formatDescription(bug);
1221
1872
  const component = bug.component || "";
1222
- const labels = ["qualiow", "exploratory-testing", domain].filter(Boolean).join(" ");
1873
+ const labels = ["qualiow", "exploratory-testing", kind].filter(Boolean).join(" ");
1223
1874
  rows.push(
1224
1875
  [
1225
1876
  csvEscape(summary),
@@ -1232,22 +1883,1167 @@ async function generateJiraExport(sessionDir) {
1232
1883
  }
1233
1884
  return rows.join("\n");
1234
1885
  }
1886
+
1887
+ // src/formatters/markdown-summary.ts
1888
+ var SEVERITY_LABEL = {
1889
+ critical: "Critical",
1890
+ high: "High",
1891
+ medium: "Medium",
1892
+ low: "Low"
1893
+ };
1894
+ async function generateMarkdownSummary(sessionDir) {
1895
+ const { session, report } = await loadSessionForOutput(sessionDir);
1896
+ const meta = extractReportMeta(report, session.id);
1897
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
1898
+ for (const bug of session.bugs) counts[bug.severity]++;
1899
+ const lines = [];
1900
+ lines.push(CONFIDENTIALITY_HEADER_MD, "");
1901
+ lines.push(`# Session Summary \u2014 ${meta.target}`, "");
1902
+ lines.push("| Field | Value |", "|---|---|");
1903
+ lines.push(`| Session | ${session.id} |`);
1904
+ if (meta.date) lines.push(`| Date | ${meta.date} |`);
1905
+ if (meta.duration) lines.push(`| Duration | ${meta.duration} |`);
1906
+ lines.push(
1907
+ `| Bugs | ${session.bugs.length} (Critical ${counts.critical} \xB7 High ${counts.high} \xB7 Medium ${counts.medium} \xB7 Low ${counts.low}) |`,
1908
+ ""
1909
+ );
1910
+ if (meta.summary) {
1911
+ lines.push("## Executive Summary", "", meta.summary, "");
1912
+ }
1913
+ if (session.bugs.length) {
1914
+ lines.push("## Bugs", "", "| ID | Severity | Component | Title |", "|---|---|---|---|");
1915
+ for (const bug of session.bugs) {
1916
+ lines.push(
1917
+ `| ${bug.id} | ${SEVERITY_LABEL[bug.severity]} | ${bug.component || "\u2014"} | ${bug.title} |`
1918
+ );
1919
+ }
1920
+ lines.push("");
1921
+ }
1922
+ const coverage = extractCoverage(report);
1923
+ if (coverage.length) {
1924
+ lines.push("## Coverage", "", "| Area | Risk | Status | Bugs | Notes |", "|---|---|---|---|---|");
1925
+ for (const c of coverage) {
1926
+ lines.push(`| ${c.area} | ${c.risk} | ${c.status} | ${c.bugsFound} | ${c.notes} |`);
1927
+ }
1928
+ lines.push("");
1929
+ }
1930
+ const recommendations = extractListSection(report, "Recommendations");
1931
+ if (recommendations.length) {
1932
+ lines.push("## Recommendations", "");
1933
+ for (const r of recommendations) lines.push(`- ${r}`);
1934
+ lines.push("");
1935
+ }
1936
+ return lines.join("\n");
1937
+ }
1938
+
1939
+ // src/cli/commands/init.ts
1940
+ import { Command } from "commander";
1941
+ import { resolve as resolve3, join as join6, relative as relative2, dirname as dirname3 } from "path";
1942
+ import {
1943
+ existsSync as existsSync6,
1944
+ readFileSync as readFileSync6,
1945
+ writeFileSync as writeFileSync2,
1946
+ mkdirSync as mkdirSync2,
1947
+ readdirSync as readdirSync3,
1948
+ statSync,
1949
+ copyFileSync,
1950
+ chmodSync
1951
+ } from "fs";
1952
+ import chalk from "chalk";
1953
+
1954
+ // src/utils/settings-merge.ts
1955
+ var QUALIOW_HOOK_ENTRIES = [
1956
+ { matcher: "Read", command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/read-guard.mjs"' },
1957
+ {
1958
+ matcher: "Write|Edit|MultiEdit",
1959
+ command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/write-guard.mjs"'
1960
+ }
1961
+ ];
1962
+ var QUALIOW_PERMISSION_ALLOW = [
1963
+ "Bash(playwright-cli:*)",
1964
+ "Bash(npx playwright-cli:*)",
1965
+ "Bash(qualiow:*)"
1966
+ ];
1967
+ function isRecord(v) {
1968
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1969
+ }
1970
+ function existingHookCommands(settings) {
1971
+ const commands = /* @__PURE__ */ new Set();
1972
+ const hooks = settings.hooks;
1973
+ if (!isRecord(hooks)) return commands;
1974
+ const preToolUse = hooks.PreToolUse;
1975
+ if (!Array.isArray(preToolUse)) return commands;
1976
+ for (const entry of preToolUse) {
1977
+ if (!isRecord(entry) || !Array.isArray(entry.hooks)) continue;
1978
+ for (const h of entry.hooks) {
1979
+ if (isRecord(h) && typeof h.command === "string") commands.add(h.command);
1980
+ }
1981
+ }
1982
+ return commands;
1983
+ }
1984
+ function mergeQualiowHookSettings(existing) {
1985
+ const settings = isRecord(existing) ? { ...existing } : {};
1986
+ let changed = false;
1987
+ const hooksSection = isRecord(settings.hooks) ? { ...settings.hooks } : {};
1988
+ const preToolUse = Array.isArray(hooksSection.PreToolUse) ? [...hooksSection.PreToolUse] : [];
1989
+ const haveCommands = existingHookCommands(settings);
1990
+ for (const { matcher, command } of QUALIOW_HOOK_ENTRIES) {
1991
+ if (haveCommands.has(command)) continue;
1992
+ preToolUse.push({ matcher, hooks: [{ type: "command", command }] });
1993
+ haveCommands.add(command);
1994
+ changed = true;
1995
+ }
1996
+ hooksSection.PreToolUse = preToolUse;
1997
+ settings.hooks = hooksSection;
1998
+ const permissions = isRecord(settings.permissions) ? { ...settings.permissions } : {};
1999
+ const allow = Array.isArray(permissions.allow) ? [...permissions.allow] : [];
2000
+ const allowSet = new Set(allow.filter((a) => typeof a === "string"));
2001
+ for (const rule of QUALIOW_PERMISSION_ALLOW) {
2002
+ if (allowSet.has(rule)) continue;
2003
+ allow.push(rule);
2004
+ allowSet.add(rule);
2005
+ changed = true;
2006
+ }
2007
+ permissions.allow = allow;
2008
+ settings.permissions = permissions;
2009
+ return { settings, changed };
2010
+ }
2011
+
2012
+ // src/cli/commands/init.ts
2013
+ function sameContent(a, b) {
2014
+ try {
2015
+ return readFileSync6(a).equals(readFileSync6(b));
2016
+ } catch {
2017
+ return false;
2018
+ }
2019
+ }
2020
+ function copyEntry(src, dest, opts) {
2021
+ let status;
2022
+ if (!existsSync6(dest)) {
2023
+ status = "installed";
2024
+ } else if (sameContent(src, dest)) {
2025
+ status = "unchanged";
2026
+ } else {
2027
+ status = opts.force ? "overwritten" : "skipped";
2028
+ }
2029
+ if (!opts.dryRun && (status === "installed" || status === "overwritten")) {
2030
+ mkdirSync2(dirname3(dest), { recursive: true });
2031
+ copyFileSync(src, dest);
2032
+ chmodSync(dest, statSync(src).mode & 511);
2033
+ }
2034
+ return { dest, status };
2035
+ }
2036
+ function listFiles(dir, filter) {
2037
+ const out = [];
2038
+ const walk = (current) => {
2039
+ for (const entry of readdirSync3(current, { withFileTypes: true })) {
2040
+ const full = join6(current, entry.name);
2041
+ if (entry.isDirectory()) {
2042
+ walk(full);
2043
+ } else {
2044
+ const rel = relative2(dir, full).split("\\").join("/");
2045
+ if (!filter || filter(rel)) out.push(rel);
2046
+ }
2047
+ }
2048
+ };
2049
+ walk(dir);
2050
+ return out.sort();
2051
+ }
2052
+ function copyTree(srcDir, destDir, opts) {
2053
+ if (!existsSync6(srcDir)) return [];
2054
+ return listFiles(srcDir, opts.filter).map(
2055
+ (rel) => copyEntry(join6(srcDir, rel), join6(destDir, rel), opts)
2056
+ );
2057
+ }
2058
+ async function runInit(options, ctx) {
2059
+ const cwd = ctx.cwd;
2060
+ const pkgRoot = ctx.pkgRoot ?? getPackageRoot();
2061
+ const log = ctx.log ?? ((line) => console.log(line));
2062
+ const copyOpts = { force: options.force, dryRun: options.dryRun };
2063
+ const copies = [];
2064
+ const createdDirs = [];
2065
+ const createdFiles = [];
2066
+ if (options.dryRun) log(chalk.cyan.bold("Dry run \u2014 nothing will be written\n"));
2067
+ if (resolve3(pkgRoot) === resolve3(cwd)) {
2068
+ log(chalk.yellow(" \u25CB Running inside the package itself \u2014 skills and data are already in place"));
2069
+ } else {
2070
+ const skillsSrc = resolveSkillsSource(pkgRoot);
2071
+ if (!skillsSrc) {
2072
+ throw new Error(`No skills directory found under ${pkgRoot}`);
2073
+ }
2074
+ copies.push(
2075
+ ...copyTree(skillsSrc, join6(cwd, ".claude", "skills"), {
2076
+ ...copyOpts,
2077
+ filter: (rel2) => rel2.startsWith("qa-")
2078
+ })
2079
+ );
2080
+ const agentsCandidates = [join6(pkgRoot, "agents"), join6(pkgRoot, ".claude", "agents")];
2081
+ const agentsSrc = agentsCandidates.find((p) => existsSync6(p));
2082
+ if (agentsSrc) {
2083
+ copies.push(
2084
+ ...copyTree(agentsSrc, join6(cwd, ".claude", "agents"), {
2085
+ ...copyOpts,
2086
+ filter: (rel2) => rel2.endsWith(".md")
2087
+ })
2088
+ );
2089
+ }
2090
+ const dataSrc = join6(pkgRoot, "data");
2091
+ copies.push(...copyTree(join6(dataSrc, "knowledge"), join6(cwd, "data", "knowledge"), copyOpts));
2092
+ copies.push(
2093
+ ...copyTree(join6(dataSrc, "domains"), join6(cwd, "data", "domains"), {
2094
+ ...copyOpts,
2095
+ filter: (rel2) => rel2.endsWith(".yml")
2096
+ })
2097
+ );
2098
+ copies.push(...copyTree(join6(dataSrc, "templates"), join6(cwd, "data", "templates"), copyOpts));
2099
+ copies.push(...copyTree(join6(dataSrc, "security"), join6(cwd, "data", "security"), copyOpts));
2100
+ copies.push(
2101
+ ...copyTree(join6(dataSrc, "targets"), join6(cwd, "data", "targets"), {
2102
+ ...copyOpts,
2103
+ filter: (rel2) => {
2104
+ if (!rel2.endsWith(".yml") || rel2.includes("/")) return false;
2105
+ if (rel2.startsWith("local-")) return false;
2106
+ if (rel2 === "_default.yml") return true;
2107
+ if (!options.includeExamples) return false;
2108
+ return rel2.startsWith("_example-") || rel2 === "testers-ai.yml";
2109
+ }
2110
+ })
2111
+ );
2112
+ const binSrc = join6(pkgRoot, "bin");
2113
+ copies.push(
2114
+ ...copyTree(binSrc, join6(cwd, "qa", "bin"), {
2115
+ ...copyOpts,
2116
+ filter: (rel2) => rel2 !== "qualiow"
2117
+ })
2118
+ );
2119
+ if (existsSync6(binSrc)) {
2120
+ const versionPath = join6(cwd, "qa", "bin", "VERSION");
2121
+ const version = `${getPackageVersion(pkgRoot)}
2122
+ `;
2123
+ const exists = existsSync6(versionPath);
2124
+ const same = exists && readFileSync6(versionPath, "utf-8") === version;
2125
+ const status = !exists ? "installed" : same ? "unchanged" : options.force ? "overwritten" : "skipped";
2126
+ if (!options.dryRun && (status === "installed" || status === "overwritten")) {
2127
+ mkdirSync2(dirname3(versionPath), { recursive: true });
2128
+ writeFileSync2(versionPath, version);
2129
+ }
2130
+ copies.push({ dest: versionPath, status });
2131
+ }
2132
+ const envExampleSrc = join6(pkgRoot, ".env.example");
2133
+ if (existsSync6(envExampleSrc)) {
2134
+ copies.push(copyEntry(envExampleSrc, join6(cwd, "qa", ".env.example"), copyOpts));
2135
+ }
2136
+ }
2137
+ let hooksSettingsChanged = false;
2138
+ if (options.hooks) {
2139
+ const hooksScriptsSrc = join6(pkgRoot, "hooks", "scripts");
2140
+ copies.push(
2141
+ ...copyTree(hooksScriptsSrc, join6(cwd, "qa", "hooks"), {
2142
+ ...copyOpts,
2143
+ filter: (rel2) => rel2.endsWith(".mjs")
2144
+ })
2145
+ );
2146
+ const settingsPath = join6(cwd, ".claude", "settings.json");
2147
+ const settingsExisted = existsSync6(settingsPath);
2148
+ let existingSettings;
2149
+ if (settingsExisted) {
2150
+ try {
2151
+ existingSettings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
2152
+ } catch {
2153
+ existingSettings = void 0;
2154
+ }
2155
+ }
2156
+ const { settings, changed } = mergeQualiowHookSettings(existingSettings);
2157
+ hooksSettingsChanged = changed || !settingsExisted;
2158
+ if (!options.dryRun) {
2159
+ mkdirSync2(dirname3(settingsPath), { recursive: true });
2160
+ writeFileSync2(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2161
+ }
2162
+ }
2163
+ for (const dir of ["output/sessions", "output/bugs", "output/context", ".auth", "qa"]) {
2164
+ const full = join6(cwd, dir);
2165
+ if (!existsSync6(full)) {
2166
+ createdDirs.push(full);
2167
+ if (!options.dryRun) mkdirSync2(full, { recursive: true });
2168
+ }
2169
+ }
2170
+ for (const [rel2, content] of [
2171
+ ["output/sessions/INDEX.md", INDEX_MD_HEADER],
2172
+ ["output/bugs/all-bugs.md", ALL_BUGS_MD_HEADER]
2173
+ ]) {
2174
+ const full = join6(cwd, rel2);
2175
+ if (!existsSync6(full)) {
2176
+ createdFiles.push(full);
2177
+ if (!options.dryRun) {
2178
+ mkdirSync2(dirname3(full), { recursive: true });
2179
+ writeFileSync2(full, content);
2180
+ }
2181
+ }
2182
+ }
2183
+ const gitignorePath = join6(cwd, ".gitignore");
2184
+ const existing = existsSync6(gitignorePath) ? readFileSync6(gitignorePath, "utf-8") : "";
2185
+ const merged = mergeGitignore(existing);
2186
+ const gitignoreUpdated = merged !== null;
2187
+ if (merged !== null && !options.dryRun) {
2188
+ writeFileSync2(gitignorePath, merged);
2189
+ }
2190
+ const counts = { installed: 0, unchanged: 0, overwritten: 0, skipped: 0 };
2191
+ for (const c of copies) counts[c.status]++;
2192
+ const rel = (p) => relative2(cwd, p) || ".";
2193
+ if (copies.length) {
2194
+ log(
2195
+ chalk.green(` \u2713 Files: ${counts.installed} installed, ${counts.unchanged} unchanged` + (counts.overwritten ? `, ${counts.overwritten} overwritten` : "") + (counts.skipped ? chalk.yellow(`, ${counts.skipped} skipped (exist and differ \u2014 use --force)`) : ""))
2196
+ );
2197
+ for (const c of copies.filter((x) => x.status === "skipped")) {
2198
+ log(chalk.yellow(` skipped ${rel(c.dest)}`));
2199
+ }
2200
+ }
2201
+ for (const d of createdDirs) log(chalk.green(` \u2713 Created ${rel(d)}/`));
2202
+ for (const f of createdFiles) log(chalk.green(` \u2713 Created ${rel(f)}`));
2203
+ log(
2204
+ gitignoreUpdated ? chalk.green(" \u2713 Updated .gitignore (Qualiow block)") : chalk.cyan(" \u25CB .gitignore already up to date")
2205
+ );
2206
+ if (options.hooks) {
2207
+ log(
2208
+ hooksSettingsChanged ? chalk.green(" \u2713 Wired hooks into .claude/settings.json") : chalk.cyan(" \u25CB .claude/settings.json hooks already up to date")
2209
+ );
2210
+ }
2211
+ log("");
2212
+ log(chalk.cyan.bold(options.dryRun ? "Dry run complete." : "Qualiow initialized."));
2213
+ log("");
2214
+ log(chalk.white("Next steps:"));
2215
+ log(chalk.white(" 1. npx playwright-cli install --skills # official Playwright skill, next to qualiow"));
2216
+ log(chalk.white(" 2. cp qa/.env.example qa/.env # credentials by env var name only"));
2217
+ if (options.hooks) {
2218
+ log(chalk.white(' QUALIOW_HOOKS=off or QUALIOW_READ_MAX_LINES=<n> under "env" in .claude/settings.json tune the guards'));
2219
+ }
2220
+ log(chalk.white(" 3. /qa-target-setup or /qa-explore https://your-app.com"));
2221
+ log(chalk.white(" 4. mobile: qa/bin/doctor-mobile.sh # then /qa-explore-mobile --target <id>"));
2222
+ log("");
2223
+ return { copies, createdDirs, createdFiles, gitignoreUpdated };
2224
+ }
2225
+
2226
+ // src/cli/commands/explore.ts
2227
+ import { Command as Command2 } from "commander";
2228
+ import { resolve as resolve4, join as join7, relative as relative3 } from "path";
2229
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
2230
+ import chalk2 from "chalk";
2231
+ function parseTimeBox(value) {
2232
+ const m = /^(\d+)m$/.exec(value.trim());
2233
+ if (!m) throw new Error(`Invalid --time-box "${value}": use minutes like 30m or 45m`);
2234
+ const minutes = parseInt(m[1], 10);
2235
+ if (minutes < 1 || minutes > 45) {
2236
+ throw new Error(`--time-box must be between 1m and 45m (got ${value})`);
2237
+ }
2238
+ return minutes;
2239
+ }
2240
+ async function runExplore(url, options, ctx) {
2241
+ const cwd = ctx.cwd;
2242
+ const now = ctx.now ?? /* @__PURE__ */ new Date();
2243
+ const log = ctx.log ?? ((line) => console.log(line));
2244
+ if (url) {
2245
+ try {
2246
+ new URL(url);
2247
+ } catch {
2248
+ throw new Error(`Invalid URL: "${url}". Provide a full URL such as https://example.com`);
2249
+ }
2250
+ }
2251
+ const minutes = parseTimeBox(options.timeBox);
2252
+ const targetPath = resolveTargetPath(cwd, options.target);
2253
+ let targetLabel = options.target ?? "adhoc";
2254
+ if (options.target || existsSync7(targetPath)) {
2255
+ if (!existsSync7(targetPath)) {
2256
+ throw new Error(
2257
+ `Target config not found: ${relative3(cwd, targetPath)}
2258
+ Available targets: npx qualiow list targets`
2259
+ );
2260
+ }
2261
+ const result = validateTargetConfig(targetPath);
2262
+ if (!result.valid) {
2263
+ const details = (result.errors ?? []).map((e) => ` \u2192 ${e.path ? `[${e.path}] ` : ""}${e.message}`).join("\n");
2264
+ throw new Error(`Target config ${relative3(cwd, targetPath)} is invalid:
2265
+ ${details}`);
2266
+ }
2267
+ if (!options.target) targetLabel = url ? slugify(url) : "adhoc";
2268
+ log(chalk2.green(` \u2713 Target config valid: ${relative3(cwd, targetPath)}`));
2269
+ } else if (url) {
2270
+ targetLabel = slugify(url);
2271
+ }
2272
+ if (options.context) {
2273
+ const contextPath = resolve4(cwd, options.context);
2274
+ if (!existsSync7(contextPath)) {
2275
+ throw new Error(`Context file not found: ${contextPath}`);
2276
+ }
2277
+ log(chalk2.green(` \u2713 Context file found: ${options.context}`));
2278
+ }
2279
+ const sessionName = sessionDirName("explore", targetLabel, now);
2280
+ const sessionDir = resolve4(cwd, "output", "sessions", sessionName);
2281
+ if (options.dryRun) {
2282
+ log("");
2283
+ log(chalk2.cyan.bold("Dry run \u2014 no files created"));
2284
+ log(chalk2.white(` Session directory: ${relative3(cwd, sessionDir)}`));
2285
+ log(chalk2.white(` URL: ${url ?? "(none \u2014 /qa-explore will ask)"}`));
2286
+ log(chalk2.white(` Target: ${options.target ?? relative3(cwd, targetPath)}`));
2287
+ log(chalk2.white(` Context: ${options.context ?? "(none)"}`));
2288
+ log(chalk2.white(` Time box: ${minutes} min`));
2289
+ return { sessionDir };
2290
+ }
2291
+ for (const sub of ["", "screenshots", "bugs", "videos", "snapshots"]) {
2292
+ mkdirSync3(join7(sessionDir, sub), { recursive: true });
2293
+ }
2294
+ const date = now.toISOString().slice(0, 10);
2295
+ writeFileSync3(
2296
+ join7(sessionDir, "charter.md"),
2297
+ `${CONFIDENTIALITY_HEADER_MD}
2298
+
2299
+ # Exploratory Testing Charter
2300
+
2301
+ **Session:** ${sessionName}
2302
+ **Date:** ${date}
2303
+ **Target:** ${options.target ?? targetLabel}
2304
+ **URL:** ${url ?? "TBD"}
2305
+ **Time Box:** ${minutes} min
2306
+
2307
+ ## Mission
2308
+
2309
+ > Filled in by /qa-explore phase 2.
2310
+
2311
+ ## Areas of Focus
2312
+
2313
+ -
2314
+
2315
+ ## Risks & Concerns
2316
+
2317
+ -
2318
+ `
2319
+ );
2320
+ writeFileSync3(
2321
+ join7(sessionDir, "session-log.md"),
2322
+ `${CONFIDENTIALITY_HEADER_MD}
2323
+
2324
+ # Session Log \u2014 ${sessionName}
2325
+
2326
+ [${now.toISOString()}] [PRE-FLIGHT] Session directory created by \`qualiow explore\`
2327
+ `
2328
+ );
2329
+ log("");
2330
+ log(chalk2.green.bold("Session skeleton created (pre-flight only \u2014 no browser was launched)."));
2331
+ log(chalk2.white(` Directory: ${relative3(cwd, sessionDir)}`));
2332
+ log("");
2333
+ log(chalk2.cyan(" Run the session in Claude Code:"));
2334
+ const args = [url ?? "<url>", options.target ? `--target ${options.target}` : "", options.context ? `--context ${options.context}` : ""].filter(Boolean).join(" ");
2335
+ log(chalk2.white(` /qa-explore ${args} --session output/sessions/${sessionName}`));
2336
+ log("");
2337
+ return { sessionDir };
2338
+ }
2339
+
2340
+ // src/cli/commands/report.ts
2341
+ import { Command as Command3 } from "commander";
2342
+ import { resolve as resolve5, join as join8, basename as basename5, relative as relative4 } from "path";
2343
+ import { existsSync as existsSync8, readdirSync as readdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "fs";
2344
+ import chalk3 from "chalk";
2345
+ var DEFAULT_FILENAMES = {
2346
+ md: "session-summary.md",
2347
+ html: "session-report.html",
2348
+ json: "session-report.json",
2349
+ jira: "jira-export.csv"
2350
+ };
2351
+ async function runReport(options, ctx) {
2352
+ const cwd = ctx.cwd;
2353
+ const log = ctx.log ?? ((line) => console.log(line));
2354
+ const sessionsDir = resolve5(cwd, "output", "sessions");
2355
+ if (!existsSync8(sessionsDir)) {
2356
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
2357
+ }
2358
+ const sessionDir = resolveSessionDir(sessionsDir, options.session);
2359
+ const sessionName = basename5(sessionDir);
2360
+ const format = options.format.toLowerCase();
2361
+ let content;
2362
+ switch (format) {
2363
+ case "md":
2364
+ content = await generateMarkdownSummary(sessionDir);
2365
+ break;
2366
+ case "html":
2367
+ content = await generateHtmlReport(sessionDir);
2368
+ break;
2369
+ case "json":
2370
+ content = JSON.stringify(await generateJsonReport(sessionDir), null, 2);
2371
+ break;
2372
+ case "jira":
2373
+ content = await generateJiraExport(sessionDir);
2374
+ break;
2375
+ default:
2376
+ throw new Error(`Unknown format: "${format}". Choose from: md, html, json, jira`);
2377
+ }
2378
+ if (options.stdout) {
2379
+ process.stdout.write(content.endsWith("\n") ? content : content + "\n");
2380
+ return { content };
2381
+ }
2382
+ const outputPath = options.output ? resolve5(cwd, options.output) : join8(sessionDir, DEFAULT_FILENAMES[format]);
2383
+ writeFileSync4(outputPath, content);
2384
+ log(chalk3.cyan(`
2385
+ Session: ${sessionName}`));
2386
+ log(chalk3.green(` ${format.toUpperCase()} written: ${relative4(cwd, outputPath)}`));
2387
+ const statsPath = join8(sessionDir, "stats.json");
2388
+ if (existsSync8(statsPath)) {
2389
+ try {
2390
+ const stats = SessionMetricsSchema.parse(JSON.parse(readFileSync7(statsPath, "utf-8")));
2391
+ if (appendSessionMetricsDeduped(resolve5(cwd, "output"), stats)) {
2392
+ log(chalk3.green(" \u2713 Metrics appended to output/metrics.jsonl"));
2393
+ }
2394
+ } catch {
2395
+ log(chalk3.yellow(" \u26A0 stats.json present but not in the expected shape \u2014 metrics not recorded"));
2396
+ }
2397
+ }
2398
+ log("");
2399
+ return { outputPath, content };
2400
+ }
2401
+ function resolveSessionDir(sessionsDir, sessionId) {
2402
+ const dirs = readdirSync4(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
2403
+ if (sessionId === "latest") {
2404
+ const canonical = dirs.filter((d) => SESSION_DIR_RE.test(d));
2405
+ const pool = canonical.length ? canonical : dirs;
2406
+ if (pool.length === 0) throw new Error("No sessions found. Run an exploratory testing session first.");
2407
+ return join8(sessionsDir, pool[pool.length - 1]);
2408
+ }
2409
+ if (dirs.includes(sessionId)) return join8(sessionsDir, sessionId);
2410
+ const matches = dirs.filter((d) => d.includes(sessionId));
2411
+ if (matches.length === 1) return join8(sessionsDir, matches[0]);
2412
+ if (matches.length > 1) {
2413
+ throw new Error(
2414
+ `"${sessionId}" matches ${matches.length} sessions \u2014 be more specific:
2415
+ ${matches.join("\n ")}`
2416
+ );
2417
+ }
2418
+ throw new Error(`No session matches "${sessionId}". List them with: npx qualiow list sessions`);
2419
+ }
2420
+
2421
+ // src/cli/commands/list.ts
2422
+ import { Command as Command4 } from "commander";
2423
+ import { resolve as resolve6, join as join9, basename as basename6 } from "path";
2424
+ import { existsSync as existsSync9, readFileSync as readFileSync8, readdirSync as readdirSync5 } from "fs";
2425
+ import { parse as parseYaml3 } from "yaml";
2426
+ import { globSync as globSync3 } from "glob";
2427
+ import chalk4 from "chalk";
2428
+ async function runList(type, cwd, options = {}, log = (line) => console.log(line)) {
2429
+ switch (type) {
2430
+ case "sessions":
2431
+ listSessions(cwd);
2432
+ break;
2433
+ case "knowledge":
2434
+ listKnowledge(cwd, options, log);
2435
+ break;
2436
+ case "targets":
2437
+ listTargets(cwd);
2438
+ break;
2439
+ case "domains":
2440
+ listDomains(cwd);
2441
+ break;
2442
+ default:
2443
+ throw new Error(`Unknown type: "${type}". Choose from: sessions, knowledge, targets, domains`);
2444
+ }
2445
+ }
2446
+ function readSessionIndex(indexPath) {
2447
+ if (!existsSync9(indexPath)) return [];
2448
+ const table2 = parseMarkdownTable(readFileSync8(indexPath, "utf-8"));
2449
+ if (!table2) return [];
2450
+ const rows = [];
2451
+ for (const row of table2.rows) {
2452
+ const date = row["date"] ?? "";
2453
+ if (!date || date.startsWith("_")) continue;
2454
+ rows.push({
2455
+ date,
2456
+ kind: row["kind"] ?? "",
2457
+ target: row["target"] ?? "",
2458
+ bugs: row["bugs"] ?? "",
2459
+ duration: row["duration"] ?? "",
2460
+ status: row["status"] ?? "",
2461
+ report: row["report"] ?? row["session directory"] ?? ""
2462
+ });
2463
+ }
2464
+ return rows;
2465
+ }
2466
+ function listSessions(cwd) {
2467
+ const sessionsDir = resolve6(cwd, "output", "sessions");
2468
+ const indexPath = join9(sessionsDir, "INDEX.md");
2469
+ if (!existsSync9(sessionsDir)) {
2470
+ console.log(chalk4.yellow("No sessions directory. Run `npx qualiow init` first, then start a session."));
2471
+ return;
2472
+ }
2473
+ const rows = readSessionIndex(indexPath);
2474
+ const indexedDirs = new Set(rows.map((r) => basename6(r.report.replace(/\/session-report\.md$/, ""))));
2475
+ const unindexed = readdirSync5(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory() && SESSION_DIR_RE.test(d.name) && !indexedDirs.has(d.name)).map((d) => d.name).sort();
2476
+ console.log(chalk4.cyan.bold("\nSessions:"));
2477
+ console.log("");
2478
+ if (rows.length === 0 && unindexed.length === 0) {
2479
+ console.log(chalk4.yellow(" No sessions recorded yet."));
2480
+ console.log(chalk4.white(" Start one with: /qa-explore <url>"));
2481
+ console.log("");
2482
+ return;
2483
+ }
2484
+ const widths = [16, 8, 22, 5, 9, 12];
2485
+ const header = INDEX_COLUMNS.map((c, i) => i < widths.length ? pad2(c, widths[i]) : c).join(" ");
2486
+ console.log(chalk4.bold(` ${header}`));
2487
+ console.log(` ${widths.map((w) => "\u2500".repeat(w)).join(" ")} ${"\u2500".repeat(30)}`);
2488
+ for (const r of rows) {
2489
+ console.log(
2490
+ ` ${pad2(r.date, 16)} ${pad2(r.kind, 8)} ${pad2(r.target, 22)} ${pad2(r.bugs, 5)} ${pad2(r.duration, 9)} ${pad2(r.status, 12)} ${r.report}`
2491
+ );
2492
+ }
2493
+ for (const d of unindexed) {
2494
+ console.log(chalk4.gray(` ${pad2(d.slice(0, 15), 16)} ${pad2("", 8)} ${pad2("", 22)} ${pad2("", 5)} ${pad2("", 9)} ${pad2("unindexed", 12)} ${d}`));
2495
+ }
2496
+ console.log("");
2497
+ console.log(chalk4.white(` Total: ${rows.length} session(s)` + (unindexed.length ? chalk4.gray(` (+${unindexed.length} unindexed)`) : "")));
2498
+ console.log("");
2499
+ }
2500
+ function listKnowledge(cwd, options, log) {
2501
+ const dataDir = resolveDataDir(cwd, options.data);
2502
+ const knowledgeDir = join9(dataDir, "knowledge");
2503
+ const manifestPath = join9(knowledgeDir, "manifest.yml");
2504
+ if (!existsSync9(manifestPath)) {
2505
+ log(chalk4.yellow(`No knowledge base at ${manifestPath}. Run \`npx qualiow init\` first.`));
2506
+ return;
2507
+ }
2508
+ const manifest = KnowledgeManifestSchema.parse(
2509
+ parseYaml3(readFileSync8(manifestPath, "utf-8"))
2510
+ );
2511
+ if (options.entry) {
2512
+ log(readEntryFile(knowledgeDir, manifest.entries, options.entry));
2513
+ return;
2514
+ }
2515
+ if (options.changelog) {
2516
+ printKnowledgeChangelog(knowledgeDir, log);
2517
+ return;
2518
+ }
2519
+ if (options.stats) {
2520
+ printKnowledgeStats(manifest, log);
2521
+ return;
2522
+ }
2523
+ const filesOnDisk = globSync3(join9(knowledgeDir, "releases", "*", "entries", "*.yml")).length;
2524
+ log(chalk4.cyan.bold("\nKnowledge Base:"));
2525
+ log(chalk4.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
2526
+ if (filesOnDisk !== manifest.entries.length || manifest.stats.total_entries !== filesOnDisk) {
2527
+ log(
2528
+ chalk4.yellow(
2529
+ ` \u26A0 Registry (${manifest.entries.length}) / stats (${manifest.stats.total_entries}) disagree with ${filesOnDisk} entry files \u2014 run: npx qualiow kb sync`
2530
+ )
2531
+ );
2532
+ }
2533
+ const filters = [];
2534
+ if (options.domain) filters.push(`domain ${options.domain}`);
2535
+ if (options.tag) filters.push(`tag ${options.tag}`);
2536
+ if (options.type) filters.push(`type ${options.type}`);
2537
+ const entries = manifest.entries.filter(
2538
+ (e) => (!options.domain || e.domains.includes(options.domain) || e.domains.includes("all")) && (!options.tag || e.tags.includes(options.tag)) && (!options.type || e.type === options.type)
2539
+ );
2540
+ if (filters.length) {
2541
+ log(chalk4.white(` Filter: ${filters.join(", ")} \u2192 ${entries.length} entries`));
2542
+ }
2543
+ log("");
2544
+ if (entries.length === 0) {
2545
+ log(chalk4.yellow(" No entries match that filter."));
2546
+ log("");
2547
+ return;
2548
+ }
2549
+ const grouped = /* @__PURE__ */ new Map();
2550
+ for (const entry of entries) {
2551
+ const list = grouped.get(entry.type) ?? [];
2552
+ list.push(entry);
2553
+ grouped.set(entry.type, list);
2554
+ }
2555
+ for (const [type, group] of grouped) {
2556
+ log(chalk4.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${group.length}):`));
2557
+ for (const entry of group) {
2558
+ const priorityColor = entry.priority === "high" ? chalk4.red : entry.priority === "medium" ? chalk4.yellow : chalk4.white;
2559
+ const tags = entry.tags.map((t) => chalk4.gray(t)).join(", ");
2560
+ log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk4.gray("tags:")} ${tags}`);
2561
+ }
2562
+ log("");
2563
+ }
2564
+ }
2565
+ function readEntryFile(knowledgeDir, entries, id) {
2566
+ const meta = entries.find((e) => e.id === id);
2567
+ const path = meta ? join9(knowledgeDir, meta.file) : join9(knowledgeDir, "custom", `${id}.yml`);
2568
+ if (!existsSync9(path)) {
2569
+ throw new Error(`Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`);
2570
+ }
2571
+ return readFileSync8(path, "utf-8").trimEnd();
2572
+ }
2573
+ function printKnowledgeChangelog(knowledgeDir, log) {
2574
+ const changelogPath = join9(knowledgeDir, "changelog.yml");
2575
+ if (!existsSync9(changelogPath)) {
2576
+ log(chalk4.yellow(`No changelog at ${changelogPath}.`));
2577
+ return;
2578
+ }
2579
+ const changelog = KnowledgeChangelogSchema.parse(
2580
+ parseYaml3(readFileSync8(changelogPath, "utf-8"))
2581
+ );
2582
+ log(chalk4.cyan.bold("\nKnowledge Base Changelog:"));
2583
+ log("");
2584
+ for (const release of changelog.releases) {
2585
+ log(` ${chalk4.bold(`v${release.version}`)} ${chalk4.gray(`\xB7 ${release.date}`)}`);
2586
+ log(` ${release.summary}`);
2587
+ const added = release.entries_added.map((e) => e.id);
2588
+ if (added.length) log(` ${chalk4.gray("added:")} ${added.join(", ")}`);
2589
+ if (release.entries_modified.length) {
2590
+ log(` ${chalk4.gray("modified:")} ${release.entries_modified.join(", ")}`);
2591
+ }
2592
+ if (release.entries_removed.length) {
2593
+ log(` ${chalk4.gray("removed:")} ${release.entries_removed.join(", ")}`);
2594
+ }
2595
+ log("");
2596
+ }
2597
+ }
2598
+ function printKnowledgeStats(manifest, log) {
2599
+ log(chalk4.cyan.bold("\nKnowledge Base Stats:"));
2600
+ log(chalk4.white(` Version: ${manifest.version}`));
2601
+ log("");
2602
+ for (const [key, value] of Object.entries(manifest.stats)) {
2603
+ log(` ${pad2(key.replace(/_/g, " "), 18)} ${value}`);
2604
+ }
2605
+ log("");
2606
+ log(chalk4.cyan(` Active releases (${manifest.active_releases.length}):`));
2607
+ log(` ${manifest.active_releases.join(", ")}`);
2608
+ log("");
2609
+ const ls = manifest.loading_strategy;
2610
+ log(chalk4.cyan(" Loading strategy:"));
2611
+ log(` ${pad2("always", 12)} ${ls.always.length} entries`);
2612
+ for (const [bucket, map] of [
2613
+ ["by_domain", ls.by_domain],
2614
+ ["by_tag", ls.by_tag],
2615
+ ["by_skill", ls.by_skill ?? {}]
2616
+ ]) {
2617
+ const keys = Object.keys(map);
2618
+ const total = Object.values(map).reduce((n, ids) => n + ids.length, 0);
2619
+ log(` ${pad2(bucket, 12)} ${keys.length} keys, ${total} references`);
2620
+ }
2621
+ log("");
2622
+ }
2623
+ function listTargets(cwd) {
2624
+ const targetsDir = resolve6(cwd, "data", "targets");
2625
+ if (!existsSync9(targetsDir)) {
2626
+ console.log(chalk4.yellow("No targets found. Run `npx qualiow init` first."));
2627
+ return;
2628
+ }
2629
+ const files = readdirSync5(targetsDir).filter((f) => f.endsWith(".yml")).sort();
2630
+ const projectLocal = resolve6(cwd, "qa", "target.yml");
2631
+ if (files.length === 0 && !existsSync9(projectLocal)) {
2632
+ console.log(chalk4.yellow("No target configurations found."));
2633
+ return;
2634
+ }
2635
+ console.log(chalk4.cyan.bold("\nTargets:"));
2636
+ console.log("");
2637
+ const header = ` ${pad2("File", 34)} ${pad2("Name", 32)} ${pad2("Domain", 11)} ${pad2("Auth", 16)} Base URL`;
2638
+ console.log(chalk4.bold(header));
2639
+ console.log(` ${"\u2500".repeat(34)} ${"\u2500".repeat(32)} ${"\u2500".repeat(11)} ${"\u2500".repeat(16)} ${"\u2500".repeat(30)}`);
2640
+ const printTarget = (label, path) => {
2641
+ try {
2642
+ const target = parseYaml3(readFileSync8(path, "utf-8"));
2643
+ const url = target.base_url || target.web?.base_url || chalk4.gray("(none)");
2644
+ console.log(
2645
+ ` ${pad2(label, 34)} ${pad2(target.name, 32)} ${pad2(target.domain, 11)} ${pad2(target.auth?.strategy ?? "", 16)} ${url}`
2646
+ );
2647
+ } catch {
2648
+ console.log(` ${chalk4.red("ERROR")} Could not parse ${label}`);
2649
+ }
2650
+ };
2651
+ if (existsSync9(projectLocal)) printTarget("qa/target.yml", projectLocal);
2652
+ for (const file of files) printTarget(`data/targets/${file}`, join9(targetsDir, file));
2653
+ console.log("");
2654
+ console.log(chalk4.white(` Total: ${files.length + (existsSync9(projectLocal) ? 1 : 0)} target(s)`));
2655
+ console.log("");
2656
+ }
2657
+ function listDomains(cwd) {
2658
+ const domainsDir = resolve6(cwd, "data", "domains");
2659
+ if (!existsSync9(domainsDir)) {
2660
+ console.log(chalk4.yellow("No domain configs found. Run `npx qualiow init` first."));
2661
+ return;
2662
+ }
2663
+ const files = readdirSync5(domainsDir).filter((f) => f.endsWith(".yml")).sort();
2664
+ if (files.length === 0) {
2665
+ console.log(chalk4.yellow("No domain configurations found."));
2666
+ return;
2667
+ }
2668
+ console.log(chalk4.cyan.bold("\nDomains:"));
2669
+ console.log("");
2670
+ const header = ` ${pad2("File", 18)} ${pad2("Name", 32)} ${pad2("Checklist", 10)} ${pad2("Journeys", 9)} ${pad2("Patterns", 9)}`;
2671
+ console.log(chalk4.bold(header));
2672
+ console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(32)} ${"\u2500".repeat(10)} ${"\u2500".repeat(9)} ${"\u2500".repeat(9)}`);
2673
+ for (const file of files) {
2674
+ try {
2675
+ const domain = parseYaml3(readFileSync8(join9(domainsDir, file), "utf-8"));
2676
+ const patterns = Object.values(domain.must_test_patterns ?? {}).reduce((n, arr) => n + arr.length, 0);
2677
+ console.log(
2678
+ ` ${pad2(file, 18)} ${pad2(domain.name, 32)} ${pad2(String(domain.completeness_checklist?.length ?? 0), 10)} ${pad2(String(domain.journeys?.length ?? 0), 9)} ${pad2(String(patterns), 9)}`
2679
+ );
2680
+ } catch {
2681
+ console.log(` ${chalk4.red("ERROR")} Could not parse ${file}`);
2682
+ }
2683
+ }
2684
+ console.log("");
2685
+ console.log(chalk4.white(` Total: ${files.length} domain(s)`));
2686
+ console.log("");
2687
+ }
2688
+ function pad2(str, len) {
2689
+ if (str.length >= len) return str.slice(0, len);
2690
+ return str + " ".repeat(len - str.length);
2691
+ }
2692
+
2693
+ // src/cli/commands/validate.ts
2694
+ import { Command as Command5 } from "commander";
2695
+ import { resolve as resolve7, relative as relative5, join as join10 } from "path";
2696
+ import { existsSync as existsSync10 } from "fs";
2697
+ import { globSync as globSync4 } from "glob";
2698
+ import chalk5 from "chalk";
2699
+ function runValidate(options, cwd) {
2700
+ const dataDir = resolve7(cwd, "data");
2701
+ const runAll = options.all || !options.targets && !options.knowledge && !options.domains && !options.kb;
2702
+ if (!existsSync10(dataDir)) {
2703
+ throw new Error("data/ directory not found. Run `npx qualiow init` first.");
2704
+ }
2705
+ const results = [];
2706
+ const section = (title, files, fn) => {
2707
+ console.log(chalk5.cyan.bold(`
2708
+ ${title} (${files.length} files):`));
2709
+ for (const file of files) {
2710
+ const result = fn(file);
2711
+ results.push(result);
2712
+ printResult(result, cwd);
2713
+ }
2714
+ };
2715
+ if (runAll || options.targets) {
2716
+ const files = globSync4(resolve7(dataDir, "targets", "*.yml")).sort();
2717
+ const projectLocal = join10(cwd, "qa", "target.yml");
2718
+ if (existsSync10(projectLocal)) files.unshift(projectLocal);
2719
+ section("Targets", files, validateTargetConfig);
2720
+ }
2721
+ if (runAll || options.domains) {
2722
+ section("Domains", globSync4(resolve7(dataDir, "domains", "*.yml")).sort(), validateDomainConfig);
2723
+ }
2724
+ if (runAll || options.knowledge) {
2725
+ section(
2726
+ "Knowledge entries",
2727
+ globSync4(resolve7(dataDir, "knowledge", "releases", "**", "entries", "*.yml")).sort(),
2728
+ validateKnowledgeEntry
2729
+ );
2730
+ }
2731
+ if (runAll || options.kb) {
2732
+ if (existsSync10(join10(dataDir, "knowledge", "manifest.yml"))) {
2733
+ console.log(chalk5.cyan.bold("\nKnowledge base:"));
2734
+ for (const result of validateKnowledgeBase(dataDir)) {
2735
+ results.push(result);
2736
+ printResult(result, cwd);
2737
+ }
2738
+ } else {
2739
+ console.log(chalk5.yellow("\n No knowledge/manifest.yml found"));
2740
+ }
2741
+ }
2742
+ const total = results.length;
2743
+ const passed = results.filter((r) => r.valid).length;
2744
+ const failed = total - passed;
2745
+ console.log("");
2746
+ console.log(chalk5.bold("Summary:"));
2747
+ console.log(
2748
+ ` ${total} checks, ${chalk5.green(`${passed} passed`)}, ${failed > 0 ? chalk5.red(`${failed} failed`) : chalk5.green("0 failed")}`
2749
+ );
2750
+ console.log("");
2751
+ return failed;
2752
+ }
2753
+ function printResult(result, cwd) {
2754
+ const relPath = relative5(cwd, result.file);
2755
+ if (result.valid) {
2756
+ console.log(` ${chalk5.green("PASS")} ${relPath}`);
2757
+ } else {
2758
+ console.log(` ${chalk5.red("FAIL")} ${relPath}`);
2759
+ for (const err of result.errors ?? []) {
2760
+ const pathStr = err.path ? `[${err.path}] ` : "";
2761
+ console.log(` ${chalk5.red("\u2192")} ${pathStr}${err.message}`);
2762
+ }
2763
+ }
2764
+ }
2765
+
2766
+ // src/cli/commands/kb.ts
2767
+ import { Command as Command6 } from "commander";
2768
+ import { resolve as resolve8, join as join11 } from "path";
2769
+ import { existsSync as existsSync11, readFileSync as readFileSync9, readdirSync as readdirSync6 } from "fs";
2770
+ import chalk6 from "chalk";
2771
+ import { parse as parseYaml4 } from "yaml";
2772
+ var DEFAULT_MAX_LINES = 12;
2773
+ var WRAP_COLUMN = 100;
2774
+ var WHEN_TO_USE_ITEMS = 3;
2775
+ function runKb(mode, cwd) {
2776
+ const dataDir = resolve8(cwd, "data");
2777
+ if (!existsSync11(resolve8(dataDir, "knowledge", "manifest.yml"))) {
2778
+ throw new Error("data/knowledge/manifest.yml not found. Run `npx qualiow init` first.");
2779
+ }
2780
+ return syncKnowledgeManifest(dataDir, { check: mode === "check" });
2781
+ }
2782
+ function runKbDigest(options, cwd) {
2783
+ const dataDir = resolveDataDir(cwd, options.data);
2784
+ const knowledgeDir = join11(dataDir, "knowledge");
2785
+ const manifestPath = join11(knowledgeDir, "manifest.yml");
2786
+ if (!existsSync11(manifestPath)) {
2787
+ throw new Error(
2788
+ `No knowledge manifest at ${manifestPath}. Pass --data <dir>, or run \`npx qualiow init\` first.`
2789
+ );
2790
+ }
2791
+ const manifest = KnowledgeManifestSchema.parse(
2792
+ parseYaml4(readFileSync9(manifestPath, "utf-8"))
2793
+ );
2794
+ const byId = new Map(manifest.entries.map((e) => [e.id, e]));
2795
+ const maxLines = Math.max(1, options.maxLines ?? DEFAULT_MAX_LINES);
2796
+ if (options.entry) {
2797
+ return readWholeEntry(knowledgeDir, byId, options.entry);
2798
+ }
2799
+ const ls = manifest.loading_strategy;
2800
+ const selected = [];
2801
+ const add = (ids) => {
2802
+ let added = 0;
2803
+ for (const id of ids ?? []) {
2804
+ if (selected.includes(id)) continue;
2805
+ selected.push(id);
2806
+ added++;
2807
+ }
2808
+ return added;
2809
+ };
2810
+ add(ls.always);
2811
+ const domainAdded = options.domain ? add(ls.by_domain[options.domain]) : 0;
2812
+ const tags = options.tag ?? [];
2813
+ let tagAdded = 0;
2814
+ for (const tag of tags) tagAdded += add(ls.by_tag[tag]);
2815
+ let skillAdded = 0;
2816
+ if (options.for) {
2817
+ const bySkill = ls.by_skill;
2818
+ if (!bySkill) {
2819
+ throw new Error(
2820
+ "This manifest has no loading_strategy.by_skill, so --for has nothing to select."
2821
+ );
2822
+ }
2823
+ if (!Object.prototype.hasOwnProperty.call(bySkill, options.for)) {
2824
+ throw new Error(
2825
+ `Unknown skill "${options.for}". Known: ${Object.keys(bySkill).sort().join(", ")}.`
2826
+ );
2827
+ }
2828
+ skillAdded = add(bySkill[options.for]);
2829
+ }
2830
+ const unknown = selected.filter((id) => !byId.has(id));
2831
+ if (unknown.length) {
2832
+ throw new Error(
2833
+ `loading_strategy references ${unknown.length} unknown entry id(s): ${unknown.join(", ")}. Run \`qualiow kb sync\` and \`qualiow validate --kb\`.`
2834
+ );
2835
+ }
2836
+ const header = [
2837
+ `# Knowledge digest v${manifest.version}`,
2838
+ `${selected.length} entries`,
2839
+ `always ${ls.always.length}`
2840
+ ];
2841
+ if (options.domain) header.push(`domain ${options.domain} +${domainAdded}`);
2842
+ if (tags.length) header.push(`tags ${tags.join(", ")} +${tagAdded}`);
2843
+ if (options.for) header.push(`skill ${options.for} +${skillAdded}`);
2844
+ const lines = [header.join(" \xB7 ")];
2845
+ for (const id of selected) {
2846
+ const meta = byId.get(id);
2847
+ lines.push(...entryBlock(join11(knowledgeDir, meta.file), meta, maxLines));
2848
+ }
2849
+ lines.push(...customSection(knowledgeDir, maxLines));
2850
+ lines.push(...learnedPatternsSection(cwd, knowledgeDir));
2851
+ return lines.join("\n");
2852
+ }
2853
+ function readWholeEntry(knowledgeDir, byId, id) {
2854
+ const meta = byId.get(id);
2855
+ const path = meta ? join11(knowledgeDir, meta.file) : join11(knowledgeDir, "custom", `${id}.yml`);
2856
+ if (!existsSync11(path)) {
2857
+ throw new Error(
2858
+ `Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`
2859
+ );
2860
+ }
2861
+ return readFileSync9(path, "utf-8").trimEnd();
2862
+ }
2863
+ function entryBlock(file, meta, maxLines, custom = false) {
2864
+ if (!existsSync11(file)) {
2865
+ throw new Error(`Entry "${meta.id}" is registered but its file is missing: ${file}`);
2866
+ }
2867
+ const entry = KnowledgeEntrySchema.parse(parseYaml4(readFileSync9(file, "utf-8")));
2868
+ const content = entry.content;
2869
+ const marker = custom ? " [custom]" : "";
2870
+ const out = [
2871
+ `- ${meta.id} [${meta.type}/${meta.priority}]${marker} tags: ${meta.tags.join(", ")}`
2872
+ ];
2873
+ out.push(...wrap(collapse(entry.content.summary)));
2874
+ for (const [key, items] of namedArrays(content)) {
2875
+ const rendered = items.map((item) => {
2876
+ const lead = subItemLead(item);
2877
+ return lead ? `${item.name} \u2014 ${lead}` : item.name;
2878
+ }).join("; ");
2879
+ out.push(...wrap(`${humanise(key)}: ${rendered}`));
2880
+ }
2881
+ const whenToUse = content["when_to_use"];
2882
+ if (Array.isArray(whenToUse) && whenToUse.length) {
2883
+ const items = whenToUse.slice(0, WHEN_TO_USE_ITEMS).filter((v) => typeof v === "string").map(collapse);
2884
+ if (items.length) out.push(...wrap(`when to use: ${items.join("; ")}`));
2885
+ }
2886
+ return capLines(out, maxLines);
2887
+ }
2888
+ function customSection(knowledgeDir, maxLines) {
2889
+ const customDir = join11(knowledgeDir, "custom");
2890
+ if (!existsSync11(customDir)) return [];
2891
+ const files = readdirSync6(customDir).filter((f) => f.endsWith(".yml")).sort();
2892
+ if (!files.length) return [];
2893
+ const lines = ["", "## Custom entries"];
2894
+ for (const file of files) {
2895
+ const path = join11(customDir, file);
2896
+ const parsed = parseYaml4(readFileSync9(path, "utf-8"));
2897
+ lines.push(
2898
+ ...entryBlock(
2899
+ path,
2900
+ {
2901
+ id: parsed.id ?? file.replace(/\.yml$/, ""),
2902
+ type: parsed.type ?? "custom",
2903
+ priority: parsed.priority ?? "medium",
2904
+ tags: parsed.tags ?? []
2905
+ },
2906
+ maxLines,
2907
+ true
2908
+ )
2909
+ );
2910
+ }
2911
+ return lines;
2912
+ }
2913
+ function learnedPatternsSection(cwd, knowledgeDir) {
2914
+ const candidates = [
2915
+ resolve8(cwd, "data", "knowledge", "learned-patterns.md"),
2916
+ join11(knowledgeDir, "learned-patterns.md")
2917
+ ];
2918
+ const path = candidates.find((p) => existsSync11(p));
2919
+ if (!path) return [];
2920
+ const sections = learnedPatternLeadIns(readFileSync9(path, "utf-8"));
2921
+ if (!sections.length) return [];
2922
+ const lines = ["", "## Learned patterns", "Grep the file for the full entry."];
2923
+ for (const section of sections) {
2924
+ lines.push(...wrap(`${section.heading}: ${section.items.join("; ")}`));
2925
+ }
2926
+ return lines;
2927
+ }
2928
+ function learnedPatternLeadIns(markdown) {
2929
+ const sections = [];
2930
+ let current = null;
2931
+ let bullet = null;
2932
+ const flush = () => {
2933
+ if (bullet !== null && current) {
2934
+ const match = /^\*\*([\s\S]+?)\*\*/.exec(bullet);
2935
+ if (match) current.items.push(collapse(match[1]));
2936
+ }
2937
+ bullet = null;
2938
+ };
2939
+ for (const raw of markdown.split("\n")) {
2940
+ const heading = /^#{2,}\s+(.+)$/.exec(raw);
2941
+ if (heading) {
2942
+ flush();
2943
+ current = { heading: heading[1].trim(), items: [] };
2944
+ sections.push(current);
2945
+ continue;
2946
+ }
2947
+ const start = /^[-*]\s+(.*)$/.exec(raw);
2948
+ if (start) {
2949
+ flush();
2950
+ bullet = start[1];
2951
+ continue;
2952
+ }
2953
+ if (bullet !== null) {
2954
+ if (raw.trim() === "") flush();
2955
+ else bullet += ` ${raw.trim()}`;
2956
+ }
2957
+ }
2958
+ flush();
2959
+ return sections.filter((s) => s.items.length > 0);
2960
+ }
2961
+ function namedArrays(content) {
2962
+ const found = [];
2963
+ for (const [key, value] of Object.entries(content)) {
2964
+ if (key === "summary" || key === "when_to_use") continue;
2965
+ if (!Array.isArray(value) || value.length === 0) continue;
2966
+ const items = value.filter(
2967
+ (v) => typeof v === "object" && v !== null && typeof v.name === "string"
2968
+ );
2969
+ if (items.length === value.length) found.push([key, items]);
2970
+ }
2971
+ return found;
2972
+ }
2973
+ function subItemLead(item) {
2974
+ const questions = item["questions"];
2975
+ if (Array.isArray(questions) && typeof questions[0] === "string") {
2976
+ return truncate(collapse(questions[0]));
2977
+ }
2978
+ const description = item["description"];
2979
+ if (typeof description === "string") return truncate(collapse(description));
2980
+ return "";
2981
+ }
2982
+ function collapse(text) {
2983
+ return text.replace(/\s+/g, " ").trim();
2984
+ }
2985
+ function truncate(text, limit = WRAP_COLUMN) {
2986
+ if (text.length <= limit) return text;
2987
+ const cut = text.slice(0, limit - 1);
2988
+ const lastSpace = cut.lastIndexOf(" ");
2989
+ return `${(lastSpace > limit / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
2990
+ }
2991
+ function humanise(key) {
2992
+ const spaced = key.replace(/_/g, " ");
2993
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
2994
+ }
2995
+ function wrap(text, width = WRAP_COLUMN, indent = " ", hanging = " ") {
2996
+ const words = collapse(text).split(" ").filter(Boolean);
2997
+ if (!words.length) return [];
2998
+ const out = [];
2999
+ let line = indent + words[0];
3000
+ for (const word of words.slice(1)) {
3001
+ if (line.length + 1 + word.length > width) {
3002
+ out.push(line);
3003
+ line = hanging + word;
3004
+ } else {
3005
+ line += ` ${word}`;
3006
+ }
3007
+ }
3008
+ out.push(line);
3009
+ return out;
3010
+ }
3011
+ function capLines(lines, maxLines) {
3012
+ if (lines.length <= maxLines) return lines;
3013
+ const kept = lines.slice(0, maxLines);
3014
+ kept[kept.length - 1] = `${kept[kept.length - 1]} \u2026`;
3015
+ return kept;
3016
+ }
1235
3017
  export {
3018
+ ALL_BUGS_COLUMNS,
3019
+ ALL_BUGS_MD_HEADER,
1236
3020
  AuthConfigSchema,
1237
3021
  BrowserConfigSchema,
3022
+ CONFIDENTIALITY_HEADER_MD,
3023
+ CONFIDENTIALITY_LINES,
3024
+ CONFIDENTIALITY_NOTICE,
1238
3025
  DomainConfigSchema,
3026
+ INDEX_COLUMNS,
3027
+ INDEX_MD_HEADER,
1239
3028
  JourneySchema,
3029
+ KnowledgeChangelogSchema,
1240
3030
  KnowledgeEntryContentSchema,
1241
3031
  KnowledgeEntrySchema,
1242
3032
  KnowledgeManifestEntrySchema,
1243
3033
  KnowledgeManifestSchema,
1244
3034
  KnowledgeManifestStatsSchema,
3035
+ KnowledgeReleaseSchema,
1245
3036
  LoadingStrategySchema,
1246
3037
  MobileAppConfigSchema,
1247
3038
  MobileDeviceConfigSchema,
1248
3039
  MobileScopeConfigSchema,
1249
3040
  MobileTargetConfigSchema,
1250
3041
  MobileWebConfigSchema,
3042
+ QUALIOW_GITIGNORE_ENTRIES,
3043
+ QUALIOW_GITIGNORE_HEADER,
3044
+ REDACTION_CATEGORIES,
3045
+ SESSION_DIR_RE,
3046
+ SESSION_KINDS,
1251
3047
  SafetyConfigSchema,
1252
3048
  ScopeConfigSchema,
1253
3049
  SessionMetricsSchema,
@@ -1256,17 +3052,51 @@ export {
1256
3052
  TargetConfigSchema,
1257
3053
  WebTargetConfigSchema,
1258
3054
  appendSessionMetrics,
3055
+ appendSessionMetricsDeduped,
3056
+ buildManifestRegistry,
3057
+ computeStats,
1259
3058
  containsSecrets,
3059
+ csvEscape,
3060
+ extractCoverage,
3061
+ extractListSection,
3062
+ extractReportMeta,
1260
3063
  generateHtmlReport,
1261
3064
  generateJiraExport,
1262
3065
  generateJsonReport,
3066
+ generateMarkdownSummary,
3067
+ getPackageRoot,
3068
+ getPackageVersion,
3069
+ hasConfidentialityHeader,
3070
+ listReleaseDirs,
3071
+ loadSessionForOutput,
3072
+ mergeGitignore,
1263
3073
  parseBugReport,
3074
+ parseMarkdownTable,
1264
3075
  parseSession,
3076
+ parseSessionDirName,
3077
+ parseTimeBox,
1265
3078
  readAllMetrics,
3079
+ readSessionIndex,
1266
3080
  redact,
3081
+ resolveDataDir,
3082
+ resolveDomainPath,
3083
+ resolveSessionDir,
3084
+ resolveSkillsSource,
3085
+ resolveTargetPath,
3086
+ runExplore,
3087
+ runInit,
3088
+ runKb,
3089
+ runKbDigest,
3090
+ runList,
3091
+ runReport,
3092
+ runValidate,
3093
+ sessionDirName,
3094
+ sessionTimestamp,
3095
+ slugify,
3096
+ syncKnowledgeManifest,
1267
3097
  validateAllConfigs,
1268
3098
  validateDomainConfig,
3099
+ validateKnowledgeBase,
1269
3100
  validateKnowledgeEntry,
1270
3101
  validateTargetConfig
1271
3102
  };
1272
- //# sourceMappingURL=index.js.map