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/cli/index.js CHANGED
@@ -1,68 +1,224 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli/index.ts
4
- import { Command as Command7 } from "commander";
4
+ import { Command as Command8 } from "commander";
5
5
 
6
6
  // src/cli/commands/init.ts
7
7
  import { Command } from "commander";
8
- import { fileURLToPath } from "url";
9
- import { dirname, resolve, join } from "path";
8
+ import { resolve as resolve2, join as join2, relative, dirname as dirname2 } from "path";
10
9
  import {
11
- existsSync,
12
- readFileSync,
10
+ existsSync as existsSync2,
11
+ readFileSync as readFileSync2,
13
12
  writeFileSync,
14
13
  mkdirSync,
15
- readdirSync
14
+ readdirSync,
15
+ statSync,
16
+ copyFileSync,
17
+ chmodSync
16
18
  } from "fs";
17
- import { cp } from "fs/promises";
18
19
  import chalk from "chalk";
19
- var __dirname = dirname(fileURLToPath(import.meta.url));
20
- function resolvePackageRoot() {
21
- let current = __dirname;
20
+
21
+ // src/utils/paths.ts
22
+ import { fileURLToPath } from "url";
23
+ import { dirname, resolve, join, basename } from "path";
24
+ import { existsSync, readFileSync } from "fs";
25
+ var HERE = dirname(fileURLToPath(import.meta.url));
26
+ function getPackageRoot() {
27
+ let current = HERE;
22
28
  for (let i = 0; i < 10; i++) {
23
29
  if (existsSync(join(current, "data")) && existsSync(join(current, "package.json"))) {
24
30
  return current;
25
31
  }
26
- current = dirname(current);
32
+ const parent = dirname(current);
33
+ if (parent === current) break;
34
+ current = parent;
35
+ }
36
+ return resolve(HERE, "..", "..");
37
+ }
38
+ function getPackageVersion(pkgRoot = getPackageRoot()) {
39
+ try {
40
+ const pkg = JSON.parse(
41
+ readFileSync(join(pkgRoot, "package.json"), "utf-8")
42
+ );
43
+ return pkg.version ?? "0.0.0";
44
+ } catch {
45
+ return "0.0.0";
27
46
  }
28
- return resolve(__dirname, "..", "..");
29
47
  }
30
- var GITIGNORE_ENTRIES = [
31
- "",
32
- "# Qualiow",
48
+ function resolveSkillsSource(pkgRoot) {
49
+ const shipped = join(pkgRoot, "skills");
50
+ if (existsSync(shipped)) return shipped;
51
+ const canonical = join(pkgRoot, ".claude", "skills");
52
+ if (existsSync(canonical)) return canonical;
53
+ return null;
54
+ }
55
+ function resolveTargetPath(cwd, name, pkgRoot = getPackageRoot()) {
56
+ if (name) {
57
+ const candidates = [
58
+ resolve(cwd, "data", "targets", `${name}.yml`),
59
+ resolve(pkgRoot, "data", "targets", `${name}.yml`)
60
+ ];
61
+ return candidates.find((p) => existsSync(p)) ?? candidates[0];
62
+ }
63
+ const projectLocal = resolve(cwd, "qa", "target.yml");
64
+ if (existsSync(projectLocal)) return projectLocal;
65
+ const cwdDefault = resolve(cwd, "data", "targets", "_default.yml");
66
+ if (existsSync(cwdDefault)) return cwdDefault;
67
+ return resolve(pkgRoot, "data", "targets", "_default.yml");
68
+ }
69
+ function resolveDataDir(cwd, explicit, pkgRoot = getPackageRoot()) {
70
+ if (explicit) return resolve(cwd, explicit);
71
+ const projectLocal = resolve(cwd, "data");
72
+ if (existsSync(join(projectLocal, "knowledge", "manifest.yml"))) {
73
+ return projectLocal;
74
+ }
75
+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
76
+ if (pluginRoot) {
77
+ const pluginData = resolve(pluginRoot, "data");
78
+ if (existsSync(pluginData)) return pluginData;
79
+ }
80
+ return resolve(pkgRoot, "data");
81
+ }
82
+
83
+ // src/utils/index-files.ts
84
+ var INDEX_COLUMNS = [
85
+ "Date",
86
+ "Kind",
87
+ "Target",
88
+ "Bugs",
89
+ "Duration",
90
+ "Status",
91
+ "Report"
92
+ ];
93
+ var ALL_BUGS_COLUMNS = [
94
+ "ID",
95
+ "Session",
96
+ "Title",
97
+ "Severity",
98
+ "Status",
99
+ "Report"
100
+ ];
101
+ function table(title, note, columns) {
102
+ const header = `| ${columns.join(" | ")} |`;
103
+ const sep2 = `|${columns.map(() => "---").join("|")}|`;
104
+ return `# ${title}
105
+
106
+ ${note}
107
+
108
+ ${header}
109
+ ${sep2}
110
+ `;
111
+ }
112
+ var INDEX_MD_HEADER = table(
113
+ "Exploratory Testing Sessions",
114
+ "_Index of exploratory testing sessions. Newest last._",
115
+ INDEX_COLUMNS
116
+ );
117
+ var ALL_BUGS_MD_HEADER = table(
118
+ "All Bugs Found",
119
+ "_Consolidated index across all exploratory testing sessions._",
120
+ ALL_BUGS_COLUMNS
121
+ );
122
+
123
+ // src/utils/gitignore.ts
124
+ var QUALIOW_GITIGNORE_HEADER = "# Qualiow";
125
+ var QUALIOW_GITIGNORE_ENTRIES = [
33
126
  ".auth/",
34
127
  ".env",
128
+ "qa/.env",
35
129
  "output/sessions/*/",
130
+ "!output/sessions/INDEX.md",
131
+ "output/context/*.md",
132
+ "data/targets/local-*.yml",
36
133
  ".playwright-cli/",
37
134
  "*.trace.zip",
38
- "*.webm",
39
- "dist/"
135
+ "*.webm"
40
136
  ];
41
- var INDEX_MD_HEADER = `# Exploratory Testing Sessions
42
-
43
- | Date | Target | Duration | Bugs | Session Directory |
44
- |------|--------|----------|------|-------------------|
45
- `;
46
- var ALL_BUGS_MD_HEADER = `# All Bugs \u2014 Exploratory Testing
47
-
48
- > Aggregated bug list across all sessions.
49
-
50
- | ID | Title | Severity | Session | Component |
51
- |----|-------|----------|---------|-----------|
52
- `;
53
- var ENV_EXAMPLE = `# Qualiow \u2014 Environment Variables
54
- # Copy this file to .env and fill in values.
137
+ function mergeGitignore(existing) {
138
+ const existingLines = new Set(
139
+ existing.split("\n").map((l) => l.replace(/\s+$/, ""))
140
+ );
141
+ const missing = QUALIOW_GITIGNORE_ENTRIES.filter(
142
+ (e) => !existingLines.has(e)
143
+ );
144
+ if (missing.length === 0) return null;
145
+ const block = [];
146
+ if (!existingLines.has(QUALIOW_GITIGNORE_HEADER)) {
147
+ block.push(QUALIOW_GITIGNORE_HEADER);
148
+ }
149
+ block.push(...missing);
150
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
151
+ const leadingBlank = existing.length > 0 ? "\n" : "";
152
+ return existing + prefix + leadingBlank + block.join("\n") + "\n";
153
+ }
55
154
 
56
- # Target auth tokens (if needed)
57
- # AUTH_TOKEN=
155
+ // src/utils/settings-merge.ts
156
+ var QUALIOW_HOOK_ENTRIES = [
157
+ { matcher: "Read", command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/read-guard.mjs"' },
158
+ {
159
+ matcher: "Write|Edit|MultiEdit",
160
+ command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/write-guard.mjs"'
161
+ }
162
+ ];
163
+ var QUALIOW_PERMISSION_ALLOW = [
164
+ "Bash(playwright-cli:*)",
165
+ "Bash(npx playwright-cli:*)",
166
+ "Bash(qualiow:*)"
167
+ ];
168
+ function isRecord(v) {
169
+ return typeof v === "object" && v !== null && !Array.isArray(v);
170
+ }
171
+ function existingHookCommands(settings) {
172
+ const commands = /* @__PURE__ */ new Set();
173
+ const hooks = settings.hooks;
174
+ if (!isRecord(hooks)) return commands;
175
+ const preToolUse = hooks.PreToolUse;
176
+ if (!Array.isArray(preToolUse)) return commands;
177
+ for (const entry of preToolUse) {
178
+ if (!isRecord(entry) || !Array.isArray(entry.hooks)) continue;
179
+ for (const h of entry.hooks) {
180
+ if (isRecord(h) && typeof h.command === "string") commands.add(h.command);
181
+ }
182
+ }
183
+ return commands;
184
+ }
185
+ function mergeQualiowHookSettings(existing) {
186
+ const settings = isRecord(existing) ? { ...existing } : {};
187
+ let changed = false;
188
+ const hooksSection = isRecord(settings.hooks) ? { ...settings.hooks } : {};
189
+ const preToolUse = Array.isArray(hooksSection.PreToolUse) ? [...hooksSection.PreToolUse] : [];
190
+ const haveCommands = existingHookCommands(settings);
191
+ for (const { matcher, command } of QUALIOW_HOOK_ENTRIES) {
192
+ if (haveCommands.has(command)) continue;
193
+ preToolUse.push({ matcher, hooks: [{ type: "command", command }] });
194
+ haveCommands.add(command);
195
+ changed = true;
196
+ }
197
+ hooksSection.PreToolUse = preToolUse;
198
+ settings.hooks = hooksSection;
199
+ const permissions = isRecord(settings.permissions) ? { ...settings.permissions } : {};
200
+ const allow = Array.isArray(permissions.allow) ? [...permissions.allow] : [];
201
+ const allowSet = new Set(allow.filter((a) => typeof a === "string"));
202
+ for (const rule of QUALIOW_PERMISSION_ALLOW) {
203
+ if (allowSet.has(rule)) continue;
204
+ allow.push(rule);
205
+ allowSet.add(rule);
206
+ changed = true;
207
+ }
208
+ permissions.allow = allow;
209
+ settings.permissions = permissions;
210
+ return { settings, changed };
211
+ }
58
212
 
59
- # Playwright options
60
- # HEADLESS=false
61
- `;
213
+ // src/cli/commands/init.ts
62
214
  function initCommand() {
63
- const cmd = new Command("init").description("Initialize qualiow in the current project").option("--include-examples", "Include example target configurations", false).option("--force", "Overwrite existing files", false).action(async (options) => {
215
+ const cmd = new Command("init").description("Initialize qualiow in the current project").option("--include-examples", "Also install the _example-* and testers-ai target configs", false).option("--force", "Overwrite files that already exist and differ", false).option("--dry-run", "Print what would be written without writing anything", false).option(
216
+ "--hooks",
217
+ "Install the PreToolUse guard hooks into qa/hooks/ and wire them into .claude/settings.json",
218
+ false
219
+ ).action(async (options) => {
64
220
  try {
65
- await runInit(options);
221
+ await runInit(options, { cwd: process.cwd() });
66
222
  } catch (err) {
67
223
  console.error(chalk.red("Error during init:"), err instanceof Error ? err.message : err);
68
224
  process.exit(1);
@@ -70,159 +226,230 @@ function initCommand() {
70
226
  });
71
227
  return cmd;
72
228
  }
73
- async function runInit(options) {
74
- const cwd = process.cwd();
75
- const pkgRoot = resolvePackageRoot();
76
- const skillsDest = join(cwd, ".claude", "skills");
77
- const existingSkills = existsSync(skillsDest) ? readdirSync(skillsDest).filter((f) => f.startsWith("qa-")) : [];
78
- if (existingSkills.length > 0 && !options.force) {
79
- console.warn(
80
- chalk.yellow(
81
- `Warning: ${existingSkills.length} skill(s) already exist in .claude/skills/ (${existingSkills.join(", ")}). Use --force to overwrite.`
82
- )
83
- );
229
+ function sameContent(a, b) {
230
+ try {
231
+ return readFileSync2(a).equals(readFileSync2(b));
232
+ } catch {
233
+ return false;
234
+ }
235
+ }
236
+ function copyEntry(src, dest, opts) {
237
+ let status;
238
+ if (!existsSync2(dest)) {
239
+ status = "installed";
240
+ } else if (sameContent(src, dest)) {
241
+ status = "unchanged";
242
+ } else {
243
+ status = opts.force ? "overwritten" : "skipped";
84
244
  }
85
- const skillsSrc = join(pkgRoot, ".claude", "skills");
86
- if (existsSync(skillsSrc)) {
87
- const srcReal = resolve(skillsSrc);
88
- const destReal = resolve(skillsDest);
89
- if (srcReal !== destReal) {
90
- if (existingSkills.length === 0 || options.force) {
91
- mkdirSync(skillsDest, { recursive: true });
92
- await cp(skillsSrc, skillsDest, { recursive: true, force: options.force });
93
- console.log(chalk.green(" \u2713 Skills installed to .claude/skills/"));
245
+ if (!opts.dryRun && (status === "installed" || status === "overwritten")) {
246
+ mkdirSync(dirname2(dest), { recursive: true });
247
+ copyFileSync(src, dest);
248
+ chmodSync(dest, statSync(src).mode & 511);
249
+ }
250
+ return { dest, status };
251
+ }
252
+ function listFiles(dir, filter) {
253
+ const out = [];
254
+ const walk = (current) => {
255
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
256
+ const full = join2(current, entry.name);
257
+ if (entry.isDirectory()) {
258
+ walk(full);
94
259
  } else {
95
- console.log(chalk.cyan(" \u25CB Skills skipped (already exist, use --force to overwrite)"));
260
+ const rel = relative(dir, full).split("\\").join("/");
261
+ if (!filter || filter(rel)) out.push(rel);
96
262
  }
97
- } else {
98
- console.log(chalk.cyan(" \u25CB Skills directory is the same as source \u2014 skipped"));
99
263
  }
264
+ };
265
+ walk(dir);
266
+ return out.sort();
267
+ }
268
+ function copyTree(srcDir, destDir, opts) {
269
+ if (!existsSync2(srcDir)) return [];
270
+ return listFiles(srcDir, opts.filter).map(
271
+ (rel) => copyEntry(join2(srcDir, rel), join2(destDir, rel), opts)
272
+ );
273
+ }
274
+ async function runInit(options, ctx) {
275
+ const cwd = ctx.cwd;
276
+ const pkgRoot = ctx.pkgRoot ?? getPackageRoot();
277
+ const log = ctx.log ?? ((line) => console.log(line));
278
+ const copyOpts = { force: options.force, dryRun: options.dryRun };
279
+ const copies = [];
280
+ const createdDirs = [];
281
+ const createdFiles = [];
282
+ if (options.dryRun) log(chalk.cyan.bold("Dry run \u2014 nothing will be written\n"));
283
+ if (resolve2(pkgRoot) === resolve2(cwd)) {
284
+ log(chalk.yellow(" \u25CB Running inside the package itself \u2014 skills and data are already in place"));
100
285
  } else {
101
- console.log(chalk.yellow(" \u26A0 No skills/ directory found in package root"));
102
- }
103
- const dataSrc = join(pkgRoot, "data");
104
- const dataDest = join(cwd, "data");
105
- if (existsSync(dataSrc)) {
106
- const srcReal = resolve(dataSrc);
107
- const destReal = resolve(dataDest);
108
- if (srcReal !== destReal) {
109
- mkdirSync(dataDest, { recursive: true });
110
- const knowledgeSrc = join(dataSrc, "knowledge");
111
- if (existsSync(knowledgeSrc)) {
112
- await cp(knowledgeSrc, join(dataDest, "knowledge"), { recursive: true, force: options.force });
113
- console.log(chalk.green(" \u2713 Knowledge base installed to data/knowledge/"));
114
- }
115
- const domainsSrc = join(dataSrc, "domains");
116
- if (existsSync(domainsSrc)) {
117
- await cp(domainsSrc, join(dataDest, "domains"), { recursive: true, force: options.force });
118
- console.log(chalk.green(" \u2713 Domain configs installed to data/domains/"));
119
- }
120
- const templatesSrc = join(dataSrc, "templates");
121
- if (existsSync(templatesSrc)) {
122
- await cp(templatesSrc, join(dataDest, "templates"), { recursive: true, force: options.force });
123
- console.log(chalk.green(" \u2713 Templates installed to data/templates/"));
124
- }
125
- const securitySrc = join(dataSrc, "security");
126
- if (existsSync(securitySrc)) {
127
- await cp(securitySrc, join(dataDest, "security"), { recursive: true, force: options.force });
128
- console.log(chalk.green(" \u2713 Security policies installed to data/security/"));
129
- }
130
- const targetsSrc = join(dataSrc, "targets");
131
- const targetsDest = join(dataDest, "targets");
132
- if (existsSync(targetsSrc)) {
133
- mkdirSync(targetsDest, { recursive: true });
134
- const defaultFile = join(targetsSrc, "_default.yml");
135
- if (existsSync(defaultFile)) {
136
- const content = readFileSync(defaultFile, "utf-8");
137
- writeFileSync(join(targetsDest, "_default.yml"), content);
138
- }
139
- if (options.includeExamples) {
140
- const targetFiles = readdirSync(targetsSrc).filter(
141
- (f) => f.endsWith(".yml") && f !== "_default.yml"
142
- );
143
- for (const file of targetFiles) {
144
- const content = readFileSync(join(targetsSrc, file), "utf-8");
145
- writeFileSync(join(targetsDest, file), content);
146
- }
147
- console.log(chalk.green(" \u2713 Target configs installed to data/targets/ (with examples)"));
148
- } else {
149
- console.log(chalk.green(" \u2713 Default target config installed to data/targets/"));
286
+ const skillsSrc = resolveSkillsSource(pkgRoot);
287
+ if (!skillsSrc) {
288
+ throw new Error(`No skills directory found under ${pkgRoot}`);
289
+ }
290
+ copies.push(
291
+ ...copyTree(skillsSrc, join2(cwd, ".claude", "skills"), {
292
+ ...copyOpts,
293
+ filter: (rel2) => rel2.startsWith("qa-")
294
+ })
295
+ );
296
+ const agentsCandidates = [join2(pkgRoot, "agents"), join2(pkgRoot, ".claude", "agents")];
297
+ const agentsSrc = agentsCandidates.find((p) => existsSync2(p));
298
+ if (agentsSrc) {
299
+ copies.push(
300
+ ...copyTree(agentsSrc, join2(cwd, ".claude", "agents"), {
301
+ ...copyOpts,
302
+ filter: (rel2) => rel2.endsWith(".md")
303
+ })
304
+ );
305
+ }
306
+ const dataSrc = join2(pkgRoot, "data");
307
+ copies.push(...copyTree(join2(dataSrc, "knowledge"), join2(cwd, "data", "knowledge"), copyOpts));
308
+ copies.push(
309
+ ...copyTree(join2(dataSrc, "domains"), join2(cwd, "data", "domains"), {
310
+ ...copyOpts,
311
+ filter: (rel2) => rel2.endsWith(".yml")
312
+ })
313
+ );
314
+ copies.push(...copyTree(join2(dataSrc, "templates"), join2(cwd, "data", "templates"), copyOpts));
315
+ copies.push(...copyTree(join2(dataSrc, "security"), join2(cwd, "data", "security"), copyOpts));
316
+ copies.push(
317
+ ...copyTree(join2(dataSrc, "targets"), join2(cwd, "data", "targets"), {
318
+ ...copyOpts,
319
+ filter: (rel2) => {
320
+ if (!rel2.endsWith(".yml") || rel2.includes("/")) return false;
321
+ if (rel2.startsWith("local-")) return false;
322
+ if (rel2 === "_default.yml") return true;
323
+ if (!options.includeExamples) return false;
324
+ return rel2.startsWith("_example-") || rel2 === "testers-ai.yml";
150
325
  }
326
+ })
327
+ );
328
+ const binSrc = join2(pkgRoot, "bin");
329
+ copies.push(
330
+ ...copyTree(binSrc, join2(cwd, "qa", "bin"), {
331
+ ...copyOpts,
332
+ filter: (rel2) => rel2 !== "qualiow"
333
+ })
334
+ );
335
+ if (existsSync2(binSrc)) {
336
+ const versionPath = join2(cwd, "qa", "bin", "VERSION");
337
+ const version = `${getPackageVersion(pkgRoot)}
338
+ `;
339
+ const exists = existsSync2(versionPath);
340
+ const same = exists && readFileSync2(versionPath, "utf-8") === version;
341
+ const status = !exists ? "installed" : same ? "unchanged" : options.force ? "overwritten" : "skipped";
342
+ if (!options.dryRun && (status === "installed" || status === "overwritten")) {
343
+ mkdirSync(dirname2(versionPath), { recursive: true });
344
+ writeFileSync(versionPath, version);
151
345
  }
152
- } else {
153
- console.log(chalk.cyan(" \u25CB Data directory is the same as source \u2014 skipped"));
346
+ copies.push({ dest: versionPath, status });
347
+ }
348
+ const envExampleSrc = join2(pkgRoot, ".env.example");
349
+ if (existsSync2(envExampleSrc)) {
350
+ copies.push(copyEntry(envExampleSrc, join2(cwd, "qa", ".env.example"), copyOpts));
154
351
  }
155
352
  }
156
- const outputDirs = [
157
- join(cwd, "output", "sessions"),
158
- join(cwd, "output", "bugs"),
159
- join(cwd, "output", "context"),
160
- join(cwd, ".auth")
161
- ];
162
- for (const dir of outputDirs) {
163
- mkdirSync(dir, { recursive: true });
164
- }
165
- console.log(chalk.green(" \u2713 Output directories created"));
166
- const indexPath = join(cwd, "output", "sessions", "INDEX.md");
167
- if (!existsSync(indexPath)) {
168
- writeFileSync(indexPath, INDEX_MD_HEADER);
169
- console.log(chalk.green(" \u2713 Created output/sessions/INDEX.md"));
170
- }
171
- const allBugsPath = join(cwd, "output", "bugs", "all-bugs.md");
172
- if (!existsSync(allBugsPath)) {
173
- writeFileSync(allBugsPath, ALL_BUGS_MD_HEADER);
174
- console.log(chalk.green(" \u2713 Created output/bugs/all-bugs.md"));
175
- }
176
- const envExamplePath = join(cwd, ".env.example");
177
- if (!existsSync(envExamplePath)) {
178
- writeFileSync(envExamplePath, ENV_EXAMPLE);
179
- console.log(chalk.green(" \u2713 Created .env.example"));
180
- }
181
- const gitignorePath = join(cwd, ".gitignore");
182
- let gitignoreContent = "";
183
- if (existsSync(gitignorePath)) {
184
- gitignoreContent = readFileSync(gitignorePath, "utf-8");
185
- }
186
- const linesToAdd = [];
187
- for (const entry of GITIGNORE_ENTRIES) {
188
- if (entry === "" || entry.startsWith("#")) {
189
- if (!gitignoreContent.includes("# Qualiow") && entry === "# Qualiow") {
190
- linesToAdd.push(entry);
191
- } else if (entry === "" && linesToAdd.length === 0) {
192
- linesToAdd.push(entry);
353
+ let hooksSettingsChanged = false;
354
+ if (options.hooks) {
355
+ const hooksScriptsSrc = join2(pkgRoot, "hooks", "scripts");
356
+ copies.push(
357
+ ...copyTree(hooksScriptsSrc, join2(cwd, "qa", "hooks"), {
358
+ ...copyOpts,
359
+ filter: (rel2) => rel2.endsWith(".mjs")
360
+ })
361
+ );
362
+ const settingsPath = join2(cwd, ".claude", "settings.json");
363
+ const settingsExisted = existsSync2(settingsPath);
364
+ let existingSettings;
365
+ if (settingsExisted) {
366
+ try {
367
+ existingSettings = JSON.parse(readFileSync2(settingsPath, "utf-8"));
368
+ } catch {
369
+ existingSettings = void 0;
193
370
  }
194
- continue;
195
371
  }
196
- if (!gitignoreContent.includes(entry)) {
197
- linesToAdd.push(entry);
372
+ const { settings, changed } = mergeQualiowHookSettings(existingSettings);
373
+ hooksSettingsChanged = changed || !settingsExisted;
374
+ if (!options.dryRun) {
375
+ mkdirSync(dirname2(settingsPath), { recursive: true });
376
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
377
+ }
378
+ }
379
+ for (const dir of ["output/sessions", "output/bugs", "output/context", ".auth", "qa"]) {
380
+ const full = join2(cwd, dir);
381
+ if (!existsSync2(full)) {
382
+ createdDirs.push(full);
383
+ if (!options.dryRun) mkdirSync(full, { recursive: true });
384
+ }
385
+ }
386
+ for (const [rel2, content] of [
387
+ ["output/sessions/INDEX.md", INDEX_MD_HEADER],
388
+ ["output/bugs/all-bugs.md", ALL_BUGS_MD_HEADER]
389
+ ]) {
390
+ const full = join2(cwd, rel2);
391
+ if (!existsSync2(full)) {
392
+ createdFiles.push(full);
393
+ if (!options.dryRun) {
394
+ mkdirSync(dirname2(full), { recursive: true });
395
+ writeFileSync(full, content);
396
+ }
198
397
  }
199
398
  }
200
- if (linesToAdd.length > 0) {
201
- const appendStr = (gitignoreContent.endsWith("\n") || gitignoreContent === "" ? "" : "\n") + linesToAdd.join("\n") + "\n";
202
- writeFileSync(gitignorePath, gitignoreContent + appendStr);
203
- console.log(chalk.green(" \u2713 Updated .gitignore"));
399
+ const gitignorePath = join2(cwd, ".gitignore");
400
+ const existing = existsSync2(gitignorePath) ? readFileSync2(gitignorePath, "utf-8") : "";
401
+ const merged = mergeGitignore(existing);
402
+ const gitignoreUpdated = merged !== null;
403
+ if (merged !== null && !options.dryRun) {
404
+ writeFileSync(gitignorePath, merged);
204
405
  }
205
- console.log("");
206
- console.log(chalk.cyan.bold("Qualiow initialized successfully!"));
207
- console.log("");
208
- console.log(chalk.white("Next steps:"));
209
- console.log(chalk.white(" 1. Install Playwright CLI: npm install @playwright/cli"));
210
- console.log(chalk.white(" 2. Run your first session: /qa-explore https://your-app.com"));
211
- console.log(chalk.white(" 3. Or use the CLI: npx qualiow explore https://your-app.com"));
212
- console.log("");
406
+ const counts = { installed: 0, unchanged: 0, overwritten: 0, skipped: 0 };
407
+ for (const c of copies) counts[c.status]++;
408
+ const rel = (p) => relative(cwd, p) || ".";
409
+ if (copies.length) {
410
+ log(
411
+ 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)`) : ""))
412
+ );
413
+ for (const c of copies.filter((x) => x.status === "skipped")) {
414
+ log(chalk.yellow(` skipped ${rel(c.dest)}`));
415
+ }
416
+ }
417
+ for (const d of createdDirs) log(chalk.green(` \u2713 Created ${rel(d)}/`));
418
+ for (const f of createdFiles) log(chalk.green(` \u2713 Created ${rel(f)}`));
419
+ log(
420
+ gitignoreUpdated ? chalk.green(" \u2713 Updated .gitignore (Qualiow block)") : chalk.cyan(" \u25CB .gitignore already up to date")
421
+ );
422
+ if (options.hooks) {
423
+ log(
424
+ hooksSettingsChanged ? chalk.green(" \u2713 Wired hooks into .claude/settings.json") : chalk.cyan(" \u25CB .claude/settings.json hooks already up to date")
425
+ );
426
+ }
427
+ log("");
428
+ log(chalk.cyan.bold(options.dryRun ? "Dry run complete." : "Qualiow initialized."));
429
+ log("");
430
+ log(chalk.white("Next steps:"));
431
+ log(chalk.white(" 1. npx playwright-cli install --skills # official Playwright skill, next to qualiow"));
432
+ log(chalk.white(" 2. cp qa/.env.example qa/.env # credentials by env var name only"));
433
+ if (options.hooks) {
434
+ log(chalk.white(' QUALIOW_HOOKS=off or QUALIOW_READ_MAX_LINES=<n> under "env" in .claude/settings.json tune the guards'));
435
+ }
436
+ log(chalk.white(" 3. /qa-target-setup or /qa-explore https://your-app.com"));
437
+ log(chalk.white(" 4. mobile: qa/bin/doctor-mobile.sh # then /qa-explore-mobile --target <id>"));
438
+ log("");
439
+ return { copies, createdDirs, createdFiles, gitignoreUpdated };
213
440
  }
214
441
 
215
442
  // src/cli/commands/validate.ts
216
443
  import { Command as Command2 } from "commander";
217
- import { resolve as resolve3, relative } from "path";
218
- import { existsSync as existsSync2 } from "fs";
219
- import { globSync as globSync2 } from "glob";
444
+ import { resolve as resolve4, relative as relative3, join as join5 } from "path";
445
+ import { existsSync as existsSync5 } from "fs";
446
+ import { globSync as globSync3 } from "glob";
220
447
  import chalk2 from "chalk";
221
448
 
222
449
  // src/utils/validate.ts
223
- import { readFileSync as readFileSync2 } from "fs";
224
- import { resolve as resolve2, join as join2 } from "path";
225
- import { parse as parseYaml } from "yaml";
450
+ import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
451
+ import { resolve as resolve3, join as join4, basename as basename3 } from "path";
452
+ import { parse as parseYaml2 } from "yaml";
226
453
  import { ZodError } from "zod";
227
454
 
228
455
  // src/schemas/target.schema.ts
@@ -244,42 +471,43 @@ var AuthConfigSchema = z.object({
244
471
  credentials: z.object({
245
472
  username: z.string(),
246
473
  password: z.string()
247
- }).optional(),
474
+ }).strict().optional(),
248
475
  token: z.string().optional(),
249
476
  identity_provider: z.string().optional(),
250
477
  // Staging builds sometimes accept a fixed OTP — recorded so the auth phase can
251
478
  // use it instead of waiting for a real code. Never a real credential.
252
479
  static_otp: z.string().optional(),
253
- test_email_pattern: z.string().optional()
254
- });
480
+ test_email_pattern: z.string().optional(),
481
+ notes: z.string().optional()
482
+ }).strict();
255
483
  var BrowserConfigSchema = z.object({
256
484
  headless: z.boolean(),
257
485
  viewport: z.object({
258
486
  width: z.number().int().positive(),
259
487
  height: z.number().int().positive()
260
- }),
488
+ }).strict(),
261
489
  // Optional engine selection + Playwright device descriptor for mobile-web
262
490
  // emulation targets (e.g. engine: webkit, device: "iPhone 15").
263
491
  engine: z.enum(["chromium", "webkit", "firefox"]).optional(),
264
492
  channel: z.string().optional(),
265
493
  device: z.string().optional()
266
- });
494
+ }).strict();
267
495
  var ScopeConfigSchema = z.object({
268
496
  start_pages: z.array(z.string()).optional(),
269
497
  max_depth: z.number().int().min(0),
270
498
  include_patterns: z.array(z.string()).optional(),
271
499
  exclude_patterns: z.array(z.string()).optional()
272
- });
500
+ }).strict();
273
501
  var SafetyConfigSchema = z.object({
274
502
  read_only: z.boolean(),
275
503
  no_form_submit: z.boolean(),
276
504
  no_file_upload: z.boolean().optional(),
277
505
  no_delete_actions: z.boolean().optional()
278
- });
506
+ }).strict();
279
507
  var EnvironmentConfigSchema = z.object({
280
508
  kind: z.enum(["dev", "ephemeral", "staging", "production"]),
281
509
  destroyed_automatically: z.boolean().optional()
282
- });
510
+ }).strict();
283
511
  var BackendConfigSchema = z.object({
284
512
  provider: z.enum(["aws"]).optional(),
285
513
  aws_profile_env: z.string().optional(),
@@ -292,13 +520,17 @@ var BackendConfigSchema = z.object({
292
520
  // Free-form logical name -> deployed resource name (config_table, dlq, ...).
293
521
  resources: z.record(z.string(), z.string()).optional(),
294
522
  notes: z.string().optional()
295
- });
523
+ }).strict();
296
524
  var ApiSurfaceConfigSchema = z.object({
297
525
  // Defaults to the target's base_url when omitted.
298
526
  base_url: z.string().optional(),
299
- auth: z.enum(["session-cookie", "bearer-env", "none"]).optional(),
300
- // NAME of the env var holding a bearer token, for `auth: bearer-env`.
527
+ auth: z.enum(["session-cookie", "bearer-env", "api-key-env", "none"]).optional(),
528
+ // NAME of the env var holding the credential, for `auth: bearer-env` (a bearer
529
+ // token) or `auth: api-key-env` (a static API key sent in its own header).
301
530
  token_env: z.string().optional(),
531
+ // Header carrying the credential for `auth: api-key-env`. Defaults to
532
+ // `X-Api-Key`. The VALUE always comes from `token_env`, never from here.
533
+ header_name: z.string().optional(),
302
534
  // Persistent browser profile directory holding the authenticated session,
303
535
  // e.g. `.auth/my-service-dev-profile`. Gitignored.
304
536
  browser_profile: z.string().optional(),
@@ -308,19 +540,23 @@ var ApiSurfaceConfigSchema = z.object({
308
540
  endpoints: z.record(z.string(), z.string()).optional(),
309
541
  // The ONLY endpoints the read-only API lane may call without asking.
310
542
  probe_allowlist: z.array(z.string()).optional(),
543
+ // The ONLY endpoints phase 4 may call through the real write path, and only in
544
+ // a dev or ephemeral environment. Empty or absent means the API lane is
545
+ // read-only here and every state-changing AC needs a different channel.
546
+ write_allowlist: z.array(z.string()).optional(),
311
547
  // Other target ids to run the same matrix against, for parity comparison.
312
548
  parity_targets: z.array(z.string()).optional(),
313
549
  // Flag name -> where its deployed value is declared for this environment.
314
550
  // A flag can select between two implementations inside one identical build.
315
551
  feature_flags: z.record(z.string(), z.string()).optional(),
316
552
  notes: z.string().optional()
317
- });
553
+ }).strict();
318
554
  var SourceBranchConfigSchema = z.object({
319
555
  repo_path: z.string(),
320
556
  branch: z.string(),
321
557
  base_branch: z.string().optional(),
322
558
  components: z.record(z.string(), z.string()).optional()
323
- });
559
+ }).strict();
324
560
  var WebTargetConfigSchema = z.object({
325
561
  id: z.string().min(1),
326
562
  name: z.string().min(1),
@@ -339,7 +575,7 @@ var WebTargetConfigSchema = z.object({
339
575
  api: ApiSurfaceConfigSchema.optional(),
340
576
  source: SourceBranchConfigSchema.optional(),
341
577
  notes: z.string().optional()
342
- });
578
+ }).strict();
343
579
  var MobileDeviceConfigSchema = z.object({
344
580
  name: z.string().optional(),
345
581
  // iOS simulator name (portable across machines)
@@ -349,7 +585,7 @@ var MobileDeviceConfigSchema = z.object({
349
585
  // Android AVD name
350
586
  serial: z.string().optional()
351
587
  // Android serial once booted (e.g. emulator-5554)
352
- });
588
+ }).strict();
353
589
  var MobileAppConfigSchema = z.object({
354
590
  bundle_id: z.string().optional(),
355
591
  // iOS bundle id (or browser bundle in web mode)
@@ -359,21 +595,21 @@ var MobileAppConfigSchema = z.object({
359
595
  // iOS .app artifact(s) — native mode
360
596
  apk_paths: z.array(z.string()).optional()
361
597
  // Android APK(s) — native mode
362
- });
598
+ }).strict();
363
599
  var MobileWebConfigSchema = z.object({
364
600
  base_url: z.string().url(),
365
601
  start_url: z.string().url().optional()
366
- });
602
+ }).strict();
367
603
  var SourceRepoConfigSchema = z.object({
368
604
  path: z.string(),
369
605
  build_commands: z.record(z.string(), z.string()).optional()
370
- });
606
+ }).strict();
371
607
  var MobileScopeConfigSchema = z.object({
372
608
  start_screen: z.string().optional(),
373
609
  start_url: z.string().optional(),
374
610
  include_patterns: z.array(z.string()).optional(),
375
611
  exclude_patterns: z.array(z.string()).optional()
376
- });
612
+ }).strict();
377
613
  var MobileTargetConfigSchema = z.object({
378
614
  id: z.string().min(1),
379
615
  name: z.string().min(1),
@@ -389,15 +625,22 @@ var MobileTargetConfigSchema = z.object({
389
625
  safety: SafetyConfigSchema.optional(),
390
626
  source_repo: SourceRepoConfigSchema.optional(),
391
627
  notes: z.string().optional()
392
- });
393
- var TargetConfigSchema = z.custom().superRefine((data, ctx) => {
394
- const isMobile = typeof data === "object" && data !== null && "platform" in data;
628
+ }).strict();
629
+ var TargetConfigSchema = z.unknown().transform((data, ctx) => {
630
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
631
+ ctx.addIssue({ code: "custom", message: "Expected a target config object" });
632
+ return z.NEVER;
633
+ }
634
+ const isMobile = "platform" in data;
395
635
  const branch = isMobile ? MobileTargetConfigSchema : WebTargetConfigSchema;
396
636
  const result = branch.safeParse(data);
397
637
  if (!result.success) {
398
- for (const issue of result.error.issues)
638
+ for (const issue of result.error.issues) {
399
639
  ctx.addIssue(issue);
640
+ }
641
+ return z.NEVER;
400
642
  }
643
+ return result.data;
401
644
  });
402
645
 
403
646
  // src/schemas/knowledge-entry.schema.ts
@@ -422,30 +665,196 @@ var KnowledgeEntrySchema = z2.object({
422
665
 
423
666
  // src/schemas/domain-config.schema.ts
424
667
  import { z as z3 } from "zod";
668
+ var RiskRankingSchema = z3.object({
669
+ p0: z3.array(z3.string()).min(1),
670
+ p1: z3.array(z3.string()).min(1),
671
+ p2: z3.array(z3.string()).min(1),
672
+ p3: z3.array(z3.string()).min(1)
673
+ }).strict();
425
674
  var JourneySchema = z3.object({
426
- id: z3.string().min(1),
427
675
  name: z3.string().min(1),
428
- description: z3.string().min(1),
429
- steps: z3.array(z3.string()).min(1),
430
- risk: z3.enum(["high", "medium", "low"])
431
- });
676
+ steps: z3.array(z3.string()).min(1)
677
+ }).strict();
432
678
  var DomainConfigSchema = z3.object({
433
679
  id: z3.string().min(1),
434
680
  name: z3.string().min(1),
435
- risk_ranking: z3.array(z3.string()).min(1),
681
+ risk_ranking: RiskRankingSchema,
436
682
  completeness_checklist: z3.array(z3.string()).min(1),
437
683
  data_integrity_checks: z3.array(z3.string()).min(1),
438
684
  journeys: z3.array(JourneySchema).min(1),
439
- guidance: z3.array(z3.string()).min(1)
685
+ must_test_patterns: z3.record(z3.string(), z3.array(z3.string())),
686
+ common_bugs: z3.array(z3.string()).min(1),
687
+ compliance: z3.array(z3.string()).min(1),
688
+ guidance: z3.string().min(1)
689
+ }).strict();
690
+
691
+ // src/schemas/knowledge-manifest.schema.ts
692
+ import { z as z4 } from "zod";
693
+ var KnowledgeManifestStatsSchema = z4.object({
694
+ total_entries: z4.number().int().min(0),
695
+ heuristics: z4.number().int().min(0),
696
+ techniques: z4.number().int().min(0),
697
+ checklists: z4.number().int().min(0),
698
+ references: z4.number().int().min(0),
699
+ domain_profiles: z4.number().int().min(0),
700
+ custom_entries: z4.number().int().min(0)
701
+ });
702
+ var KnowledgeManifestEntrySchema = z4.object({
703
+ id: z4.string().min(1),
704
+ file: z4.string().min(1),
705
+ type: z4.string().min(1),
706
+ priority: z4.enum(["high", "medium", "low"]),
707
+ tags: z4.array(z4.string()),
708
+ domains: z4.array(z4.string())
709
+ });
710
+ var LoadingStrategySchema = z4.object({
711
+ always: z4.array(z4.string()),
712
+ by_domain: z4.record(z4.string(), z4.array(z4.string())),
713
+ by_tag: z4.record(z4.string(), z4.array(z4.string())),
714
+ /** Per-skill selection used by `qualiow kb digest --for <skill>`. Optional so
715
+ * a manifest written before this key still validates. */
716
+ by_skill: z4.record(z4.string(), z4.array(z4.string())).optional()
717
+ });
718
+ var KnowledgeManifestSchema = z4.object({
719
+ version: z4.string().min(1),
720
+ last_updated: z4.string().min(1),
721
+ active_releases: z4.array(z4.string()).min(1),
722
+ stats: KnowledgeManifestStatsSchema,
723
+ loading_strategy: LoadingStrategySchema,
724
+ entries: z4.array(KnowledgeManifestEntrySchema).min(1)
440
725
  });
441
726
 
442
- // src/utils/validate.ts
727
+ // src/schemas/knowledge-release.schema.ts
728
+ import { z as z5 } from "zod";
729
+ var KnowledgeReleaseSchema = z5.object({
730
+ version: z5.string().min(1),
731
+ date: z5.string().min(1),
732
+ author: z5.string().min(1),
733
+ status: z5.enum(["active", "deprecated"]),
734
+ notes: z5.string().min(1),
735
+ entry_count: z5.number().int().min(0),
736
+ entries: z5.array(z5.string().min(1)).min(1)
737
+ }).strict().refine((r) => r.entry_count === r.entries.length, {
738
+ message: "entry_count must equal the number of listed entries",
739
+ path: ["entry_count"]
740
+ });
741
+
742
+ // src/schemas/knowledge-changelog.schema.ts
743
+ import { z as z6 } from "zod";
744
+ var ChangelogEntrySchema = z6.object({
745
+ id: z6.string().min(1),
746
+ type: z6.enum(["heuristic", "technique", "checklist", "reference"]),
747
+ name: z6.string().min(1),
748
+ description: z6.string().min(1)
749
+ }).strict();
750
+ var ChangelogReleaseSchema = z6.object({
751
+ version: z6.string().min(1),
752
+ date: z6.string().min(1),
753
+ summary: z6.string().min(1),
754
+ entries_added: z6.array(ChangelogEntrySchema),
755
+ entries_modified: z6.array(z6.string()).default([]),
756
+ entries_removed: z6.array(z6.string()).default([]),
757
+ origin: z6.string().optional()
758
+ }).strict();
759
+ var KnowledgeChangelogSchema = z6.object({
760
+ releases: z6.array(ChangelogReleaseSchema).min(1)
761
+ }).strict();
762
+
763
+ // src/utils/kb-sync.ts
764
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync3, readdirSync as readdirSync2 } from "fs";
765
+ import { join as join3, relative as relative2, basename as basename2 } from "path";
766
+ import { parse as parseYaml, parseDocument } from "yaml";
443
767
  import { globSync } from "glob";
768
+ var TYPE_TO_STAT = {
769
+ heuristic: "heuristics",
770
+ technique: "techniques",
771
+ checklist: "checklists",
772
+ reference: "references"
773
+ };
774
+ function listReleaseDirs(knowledgeDir) {
775
+ const releasesDir = join3(knowledgeDir, "releases");
776
+ if (!existsSync3(releasesDir)) return [];
777
+ return readdirSync2(releasesDir, { withFileTypes: true }).filter((d) => d.isDirectory() && /^v\d+\.\d+\.\d+$/.test(d.name)).map((d) => d.name).sort(compareVersions);
778
+ }
779
+ function compareVersions(a, b) {
780
+ const pa = a.replace(/^v/, "").split(".").map(Number);
781
+ const pb = b.replace(/^v/, "").split(".").map(Number);
782
+ for (let i = 0; i < 3; i++) {
783
+ if (pa[i] !== pb[i]) return pa[i] - pb[i];
784
+ }
785
+ return 0;
786
+ }
787
+ function buildManifestRegistry(dataDir) {
788
+ const knowledgeDir = join3(dataDir, "knowledge");
789
+ const registry = [];
790
+ for (const rel of listReleaseDirs(knowledgeDir)) {
791
+ const files = globSync(join3(knowledgeDir, "releases", rel, "entries", "*.yml")).sort();
792
+ for (const file of files) {
793
+ const entry = parseYaml(readFileSync3(file, "utf-8"));
794
+ registry.push({
795
+ id: entry.id,
796
+ file: relative2(knowledgeDir, file).split("\\").join("/"),
797
+ type: entry.type,
798
+ priority: entry.priority,
799
+ tags: entry.tags,
800
+ domains: entry.domains
801
+ });
802
+ }
803
+ }
804
+ return registry;
805
+ }
806
+ function computeStats(dataDir, registry) {
807
+ const stats = {
808
+ total_entries: registry.length,
809
+ heuristics: 0,
810
+ techniques: 0,
811
+ checklists: 0,
812
+ references: 0,
813
+ domain_profiles: 0,
814
+ custom_entries: 0
815
+ };
816
+ for (const e of registry) {
817
+ const key = TYPE_TO_STAT[e.type];
818
+ if (key) stats[key]++;
819
+ }
820
+ const domainsDir = join3(dataDir, "domains");
821
+ if (existsSync3(domainsDir)) {
822
+ stats.domain_profiles = readdirSync2(domainsDir).filter(
823
+ (f) => f.endsWith(".yml")
824
+ ).length;
825
+ }
826
+ const customDir = join3(dataDir, "knowledge", "custom");
827
+ if (existsSync3(customDir)) {
828
+ stats.custom_entries = readdirSync2(customDir).filter(
829
+ (f) => f.endsWith(".yml")
830
+ ).length;
831
+ }
832
+ return stats;
833
+ }
834
+ function syncKnowledgeManifest(dataDir, opts = {}) {
835
+ const manifestPath = join3(dataDir, "knowledge", "manifest.yml");
836
+ const raw = readFileSync3(manifestPath, "utf-8");
837
+ const doc = parseDocument(raw);
838
+ const registry = buildManifestRegistry(dataDir);
839
+ const stats = computeStats(dataDir, registry);
840
+ const current = parseYaml(raw);
841
+ const inSync = JSON.stringify(current.entries) === JSON.stringify(registry) && JSON.stringify(current.stats) === JSON.stringify(stats);
842
+ if (!opts.check && !inSync) {
843
+ doc.set("stats", stats);
844
+ doc.set("entries", registry);
845
+ doc.set("last_updated", (/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
846
+ writeFileSync2(manifestPath, doc.toString(), "utf-8");
847
+ }
848
+ return { changed: !inSync, stats, entryCount: registry.length };
849
+ }
850
+
851
+ // src/utils/validate.ts
852
+ import { globSync as globSync2 } from "glob";
444
853
  function validateYamlFile(filePath, schema) {
445
- const absPath = resolve2(filePath);
854
+ const absPath = resolve3(filePath);
446
855
  try {
447
- const raw = readFileSync2(absPath, "utf-8");
448
- const data = parseYaml(raw);
856
+ const raw = readFileSync4(absPath, "utf-8");
857
+ const data = parseYaml2(raw);
449
858
  schema.parse(data);
450
859
  return { file: absPath, valid: true };
451
860
  } catch (err) {
@@ -471,21 +880,137 @@ function validateYamlFile(filePath, schema) {
471
880
  };
472
881
  }
473
882
  }
883
+ function validateWithId(filePath, schema) {
884
+ const result = validateYamlFile(filePath, schema);
885
+ if (!result.valid) return result;
886
+ try {
887
+ const data = parseYaml2(readFileSync4(filePath, "utf-8"));
888
+ const stem = basename3(filePath, ".yml");
889
+ if (data.id !== stem) {
890
+ return {
891
+ file: resolve3(filePath),
892
+ valid: false,
893
+ errors: [
894
+ {
895
+ path: "id",
896
+ message: `id "${data.id}" must equal the file name "${stem}"`
897
+ }
898
+ ]
899
+ };
900
+ }
901
+ } catch {
902
+ }
903
+ return result;
904
+ }
474
905
  function validateTargetConfig(filePath) {
475
- return validateYamlFile(filePath, TargetConfigSchema);
906
+ return validateWithId(filePath, TargetConfigSchema);
476
907
  }
477
908
  function validateKnowledgeEntry(filePath) {
478
909
  return validateYamlFile(filePath, KnowledgeEntrySchema);
479
910
  }
480
911
  function validateDomainConfig(filePath) {
481
- return validateYamlFile(filePath, DomainConfigSchema);
912
+ return validateWithId(filePath, DomainConfigSchema);
913
+ }
914
+ function validateKnowledgeBase(dataDir) {
915
+ const results = [];
916
+ const knowledgeDir = resolve3(dataDir, "knowledge");
917
+ const manifestPath = join4(knowledgeDir, "manifest.yml");
918
+ const changelogPath = join4(knowledgeDir, "changelog.yml");
919
+ results.push(validateYamlFile(manifestPath, KnowledgeManifestSchema));
920
+ results.push(validateYamlFile(changelogPath, KnowledgeChangelogSchema));
921
+ const releaseDirs = listReleaseDirs(knowledgeDir);
922
+ for (const rel of releaseDirs) {
923
+ const releasePath = join4(knowledgeDir, "releases", rel, "release.yml");
924
+ const schemaResult = validateYamlFile(releasePath, KnowledgeReleaseSchema);
925
+ const errors = schemaResult.errors ?? [];
926
+ if (schemaResult.valid || errors.length === 0) {
927
+ try {
928
+ const release = parseYaml2(readFileSync4(releasePath, "utf-8"));
929
+ if (`v${release.version}` !== rel) {
930
+ errors.push({
931
+ path: "version",
932
+ message: `version "${release.version}" does not match directory "${rel}"`
933
+ });
934
+ }
935
+ const entryDir = join4(knowledgeDir, "releases", rel, "entries");
936
+ const filesOnDisk = existsSync4(entryDir) ? globSync2(join4(entryDir, "*.yml")).map((f) => basename3(f, ".yml")) : [];
937
+ for (const id of release.entries) {
938
+ if (!filesOnDisk.includes(id)) {
939
+ errors.push({ path: "entries", message: `declared entry "${id}" has no file` });
940
+ }
941
+ }
942
+ for (const id of filesOnDisk) {
943
+ if (!release.entries.includes(id)) {
944
+ errors.push({ path: "entries", message: `entry file "${id}" is not declared` });
945
+ }
946
+ }
947
+ } catch {
948
+ }
949
+ }
950
+ results.push(
951
+ errors.length ? { file: resolve3(releasePath), valid: false, errors } : { file: resolve3(releasePath), valid: true }
952
+ );
953
+ }
954
+ const crossErrors = [];
955
+ try {
956
+ const manifest = parseYaml2(readFileSync4(manifestPath, "utf-8"));
957
+ const registry = buildManifestRegistry(dataDir);
958
+ const stats = computeStats(dataDir, registry);
959
+ const registryIds = new Set(registry.map((e) => e.id));
960
+ if (JSON.stringify(manifest.entries) !== JSON.stringify(registry)) {
961
+ crossErrors.push({
962
+ path: "entries",
963
+ message: "registry is out of sync with the entry files (run `qualiow kb sync`)"
964
+ });
965
+ }
966
+ if (JSON.stringify(manifest.stats) !== JSON.stringify(stats)) {
967
+ crossErrors.push({
968
+ path: "stats",
969
+ message: `stats out of sync (expected total_entries ${stats.total_entries})`
970
+ });
971
+ }
972
+ const activeExpected = [...listReleaseDirs(knowledgeDir)].sort();
973
+ if (JSON.stringify([...manifest.active_releases].sort()) !== JSON.stringify(activeExpected)) {
974
+ crossErrors.push({ path: "active_releases", message: "does not match the release directories" });
975
+ }
976
+ const ls = manifest.loading_strategy;
977
+ const allRefs = [
978
+ ...ls.always,
979
+ ...Object.values(ls.by_domain).flat(),
980
+ ...Object.values(ls.by_tag).flat(),
981
+ ...Object.values(ls.by_skill ?? {}).flat()
982
+ ];
983
+ for (const id of allRefs) {
984
+ if (!registryIds.has(id)) {
985
+ crossErrors.push({ path: "loading_strategy", message: `references unknown entry "${id}"` });
986
+ }
987
+ }
988
+ const changelog = parseYaml2(readFileSync4(changelogPath, "utf-8"));
989
+ for (const r of changelog.releases) {
990
+ for (const e of r.entries_added) {
991
+ if (!registryIds.has(e.id)) {
992
+ crossErrors.push({ path: "changelog", message: `entry "${e.id}" is not in the registry` });
993
+ }
994
+ }
995
+ }
996
+ } catch (err) {
997
+ crossErrors.push({
998
+ path: "",
999
+ message: err instanceof Error ? err.message : "cross-check failed"
1000
+ });
1001
+ }
1002
+ results.push(
1003
+ crossErrors.length ? { file: join4(knowledgeDir, "(cross-check)"), valid: false, errors: crossErrors } : { file: join4(knowledgeDir, "(cross-check)"), valid: true }
1004
+ );
1005
+ return results;
482
1006
  }
483
1007
 
484
1008
  // src/cli/commands/validate.ts
485
1009
  function validateCommand() {
486
- const cmd = new Command2("validate").description("Validate all configuration files").option("--targets", "Validate target configurations only").option("--knowledge", "Validate knowledge entries only").option("--domains", "Validate domain configurations only").option("--all", "Validate all configurations (default)").action(async (options) => {
1010
+ const cmd = new Command2("validate").description("Validate configuration files (targets, domains, knowledge entries, knowledge base)").option("--targets", "Validate target configurations (data/targets/*.yml and qa/target.yml)").option("--knowledge", "Validate knowledge entries").option("--domains", "Validate domain configurations").option("--kb", "Cross-check the knowledge base (manifest, releases, changelog)").option("--all", "Validate everything (default)").action(async (options) => {
487
1011
  try {
488
- runValidate(options);
1012
+ const failed = runValidate(options, process.cwd());
1013
+ if (failed > 0) process.exit(1);
489
1014
  } catch (err) {
490
1015
  console.error(chalk2.red("Error during validation:"), err instanceof Error ? err.message : err);
491
1016
  process.exit(1);
@@ -493,58 +1018,47 @@ function validateCommand() {
493
1018
  });
494
1019
  return cmd;
495
1020
  }
496
- function runValidate(options) {
497
- const cwd = process.cwd();
498
- const dataDir = resolve3(cwd, "data");
499
- const runAll = options.all || !options.targets && !options.knowledge && !options.domains;
500
- if (!existsSync2(dataDir)) {
501
- console.error(chalk2.red("Error: data/ directory not found. Run `npx qualiow init` first."));
502
- process.exit(1);
1021
+ function runValidate(options, cwd) {
1022
+ const dataDir = resolve4(cwd, "data");
1023
+ const runAll = options.all || !options.targets && !options.knowledge && !options.domains && !options.kb;
1024
+ if (!existsSync5(dataDir)) {
1025
+ throw new Error("data/ directory not found. Run `npx qualiow init` first.");
503
1026
  }
504
1027
  const results = [];
505
- if (runAll || options.targets) {
506
- const targetDir = resolve3(dataDir, "targets");
507
- if (existsSync2(targetDir)) {
508
- const files = globSync2(resolve3(targetDir, "*.yml"));
509
- console.log(chalk2.cyan.bold(`
510
- Targets (${files.length} files):`));
511
- for (const file of files) {
512
- const result = validateTargetConfig(file);
513
- results.push(result);
514
- printResult(result, cwd);
515
- }
516
- } else {
517
- console.log(chalk2.yellow("\n No targets/ directory found"));
1028
+ const section = (title, files, fn) => {
1029
+ console.log(chalk2.cyan.bold(`
1030
+ ${title} (${files.length} files):`));
1031
+ for (const file of files) {
1032
+ const result = fn(file);
1033
+ results.push(result);
1034
+ printResult(result, cwd);
518
1035
  }
1036
+ };
1037
+ if (runAll || options.targets) {
1038
+ const files = globSync3(resolve4(dataDir, "targets", "*.yml")).sort();
1039
+ const projectLocal = join5(cwd, "qa", "target.yml");
1040
+ if (existsSync5(projectLocal)) files.unshift(projectLocal);
1041
+ section("Targets", files, validateTargetConfig);
1042
+ }
1043
+ if (runAll || options.domains) {
1044
+ section("Domains", globSync3(resolve4(dataDir, "domains", "*.yml")).sort(), validateDomainConfig);
519
1045
  }
520
1046
  if (runAll || options.knowledge) {
521
- const knowledgeDir = resolve3(dataDir, "knowledge");
522
- if (existsSync2(knowledgeDir)) {
523
- const files = globSync2(resolve3(knowledgeDir, "releases", "**", "entries", "*.yml"));
524
- console.log(chalk2.cyan.bold(`
525
- Knowledge entries (${files.length} files):`));
526
- for (const file of files) {
527
- const result = validateKnowledgeEntry(file);
528
- results.push(result);
529
- printResult(result, cwd);
530
- }
531
- } else {
532
- console.log(chalk2.yellow("\n No knowledge/ directory found"));
533
- }
1047
+ section(
1048
+ "Knowledge entries",
1049
+ globSync3(resolve4(dataDir, "knowledge", "releases", "**", "entries", "*.yml")).sort(),
1050
+ validateKnowledgeEntry
1051
+ );
534
1052
  }
535
- if (runAll || options.domains) {
536
- const domainsDir = resolve3(dataDir, "domains");
537
- if (existsSync2(domainsDir)) {
538
- const files = globSync2(resolve3(domainsDir, "*.yml"));
539
- console.log(chalk2.cyan.bold(`
540
- Domains (${files.length} files):`));
541
- for (const file of files) {
542
- const result = validateDomainConfig(file);
1053
+ if (runAll || options.kb) {
1054
+ if (existsSync5(join5(dataDir, "knowledge", "manifest.yml"))) {
1055
+ console.log(chalk2.cyan.bold("\nKnowledge base:"));
1056
+ for (const result of validateKnowledgeBase(dataDir)) {
543
1057
  results.push(result);
544
1058
  printResult(result, cwd);
545
1059
  }
546
1060
  } else {
547
- console.log(chalk2.yellow("\n No domains/ directory found"));
1061
+ console.log(chalk2.yellow("\n No knowledge/manifest.yml found"));
548
1062
  }
549
1063
  }
550
1064
  const total = results.length;
@@ -553,38 +1067,121 @@ Domains (${files.length} files):`));
553
1067
  console.log("");
554
1068
  console.log(chalk2.bold("Summary:"));
555
1069
  console.log(
556
- ` ${total} files validated, ${chalk2.green(`${passed} passed`)}, ${failed > 0 ? chalk2.red(`${failed} failed`) : chalk2.green(`${failed} failed`)}`
1070
+ ` ${total} checks, ${chalk2.green(`${passed} passed`)}, ${failed > 0 ? chalk2.red(`${failed} failed`) : chalk2.green("0 failed")}`
557
1071
  );
558
1072
  console.log("");
559
- if (failed > 0) {
560
- process.exit(1);
561
- }
1073
+ return failed;
562
1074
  }
563
1075
  function printResult(result, cwd) {
564
- const relPath = relative(cwd, result.file);
1076
+ const relPath = relative3(cwd, result.file);
565
1077
  if (result.valid) {
566
1078
  console.log(` ${chalk2.green("PASS")} ${relPath}`);
567
1079
  } else {
568
1080
  console.log(` ${chalk2.red("FAIL")} ${relPath}`);
569
- if (result.errors) {
570
- for (const err of result.errors) {
571
- const pathStr = err.path ? `[${err.path}] ` : "";
572
- console.log(` ${chalk2.red("\u2192")} ${pathStr}${err.message}`);
573
- }
1081
+ for (const err of result.errors ?? []) {
1082
+ const pathStr = err.path ? `[${err.path}] ` : "";
1083
+ console.log(` ${chalk2.red("\u2192")} ${pathStr}${err.message}`);
574
1084
  }
575
1085
  }
576
1086
  }
577
1087
 
578
1088
  // src/cli/commands/list.ts
579
1089
  import { Command as Command3 } from "commander";
580
- import { resolve as resolve4, join as join3 } from "path";
581
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync as readdirSync2 } from "fs";
582
- import { parse as parseYaml2 } from "yaml";
1090
+ import { resolve as resolve5, join as join6, basename as basename4 } from "path";
1091
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync3 } from "fs";
1092
+ import { parse as parseYaml3 } from "yaml";
1093
+ import { globSync as globSync4 } from "glob";
583
1094
  import chalk3 from "chalk";
1095
+
1096
+ // src/utils/markdown-table.ts
1097
+ function splitRow(line) {
1098
+ const cells = line.split("|").map((c) => c.trim());
1099
+ if (cells.length && cells[0] === "") cells.shift();
1100
+ if (cells.length && cells[cells.length - 1] === "") cells.pop();
1101
+ return cells;
1102
+ }
1103
+ function isSeparator(line) {
1104
+ return /^\s*\|?\s*:?-{2,}/.test(line) && /-\s*\|/.test(line + "|");
1105
+ }
1106
+ function parseMarkdownTable(md, opts = {}) {
1107
+ const lines = md.split("\n");
1108
+ let start = 0;
1109
+ if (opts.headingPrefix) {
1110
+ const prefix = opts.headingPrefix.toLowerCase();
1111
+ let found = -1;
1112
+ for (let i = 0; i < lines.length; i++) {
1113
+ const h = lines[i].match(/^#{1,6}\s+(.*)$/);
1114
+ if (h && h[1].trim().toLowerCase().startsWith(prefix)) {
1115
+ found = i + 1;
1116
+ break;
1117
+ }
1118
+ }
1119
+ if (found === -1) return null;
1120
+ start = found;
1121
+ }
1122
+ let headerIdx = -1;
1123
+ for (let i = start; i < lines.length - 1; i++) {
1124
+ const line = lines[i];
1125
+ if (line.includes("|") && isSeparator(lines[i + 1])) {
1126
+ headerIdx = i;
1127
+ break;
1128
+ }
1129
+ if (opts.headingPrefix && /^#{1,6}\s/.test(line) && i > start) {
1130
+ return null;
1131
+ }
1132
+ }
1133
+ if (headerIdx === -1) return null;
1134
+ const headers = splitRow(lines[headerIdx]);
1135
+ const keys = headers.map((h) => h.toLowerCase());
1136
+ const rows = [];
1137
+ for (let i = headerIdx + 2; i < lines.length; i++) {
1138
+ const line = lines[i];
1139
+ if (!line.includes("|")) break;
1140
+ if (isSeparator(line)) continue;
1141
+ const cells = splitRow(line);
1142
+ if (cells.every((c) => c === "")) continue;
1143
+ const row = {};
1144
+ keys.forEach((k, idx) => {
1145
+ row[k] = cells[idx] ?? "";
1146
+ });
1147
+ rows.push(row);
1148
+ }
1149
+ return { headers, rows };
1150
+ }
1151
+
1152
+ // src/utils/session-dir.ts
1153
+ var SESSION_DIR_RE = /^(\d{4}-\d{2}-\d{2}-\d{4})-(explore|quick|mobile|backend)-([a-z0-9][a-z0-9-]*)$/;
1154
+ function slugify(input) {
1155
+ let s = (input ?? "").trim();
1156
+ try {
1157
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) {
1158
+ s = new URL(s).hostname;
1159
+ }
1160
+ } catch {
1161
+ }
1162
+ s = s.toLowerCase().replace(/^_+/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/g, "");
1163
+ return s || "session";
1164
+ }
1165
+ function pad(n) {
1166
+ return String(n).padStart(2, "0");
1167
+ }
1168
+ function sessionTimestamp(date = /* @__PURE__ */ new Date()) {
1169
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}`;
1170
+ }
1171
+ function sessionDirName(kind, target, date = /* @__PURE__ */ new Date()) {
1172
+ return `${sessionTimestamp(date)}-${kind}-${slugify(target)}`;
1173
+ }
1174
+ function parseSessionDirName(name) {
1175
+ const m = SESSION_DIR_RE.exec(name);
1176
+ if (!m) return null;
1177
+ return { timestamp: m[1], kind: m[2], slug: m[3] };
1178
+ }
1179
+
1180
+ // src/cli/commands/list.ts
584
1181
  function listCommand() {
585
- const cmd = new Command3("list").description("List sessions, knowledge, targets, or domains").argument("<type>", "What to list: sessions, knowledge, targets, domains").action(async (type) => {
1182
+ const cmd = new Command3("list").description("List sessions, knowledge, targets, or domains").argument("<type>", "What to list: sessions, knowledge, targets, domains").option("--domain <id>", "knowledge: only entries for this domain").option("--tag <tag>", "knowledge: only entries carrying this tag").option("--type <type>", "knowledge: only entries of this type (heuristic, technique, \u2026)").option("--entry <id>", "knowledge: print this entry's YAML file instead of the listing").option("--changelog", "knowledge: print the release changelog").option("--stats", "knowledge: print stats, active releases and loading-strategy counts").option("--data <dir>", "knowledge: read the knowledge base from this data directory").action(async (type, options) => {
586
1183
  try {
587
- await runList(type);
1184
+ await runList(type, process.cwd(), options);
588
1185
  } catch (err) {
589
1186
  console.error(chalk3.red("Error:"), err instanceof Error ? err.message : err);
590
1187
  process.exit(1);
@@ -592,14 +1189,13 @@ function listCommand() {
592
1189
  });
593
1190
  return cmd;
594
1191
  }
595
- async function runList(type) {
596
- const cwd = process.cwd();
1192
+ async function runList(type, cwd, options = {}, log = (line) => console.log(line)) {
597
1193
  switch (type) {
598
1194
  case "sessions":
599
1195
  listSessions(cwd);
600
1196
  break;
601
1197
  case "knowledge":
602
- listKnowledge(cwd);
1198
+ listKnowledge(cwd, options, log);
603
1199
  break;
604
1200
  case "targets":
605
1201
  listTargets(cwd);
@@ -608,128 +1204,242 @@ async function runList(type) {
608
1204
  listDomains(cwd);
609
1205
  break;
610
1206
  default:
611
- console.error(chalk3.red(`Unknown type: "${type}". Choose from: sessions, knowledge, targets, domains`));
612
- process.exit(1);
1207
+ throw new Error(`Unknown type: "${type}". Choose from: sessions, knowledge, targets, domains`);
613
1208
  }
614
1209
  }
1210
+ function readSessionIndex(indexPath) {
1211
+ if (!existsSync6(indexPath)) return [];
1212
+ const table2 = parseMarkdownTable(readFileSync5(indexPath, "utf-8"));
1213
+ if (!table2) return [];
1214
+ const rows = [];
1215
+ for (const row of table2.rows) {
1216
+ const date = row["date"] ?? "";
1217
+ if (!date || date.startsWith("_")) continue;
1218
+ rows.push({
1219
+ date,
1220
+ kind: row["kind"] ?? "",
1221
+ target: row["target"] ?? "",
1222
+ bugs: row["bugs"] ?? "",
1223
+ duration: row["duration"] ?? "",
1224
+ status: row["status"] ?? "",
1225
+ report: row["report"] ?? row["session directory"] ?? ""
1226
+ });
1227
+ }
1228
+ return rows;
1229
+ }
615
1230
  function listSessions(cwd) {
616
- const indexPath = resolve4(cwd, "output", "sessions", "INDEX.md");
617
- if (!existsSync3(indexPath)) {
618
- console.log(chalk3.yellow("No sessions found. Run `npx qualiow init` first, then start a session."));
1231
+ const sessionsDir = resolve5(cwd, "output", "sessions");
1232
+ const indexPath = join6(sessionsDir, "INDEX.md");
1233
+ if (!existsSync6(sessionsDir)) {
1234
+ console.log(chalk3.yellow("No sessions directory. Run `npx qualiow init` first, then start a session."));
619
1235
  return;
620
1236
  }
621
- const content = readFileSync3(indexPath, "utf-8");
622
- const lines = content.split("\n");
623
- const tableRows = lines.filter(
624
- (line) => line.startsWith("|") && !line.startsWith("|---") && !line.startsWith("| Date") && line.trim() !== ""
625
- );
626
- if (tableRows.length === 0) {
627
- console.log(chalk3.cyan("\nSessions:"));
1237
+ const rows = readSessionIndex(indexPath);
1238
+ const indexedDirs = new Set(rows.map((r) => basename4(r.report.replace(/\/session-report\.md$/, ""))));
1239
+ const unindexed = readdirSync3(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory() && SESSION_DIR_RE.test(d.name) && !indexedDirs.has(d.name)).map((d) => d.name).sort();
1240
+ console.log(chalk3.cyan.bold("\nSessions:"));
1241
+ console.log("");
1242
+ if (rows.length === 0 && unindexed.length === 0) {
628
1243
  console.log(chalk3.yellow(" No sessions recorded yet."));
629
- console.log(chalk3.white(" Start one with: npx qualiow explore <url>"));
1244
+ console.log(chalk3.white(" Start one with: /qa-explore <url>"));
1245
+ console.log("");
630
1246
  return;
631
1247
  }
632
- console.log(chalk3.cyan.bold("\nSessions:"));
633
- console.log("");
634
- const header = ` ${pad("Date", 12)} ${pad("Target", 20)} ${pad("Duration", 10)} ${pad("Bugs", 6)} Session Directory`;
635
- console.log(chalk3.bold(header));
636
- console.log(` ${"\u2500".repeat(12)} ${"\u2500".repeat(20)} ${"\u2500".repeat(10)} ${"\u2500".repeat(6)} ${"\u2500".repeat(30)}`);
637
- for (const row of tableRows) {
638
- const cells = row.split("|").map((c) => c.trim()).filter((c) => c !== "");
639
- if (cells.length >= 5) {
640
- console.log(
641
- ` ${pad(cells[0], 12)} ${pad(cells[1], 20)} ${pad(cells[2], 10)} ${pad(cells[3], 6)} ${cells[4]}`
642
- );
643
- }
1248
+ const widths = [16, 8, 22, 5, 9, 12];
1249
+ const header = INDEX_COLUMNS.map((c, i) => i < widths.length ? pad2(c, widths[i]) : c).join(" ");
1250
+ console.log(chalk3.bold(` ${header}`));
1251
+ console.log(` ${widths.map((w) => "\u2500".repeat(w)).join(" ")} ${"\u2500".repeat(30)}`);
1252
+ for (const r of rows) {
1253
+ console.log(
1254
+ ` ${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}`
1255
+ );
1256
+ }
1257
+ for (const d of unindexed) {
1258
+ console.log(chalk3.gray(` ${pad2(d.slice(0, 15), 16)} ${pad2("", 8)} ${pad2("", 22)} ${pad2("", 5)} ${pad2("", 9)} ${pad2("unindexed", 12)} ${d}`));
644
1259
  }
645
1260
  console.log("");
646
- console.log(chalk3.white(` Total: ${tableRows.length} session(s)`));
1261
+ console.log(chalk3.white(` Total: ${rows.length} session(s)` + (unindexed.length ? chalk3.gray(` (+${unindexed.length} unindexed)`) : "")));
647
1262
  console.log("");
648
1263
  }
649
- function listKnowledge(cwd) {
650
- const manifestPath = resolve4(cwd, "data", "knowledge", "manifest.yml");
651
- if (!existsSync3(manifestPath)) {
652
- console.log(chalk3.yellow("No knowledge base found. Run `npx qualiow init` first."));
1264
+ function listKnowledge(cwd, options, log) {
1265
+ const dataDir = resolveDataDir(cwd, options.data);
1266
+ const knowledgeDir = join6(dataDir, "knowledge");
1267
+ const manifestPath = join6(knowledgeDir, "manifest.yml");
1268
+ if (!existsSync6(manifestPath)) {
1269
+ log(chalk3.yellow(`No knowledge base at ${manifestPath}. Run \`npx qualiow init\` first.`));
1270
+ return;
1271
+ }
1272
+ const manifest = KnowledgeManifestSchema.parse(
1273
+ parseYaml3(readFileSync5(manifestPath, "utf-8"))
1274
+ );
1275
+ if (options.entry) {
1276
+ log(readEntryFile(knowledgeDir, manifest.entries, options.entry));
1277
+ return;
1278
+ }
1279
+ if (options.changelog) {
1280
+ printKnowledgeChangelog(knowledgeDir, log);
1281
+ return;
1282
+ }
1283
+ if (options.stats) {
1284
+ printKnowledgeStats(manifest, log);
1285
+ return;
1286
+ }
1287
+ const filesOnDisk = globSync4(join6(knowledgeDir, "releases", "*", "entries", "*.yml")).length;
1288
+ log(chalk3.cyan.bold("\nKnowledge Base:"));
1289
+ log(chalk3.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
1290
+ if (filesOnDisk !== manifest.entries.length || manifest.stats.total_entries !== filesOnDisk) {
1291
+ log(
1292
+ chalk3.yellow(
1293
+ ` \u26A0 Registry (${manifest.entries.length}) / stats (${manifest.stats.total_entries}) disagree with ${filesOnDisk} entry files \u2014 run: npx qualiow kb sync`
1294
+ )
1295
+ );
1296
+ }
1297
+ const filters = [];
1298
+ if (options.domain) filters.push(`domain ${options.domain}`);
1299
+ if (options.tag) filters.push(`tag ${options.tag}`);
1300
+ if (options.type) filters.push(`type ${options.type}`);
1301
+ const entries = manifest.entries.filter(
1302
+ (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)
1303
+ );
1304
+ if (filters.length) {
1305
+ log(chalk3.white(` Filter: ${filters.join(", ")} \u2192 ${entries.length} entries`));
1306
+ }
1307
+ log("");
1308
+ if (entries.length === 0) {
1309
+ log(chalk3.yellow(" No entries match that filter."));
1310
+ log("");
653
1311
  return;
654
1312
  }
655
- const raw = readFileSync3(manifestPath, "utf-8");
656
- const manifest = parseYaml2(raw);
657
- console.log(chalk3.cyan.bold("\nKnowledge Base:"));
658
- console.log(chalk3.white(` Version: ${manifest.version} | Entries: ${manifest.stats.total_entries}`));
659
- console.log("");
660
1313
  const grouped = /* @__PURE__ */ new Map();
661
- for (const entry of manifest.entries) {
1314
+ for (const entry of entries) {
662
1315
  const list = grouped.get(entry.type) ?? [];
663
1316
  list.push(entry);
664
1317
  grouped.set(entry.type, list);
665
1318
  }
666
- for (const [type, entries] of grouped) {
667
- console.log(chalk3.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${entries.length}):`));
668
- for (const entry of entries) {
1319
+ for (const [type, group] of grouped) {
1320
+ log(chalk3.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${group.length}):`));
1321
+ for (const entry of group) {
669
1322
  const priorityColor = entry.priority === "high" ? chalk3.red : entry.priority === "medium" ? chalk3.yellow : chalk3.white;
670
1323
  const tags = entry.tags.map((t) => chalk3.gray(t)).join(", ");
671
- console.log(
672
- ` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk3.gray("tags:")} ${tags}`
673
- );
1324
+ log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk3.gray("tags:")} ${tags}`);
674
1325
  }
675
- console.log("");
1326
+ log("");
1327
+ }
1328
+ }
1329
+ function readEntryFile(knowledgeDir, entries, id) {
1330
+ const meta = entries.find((e) => e.id === id);
1331
+ const path = meta ? join6(knowledgeDir, meta.file) : join6(knowledgeDir, "custom", `${id}.yml`);
1332
+ if (!existsSync6(path)) {
1333
+ throw new Error(`Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`);
1334
+ }
1335
+ return readFileSync5(path, "utf-8").trimEnd();
1336
+ }
1337
+ function printKnowledgeChangelog(knowledgeDir, log) {
1338
+ const changelogPath = join6(knowledgeDir, "changelog.yml");
1339
+ if (!existsSync6(changelogPath)) {
1340
+ log(chalk3.yellow(`No changelog at ${changelogPath}.`));
1341
+ return;
1342
+ }
1343
+ const changelog = KnowledgeChangelogSchema.parse(
1344
+ parseYaml3(readFileSync5(changelogPath, "utf-8"))
1345
+ );
1346
+ log(chalk3.cyan.bold("\nKnowledge Base Changelog:"));
1347
+ log("");
1348
+ for (const release of changelog.releases) {
1349
+ log(` ${chalk3.bold(`v${release.version}`)} ${chalk3.gray(`\xB7 ${release.date}`)}`);
1350
+ log(` ${release.summary}`);
1351
+ const added = release.entries_added.map((e) => e.id);
1352
+ if (added.length) log(` ${chalk3.gray("added:")} ${added.join(", ")}`);
1353
+ if (release.entries_modified.length) {
1354
+ log(` ${chalk3.gray("modified:")} ${release.entries_modified.join(", ")}`);
1355
+ }
1356
+ if (release.entries_removed.length) {
1357
+ log(` ${chalk3.gray("removed:")} ${release.entries_removed.join(", ")}`);
1358
+ }
1359
+ log("");
676
1360
  }
677
1361
  }
1362
+ function printKnowledgeStats(manifest, log) {
1363
+ log(chalk3.cyan.bold("\nKnowledge Base Stats:"));
1364
+ log(chalk3.white(` Version: ${manifest.version}`));
1365
+ log("");
1366
+ for (const [key, value] of Object.entries(manifest.stats)) {
1367
+ log(` ${pad2(key.replace(/_/g, " "), 18)} ${value}`);
1368
+ }
1369
+ log("");
1370
+ log(chalk3.cyan(` Active releases (${manifest.active_releases.length}):`));
1371
+ log(` ${manifest.active_releases.join(", ")}`);
1372
+ log("");
1373
+ const ls = manifest.loading_strategy;
1374
+ log(chalk3.cyan(" Loading strategy:"));
1375
+ log(` ${pad2("always", 12)} ${ls.always.length} entries`);
1376
+ for (const [bucket, map] of [
1377
+ ["by_domain", ls.by_domain],
1378
+ ["by_tag", ls.by_tag],
1379
+ ["by_skill", ls.by_skill ?? {}]
1380
+ ]) {
1381
+ const keys = Object.keys(map);
1382
+ const total = Object.values(map).reduce((n, ids) => n + ids.length, 0);
1383
+ log(` ${pad2(bucket, 12)} ${keys.length} keys, ${total} references`);
1384
+ }
1385
+ log("");
1386
+ }
678
1387
  function listTargets(cwd) {
679
- const targetsDir = resolve4(cwd, "data", "targets");
680
- if (!existsSync3(targetsDir)) {
1388
+ const targetsDir = resolve5(cwd, "data", "targets");
1389
+ if (!existsSync6(targetsDir)) {
681
1390
  console.log(chalk3.yellow("No targets found. Run `npx qualiow init` first."));
682
1391
  return;
683
1392
  }
684
- const files = readdirSync2(targetsDir).filter((f) => f.endsWith(".yml"));
685
- if (files.length === 0) {
1393
+ const files = readdirSync3(targetsDir).filter((f) => f.endsWith(".yml")).sort();
1394
+ const projectLocal = resolve5(cwd, "qa", "target.yml");
1395
+ if (files.length === 0 && !existsSync6(projectLocal)) {
686
1396
  console.log(chalk3.yellow("No target configurations found."));
687
1397
  return;
688
1398
  }
689
1399
  console.log(chalk3.cyan.bold("\nTargets:"));
690
1400
  console.log("");
691
- const header = ` ${pad("ID", 22)} ${pad("Name", 35)} ${pad("Domain", 12)} ${pad("Auth", 16)} Base URL`;
1401
+ const header = ` ${pad2("File", 34)} ${pad2("Name", 32)} ${pad2("Domain", 11)} ${pad2("Auth", 16)} Base URL`;
692
1402
  console.log(chalk3.bold(header));
693
- console.log(` ${"\u2500".repeat(22)} ${"\u2500".repeat(35)} ${"\u2500".repeat(12)} ${"\u2500".repeat(16)} ${"\u2500".repeat(30)}`);
694
- for (const file of files) {
1403
+ console.log(` ${"\u2500".repeat(34)} ${"\u2500".repeat(32)} ${"\u2500".repeat(11)} ${"\u2500".repeat(16)} ${"\u2500".repeat(30)}`);
1404
+ const printTarget = (label, path) => {
695
1405
  try {
696
- const raw = readFileSync3(join3(targetsDir, file), "utf-8");
697
- const target = parseYaml2(raw);
1406
+ const target = parseYaml3(readFileSync5(path, "utf-8"));
1407
+ const url = target.base_url || target.web?.base_url || chalk3.gray("(none)");
698
1408
  console.log(
699
- ` ${pad(target.id, 22)} ${pad(target.name, 35)} ${pad(target.domain, 12)} ${pad(target.auth.strategy, 16)} ${target.base_url || chalk3.gray("(none)")}`
1409
+ ` ${pad2(label, 34)} ${pad2(target.name, 32)} ${pad2(target.domain, 11)} ${pad2(target.auth?.strategy ?? "", 16)} ${url}`
700
1410
  );
701
1411
  } catch {
702
- console.log(` ${chalk3.red("ERROR")} Could not parse ${file}`);
1412
+ console.log(` ${chalk3.red("ERROR")} Could not parse ${label}`);
703
1413
  }
704
- }
1414
+ };
1415
+ if (existsSync6(projectLocal)) printTarget("qa/target.yml", projectLocal);
1416
+ for (const file of files) printTarget(`data/targets/${file}`, join6(targetsDir, file));
705
1417
  console.log("");
706
- console.log(chalk3.white(` Total: ${files.length} target(s)`));
1418
+ console.log(chalk3.white(` Total: ${files.length + (existsSync6(projectLocal) ? 1 : 0)} target(s)`));
707
1419
  console.log("");
708
1420
  }
709
1421
  function listDomains(cwd) {
710
- const domainsDir = resolve4(cwd, "data", "domains");
711
- if (!existsSync3(domainsDir)) {
1422
+ const domainsDir = resolve5(cwd, "data", "domains");
1423
+ if (!existsSync6(domainsDir)) {
712
1424
  console.log(chalk3.yellow("No domain configs found. Run `npx qualiow init` first."));
713
1425
  return;
714
1426
  }
715
- const files = readdirSync2(domainsDir).filter((f) => f.endsWith(".yml"));
1427
+ const files = readdirSync3(domainsDir).filter((f) => f.endsWith(".yml")).sort();
716
1428
  if (files.length === 0) {
717
1429
  console.log(chalk3.yellow("No domain configurations found."));
718
1430
  return;
719
1431
  }
720
1432
  console.log(chalk3.cyan.bold("\nDomains:"));
721
1433
  console.log("");
722
- const header = ` ${pad("ID", 16)} ${pad("Name", 28)} ${pad("Checklist", 12)} ${pad("Journeys", 10)}`;
1434
+ const header = ` ${pad2("File", 18)} ${pad2("Name", 32)} ${pad2("Checklist", 10)} ${pad2("Journeys", 9)} ${pad2("Patterns", 9)}`;
723
1435
  console.log(chalk3.bold(header));
724
- console.log(` ${"\u2500".repeat(16)} ${"\u2500".repeat(28)} ${"\u2500".repeat(12)} ${"\u2500".repeat(10)}`);
1436
+ console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(32)} ${"\u2500".repeat(10)} ${"\u2500".repeat(9)} ${"\u2500".repeat(9)}`);
725
1437
  for (const file of files) {
726
1438
  try {
727
- const raw = readFileSync3(join3(domainsDir, file), "utf-8");
728
- const domain = parseYaml2(raw);
729
- const checklistCount = domain.completeness_checklist?.length ?? 0;
730
- const journeyCount = domain.journeys?.length ?? 0;
1439
+ const domain = parseYaml3(readFileSync5(join6(domainsDir, file), "utf-8"));
1440
+ const patterns = Object.values(domain.must_test_patterns ?? {}).reduce((n, arr) => n + arr.length, 0);
731
1441
  console.log(
732
- ` ${pad(domain.id, 16)} ${pad(domain.name, 28)} ${pad(String(checklistCount), 12)} ${pad(String(journeyCount), 10)}`
1442
+ ` ${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)}`
733
1443
  );
734
1444
  } catch {
735
1445
  console.log(` ${chalk3.red("ERROR")} Could not parse ${file}`);
@@ -739,25 +1449,23 @@ function listDomains(cwd) {
739
1449
  console.log(chalk3.white(` Total: ${files.length} domain(s)`));
740
1450
  console.log("");
741
1451
  }
742
- function pad(str, len) {
743
- if (str.length >= len) {
744
- return str.slice(0, len);
745
- }
1452
+ function pad2(str, len) {
1453
+ if (str.length >= len) return str.slice(0, len);
746
1454
  return str + " ".repeat(len - str.length);
747
1455
  }
748
1456
 
749
1457
  // src/cli/commands/report.ts
750
1458
  import { Command as Command4 } from "commander";
751
- import { resolve as resolve5, join as join5, basename as basename2 } from "path";
752
- import { existsSync as existsSync5, readdirSync as readdirSync4, writeFileSync as writeFileSync2 } from "fs";
1459
+ import { resolve as resolve6, join as join9, basename as basename6, relative as relative4 } from "path";
1460
+ import { existsSync as existsSync9, readdirSync as readdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
753
1461
  import chalk4 from "chalk";
754
1462
 
755
1463
  // src/formatters/html-report.ts
756
1464
  import Handlebars from "handlebars";
757
1465
 
758
1466
  // src/utils/parse-session.ts
759
- import { readFileSync as readFileSync4, readdirSync as readdirSync3, existsSync as existsSync4 } from "fs";
760
- import { join as join4, basename } from "path";
1467
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, existsSync as existsSync7 } from "fs";
1468
+ import { join as join7, basename as basename5 } from "path";
761
1469
  var SEVERITY_ORDER = {
762
1470
  critical: 0,
763
1471
  high: 1,
@@ -811,33 +1519,48 @@ function extractNumberedList(text) {
811
1519
  }
812
1520
  return steps;
813
1521
  }
1522
+ function cleanValue(v) {
1523
+ return v.trim().replace(/^`|`$/g, "").trim();
1524
+ }
814
1525
  function extractEvidence(content) {
815
- const screenshots = [];
816
- const console_errors = [];
1526
+ const evidence = {
1527
+ screenshots: [],
1528
+ videos: [],
1529
+ logs: [],
1530
+ console_errors: [],
1531
+ network_failures: []
1532
+ };
817
1533
  const evidenceText = extractSection(content, "Evidence");
818
- if (!evidenceText) {
819
- return { screenshots, console_errors };
820
- }
1534
+ if (!evidenceText) return evidence;
821
1535
  for (const line of evidenceText.split("\n")) {
822
1536
  const trimmed = line.replace(/^[-*]\s*/, "").trim();
823
- if (/screenshot/i.test(trimmed)) {
824
- const pathMatch = trimmed.match(/:\s*(.+)/);
825
- if (pathMatch) {
826
- screenshots.push(pathMatch[1].trim());
827
- }
828
- }
829
- if (/console\s*(error|log)/i.test(trimmed)) {
830
- const msgMatch = trimmed.match(/:\s*(.+)/);
831
- if (msgMatch && !/none/i.test(msgMatch[1])) {
832
- console_errors.push(msgMatch[1].trim());
833
- }
834
- }
835
- }
836
- return { screenshots, console_errors };
1537
+ const value = () => {
1538
+ const m = trimmed.match(/:\s*(.+)/);
1539
+ return m ? cleanValue(m[1]) : "";
1540
+ };
1541
+ const nonEmpty = (v) => v && !/^none\b/i.test(v);
1542
+ if (/^screenshot/i.test(trimmed)) {
1543
+ const v = value();
1544
+ if (nonEmpty(v)) evidence.screenshots.push(v);
1545
+ } else if (/^video/i.test(trimmed)) {
1546
+ const v = value();
1547
+ if (nonEmpty(v)) evidence.videos.push(v);
1548
+ } else if (/^log\b/i.test(trimmed)) {
1549
+ const v = value();
1550
+ if (nonEmpty(v)) evidence.logs.push(v);
1551
+ } else if (/console\s*(error|log)/i.test(trimmed)) {
1552
+ const v = value();
1553
+ if (nonEmpty(v)) evidence.console_errors.push(v);
1554
+ } else if (/network\s*(failure|error|request)/i.test(trimmed)) {
1555
+ const v = value();
1556
+ if (nonEmpty(v)) evidence.network_failures.push(v);
1557
+ }
1558
+ }
1559
+ return evidence;
837
1560
  }
838
1561
  async function parseBugReport(filePath) {
839
- const content = readFileSync4(filePath, "utf-8");
840
- const filename = basename(filePath, ".md");
1562
+ const content = readFileSync6(filePath, "utf-8");
1563
+ const filename = basename5(filePath, ".md");
841
1564
  const id = filename;
842
1565
  let title = "";
843
1566
  let component = "";
@@ -850,6 +1573,10 @@ async function parseBugReport(filePath) {
850
1573
  component = componentMatch[1];
851
1574
  title = title.replace(/^\[[^\]]+\]\s*/, "").trim();
852
1575
  }
1576
+ const componentField = content.match(/\*\*Component:\*\*\s*(.+)/i);
1577
+ if (componentField) {
1578
+ component = cleanValue(componentField[1]);
1579
+ }
853
1580
  if (!component) {
854
1581
  const categoryMatch = content.match(/\|\s*Category\s*\|\s*(.+?)\s*\|/i);
855
1582
  if (categoryMatch) {
@@ -864,8 +1591,14 @@ async function parseBugReport(filePath) {
864
1591
  let url = "";
865
1592
  const urlMatch = content.match(/\*\*URL:\*\*\s*(.+)/i) ?? content.match(/URL:\s*(https?:\/\/[^\s]+)/i);
866
1593
  if (urlMatch) {
867
- url = urlMatch[1].trim();
1594
+ url = cleanValue(urlMatch[1]);
868
1595
  }
1596
+ const priority = cleanValue(content.match(/\*\*Priority:\*\*\s*(.+)/i)?.[1] ?? "");
1597
+ const environment = cleanValue(content.match(/\*\*Environment:\*\*\s*(.+)/i)?.[1] ?? "");
1598
+ const reproduction_rate = cleanValue(
1599
+ content.match(/\*\*Reproduction rate:\*\*\s*(.+)/i)?.[1] ?? ""
1600
+ );
1601
+ const summary = extractSection(content, "Summary").replace(/^>\s*/gm, "").trim();
869
1602
  const expected = extractSection(content, "Expected").replace(/^_.*_\n?/, "").replace(/^>\s*/gm, "").trim();
870
1603
  const actual = extractSection(content, "Actual").replace(/^_.*_\n?/, "").replace(/^>\s*/gm, "").trim();
871
1604
  const stepsSection = extractSection(content, "Steps to Reproduce");
@@ -876,8 +1609,12 @@ async function parseBugReport(filePath) {
876
1609
  id,
877
1610
  title,
878
1611
  severity,
1612
+ priority,
879
1613
  component,
880
1614
  url,
1615
+ environment,
1616
+ reproduction_rate,
1617
+ summary,
881
1618
  expected,
882
1619
  actual,
883
1620
  steps,
@@ -886,33 +1623,33 @@ async function parseBugReport(filePath) {
886
1623
  };
887
1624
  }
888
1625
  async function parseSession(sessionDir) {
889
- const id = basename(sessionDir);
1626
+ const id = basename5(sessionDir);
890
1627
  let charter;
891
- const charterPath = join4(sessionDir, "charter.md");
892
- if (existsSync4(charterPath)) {
893
- charter = readFileSync4(charterPath, "utf-8");
1628
+ const charterPath = join7(sessionDir, "charter.md");
1629
+ if (existsSync7(charterPath)) {
1630
+ charter = readFileSync6(charterPath, "utf-8");
894
1631
  }
895
1632
  let report;
896
- const reportPath = join4(sessionDir, "session-report.md");
897
- if (existsSync4(reportPath)) {
898
- report = readFileSync4(reportPath, "utf-8");
1633
+ const reportPath = join7(sessionDir, "session-report.md");
1634
+ if (existsSync7(reportPath)) {
1635
+ report = readFileSync6(reportPath, "utf-8");
899
1636
  }
900
1637
  const phases = [];
901
- if (existsSync4(sessionDir)) {
902
- const files = readdirSync3(sessionDir);
1638
+ if (existsSync7(sessionDir)) {
1639
+ const files = readdirSync4(sessionDir);
903
1640
  const phaseFiles = files.filter((f) => /^phase-\d+/i.test(f)).sort();
904
1641
  for (const file of phaseFiles) {
905
- const content = readFileSync4(join4(sessionDir, file), "utf-8");
1642
+ const content = readFileSync6(join7(sessionDir, file), "utf-8");
906
1643
  const name = file.replace(/\.md$/, "");
907
1644
  phases.push({ name, content });
908
1645
  }
909
1646
  }
910
- const bugsDir = join4(sessionDir, "bugs");
1647
+ const bugsDir = join7(sessionDir, "bugs");
911
1648
  const bugs = [];
912
- if (existsSync4(bugsDir)) {
913
- const bugFiles = readdirSync3(bugsDir).filter((f) => /^BUG-.*\.md$/i.test(f)).sort();
1649
+ if (existsSync7(bugsDir)) {
1650
+ const bugFiles = readdirSync4(bugsDir).filter((f) => /^BUG-.*\.md$/i.test(f)).sort();
914
1651
  for (const file of bugFiles) {
915
- const bug = await parseBugReport(join4(bugsDir, file));
1652
+ const bug = await parseBugReport(join7(bugsDir, file));
916
1653
  bugs.push(bug);
917
1654
  }
918
1655
  }
@@ -926,7 +1663,167 @@ async function parseSession(sessionDir) {
926
1663
  };
927
1664
  }
928
1665
 
929
- // src/formatters/html-report.ts
1666
+ // src/utils/redact.ts
1667
+ var EMAIL_ALLOW = /(?:@|\.)(?:example\.(?:com|org|net)|localhost)$/i;
1668
+ function luhnValid(digits) {
1669
+ let sum = 0;
1670
+ let alt = false;
1671
+ for (let i = digits.length - 1; i >= 0; i--) {
1672
+ let d = digits.charCodeAt(i) - 48;
1673
+ if (d < 0 || d > 9) return false;
1674
+ if (alt) {
1675
+ d *= 2;
1676
+ if (d > 9) d -= 9;
1677
+ }
1678
+ sum += d;
1679
+ alt = !alt;
1680
+ }
1681
+ return sum % 10 === 0;
1682
+ }
1683
+ var RULES = [
1684
+ {
1685
+ name: "Private key",
1686
+ pattern: /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/g,
1687
+ replacement: "[PRIVATE_KEY_REDACTED]"
1688
+ },
1689
+ {
1690
+ name: "JWT",
1691
+ pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,
1692
+ replacement: "[JWT_REDACTED]"
1693
+ },
1694
+ {
1695
+ name: "Authorization header",
1696
+ pattern: /(authorization)(\s*[:=]\s*)(\S[^\n\r]*)/gi,
1697
+ replace: (m, k, sep2, value) => /_REDACTED\]/.test(value) ? m : `${k}${sep2}[REDACTED]`
1698
+ },
1699
+ {
1700
+ name: "Cookie header",
1701
+ pattern: /^(set-cookie|cookie)(\s*:\s*).+$/gim,
1702
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1703
+ },
1704
+ {
1705
+ name: "AWS access key id",
1706
+ pattern: /\b(?:AKIA|ASIA|AROA|AIDA)[0-9A-Z]{16}\b/g,
1707
+ replacement: "[AWS_KEY_REDACTED]"
1708
+ },
1709
+ {
1710
+ name: "AWS secret access key",
1711
+ pattern: /(aws_secret_access_key)(\s*[:=]\s*)\S+/gi,
1712
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1713
+ },
1714
+ {
1715
+ name: "OpenAI-style key",
1716
+ pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,
1717
+ replacement: "[SK_KEY_REDACTED]"
1718
+ },
1719
+ {
1720
+ name: "GitHub token",
1721
+ pattern: /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g,
1722
+ replacement: "[GITHUB_TOKEN_REDACTED]"
1723
+ },
1724
+ {
1725
+ name: "Slack token",
1726
+ pattern: /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g,
1727
+ replacement: "[SLACK_TOKEN_REDACTED]"
1728
+ },
1729
+ {
1730
+ name: "API key",
1731
+ pattern: /(x-api-key|api[_-]?key)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
1732
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1733
+ },
1734
+ {
1735
+ name: "Password",
1736
+ pattern: /(password|passwd|pwd)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
1737
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1738
+ },
1739
+ {
1740
+ name: "Token",
1741
+ pattern: /(access[_-]?token|refresh[_-]?token|token)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
1742
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1743
+ },
1744
+ {
1745
+ name: "Secret",
1746
+ pattern: /([a-z_]*secret)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
1747
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1748
+ },
1749
+ {
1750
+ name: "SSN",
1751
+ pattern: /\b\d{3}-\d{2}-\d{4}\b/g,
1752
+ replacement: "[SSN_REDACTED]"
1753
+ },
1754
+ {
1755
+ name: "Credit card number",
1756
+ pattern: /\b\d(?:[ -]?\d){12,18}\b/g,
1757
+ replace: (match) => {
1758
+ const digits = match.replace(/\D/g, "");
1759
+ if (digits.length < 13 || digits.length > 19) return match;
1760
+ if (!/^[3-6]/.test(digits)) return match;
1761
+ return luhnValid(digits) ? "[CARD_NUMBER_REDACTED]" : match;
1762
+ }
1763
+ }
1764
+ ];
1765
+ function redact(text, opts = {}) {
1766
+ const redactions = /* @__PURE__ */ new Set();
1767
+ let result = text;
1768
+ const rules = RULES.slice();
1769
+ if (opts.emails !== false) {
1770
+ rules.push({
1771
+ name: "Email",
1772
+ pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
1773
+ replace: (match) => EMAIL_ALLOW.test(match) ? match : "[EMAIL_REDACTED]"
1774
+ });
1775
+ }
1776
+ for (const rule of rules) {
1777
+ rule.pattern.lastIndex = 0;
1778
+ let fired = false;
1779
+ result = result.replace(rule.pattern, (...args) => {
1780
+ const match = args[0];
1781
+ const groups = args.slice(1, -2);
1782
+ const out = rule.replace ? rule.replace(match, ...groups) : rule.replacement;
1783
+ if (out !== match) fired = true;
1784
+ return out;
1785
+ });
1786
+ if (fired) redactions.add(rule.name);
1787
+ }
1788
+ return { text: result, redactions: [...redactions] };
1789
+ }
1790
+ function containsSecrets(text) {
1791
+ return redact(text).redactions.length > 0;
1792
+ }
1793
+ var REDACTION_CATEGORIES = RULES.map((r) => r.name).concat("Email");
1794
+
1795
+ // src/formatters/common.ts
1796
+ function redactString(s) {
1797
+ return s ? redact(s).text : s;
1798
+ }
1799
+ function redactBug(bug) {
1800
+ return {
1801
+ ...bug,
1802
+ title: redactString(bug.title),
1803
+ url: redactString(bug.url),
1804
+ environment: redactString(bug.environment),
1805
+ summary: redactString(bug.summary),
1806
+ expected: redactString(bug.expected),
1807
+ actual: redactString(bug.actual),
1808
+ steps: bug.steps.map(redactString),
1809
+ business_impact: redactString(bug.business_impact),
1810
+ evidence: {
1811
+ screenshots: bug.evidence.screenshots.map(redactString),
1812
+ videos: bug.evidence.videos.map(redactString),
1813
+ logs: bug.evidence.logs.map(redactString),
1814
+ console_errors: bug.evidence.console_errors.map(redactString),
1815
+ network_failures: bug.evidence.network_failures.map(redactString)
1816
+ }
1817
+ };
1818
+ }
1819
+ async function loadSessionForOutput(sessionDir) {
1820
+ const session = await parseSession(sessionDir);
1821
+ const report = session.report ? redact(session.report).text : "";
1822
+ return {
1823
+ session: { ...session, bugs: session.bugs.map(redactBug), report },
1824
+ report
1825
+ };
1826
+ }
930
1827
  function extractReportMeta(report, sessionId) {
931
1828
  const meta = {
932
1829
  target: sessionId,
@@ -941,40 +1838,34 @@ function extractReportMeta(report, sessionId) {
941
1838
  if (durationMatch) meta.duration = durationMatch[1].trim();
942
1839
  const targetMatch = report.match(/\*\*Application:\*\*\s*(.+)/i) ?? report.match(/\*\*Target:\*\*\s*(.+)/i) ?? report.match(/\|\s*Target\s*\|\s*(.+?)\s*\|/i);
943
1840
  if (targetMatch) meta.target = targetMatch[1].trim();
944
- const summaryMatch = report.match(/##\s+Executive Summary\s*\n+([\s\S]*?)(?=\n##\s|\n---)/i);
1841
+ const summaryMatch = report.match(
1842
+ /##\s+Executive Summary\s*\n+([\s\S]*?)(?=\n##\s|\n---|$)/i
1843
+ );
945
1844
  if (summaryMatch) meta.summary = summaryMatch[1].trim();
946
1845
  return meta;
947
1846
  }
948
1847
  function extractCoverage(report) {
949
- const entries = [];
950
- const tableMatch = report.match(
951
- /\|\s*Area\s*\|\s*Status\s*\|[\s\S]*?\n((?:\|.+\|.+\n?)+)/i
952
- );
953
- if (!tableMatch) return entries;
954
- const rows = tableMatch[1].split("\n").filter((r) => r.trim().startsWith("|"));
955
- for (const row of rows) {
956
- const cells = row.split("|").map((c) => c.trim()).filter(Boolean);
957
- if (cells.length >= 2 && !cells[0].startsWith("---")) {
958
- entries.push({
959
- area: cells[0] || "",
960
- status: cells[1] || "",
961
- bugsFound: cells[3] || "0",
962
- notes: cells[4] || ""
963
- });
964
- }
965
- }
966
- return entries;
1848
+ const table2 = parseMarkdownTable(report, { headingPrefix: "Coverage" });
1849
+ if (!table2) return [];
1850
+ return table2.rows.map((row) => ({
1851
+ area: row["area"] ?? "",
1852
+ risk: row["risk"] ?? "",
1853
+ status: row["status"] ?? row["tested?"] ?? row["tested"] ?? "",
1854
+ bugsFound: row["bugs"] ?? row["bugs found"] ?? row["findings"] ?? "0",
1855
+ notes: row["notes"] ?? ""
1856
+ }));
967
1857
  }
968
1858
  function extractListSection(report, heading) {
969
1859
  const items = [];
970
- const regex = new RegExp(`##\\s+${heading}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|\\n---|$)`, "i");
1860
+ const regex = new RegExp(
1861
+ `##\\s+${heading}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|\\n---|$)`,
1862
+ "i"
1863
+ );
971
1864
  const match = report.match(regex);
972
1865
  if (!match) return items;
973
1866
  for (const line of match[1].split("\n")) {
974
1867
  const itemMatch = line.match(/^[-*]\s+(?:\[.\]\s+)?(.+)/);
975
- if (itemMatch) {
976
- items.push(itemMatch[1].trim());
977
- }
1868
+ if (itemMatch) items.push(itemMatch[1].trim());
978
1869
  const numberedMatch = line.match(/^\d+\.\s+\*\*(.+?)\*\*\s*(.+)?/);
979
1870
  if (numberedMatch) {
980
1871
  const text = numberedMatch[2] ? `${numberedMatch[1]} ${numberedMatch[2]}` : numberedMatch[1];
@@ -983,11 +1874,30 @@ function extractListSection(report, heading) {
983
1874
  }
984
1875
  return items;
985
1876
  }
1877
+
1878
+ // src/utils/confidentiality.ts
1879
+ var CONFIDENTIALITY_LINES = [
1880
+ "CONFIDENTIAL: This report may contain internal URLs, security vulnerabilities,",
1881
+ "and application details. Do not share outside your organization without review."
1882
+ ];
1883
+ var CONFIDENTIALITY_HEADER_MD = CONFIDENTIALITY_LINES.map(
1884
+ (l) => `> ${l}`
1885
+ ).join("\n");
1886
+ var CONFIDENTIALITY_NOTICE = CONFIDENTIALITY_LINES.join(" ");
1887
+ function hasConfidentialityHeader(text) {
1888
+ return /CONFIDENTIAL:\s*This report may contain internal URLs/i.test(
1889
+ text.slice(0, 400)
1890
+ );
1891
+ }
1892
+
1893
+ // src/formatters/html-report.ts
986
1894
  var HTML_TEMPLATE = `<!DOCTYPE html>
987
1895
  <html lang="en">
988
1896
  <head>
989
1897
  <meta charset="UTF-8">
990
1898
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1899
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:">
1900
+ <meta name="robots" content="noindex, nofollow">
991
1901
  <title>Qualiow Report \u2014 {{meta.target}}</title>
992
1902
  <style>
993
1903
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -1181,6 +2091,18 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
1181
2091
  margin-bottom: 0.35rem;
1182
2092
  }
1183
2093
 
2094
+ /* Confidentiality banner */
2095
+ .confidential {
2096
+ background: #2a1a1a;
2097
+ border: 1px solid #663333;
2098
+ color: #e0b0b0;
2099
+ border-radius: 6px;
2100
+ padding: 0.6rem 1rem;
2101
+ font-size: 0.8rem;
2102
+ margin-bottom: 1.5rem;
2103
+ letter-spacing: 0.02em;
2104
+ }
2105
+
1184
2106
  /* Footer */
1185
2107
  .footer {
1186
2108
  margin-top: 3rem;
@@ -1227,6 +2149,8 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
1227
2149
  <body>
1228
2150
  <div class="container">
1229
2151
 
2152
+ <div class="confidential">{{confidentialityNotice}}</div>
2153
+
1230
2154
  <div class="header">
1231
2155
  <h1>Exploratory Testing Report</h1>
1232
2156
  <div class="meta">
@@ -1347,7 +2271,7 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
1347
2271
  {{/if}}
1348
2272
 
1349
2273
  <div class="footer">
1350
- Generated by Qualiow Exploratory Testing
2274
+ Generated by Qualiow Exploratory Testing \xB7 CONFIDENTIAL \u2014 internal use only
1351
2275
  </div>
1352
2276
 
1353
2277
  </div>
@@ -1355,8 +2279,7 @@ var HTML_TEMPLATE = `<!DOCTYPE html>
1355
2279
  </html>`;
1356
2280
  var compiledTemplate = Handlebars.compile(HTML_TEMPLATE);
1357
2281
  async function generateHtmlReport(sessionDir) {
1358
- const session = await parseSession(sessionDir);
1359
- const report = session.report ?? "";
2282
+ const { session, report } = await loadSessionForOutput(sessionDir);
1360
2283
  const meta = extractReportMeta(report, session.id);
1361
2284
  const coverage = extractCoverage(report);
1362
2285
  const observations = extractListSection(report, "Observations");
@@ -1372,6 +2295,7 @@ async function generateHtmlReport(sessionDir) {
1372
2295
  }));
1373
2296
  const html = compiledTemplate({
1374
2297
  meta,
2298
+ confidentialityNotice: CONFIDENTIALITY_NOTICE,
1375
2299
  totalBugs: session.bugs.length,
1376
2300
  criticalCount: counts.critical,
1377
2301
  highCount: counts.high,
@@ -1401,8 +2325,7 @@ function summarizeBusinessImpact(impact) {
1401
2325
  function extractTarget(report, sessionId) {
1402
2326
  const match = report.match(/\*\*Application:\*\*\s*(.+)/i) ?? report.match(/\*\*Target:\*\*\s*(.+)/i) ?? report.match(/\|\s*Target\s*\|\s*(.+?)\s*\|/i);
1403
2327
  if (match) return match[1].trim();
1404
- const parts = sessionId.split("-");
1405
- return parts[parts.length - 1] || sessionId;
2328
+ return parseSessionDirName(sessionId)?.slug ?? sessionId;
1406
2329
  }
1407
2330
  function extractDate(report) {
1408
2331
  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);
@@ -1416,64 +2339,33 @@ function extractPagesExplored(report) {
1416
2339
  const match = report.match(/Pages\s+Explored\s*\|\s*(\d+)/i);
1417
2340
  return match ? parseInt(match[1], 10) : 0;
1418
2341
  }
1419
- function extractCoverage2(report) {
1420
- const entries = [];
1421
- const tableMatch = report.match(
1422
- /\|\s*Area\s*\|\s*Status\s*\|[\s\S]*?\n((?:\|.+\|.+\n?)+)/i
1423
- );
1424
- if (!tableMatch) return entries;
1425
- const rows = tableMatch[1].split("\n").filter((r) => r.trim().startsWith("|"));
1426
- for (const row of rows) {
1427
- const cells = row.split("|").map((c) => c.trim()).filter(Boolean);
1428
- if (cells.length >= 2 && !cells[0].startsWith("---")) {
1429
- entries.push({
1430
- area: cells[0] || "",
1431
- status: cells[1] || "",
1432
- bugs_found: parseInt(cells[3] || "0", 10) || 0,
1433
- notes: cells[4] || ""
1434
- });
1435
- }
1436
- }
1437
- return entries;
1438
- }
1439
- function extractListSection2(report, heading) {
1440
- const items = [];
1441
- const regex = new RegExp(`##\\s+${heading}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|\\n---|$)`, "i");
1442
- const match = report.match(regex);
1443
- if (!match) return items;
1444
- for (const line of match[1].split("\n")) {
1445
- const itemMatch = line.match(/^[-*]\s+(?:\[.\]\s+)?(.+)/);
1446
- if (itemMatch) {
1447
- items.push(itemMatch[1].trim());
1448
- }
1449
- const numberedMatch = line.match(/^\d+\.\s+\*\*(.+?)\*\*\s*(.+)?/);
1450
- if (numberedMatch) {
1451
- const text = numberedMatch[2] ? `${numberedMatch[1]} ${numberedMatch[2]}` : numberedMatch[1];
1452
- items.push(text.replace(/\s*--\s*/, " -- "));
1453
- }
1454
- }
1455
- return items;
1456
- }
1457
2342
  async function generateJsonReport(sessionDir) {
1458
- const session = await parseSession(sessionDir);
1459
- const report = session.report ?? "";
1460
- const target = extractTarget(report, session.id);
1461
- const date = extractDate(report);
1462
- const duration_min = extractDuration(report);
1463
- const pages_explored = extractPagesExplored(report);
2343
+ const { session, report } = await loadSessionForOutput(sessionDir);
1464
2344
  const counts = { critical: 0, high: 0, medium: 0, low: 0 };
1465
2345
  for (const bug of session.bugs) {
1466
2346
  counts[bug.severity]++;
1467
2347
  }
1468
- const coverage = extractCoverage2(report);
1469
- const observations = extractListSection2(report, "Observations");
1470
- const recommendations = extractListSection2(report, "Recommendations");
2348
+ const coverage = extractCoverage(report).map((c) => ({
2349
+ area: c.area,
2350
+ risk: c.risk,
2351
+ status: c.status,
2352
+ bugs_found: parseInt(c.bugsFound, 10) || 0,
2353
+ notes: c.notes
2354
+ }));
1471
2355
  return {
2356
+ meta: {
2357
+ classification: "CONFIDENTIAL",
2358
+ notice: CONFIDENTIALITY_NOTICE,
2359
+ generated_by: `qualiow-exploratory-testing ${getPackageVersion()}`,
2360
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
2361
+ redacted: true
2362
+ },
1472
2363
  session: {
1473
2364
  id: session.id,
1474
- target,
1475
- date,
1476
- duration_min
2365
+ kind: parseSessionDirName(session.id)?.kind ?? null,
2366
+ target: extractTarget(report, session.id),
2367
+ date: extractDate(report),
2368
+ duration_min: extractDuration(report)
1477
2369
  },
1478
2370
  summary: {
1479
2371
  total_bugs: session.bugs.length,
@@ -1481,21 +2373,25 @@ async function generateJsonReport(sessionDir) {
1481
2373
  high: counts.high,
1482
2374
  medium: counts.medium,
1483
2375
  low: counts.low,
1484
- pages_explored
2376
+ pages_explored: extractPagesExplored(report)
1485
2377
  },
1486
2378
  bugs: session.bugs.map((bug) => ({
1487
2379
  id: bug.id,
1488
2380
  title: bug.title,
1489
2381
  severity: bug.severity,
2382
+ priority: bug.priority,
1490
2383
  component: bug.component,
1491
2384
  url: bug.url,
2385
+ environment: bug.environment,
2386
+ reproduction_rate: bug.reproduction_rate,
2387
+ summary: bug.summary,
1492
2388
  business_impact: bug.business_impact,
1493
2389
  steps: bug.steps,
1494
2390
  evidence: bug.evidence
1495
2391
  })),
1496
2392
  coverage,
1497
- observations,
1498
- recommendations
2393
+ observations: extractListSection(report, "Observations"),
2394
+ recommendations: extractListSection(report, "Recommendations")
1499
2395
  };
1500
2396
  }
1501
2397
 
@@ -1508,53 +2404,49 @@ var SEVERITY_TO_JIRA_PRIORITY = {
1508
2404
  };
1509
2405
  function csvEscape(value) {
1510
2406
  if (!value) return '""';
1511
- const escaped = value.replace(/"/g, '""');
1512
- return `"${escaped}"`;
2407
+ let v = value;
2408
+ if (/^[=+\-@\t\r]/.test(v)) v = `'${v}`;
2409
+ return `"${v.replace(/"/g, '""')}"`;
1513
2410
  }
1514
2411
  function formatDescription(bug) {
1515
2412
  const parts = [];
2413
+ if (bug.summary) {
2414
+ parts.push(bug.summary, "");
2415
+ }
1516
2416
  if (bug.steps.length > 0) {
1517
2417
  parts.push("h3. Steps to Reproduce");
1518
- for (const step of bug.steps) {
1519
- parts.push(`# ${step}`);
1520
- }
2418
+ for (const step of bug.steps) parts.push(`# ${step}`);
1521
2419
  parts.push("");
1522
2420
  }
1523
2421
  if (bug.expected) {
1524
- parts.push(`h3. Expected Behavior`);
1525
- parts.push(bug.expected);
1526
- parts.push("");
2422
+ parts.push("h3. Expected Behavior", bug.expected, "");
1527
2423
  }
1528
2424
  if (bug.actual) {
1529
- parts.push(`h3. Actual Behavior`);
1530
- parts.push(bug.actual);
1531
- parts.push("");
2425
+ parts.push("h3. Actual Behavior", bug.actual, "");
1532
2426
  }
1533
2427
  if (bug.business_impact) {
1534
- parts.push("h3. Business Impact");
1535
- parts.push(bug.business_impact);
1536
- parts.push("");
2428
+ parts.push("h3. Business Impact", bug.business_impact, "");
2429
+ }
2430
+ if (bug.environment) {
2431
+ parts.push("h3. Environment", bug.environment, "");
1537
2432
  }
1538
2433
  if (bug.url) {
1539
- parts.push(`h3. URL`);
1540
- parts.push(bug.url);
2434
+ parts.push("h3. URL", bug.url, "");
1541
2435
  }
2436
+ parts.push(`_${CONFIDENTIALITY_NOTICE}_`);
1542
2437
  return parts.join("\n");
1543
2438
  }
1544
- function extractDomain(sessionId) {
1545
- return "general";
1546
- }
1547
2439
  async function generateJiraExport(sessionDir) {
1548
- const session = await parseSession(sessionDir);
2440
+ const { session } = await loadSessionForOutput(sessionDir);
1549
2441
  const headers = ["Summary", "Priority", "Description", "Component", "Labels"];
1550
2442
  const rows = [headers.join(",")];
1551
- const domain = extractDomain(session.id);
2443
+ const kind = parseSessionDirName(session.id)?.kind ?? "";
1552
2444
  for (const bug of session.bugs) {
1553
2445
  const summary = `${bug.id}: ${bug.title}`;
1554
2446
  const priority = SEVERITY_TO_JIRA_PRIORITY[bug.severity] ?? "Major";
1555
2447
  const description = formatDescription(bug);
1556
2448
  const component = bug.component || "";
1557
- const labels = ["qualiow", "exploratory-testing", domain].filter(Boolean).join(" ");
2449
+ const labels = ["qualiow", "exploratory-testing", kind].filter(Boolean).join(" ");
1558
2450
  rows.push(
1559
2451
  [
1560
2452
  csvEscape(summary),
@@ -1568,11 +2460,139 @@ async function generateJiraExport(sessionDir) {
1568
2460
  return rows.join("\n");
1569
2461
  }
1570
2462
 
2463
+ // src/formatters/markdown-summary.ts
2464
+ var SEVERITY_LABEL = {
2465
+ critical: "Critical",
2466
+ high: "High",
2467
+ medium: "Medium",
2468
+ low: "Low"
2469
+ };
2470
+ async function generateMarkdownSummary(sessionDir) {
2471
+ const { session, report } = await loadSessionForOutput(sessionDir);
2472
+ const meta = extractReportMeta(report, session.id);
2473
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
2474
+ for (const bug of session.bugs) counts[bug.severity]++;
2475
+ const lines = [];
2476
+ lines.push(CONFIDENTIALITY_HEADER_MD, "");
2477
+ lines.push(`# Session Summary \u2014 ${meta.target}`, "");
2478
+ lines.push("| Field | Value |", "|---|---|");
2479
+ lines.push(`| Session | ${session.id} |`);
2480
+ if (meta.date) lines.push(`| Date | ${meta.date} |`);
2481
+ if (meta.duration) lines.push(`| Duration | ${meta.duration} |`);
2482
+ lines.push(
2483
+ `| Bugs | ${session.bugs.length} (Critical ${counts.critical} \xB7 High ${counts.high} \xB7 Medium ${counts.medium} \xB7 Low ${counts.low}) |`,
2484
+ ""
2485
+ );
2486
+ if (meta.summary) {
2487
+ lines.push("## Executive Summary", "", meta.summary, "");
2488
+ }
2489
+ if (session.bugs.length) {
2490
+ lines.push("## Bugs", "", "| ID | Severity | Component | Title |", "|---|---|---|---|");
2491
+ for (const bug of session.bugs) {
2492
+ lines.push(
2493
+ `| ${bug.id} | ${SEVERITY_LABEL[bug.severity]} | ${bug.component || "\u2014"} | ${bug.title} |`
2494
+ );
2495
+ }
2496
+ lines.push("");
2497
+ }
2498
+ const coverage = extractCoverage(report);
2499
+ if (coverage.length) {
2500
+ lines.push("## Coverage", "", "| Area | Risk | Status | Bugs | Notes |", "|---|---|---|---|---|");
2501
+ for (const c of coverage) {
2502
+ lines.push(`| ${c.area} | ${c.risk} | ${c.status} | ${c.bugsFound} | ${c.notes} |`);
2503
+ }
2504
+ lines.push("");
2505
+ }
2506
+ const recommendations = extractListSection(report, "Recommendations");
2507
+ if (recommendations.length) {
2508
+ lines.push("## Recommendations", "");
2509
+ for (const r of recommendations) lines.push(`- ${r}`);
2510
+ lines.push("");
2511
+ }
2512
+ return lines.join("\n");
2513
+ }
2514
+
2515
+ // src/schemas/session-metrics.schema.ts
2516
+ import { z as z7 } from "zod";
2517
+ var SeverityCountsSchema = z7.object({
2518
+ critical: z7.number().int().min(0),
2519
+ high: z7.number().int().min(0),
2520
+ medium: z7.number().int().min(0),
2521
+ low: z7.number().int().min(0)
2522
+ });
2523
+ var SessionMetricsSchema = z7.object({
2524
+ session_id: z7.string().min(1),
2525
+ target: z7.string().min(1),
2526
+ date: z7.string().min(1),
2527
+ duration_min: z7.number().min(0),
2528
+ bugs_found: z7.number().int().min(0),
2529
+ severity_counts: SeverityCountsSchema,
2530
+ pages_explored: z7.number().int().min(0),
2531
+ // Optional context.
2532
+ kind: z7.enum(["explore", "quick", "mobile", "backend"]).optional(),
2533
+ domain: z7.string().optional(),
2534
+ started_at: z7.string().optional(),
2535
+ completed_at: z7.string().optional(),
2536
+ phases_completed: z7.number().int().min(0).optional(),
2537
+ total_phases: z7.number().int().min(0).optional(),
2538
+ coverage: z7.record(z7.string(), z7.unknown()).optional(),
2539
+ evidence: z7.record(z7.string(), z7.unknown()).optional(),
2540
+ areas_not_tested: z7.array(z7.string()).optional(),
2541
+ blocked_by: z7.string().nullable().optional()
2542
+ });
2543
+
2544
+ // src/utils/metrics.ts
2545
+ import { readFileSync as readFileSync7, appendFileSync, existsSync as existsSync8, mkdirSync as mkdirSync2 } from "fs";
2546
+ import { join as join8, dirname as dirname3 } from "path";
2547
+ var METRICS_FILENAME = "metrics.jsonl";
2548
+ function appendSessionMetrics(outputDir, metrics) {
2549
+ SessionMetricsSchema.parse(metrics);
2550
+ const filePath = join8(outputDir, METRICS_FILENAME);
2551
+ const dir = dirname3(filePath);
2552
+ if (!existsSync8(dir)) {
2553
+ mkdirSync2(dir, { recursive: true });
2554
+ }
2555
+ const line = JSON.stringify(metrics) + "\n";
2556
+ appendFileSync(filePath, line, "utf-8");
2557
+ }
2558
+ function readAllMetrics(outputDir) {
2559
+ const filePath = join8(outputDir, METRICS_FILENAME);
2560
+ if (!existsSync8(filePath)) {
2561
+ return [];
2562
+ }
2563
+ const content = readFileSync7(filePath, "utf-8").trim();
2564
+ if (!content) {
2565
+ return [];
2566
+ }
2567
+ const lines = content.split("\n");
2568
+ const results = [];
2569
+ for (const line of lines) {
2570
+ if (!line.trim()) continue;
2571
+ let parsed;
2572
+ try {
2573
+ parsed = JSON.parse(line);
2574
+ } catch {
2575
+ continue;
2576
+ }
2577
+ const result = SessionMetricsSchema.safeParse(parsed);
2578
+ if (result.success) results.push(result.data);
2579
+ }
2580
+ return results;
2581
+ }
2582
+ function appendSessionMetricsDeduped(outputDir, metrics) {
2583
+ const existing = readAllMetrics(outputDir);
2584
+ if (existing.some((m) => m.session_id === metrics.session_id)) {
2585
+ return false;
2586
+ }
2587
+ appendSessionMetrics(outputDir, metrics);
2588
+ return true;
2589
+ }
2590
+
1571
2591
  // src/cli/commands/report.ts
1572
2592
  function reportCommand() {
1573
- const cmd = new Command4("report").description("Generate a report from a session").option("-s, --session <id>", 'Session ID or "latest"', "latest").option("-f, --format <format>", "Output format: md, html, json, jira", "md").action(async (options) => {
2593
+ const cmd = new Command4("report").description("Generate a report (md summary, html, json or jira csv) from a session").option("-s, --session <id>", 'Session directory name, a unique substring, or "latest"', "latest").option("-f, --format <format>", "Output format: md, html, json, jira", "md").option("-o, --output <file>", "Write to this file instead of the session directory").option("--stdout", "Print to stdout instead of writing a file", false).action(async (options) => {
1574
2594
  try {
1575
- await runReport(options);
2595
+ await runReport(options, { cwd: process.cwd() });
1576
2596
  } catch (err) {
1577
2597
  console.error(chalk4.red("Error:"), err instanceof Error ? err.message : err);
1578
2598
  process.exit(1);
@@ -1580,90 +2600,93 @@ function reportCommand() {
1580
2600
  });
1581
2601
  return cmd;
1582
2602
  }
1583
- async function runReport(options) {
1584
- const cwd = process.cwd();
1585
- const sessionsDir = resolve5(cwd, "output", "sessions");
1586
- if (!existsSync5(sessionsDir)) {
1587
- console.error(chalk4.red("No sessions directory found. Run `npx qualiow init` first."));
1588
- process.exit(1);
2603
+ var DEFAULT_FILENAMES = {
2604
+ md: "session-summary.md",
2605
+ html: "session-report.html",
2606
+ json: "session-report.json",
2607
+ jira: "jira-export.csv"
2608
+ };
2609
+ async function runReport(options, ctx) {
2610
+ const cwd = ctx.cwd;
2611
+ const log = ctx.log ?? ((line) => console.log(line));
2612
+ const sessionsDir = resolve6(cwd, "output", "sessions");
2613
+ if (!existsSync9(sessionsDir)) {
2614
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
1589
2615
  }
1590
2616
  const sessionDir = resolveSessionDir(sessionsDir, options.session);
1591
- if (!sessionDir) {
1592
- console.error(chalk4.red("No session found. Run an exploratory testing session first."));
1593
- process.exit(1);
1594
- }
1595
- const sessionName = basename2(sessionDir);
1596
- console.log(chalk4.cyan(`
1597
- Session: ${sessionName}`));
2617
+ const sessionName = basename6(sessionDir);
1598
2618
  const format = options.format.toLowerCase();
2619
+ let content;
1599
2620
  switch (format) {
1600
- case "md": {
1601
- const reportPath = join5(sessionDir, "session-report.md");
1602
- if (existsSync5(reportPath)) {
1603
- console.log(chalk4.green(`
1604
- Report: ${reportPath}`));
1605
- } else {
1606
- console.log(chalk4.yellow(" No session-report.md found in this session."));
1607
- }
2621
+ case "md":
2622
+ content = await generateMarkdownSummary(sessionDir);
1608
2623
  break;
1609
- }
1610
- case "html": {
1611
- const html = await generateHtmlReport(sessionDir);
1612
- const outputPath = join5(sessionDir, "session-report.html");
1613
- writeFileSync2(outputPath, html);
1614
- console.log(chalk4.green(`
1615
- HTML report saved: ${outputPath}`));
2624
+ case "html":
2625
+ content = await generateHtmlReport(sessionDir);
1616
2626
  break;
1617
- }
1618
- case "json": {
1619
- const data = await generateJsonReport(sessionDir);
1620
- const outputPath = join5(sessionDir, "session-report.json");
1621
- writeFileSync2(outputPath, JSON.stringify(data, null, 2));
1622
- console.log(chalk4.green(`
1623
- JSON report saved: ${outputPath}`));
2627
+ case "json":
2628
+ content = JSON.stringify(await generateJsonReport(sessionDir), null, 2);
1624
2629
  break;
1625
- }
1626
- case "jira": {
1627
- const csv = await generateJiraExport(sessionDir);
1628
- const outputPath = join5(sessionDir, "jira-export.csv");
1629
- writeFileSync2(outputPath, csv);
1630
- console.log(chalk4.green(`
1631
- Jira export saved: ${outputPath}`));
2630
+ case "jira":
2631
+ content = await generateJiraExport(sessionDir);
1632
2632
  break;
1633
- }
1634
2633
  default:
1635
- console.error(chalk4.red(`Unknown format: "${format}". Choose from: md, html, json, jira`));
1636
- process.exit(1);
2634
+ throw new Error(`Unknown format: "${format}". Choose from: md, html, json, jira`);
1637
2635
  }
1638
- console.log("");
2636
+ if (options.stdout) {
2637
+ process.stdout.write(content.endsWith("\n") ? content : content + "\n");
2638
+ return { content };
2639
+ }
2640
+ const outputPath = options.output ? resolve6(cwd, options.output) : join9(sessionDir, DEFAULT_FILENAMES[format]);
2641
+ writeFileSync3(outputPath, content);
2642
+ log(chalk4.cyan(`
2643
+ Session: ${sessionName}`));
2644
+ log(chalk4.green(` ${format.toUpperCase()} written: ${relative4(cwd, outputPath)}`));
2645
+ const statsPath = join9(sessionDir, "stats.json");
2646
+ if (existsSync9(statsPath)) {
2647
+ try {
2648
+ const stats = SessionMetricsSchema.parse(JSON.parse(readFileSync8(statsPath, "utf-8")));
2649
+ if (appendSessionMetricsDeduped(resolve6(cwd, "output"), stats)) {
2650
+ log(chalk4.green(" \u2713 Metrics appended to output/metrics.jsonl"));
2651
+ }
2652
+ } catch {
2653
+ log(chalk4.yellow(" \u26A0 stats.json present but not in the expected shape \u2014 metrics not recorded"));
2654
+ }
2655
+ }
2656
+ log("");
2657
+ return { outputPath, content };
1639
2658
  }
1640
2659
  function resolveSessionDir(sessionsDir, sessionId) {
2660
+ const dirs = readdirSync5(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
1641
2661
  if (sessionId === "latest") {
1642
- const dirs2 = readdirSync4(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
1643
- if (dirs2.length === 0) return null;
1644
- return join5(sessionsDir, dirs2[dirs2.length - 1]);
1645
- }
1646
- const exactPath = join5(sessionsDir, sessionId);
1647
- if (existsSync5(exactPath)) {
1648
- return exactPath;
1649
- }
1650
- const dirs = readdirSync4(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory() && d.name.includes(sessionId)).map((d) => d.name).sort();
1651
- if (dirs.length > 0) {
1652
- return join5(sessionsDir, dirs[dirs.length - 1]);
2662
+ const canonical = dirs.filter((d) => SESSION_DIR_RE.test(d));
2663
+ const pool = canonical.length ? canonical : dirs;
2664
+ if (pool.length === 0) throw new Error("No sessions found. Run an exploratory testing session first.");
2665
+ return join9(sessionsDir, pool[pool.length - 1]);
2666
+ }
2667
+ if (dirs.includes(sessionId)) return join9(sessionsDir, sessionId);
2668
+ const matches = dirs.filter((d) => d.includes(sessionId));
2669
+ if (matches.length === 1) return join9(sessionsDir, matches[0]);
2670
+ if (matches.length > 1) {
2671
+ throw new Error(
2672
+ `"${sessionId}" matches ${matches.length} sessions \u2014 be more specific:
2673
+ ${matches.join("\n ")}`
2674
+ );
1653
2675
  }
1654
- return null;
2676
+ throw new Error(`No session matches "${sessionId}". List them with: npx qualiow list sessions`);
1655
2677
  }
1656
2678
 
1657
2679
  // src/cli/commands/explore.ts
1658
2680
  import { Command as Command5 } from "commander";
1659
- import { resolve as resolve6, join as join6 } from "path";
1660
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
1661
- import { execSync } from "child_process";
2681
+ import { resolve as resolve7, join as join10, relative as relative5 } from "path";
2682
+ import { existsSync as existsSync10, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
1662
2683
  import chalk5 from "chalk";
1663
2684
  function exploreCommand() {
1664
- const cmd = new Command5("explore").description("Run an exploratory testing session").argument("[url]", "Target URL to explore").option("-t, --target <name>", "Target configuration name").option("-c, --context <file>", "Context file path").option("--time-box <duration>", "Time box duration (e.g., 30m, 1h)", "30m").option("--dry-run", "Validate inputs and show what would happen", false).action(async (url, options) => {
2685
+ const cmd = new Command5("explore").description(
2686
+ "Pre-flight for an exploratory session: validates inputs and creates the session directory. The session itself runs in Claude Code via /qa-explore."
2687
+ ).argument("[url]", "Target URL to explore").option("-t, --target <name>", "Target configuration name (data/targets/<name>.yml)").option("-c, --context <file>", "Context file path").option("--time-box <duration>", "Time box, e.g. 45m (max 45m)", "45m").option("--dry-run", "Validate inputs and show what would happen", false).action(async (url, options) => {
1665
2688
  try {
1666
- await runExplore(url, options);
2689
+ await runExplore(url, options, { cwd: process.cwd() });
1667
2690
  } catch (err) {
1668
2691
  console.error(chalk5.red("Error:"), err instanceof Error ? err.message : err);
1669
2692
  process.exit(1);
@@ -1671,86 +2694,85 @@ function exploreCommand() {
1671
2694
  });
1672
2695
  return cmd;
1673
2696
  }
1674
- async function runExplore(url, options) {
1675
- const cwd = process.cwd();
2697
+ function parseTimeBox(value) {
2698
+ const m = /^(\d+)m$/.exec(value.trim());
2699
+ if (!m) throw new Error(`Invalid --time-box "${value}": use minutes like 30m or 45m`);
2700
+ const minutes = parseInt(m[1], 10);
2701
+ if (minutes < 1 || minutes > 45) {
2702
+ throw new Error(`--time-box must be between 1m and 45m (got ${value})`);
2703
+ }
2704
+ return minutes;
2705
+ }
2706
+ async function runExplore(url, options, ctx) {
2707
+ const cwd = ctx.cwd;
2708
+ const now = ctx.now ?? /* @__PURE__ */ new Date();
2709
+ const log = ctx.log ?? ((line) => console.log(line));
1676
2710
  if (url) {
1677
2711
  try {
1678
2712
  new URL(url);
1679
2713
  } catch {
1680
- console.error(chalk5.red(`Invalid URL: "${url}". Please provide a valid URL (e.g., https://example.com).`));
1681
- process.exit(1);
2714
+ throw new Error(`Invalid URL: "${url}". Provide a full URL such as https://example.com`);
1682
2715
  }
1683
2716
  }
1684
- let targetName = "adhoc";
1685
- if (options.target) {
1686
- const targetPath = resolve6(cwd, "data", "targets", `${options.target}.yml`);
1687
- if (!existsSync6(targetPath)) {
1688
- console.error(
1689
- chalk5.red(`Target config not found: ${targetPath}`)
2717
+ const minutes = parseTimeBox(options.timeBox);
2718
+ const targetPath = resolveTargetPath(cwd, options.target);
2719
+ let targetLabel = options.target ?? "adhoc";
2720
+ if (options.target || existsSync10(targetPath)) {
2721
+ if (!existsSync10(targetPath)) {
2722
+ throw new Error(
2723
+ `Target config not found: ${relative5(cwd, targetPath)}
2724
+ Available targets: npx qualiow list targets`
1690
2725
  );
1691
- console.error(chalk5.white(" Available targets: npx qualiow list targets"));
1692
- process.exit(1);
1693
2726
  }
1694
2727
  const result = validateTargetConfig(targetPath);
1695
2728
  if (!result.valid) {
1696
- console.error(chalk5.red(`Target config "${options.target}" is invalid:`));
1697
- for (const err of result.errors ?? []) {
1698
- console.error(chalk5.red(` \u2192 ${err.path ? `[${err.path}] ` : ""}${err.message}`));
1699
- }
1700
- process.exit(1);
2729
+ const details = (result.errors ?? []).map((e) => ` \u2192 ${e.path ? `[${e.path}] ` : ""}${e.message}`).join("\n");
2730
+ throw new Error(`Target config ${relative5(cwd, targetPath)} is invalid:
2731
+ ${details}`);
1701
2732
  }
1702
- targetName = options.target;
1703
- console.log(chalk5.green(` \u2713 Target config "${options.target}" is valid`));
2733
+ if (!options.target) targetLabel = url ? slugify(url) : "adhoc";
2734
+ log(chalk5.green(` \u2713 Target config valid: ${relative5(cwd, targetPath)}`));
2735
+ } else if (url) {
2736
+ targetLabel = slugify(url);
1704
2737
  }
1705
2738
  if (options.context) {
1706
- const contextPath = resolve6(cwd, options.context);
1707
- if (!existsSync6(contextPath)) {
1708
- console.error(chalk5.red(`Context file not found: ${contextPath}`));
1709
- process.exit(1);
2739
+ const contextPath = resolve7(cwd, options.context);
2740
+ if (!existsSync10(contextPath)) {
2741
+ throw new Error(`Context file not found: ${contextPath}`);
1710
2742
  }
1711
- console.log(chalk5.green(` \u2713 Context file found: ${options.context}`));
1712
- }
1713
- const now = /* @__PURE__ */ new Date();
1714
- const timestamp = [
1715
- now.getFullYear(),
1716
- String(now.getMonth() + 1).padStart(2, "0"),
1717
- String(now.getDate()).padStart(2, "0"),
1718
- "-",
1719
- String(now.getHours()).padStart(2, "0"),
1720
- String(now.getMinutes()).padStart(2, "0")
1721
- ].join("");
1722
- const sessionName = `${timestamp}-${targetName}`;
1723
- const sessionDir = resolve6(cwd, "output", "sessions", sessionName);
2743
+ log(chalk5.green(` \u2713 Context file found: ${options.context}`));
2744
+ }
2745
+ const sessionName = sessionDirName("explore", targetLabel, now);
2746
+ const sessionDir = resolve7(cwd, "output", "sessions", sessionName);
1724
2747
  if (options.dryRun) {
1725
- console.log("");
1726
- console.log(chalk5.cyan.bold("Dry run \u2014 no files created"));
1727
- console.log("");
1728
- console.log(chalk5.white(" Session would be created at:"));
1729
- console.log(chalk5.white(` ${sessionDir}`));
1730
- console.log("");
1731
- console.log(chalk5.white(" Configuration:"));
1732
- console.log(chalk5.white(` URL: ${url ?? "(none \u2014 will be prompted)"}`));
1733
- console.log(chalk5.white(` Target: ${options.target ?? "(ad-hoc)"}`));
1734
- console.log(chalk5.white(` Context: ${options.context ?? "(none)"}`));
1735
- console.log(chalk5.white(` Time box: ${options.timeBox}`));
1736
- console.log("");
1737
- console.log(chalk5.green(" \u2713 All inputs valid"));
1738
- return;
2748
+ log("");
2749
+ log(chalk5.cyan.bold("Dry run \u2014 no files created"));
2750
+ log(chalk5.white(` Session directory: ${relative5(cwd, sessionDir)}`));
2751
+ log(chalk5.white(` URL: ${url ?? "(none \u2014 /qa-explore will ask)"}`));
2752
+ log(chalk5.white(` Target: ${options.target ?? relative5(cwd, targetPath)}`));
2753
+ log(chalk5.white(` Context: ${options.context ?? "(none)"}`));
2754
+ log(chalk5.white(` Time box: ${minutes} min`));
2755
+ return { sessionDir };
2756
+ }
2757
+ for (const sub of ["", "screenshots", "bugs", "videos", "snapshots"]) {
2758
+ mkdirSync3(join10(sessionDir, sub), { recursive: true });
1739
2759
  }
1740
- mkdirSync2(sessionDir, { recursive: true });
1741
- mkdirSync2(join6(sessionDir, "screenshots"), { recursive: true });
1742
- mkdirSync2(join6(sessionDir, "bugs"), { recursive: true });
1743
- const charterContent = `# Exploratory Testing Charter
2760
+ const date = now.toISOString().slice(0, 10);
2761
+ writeFileSync4(
2762
+ join10(sessionDir, "charter.md"),
2763
+ `${CONFIDENTIALITY_HEADER_MD}
2764
+
2765
+ # Exploratory Testing Charter
1744
2766
 
1745
2767
  **Session:** ${sessionName}
1746
- **Date:** ${now.toISOString().split("T")[0]}
1747
- **Target:** ${options.target ?? "Ad-hoc"}
2768
+ **Date:** ${date}
2769
+ **Target:** ${options.target ?? targetLabel}
1748
2770
  **URL:** ${url ?? "TBD"}
1749
- **Time Box:** ${options.timeBox}
2771
+ **Time Box:** ${minutes} min
1750
2772
 
1751
2773
  ## Mission
1752
2774
 
1753
- > Describe the testing mission here.
2775
+ > Filled in by /qa-explore phase 2.
1754
2776
 
1755
2777
  ## Areas of Focus
1756
2778
 
@@ -1759,53 +2781,66 @@ async function runExplore(url, options) {
1759
2781
  ## Risks & Concerns
1760
2782
 
1761
2783
  -
2784
+ `
2785
+ );
2786
+ writeFileSync4(
2787
+ join10(sessionDir, "session-log.md"),
2788
+ `${CONFIDENTIALITY_HEADER_MD}
1762
2789
 
1763
- ## Notes
1764
-
1765
- -
1766
- `;
1767
- writeFileSync3(join6(sessionDir, "charter.md"), charterContent);
1768
- const sessionLogContent = `# Session Log \u2014 ${sessionName}
2790
+ # Session Log \u2014 ${sessionName}
1769
2791
 
1770
- | Time | Action | Observation | Bug? |
1771
- |------|--------|-------------|------|
1772
- `;
1773
- writeFileSync3(join6(sessionDir, "session-log.md"), sessionLogContent);
1774
- console.log("");
1775
- console.log(chalk5.green.bold("Session created!"));
1776
- console.log("");
1777
- console.log(chalk5.white(` Directory: ${sessionDir}`));
1778
- console.log("");
1779
- let claudeAvailable = false;
1780
- try {
1781
- execSync("which claude", { stdio: "pipe" });
1782
- claudeAvailable = true;
1783
- } catch {
1784
- }
1785
- if (claudeAvailable) {
1786
- console.log(chalk5.cyan(" Claude Code detected! To start exploring:"));
1787
- console.log("");
1788
- console.log(chalk5.white(` /qa-explore ${url ?? "<url>"}`));
1789
- } else {
1790
- console.log(chalk5.cyan(" Next steps:"));
1791
- console.log(chalk5.white(" 1. Install Claude Code (https://docs.anthropic.com/en/docs/claude-code)"));
1792
- console.log(chalk5.white(` 2. Run: /qa-explore ${url ?? "<url>"}`));
1793
- }
1794
- console.log("");
1795
- console.log(chalk5.gray(` Session directory: ${sessionDir}`));
1796
- console.log("");
2792
+ [${now.toISOString()}] [PRE-FLIGHT] Session directory created by \`qualiow explore\`
2793
+ `
2794
+ );
2795
+ log("");
2796
+ log(chalk5.green.bold("Session skeleton created (pre-flight only \u2014 no browser was launched)."));
2797
+ log(chalk5.white(` Directory: ${relative5(cwd, sessionDir)}`));
2798
+ log("");
2799
+ log(chalk5.cyan(" Run the session in Claude Code:"));
2800
+ const args = [url ?? "<url>", options.target ? `--target ${options.target}` : "", options.context ? `--context ${options.context}` : ""].filter(Boolean).join(" ");
2801
+ log(chalk5.white(` /qa-explore ${args} --session output/sessions/${sessionName}`));
2802
+ log("");
2803
+ return { sessionDir };
1797
2804
  }
1798
2805
 
1799
- // src/cli/commands/gather.ts
2806
+ // src/cli/commands/kb.ts
1800
2807
  import { Command as Command6 } from "commander";
1801
- import { resolve as resolve7 } from "path";
1802
- import { existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
1803
- import { execSync as execSync2 } from "child_process";
2808
+ import { resolve as resolve8, join as join11 } from "path";
2809
+ import { existsSync as existsSync11, readFileSync as readFileSync9, readdirSync as readdirSync6 } from "fs";
1804
2810
  import chalk6 from "chalk";
1805
- function gatherCommand() {
1806
- const cmd = new Command6("gather").description("Gather and analyze requirements for testing context").argument("<source>", "Source file path or URL to gather context from").option("-o, --output <file>", "Output file path").option("-d, --domain <name>", "Domain configuration name").action(async (source, options) => {
2811
+ import { parse as parseYaml4 } from "yaml";
2812
+ var DEFAULT_MAX_LINES = 12;
2813
+ var WRAP_COLUMN = 100;
2814
+ var WHEN_TO_USE_ITEMS = 3;
2815
+ function kbCommand() {
2816
+ const cmd = new Command6("kb").description("Knowledge-base maintenance");
2817
+ cmd.command("sync").description("Regenerate data/knowledge/manifest.yml entries and stats from the release files").action(() => {
2818
+ try {
2819
+ const result = runKb("sync", process.cwd());
2820
+ console.log(
2821
+ result.changed ? chalk6.green(` \u2713 manifest.yml updated (${result.entryCount} entries)`) : chalk6.cyan(` \u25CB manifest.yml already in sync (${result.entryCount} entries)`)
2822
+ );
2823
+ } catch (err) {
2824
+ console.error(chalk6.red("Error:"), err instanceof Error ? err.message : err);
2825
+ process.exit(1);
2826
+ }
2827
+ });
2828
+ cmd.command("check").description("Exit 1 if manifest.yml is out of sync with the release files").action(() => {
2829
+ try {
2830
+ const result = runKb("check", process.cwd());
2831
+ if (result.changed) {
2832
+ console.error(chalk6.red(" \u2717 manifest.yml is out of sync \u2014 run: npx qualiow kb sync"));
2833
+ process.exit(1);
2834
+ }
2835
+ console.log(chalk6.green(` \u2713 manifest.yml in sync (${result.entryCount} entries)`));
2836
+ } catch (err) {
2837
+ console.error(chalk6.red("Error:"), err instanceof Error ? err.message : err);
2838
+ process.exit(1);
2839
+ }
2840
+ });
2841
+ cmd.command("digest").description("Print a bounded plain-text digest of the entries a session should load").option("--domain <id>", "Add the entries listed under loading_strategy.by_domain").option("--tag <tag...>", "Add the entries listed under loading_strategy.by_tag (repeatable)").option("--for <skill>", "Add the entries listed under loading_strategy.by_skill (explore, backend, mobile)").option("--entry <id>", "Print the full YAML of one entry instead of the digest").option("--data <dir>", "Read the knowledge base from this data directory").option("--max-lines <n>", "Per-entry line cap", (v) => parseInt(v, 10), DEFAULT_MAX_LINES).action((options) => {
1807
2842
  try {
1808
- await runGather(source, options);
2843
+ console.log(runKbDigest(options, process.cwd()));
1809
2844
  } catch (err) {
1810
2845
  console.error(chalk6.red("Error:"), err instanceof Error ? err.message : err);
1811
2846
  process.exit(1);
@@ -1813,77 +2848,627 @@ function gatherCommand() {
1813
2848
  });
1814
2849
  return cmd;
1815
2850
  }
1816
- async function runGather(source, options) {
1817
- const cwd = process.cwd();
1818
- const isUrl = isValidUrl(source);
1819
- const isFile = !isUrl && existsSync7(resolve7(cwd, source));
1820
- if (!isUrl && !isFile) {
1821
- console.error(chalk6.red(`Source not found: "${source}"`));
1822
- console.error(chalk6.white(" Provide a valid file path or URL."));
1823
- process.exit(1);
1824
- }
1825
- if (isUrl) {
1826
- console.log(chalk6.green(` \u2713 Source is a URL: ${source}`));
1827
- } else {
1828
- console.log(chalk6.green(` \u2713 Source file found: ${resolve7(cwd, source)}`));
2851
+ function runKb(mode, cwd) {
2852
+ const dataDir = resolve8(cwd, "data");
2853
+ if (!existsSync11(resolve8(dataDir, "knowledge", "manifest.yml"))) {
2854
+ throw new Error("data/knowledge/manifest.yml not found. Run `npx qualiow init` first.");
1829
2855
  }
1830
- if (options.domain) {
1831
- const domainPath = resolve7(cwd, "data", "domains", `${options.domain}.yml`);
1832
- if (!existsSync7(domainPath)) {
1833
- console.error(chalk6.red(`Domain config not found: ${domainPath}`));
1834
- console.error(chalk6.white(" Available domains: npx qualiow list domains"));
1835
- process.exit(1);
2856
+ return syncKnowledgeManifest(dataDir, { check: mode === "check" });
2857
+ }
2858
+ function runKbDigest(options, cwd) {
2859
+ const dataDir = resolveDataDir(cwd, options.data);
2860
+ const knowledgeDir = join11(dataDir, "knowledge");
2861
+ const manifestPath = join11(knowledgeDir, "manifest.yml");
2862
+ if (!existsSync11(manifestPath)) {
2863
+ throw new Error(
2864
+ `No knowledge manifest at ${manifestPath}. Pass --data <dir>, or run \`npx qualiow init\` first.`
2865
+ );
2866
+ }
2867
+ const manifest = KnowledgeManifestSchema.parse(
2868
+ parseYaml4(readFileSync9(manifestPath, "utf-8"))
2869
+ );
2870
+ const byId = new Map(manifest.entries.map((e) => [e.id, e]));
2871
+ const maxLines = Math.max(1, options.maxLines ?? DEFAULT_MAX_LINES);
2872
+ if (options.entry) {
2873
+ return readWholeEntry(knowledgeDir, byId, options.entry);
2874
+ }
2875
+ const ls = manifest.loading_strategy;
2876
+ const selected = [];
2877
+ const add = (ids) => {
2878
+ let added = 0;
2879
+ for (const id of ids ?? []) {
2880
+ if (selected.includes(id)) continue;
2881
+ selected.push(id);
2882
+ added++;
2883
+ }
2884
+ return added;
2885
+ };
2886
+ add(ls.always);
2887
+ const domainAdded = options.domain ? add(ls.by_domain[options.domain]) : 0;
2888
+ const tags = options.tag ?? [];
2889
+ let tagAdded = 0;
2890
+ for (const tag of tags) tagAdded += add(ls.by_tag[tag]);
2891
+ let skillAdded = 0;
2892
+ if (options.for) {
2893
+ const bySkill = ls.by_skill;
2894
+ if (!bySkill) {
2895
+ throw new Error(
2896
+ "This manifest has no loading_strategy.by_skill, so --for has nothing to select."
2897
+ );
2898
+ }
2899
+ if (!Object.prototype.hasOwnProperty.call(bySkill, options.for)) {
2900
+ throw new Error(
2901
+ `Unknown skill "${options.for}". Known: ${Object.keys(bySkill).sort().join(", ")}.`
2902
+ );
1836
2903
  }
1837
- console.log(chalk6.green(` \u2713 Domain config "${options.domain}" found`));
2904
+ skillAdded = add(bySkill[options.for]);
1838
2905
  }
1839
- const outputDir = resolve7(cwd, "output", "context");
1840
- mkdirSync3(outputDir, { recursive: true });
1841
- if (options.output) {
1842
- console.log(chalk6.green(` \u2713 Output will be saved to: ${resolve7(cwd, options.output)}`));
1843
- } else {
1844
- console.log(chalk6.green(` \u2713 Output directory ready: ${outputDir}`));
2906
+ const unknown = selected.filter((id) => !byId.has(id));
2907
+ if (unknown.length) {
2908
+ throw new Error(
2909
+ `loading_strategy references ${unknown.length} unknown entry id(s): ${unknown.join(", ")}. Run \`qualiow kb sync\` and \`qualiow validate --kb\`.`
2910
+ );
1845
2911
  }
1846
- let claudeAvailable = false;
1847
- try {
1848
- execSync2("which claude", { stdio: "pipe" });
1849
- claudeAvailable = true;
1850
- } catch {
2912
+ const header = [
2913
+ `# Knowledge digest v${manifest.version}`,
2914
+ `${selected.length} entries`,
2915
+ `always ${ls.always.length}`
2916
+ ];
2917
+ if (options.domain) header.push(`domain ${options.domain} +${domainAdded}`);
2918
+ if (tags.length) header.push(`tags ${tags.join(", ")} +${tagAdded}`);
2919
+ if (options.for) header.push(`skill ${options.for} +${skillAdded}`);
2920
+ const lines = [header.join(" \xB7 ")];
2921
+ for (const id of selected) {
2922
+ const meta = byId.get(id);
2923
+ lines.push(...entryBlock(join11(knowledgeDir, meta.file), meta, maxLines));
2924
+ }
2925
+ lines.push(...customSection(knowledgeDir, maxLines));
2926
+ lines.push(...learnedPatternsSection(cwd, knowledgeDir));
2927
+ return lines.join("\n");
2928
+ }
2929
+ function readWholeEntry(knowledgeDir, byId, id) {
2930
+ const meta = byId.get(id);
2931
+ const path = meta ? join11(knowledgeDir, meta.file) : join11(knowledgeDir, "custom", `${id}.yml`);
2932
+ if (!existsSync11(path)) {
2933
+ throw new Error(
2934
+ `Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`
2935
+ );
1851
2936
  }
1852
- console.log("");
1853
- console.log(chalk6.cyan.bold("Ready to gather context!"));
1854
- console.log("");
1855
- if (claudeAvailable) {
1856
- console.log(chalk6.cyan(" Claude Code detected! To gather context:"));
1857
- console.log("");
1858
- console.log(chalk6.white(` /qa-gather ${source}`));
2937
+ return readFileSync9(path, "utf-8").trimEnd();
2938
+ }
2939
+ function entryBlock(file, meta, maxLines, custom = false) {
2940
+ if (!existsSync11(file)) {
2941
+ throw new Error(`Entry "${meta.id}" is registered but its file is missing: ${file}`);
2942
+ }
2943
+ const entry = KnowledgeEntrySchema.parse(parseYaml4(readFileSync9(file, "utf-8")));
2944
+ const content = entry.content;
2945
+ const marker = custom ? " [custom]" : "";
2946
+ const out = [
2947
+ `- ${meta.id} [${meta.type}/${meta.priority}]${marker} tags: ${meta.tags.join(", ")}`
2948
+ ];
2949
+ out.push(...wrap(collapse(entry.content.summary)));
2950
+ for (const [key, items] of namedArrays(content)) {
2951
+ const rendered = items.map((item) => {
2952
+ const lead = subItemLead(item);
2953
+ return lead ? `${item.name} \u2014 ${lead}` : item.name;
2954
+ }).join("; ");
2955
+ out.push(...wrap(`${humanise(key)}: ${rendered}`));
2956
+ }
2957
+ const whenToUse = content["when_to_use"];
2958
+ if (Array.isArray(whenToUse) && whenToUse.length) {
2959
+ const items = whenToUse.slice(0, WHEN_TO_USE_ITEMS).filter((v) => typeof v === "string").map(collapse);
2960
+ if (items.length) out.push(...wrap(`when to use: ${items.join("; ")}`));
2961
+ }
2962
+ return capLines(out, maxLines);
2963
+ }
2964
+ function customSection(knowledgeDir, maxLines) {
2965
+ const customDir = join11(knowledgeDir, "custom");
2966
+ if (!existsSync11(customDir)) return [];
2967
+ const files = readdirSync6(customDir).filter((f) => f.endsWith(".yml")).sort();
2968
+ if (!files.length) return [];
2969
+ const lines = ["", "## Custom entries"];
2970
+ for (const file of files) {
2971
+ const path = join11(customDir, file);
2972
+ const parsed = parseYaml4(readFileSync9(path, "utf-8"));
2973
+ lines.push(
2974
+ ...entryBlock(
2975
+ path,
2976
+ {
2977
+ id: parsed.id ?? file.replace(/\.yml$/, ""),
2978
+ type: parsed.type ?? "custom",
2979
+ priority: parsed.priority ?? "medium",
2980
+ tags: parsed.tags ?? []
2981
+ },
2982
+ maxLines,
2983
+ true
2984
+ )
2985
+ );
2986
+ }
2987
+ return lines;
2988
+ }
2989
+ function learnedPatternsSection(cwd, knowledgeDir) {
2990
+ const candidates = [
2991
+ resolve8(cwd, "data", "knowledge", "learned-patterns.md"),
2992
+ join11(knowledgeDir, "learned-patterns.md")
2993
+ ];
2994
+ const path = candidates.find((p) => existsSync11(p));
2995
+ if (!path) return [];
2996
+ const sections = learnedPatternLeadIns(readFileSync9(path, "utf-8"));
2997
+ if (!sections.length) return [];
2998
+ const lines = ["", "## Learned patterns", "Grep the file for the full entry."];
2999
+ for (const section of sections) {
3000
+ lines.push(...wrap(`${section.heading}: ${section.items.join("; ")}`));
3001
+ }
3002
+ return lines;
3003
+ }
3004
+ function learnedPatternLeadIns(markdown) {
3005
+ const sections = [];
3006
+ let current = null;
3007
+ let bullet = null;
3008
+ const flush = () => {
3009
+ if (bullet !== null && current) {
3010
+ const match = /^\*\*([\s\S]+?)\*\*/.exec(bullet);
3011
+ if (match) current.items.push(collapse(match[1]));
3012
+ }
3013
+ bullet = null;
3014
+ };
3015
+ for (const raw of markdown.split("\n")) {
3016
+ const heading = /^#{2,}\s+(.+)$/.exec(raw);
3017
+ if (heading) {
3018
+ flush();
3019
+ current = { heading: heading[1].trim(), items: [] };
3020
+ sections.push(current);
3021
+ continue;
3022
+ }
3023
+ const start = /^[-*]\s+(.*)$/.exec(raw);
3024
+ if (start) {
3025
+ flush();
3026
+ bullet = start[1];
3027
+ continue;
3028
+ }
3029
+ if (bullet !== null) {
3030
+ if (raw.trim() === "") flush();
3031
+ else bullet += ` ${raw.trim()}`;
3032
+ }
3033
+ }
3034
+ flush();
3035
+ return sections.filter((s) => s.items.length > 0);
3036
+ }
3037
+ function namedArrays(content) {
3038
+ const found = [];
3039
+ for (const [key, value] of Object.entries(content)) {
3040
+ if (key === "summary" || key === "when_to_use") continue;
3041
+ if (!Array.isArray(value) || value.length === 0) continue;
3042
+ const items = value.filter(
3043
+ (v) => typeof v === "object" && v !== null && typeof v.name === "string"
3044
+ );
3045
+ if (items.length === value.length) found.push([key, items]);
3046
+ }
3047
+ return found;
3048
+ }
3049
+ function subItemLead(item) {
3050
+ const questions = item["questions"];
3051
+ if (Array.isArray(questions) && typeof questions[0] === "string") {
3052
+ return truncate(collapse(questions[0]));
3053
+ }
3054
+ const description = item["description"];
3055
+ if (typeof description === "string") return truncate(collapse(description));
3056
+ return "";
3057
+ }
3058
+ function collapse(text) {
3059
+ return text.replace(/\s+/g, " ").trim();
3060
+ }
3061
+ function truncate(text, limit = WRAP_COLUMN) {
3062
+ if (text.length <= limit) return text;
3063
+ const cut = text.slice(0, limit - 1);
3064
+ const lastSpace = cut.lastIndexOf(" ");
3065
+ return `${(lastSpace > limit / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
3066
+ }
3067
+ function humanise(key) {
3068
+ const spaced = key.replace(/_/g, " ");
3069
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
3070
+ }
3071
+ function wrap(text, width = WRAP_COLUMN, indent = " ", hanging = " ") {
3072
+ const words = collapse(text).split(" ").filter(Boolean);
3073
+ if (!words.length) return [];
3074
+ const out = [];
3075
+ let line = indent + words[0];
3076
+ for (const word of words.slice(1)) {
3077
+ if (line.length + 1 + word.length > width) {
3078
+ out.push(line);
3079
+ line = hanging + word;
3080
+ } else {
3081
+ line += ` ${word}`;
3082
+ }
3083
+ }
3084
+ out.push(line);
3085
+ return out;
3086
+ }
3087
+ function capLines(lines, maxLines) {
3088
+ if (lines.length <= maxLines) return lines;
3089
+ const kept = lines.slice(0, maxLines);
3090
+ kept[kept.length - 1] = `${kept[kept.length - 1]} \u2026`;
3091
+ return kept;
3092
+ }
3093
+
3094
+ // src/cli/commands/session.ts
3095
+ import { Command as Command7 } from "commander";
3096
+ import { execFileSync } from "child_process";
3097
+ import {
3098
+ appendFileSync as appendFileSync2,
3099
+ existsSync as existsSync12,
3100
+ mkdirSync as mkdirSync4,
3101
+ readFileSync as readFileSync10,
3102
+ readdirSync as readdirSync7,
3103
+ rmSync,
3104
+ statSync as statSync2,
3105
+ writeFileSync as writeFileSync5
3106
+ } from "fs";
3107
+ import { basename as basename7, dirname as dirname4, join as join12, relative as relative6, resolve as resolve9, sep } from "path";
3108
+ import chalk7 from "chalk";
3109
+ var defaultLog = (line) => console.log(line);
3110
+ function sessionCommand() {
3111
+ const cmd = new Command7("session").description(
3112
+ "Manage exploratory testing session output: finalize, list, archive, delete, prune"
3113
+ );
3114
+ cmd.command("finalize").description(
3115
+ "Validate a session (confidentiality header, no secrets, stats.json shape) and append its INDEX.md / all-bugs.md rows"
3116
+ ).argument("<dir>", 'Session directory name, a unique substring, or "latest"').option("--check", "Validate only; write nothing", false).option("--redact", "Rewrite files containing secrets with the redacted text", false).action(async (dir, options) => {
3117
+ try {
3118
+ const result = await runSessionFinalize(dir, options, { cwd: process.cwd() });
3119
+ if (!result.ok) {
3120
+ console.error(chalk7.red(`
3121
+ ${result.violations.length} violation(s):`));
3122
+ result.violations.forEach((v, i) => console.error(chalk7.red(` ${i + 1}. ${v}`)));
3123
+ console.error("");
3124
+ process.exit(1);
3125
+ }
3126
+ } catch (err) {
3127
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3128
+ process.exit(1);
3129
+ }
3130
+ });
3131
+ cmd.command("list").description("List sessions (same as `qualiow list sessions`)").action(async () => {
3132
+ try {
3133
+ await runList("sessions", process.cwd());
3134
+ } catch (err) {
3135
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3136
+ process.exit(1);
3137
+ }
3138
+ });
3139
+ cmd.command("archive").description("Archive a session directory to a .tar.gz next to it").argument("<dir>", 'Session directory name, a unique substring, or "latest"').option("--remove", "Delete the session directory after archiving", false).action((dir, options) => {
3140
+ try {
3141
+ runSessionArchive(dir, options, { cwd: process.cwd() });
3142
+ } catch (err) {
3143
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3144
+ process.exit(1);
3145
+ }
3146
+ });
3147
+ cmd.command("delete").description("Delete a session directory (dry run unless --yes)").argument("<dir>", 'Session directory name, a unique substring, or "latest"').option("--yes", "Perform the deletion instead of a dry run", false).action((dir, options) => {
3148
+ try {
3149
+ runSessionDelete(dir, options, { cwd: process.cwd() });
3150
+ } catch (err) {
3151
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3152
+ process.exit(1);
3153
+ }
3154
+ });
3155
+ cmd.command("prune").description("Delete sessions older than N days (dry run unless --yes)").requiredOption("--older-than <days>", "Delete sessions with a timestamp older than N days").option("--yes", "Perform the deletion instead of a dry run", false).action((options) => {
3156
+ try {
3157
+ runSessionPrune(options, { cwd: process.cwd() });
3158
+ } catch (err) {
3159
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3160
+ process.exit(1);
3161
+ }
3162
+ });
3163
+ return cmd;
3164
+ }
3165
+ async function runSessionFinalize(dir, options, ctx) {
3166
+ const cwd = ctx.cwd;
3167
+ const log = ctx.log ?? defaultLog;
3168
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3169
+ if (!existsSync12(sessionsDir)) {
3170
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3171
+ }
3172
+ const sessionDir = resolveSessionDir(sessionsDir, dir);
3173
+ const dirName = basename7(sessionDir);
3174
+ const parsedDirName = parseSessionDirName(dirName);
3175
+ const violations = [];
3176
+ const redactedFiles = [];
3177
+ let stats;
3178
+ const statsPath = join12(sessionDir, "stats.json");
3179
+ if (!existsSync12(statsPath)) {
3180
+ violations.push("stats.json is missing");
1859
3181
  } else {
1860
- console.log(chalk6.cyan(" Next steps:"));
1861
- console.log(chalk6.white(" 1. Install Claude Code (https://docs.anthropic.com/en/docs/claude-code)"));
1862
- console.log(chalk6.white(` 2. Run: /qa-gather ${source}`));
3182
+ let raw;
3183
+ try {
3184
+ raw = JSON.parse(readFileSync10(statsPath, "utf-8"));
3185
+ } catch (err) {
3186
+ violations.push(`stats.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
3187
+ }
3188
+ if (raw) {
3189
+ const effective = { ...raw };
3190
+ if (effective.kind === void 0 && parsedDirName) {
3191
+ effective.kind = parsedDirName.kind;
3192
+ }
3193
+ const result = SessionMetricsSchema.strict().safeParse(effective);
3194
+ if (!result.success) {
3195
+ for (const issue of result.error.issues) {
3196
+ const path = issue.path.length ? issue.path.join(".") : "(root)";
3197
+ violations.push(`stats.json: ${path} \u2014 ${issue.message}`);
3198
+ }
3199
+ } else {
3200
+ stats = result.data;
3201
+ }
3202
+ }
1863
3203
  }
1864
- console.log("");
1865
- console.log(chalk6.gray(" The /qa-gather skill will:"));
1866
- console.log(chalk6.gray(" - Analyze the source for testable requirements"));
1867
- console.log(chalk6.gray(" - Generate testing context and risk assessment"));
1868
- console.log(chalk6.gray(" - Save output to output/context/"));
1869
- console.log("");
3204
+ const allFiles = listFilesRecursive(sessionDir);
3205
+ for (const file of allFiles) {
3206
+ if (!file.toLowerCase().endsWith(".md")) continue;
3207
+ const content = readFileSync10(file, "utf-8");
3208
+ if (!hasConfidentialityHeader(content)) {
3209
+ violations.push(`${relative6(sessionDir, file)} is missing the confidentiality header`);
3210
+ }
3211
+ }
3212
+ const scannedExtRe = /\.(md|json|log|ya?ml)$/i;
3213
+ for (const file of allFiles) {
3214
+ if (!scannedExtRe.test(file)) continue;
3215
+ const rel = relative6(sessionDir, file);
3216
+ if (rel.split(sep).includes("snapshots")) continue;
3217
+ const content = readFileSync10(file, "utf-8");
3218
+ if (!containsSecrets(content)) continue;
3219
+ const { text, redactions } = redact(content);
3220
+ if (options.redact) {
3221
+ writeFileSync5(file, text);
3222
+ redactedFiles.push({ file: rel, categories: redactions });
3223
+ log(chalk7.yellow(` \u26A0 Redacted ${rel}: ${redactions.join(", ")}`));
3224
+ } else {
3225
+ violations.push(`${rel} contains a secret: ${redactions.join(", ")} (run with --redact to fix)`);
3226
+ }
3227
+ }
3228
+ if (violations.length > 0) {
3229
+ return { ok: false, violations, sessionDir, redactedFiles };
3230
+ }
3231
+ if (options.check) {
3232
+ log(chalk7.green(` \u2713 ${dirName} passes finalize checks (--check \u2014 nothing written)`));
3233
+ return { ok: true, violations: [], sessionDir, redactedFiles };
3234
+ }
3235
+ const finalStats = stats;
3236
+ const kind = finalStats.kind ?? parsedDirName?.kind ?? "";
3237
+ const indexPath = join12(sessionsDir, "INDEX.md");
3238
+ ensureFileWithHeader(indexPath, INDEX_MD_HEADER);
3239
+ const bugsOutputDir = resolve9(cwd, "output", "bugs");
3240
+ mkdirSync4(bugsOutputDir, { recursive: true });
3241
+ const allBugsPath = join12(bugsOutputDir, "all-bugs.md");
3242
+ ensureFileWithHeader(allBugsPath, ALL_BUGS_MD_HEADER);
3243
+ let indexRowAdded = false;
3244
+ const existingIndexRows = readSessionIndex(indexPath);
3245
+ if (!existingIndexRows.some((r) => r.report.includes(`${dirName}/`))) {
3246
+ const row = `| ${finalStats.date} | ${kind} | ${finalStats.target} | ${finalStats.bugs_found} | ${finalStats.duration_min} min | complete | ${dirName}/session-report.md |
3247
+ `;
3248
+ appendFileSync2(indexPath, row);
3249
+ indexRowAdded = true;
3250
+ }
3251
+ const parsedSession = await parseSession(sessionDir);
3252
+ const bugs = [...parsedSession.bugs].sort((a, b) => a.id.localeCompare(b.id));
3253
+ const existingBugRows = readAllBugsRows(allBugsPath);
3254
+ const bugRowsAdded = [];
3255
+ for (const bug of bugs) {
3256
+ if (existingBugRows.some((r) => r.id === bug.id && r.session === dirName)) continue;
3257
+ const title = bug.component ? `[${bug.component}] ${bug.title}` : bug.title;
3258
+ const severity = bug.severity.charAt(0).toUpperCase() + bug.severity.slice(1);
3259
+ const row = `| ${bug.id} | ${dirName} | ${title} | ${severity} | open | ${dirName}/bugs/${bug.id}.md |
3260
+ `;
3261
+ appendFileSync2(allBugsPath, row);
3262
+ bugRowsAdded.push(bug.id);
3263
+ }
3264
+ if (appendSessionMetricsDeduped(resolve9(cwd, "output"), finalStats)) {
3265
+ log(chalk7.green(" \u2713 Metrics appended to output/metrics.jsonl"));
3266
+ }
3267
+ const progressPath = join12(sessionDir, "progress.json");
3268
+ if (existsSync12(progressPath)) {
3269
+ try {
3270
+ const progress = JSON.parse(readFileSync10(progressPath, "utf-8"));
3271
+ progress.status = "complete";
3272
+ writeFileSync5(progressPath, `${JSON.stringify(progress, null, 2)}
3273
+ `);
3274
+ } catch {
3275
+ }
3276
+ }
3277
+ log(chalk7.green(` \u2713 ${dirName} finalized`));
3278
+ if (indexRowAdded) log(chalk7.white(" INDEX.md row appended"));
3279
+ if (bugRowsAdded.length) log(chalk7.white(` all-bugs.md rows appended: ${bugRowsAdded.join(", ")}`));
3280
+ return { ok: true, violations: [], sessionDir, redactedFiles, indexRowAdded, bugRowsAdded };
1870
3281
  }
1871
- function isValidUrl(str) {
1872
- try {
1873
- const url = new URL(str);
1874
- return url.protocol === "http:" || url.protocol === "https:";
1875
- } catch {
1876
- return false;
3282
+ function ensureFileWithHeader(path, header) {
3283
+ if (existsSync12(path)) return;
3284
+ mkdirSync4(dirname4(path), { recursive: true });
3285
+ writeFileSync5(path, header);
3286
+ }
3287
+ function readAllBugsRows(path) {
3288
+ if (!existsSync12(path)) return [];
3289
+ const table2 = parseMarkdownTable(readFileSync10(path, "utf-8"));
3290
+ if (!table2) return [];
3291
+ return table2.rows.map((r) => ({
3292
+ id: r["id"] ?? "",
3293
+ session: r["session"] ?? "",
3294
+ title: r["title"] ?? "",
3295
+ severity: r["severity"] ?? "",
3296
+ status: r["status"] ?? "",
3297
+ report: r["report"] ?? ""
3298
+ })).filter((r) => r.id);
3299
+ }
3300
+ function listFilesRecursive(dir) {
3301
+ const out = [];
3302
+ for (const entry of readdirSync7(dir, { withFileTypes: true })) {
3303
+ const full = join12(dir, entry.name);
3304
+ if (entry.isDirectory()) {
3305
+ out.push(...listFilesRecursive(full));
3306
+ } else if (entry.isFile()) {
3307
+ out.push(full);
3308
+ }
1877
3309
  }
3310
+ return out;
3311
+ }
3312
+ function runSessionArchive(dir, options, ctx) {
3313
+ const cwd = ctx.cwd;
3314
+ const log = ctx.log ?? defaultLog;
3315
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3316
+ if (!existsSync12(sessionsDir)) {
3317
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3318
+ }
3319
+ const sessionDir = resolveSessionDir(sessionsDir, dir);
3320
+ const dirName = basename7(sessionDir);
3321
+ const tarPath = join12(sessionsDir, `${dirName}.tar.gz`);
3322
+ execFileSync("tar", ["-czf", tarPath, "-C", sessionsDir, dirName]);
3323
+ log(chalk7.green(` \u2713 Archived ${dirName} \u2192 ${relative6(cwd, tarPath)}`));
3324
+ let removed = false;
3325
+ if (options.remove) {
3326
+ rmSync(sessionDir, { recursive: true, force: true });
3327
+ setIndexRowStatus(join12(sessionsDir, "INDEX.md"), dirName, "archived");
3328
+ removed = true;
3329
+ log(chalk7.green(` \u2713 Removed ${dirName} (INDEX.md row marked archived)`));
3330
+ }
3331
+ return { ok: true, sessionDir, tarPath, removed };
3332
+ }
3333
+ function setIndexRowStatus(indexPath, dirName, status) {
3334
+ if (!existsSync12(indexPath)) return;
3335
+ const statusIdx = INDEX_COLUMNS.indexOf("Status");
3336
+ const lines = readFileSync10(indexPath, "utf-8").split("\n");
3337
+ const updated = lines.map((line) => {
3338
+ if (!line.trim().startsWith("|")) return line;
3339
+ if (!line.includes(`${dirName}/`)) return line;
3340
+ const cells = line.split("|");
3341
+ if (cells.length < 3) return line;
3342
+ const inner = cells.slice(1, -1).map((c) => c.trim());
3343
+ if (inner.length <= statusIdx) return line;
3344
+ inner[statusIdx] = status;
3345
+ return `| ${inner.join(" | ")} |`;
3346
+ });
3347
+ writeFileSync5(indexPath, updated.join("\n"));
3348
+ }
3349
+ function runSessionDelete(dir, options, ctx) {
3350
+ const cwd = ctx.cwd;
3351
+ const log = ctx.log ?? defaultLog;
3352
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3353
+ if (!existsSync12(sessionsDir)) {
3354
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3355
+ }
3356
+ const sessionDir = resolveSessionDir(sessionsDir, dir);
3357
+ const dirName = basename7(sessionDir);
3358
+ const { fileCount, totalBytes } = dirStats(sessionDir);
3359
+ const indexPath = join12(sessionsDir, "INDEX.md");
3360
+ const allBugsPath = resolve9(cwd, "output", "bugs", "all-bugs.md");
3361
+ const indexRows = readSessionIndex(indexPath).filter((r) => r.report.includes(`${dirName}/`));
3362
+ const bugRows = readAllBugsRows(allBugsPath).filter((r) => r.session === dirName);
3363
+ if (!options.yes) {
3364
+ log(chalk7.cyan(`
3365
+ Dry run \u2014 would delete ${dirName}`));
3366
+ log(chalk7.white(` Files: ${fileCount} Size: ${formatBytes(totalBytes)}`));
3367
+ log(chalk7.white(` INDEX.md rows to remove: ${indexRows.length}`));
3368
+ log(chalk7.white(` all-bugs.md rows to remove: ${bugRows.length}`));
3369
+ log(chalk7.white(" Re-run with --yes to delete.\n"));
3370
+ return {
3371
+ ok: true,
3372
+ dryRun: true,
3373
+ sessionDir,
3374
+ fileCount,
3375
+ totalBytes,
3376
+ indexRows: indexRows.length,
3377
+ bugRows: bugRows.length
3378
+ };
3379
+ }
3380
+ performDelete(cwd, sessionDir);
3381
+ log(chalk7.green(` \u2713 Deleted ${dirName} (${fileCount} files, ${formatBytes(totalBytes)})`));
3382
+ return {
3383
+ ok: true,
3384
+ dryRun: false,
3385
+ sessionDir,
3386
+ fileCount,
3387
+ totalBytes,
3388
+ indexRows: indexRows.length,
3389
+ bugRows: bugRows.length
3390
+ };
3391
+ }
3392
+ function performDelete(cwd, sessionDir) {
3393
+ const dirName = basename7(sessionDir);
3394
+ rmSync(sessionDir, { recursive: true, force: true });
3395
+ removeTableRows(
3396
+ join12(cwd, "output", "sessions", "INDEX.md"),
3397
+ (line) => line.includes(`${dirName}/session-report.md`)
3398
+ );
3399
+ removeTableRows(join12(cwd, "output", "bugs", "all-bugs.md"), (line) => line.includes(`${dirName}/bugs/`));
3400
+ }
3401
+ function removeTableRows(filePath, matches) {
3402
+ if (!existsSync12(filePath)) return;
3403
+ const lines = readFileSync10(filePath, "utf-8").split("\n");
3404
+ const sepIdx = lines.findIndex((l) => /^\|(\s*:?-{2,}\s*\|)+\s*$/.test(l.trim()));
3405
+ if (sepIdx === -1) return;
3406
+ const head = lines.slice(0, sepIdx + 1);
3407
+ const rest = lines.slice(sepIdx + 1).filter((l) => !matches(l));
3408
+ writeFileSync5(filePath, [...head, ...rest].join("\n"));
3409
+ }
3410
+ function dirStats(dir) {
3411
+ let fileCount = 0;
3412
+ let totalBytes = 0;
3413
+ for (const file of listFilesRecursive(dir)) {
3414
+ fileCount++;
3415
+ totalBytes += statSync2(file).size;
3416
+ }
3417
+ return { fileCount, totalBytes };
3418
+ }
3419
+ function formatBytes(n) {
3420
+ if (n < 1024) return `${n} B`;
3421
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
3422
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
3423
+ }
3424
+ function runSessionPrune(options, ctx) {
3425
+ const cwd = ctx.cwd;
3426
+ const log = ctx.log ?? defaultLog;
3427
+ const now = ctx.now ?? /* @__PURE__ */ new Date();
3428
+ const days = typeof options.olderThan === "string" ? Number(options.olderThan) : options.olderThan;
3429
+ if (!Number.isFinite(days) || days < 0) {
3430
+ throw new Error(`--older-than must be a non-negative number of days (got "${options.olderThan}")`);
3431
+ }
3432
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3433
+ if (!existsSync12(sessionsDir)) {
3434
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3435
+ }
3436
+ const thresholdMs = days * 24 * 60 * 60 * 1e3;
3437
+ const dirs = readdirSync7(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory() && SESSION_DIR_RE.test(d.name)).map((d) => d.name).sort();
3438
+ const candidates = dirs.filter((name) => {
3439
+ const parsed = parseSessionDirName(name);
3440
+ if (!parsed) return false;
3441
+ const dirDate = timestampToDate(parsed.timestamp);
3442
+ return now.getTime() - dirDate.getTime() > thresholdMs;
3443
+ });
3444
+ if (!options.yes) {
3445
+ log(chalk7.cyan(`
3446
+ Dry run \u2014 ${candidates.length} session(s) older than ${days} day(s):`));
3447
+ for (const c of candidates) log(chalk7.white(` ${c}`));
3448
+ if (!candidates.length) log(chalk7.white(" (none)"));
3449
+ log("");
3450
+ return { ok: true, dryRun: true, candidates };
3451
+ }
3452
+ for (const name of candidates) {
3453
+ performDelete(cwd, join12(sessionsDir, name));
3454
+ log(chalk7.green(` \u2713 Deleted ${name}`));
3455
+ }
3456
+ return { ok: true, dryRun: false, candidates };
3457
+ }
3458
+ function timestampToDate(ts) {
3459
+ const m = /^(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})$/.exec(ts);
3460
+ if (!m) return /* @__PURE__ */ new Date(NaN);
3461
+ const [, y, mo, d, h, mi] = m;
3462
+ return new Date(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi));
1878
3463
  }
1879
3464
 
1880
3465
  // src/cli/index.ts
1881
- var program = new Command7().name("qualiow").description("qualiow \u2014 AI-powered exploratory testing").version("1.0.0");
3466
+ var program = new Command8().name("qualiow").description("qualiow \u2014 AI-powered exploratory testing (web, mobile, backend)").version(getPackageVersion());
1882
3467
  program.addCommand(initCommand());
1883
3468
  program.addCommand(validateCommand());
1884
3469
  program.addCommand(listCommand());
1885
3470
  program.addCommand(reportCommand());
1886
3471
  program.addCommand(exploreCommand());
1887
- program.addCommand(gatherCommand());
3472
+ program.addCommand(kbCommand());
3473
+ program.addCommand(sessionCommand());
1888
3474
  program.parse();
1889
- //# sourceMappingURL=index.js.map