qualiow-exploratory-testing 2.0.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 (43) hide show
  1. package/.claude-plugin/marketplace.json +26 -0
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +65 -0
  4. package/README.md +123 -12
  5. package/agents/qa-diff-indexer-agent.md +81 -0
  6. package/agents/qa-gather-agent.md +21 -4
  7. package/agents/qa-page-mapper-agent.md +74 -0
  8. package/agents/qa-reporting-agent.md +103 -0
  9. package/bin/qualiow +30 -0
  10. package/data/knowledge/manifest.yml +22 -0
  11. package/dist/cli/index.js +876 -43
  12. package/dist/index.d.ts +50 -2
  13. package/dist/index.js +474 -29
  14. package/docs/GETTING-STARTED.md +127 -8
  15. package/hooks/hooks.json +27 -0
  16. package/hooks/scripts/read-guard.mjs +95 -0
  17. package/hooks/scripts/secret-patterns.d.mts +8 -0
  18. package/hooks/scripts/secret-patterns.mjs +136 -0
  19. package/hooks/scripts/write-guard.mjs +87 -0
  20. package/package.json +3 -2
  21. package/skills/qa-explore/SKILL.md +2 -1
  22. package/skills/qa-explore/phases/00-setup.md +16 -8
  23. package/skills/qa-explore/phases/03-discovery.md +48 -6
  24. package/skills/qa-explore/phases/07-reporting.md +36 -15
  25. package/skills/qa-explore/references/delegation-rules.md +82 -0
  26. package/skills/qa-explore/references/output-contract.md +7 -2
  27. package/skills/qa-explore/references/paths.md +25 -1
  28. package/skills/qa-explore/references/security-rules.md +4 -0
  29. package/skills/qa-explore/references/session-rules.md +2 -1
  30. package/skills/qa-explore-cleanup/SKILL.md +44 -19
  31. package/skills/qa-explore-feedback/SKILL.md +5 -0
  32. package/skills/qa-explore-mobile/SKILL.md +1 -1
  33. package/skills/qa-explore-mobile/phases/07-reporting.md +33 -11
  34. package/skills/qa-explore-quick/SKILL.md +12 -2
  35. package/skills/qa-explore-report/SKILL.md +29 -5
  36. package/skills/qa-gather/SKILL.md +30 -9
  37. package/skills/qa-knowledge-add/SKILL.md +10 -5
  38. package/skills/qa-knowledge-list/SKILL.md +28 -40
  39. package/skills/qa-verify-backend/SKILL.md +7 -4
  40. package/skills/qa-verify-backend/phases/02-static-review.md +11 -0
  41. package/skills/qa-verify-backend/phases/03-live-verification.md +3 -1
  42. package/skills/qa-verify-backend/phases/03b-api-verification.md +3 -1
  43. package/skills/qa-verify-backend/phases/05-reporting.md +51 -19
package/dist/cli/index.js CHANGED
@@ -1,7 +1,7 @@
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";
@@ -66,6 +66,19 @@ function resolveTargetPath(cwd, name, pkgRoot = getPackageRoot()) {
66
66
  if (existsSync(cwdDefault)) return cwdDefault;
67
67
  return resolve(pkgRoot, "data", "targets", "_default.yml");
68
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
+ }
69
82
 
70
83
  // src/utils/index-files.ts
71
84
  var INDEX_COLUMNS = [
@@ -87,13 +100,13 @@ var ALL_BUGS_COLUMNS = [
87
100
  ];
88
101
  function table(title, note, columns) {
89
102
  const header = `| ${columns.join(" | ")} |`;
90
- const sep = `|${columns.map(() => "---").join("|")}|`;
103
+ const sep2 = `|${columns.map(() => "---").join("|")}|`;
91
104
  return `# ${title}
92
105
 
93
106
  ${note}
94
107
 
95
108
  ${header}
96
- ${sep}
109
+ ${sep2}
97
110
  `;
98
111
  }
99
112
  var INDEX_MD_HEADER = table(
@@ -139,9 +152,71 @@ function mergeGitignore(existing) {
139
152
  return existing + prefix + leadingBlank + block.join("\n") + "\n";
140
153
  }
141
154
 
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
+ }
212
+
142
213
  // src/cli/commands/init.ts
143
214
  function initCommand() {
144
- 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).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) => {
145
220
  try {
146
221
  await runInit(options, { cwd: process.cwd() });
147
222
  } catch (err) {
@@ -218,14 +293,14 @@ async function runInit(options, ctx) {
218
293
  filter: (rel2) => rel2.startsWith("qa-")
219
294
  })
220
295
  );
221
- const agentCandidates = [
222
- join2(pkgRoot, "agents", "qa-gather-agent.md"),
223
- join2(pkgRoot, ".claude", "agents", "qa-gather-agent.md")
224
- ];
225
- const agentSrc = agentCandidates.find((p) => existsSync2(p));
226
- if (agentSrc) {
296
+ const agentsCandidates = [join2(pkgRoot, "agents"), join2(pkgRoot, ".claude", "agents")];
297
+ const agentsSrc = agentsCandidates.find((p) => existsSync2(p));
298
+ if (agentsSrc) {
227
299
  copies.push(
228
- copyEntry(agentSrc, join2(cwd, ".claude", "agents", "qa-gather-agent.md"), copyOpts)
300
+ ...copyTree(agentsSrc, join2(cwd, ".claude", "agents"), {
301
+ ...copyOpts,
302
+ filter: (rel2) => rel2.endsWith(".md")
303
+ })
229
304
  );
230
305
  }
231
306
  const dataSrc = join2(pkgRoot, "data");
@@ -251,7 +326,12 @@ async function runInit(options, ctx) {
251
326
  })
252
327
  );
253
328
  const binSrc = join2(pkgRoot, "bin");
254
- copies.push(...copyTree(binSrc, join2(cwd, "qa", "bin"), copyOpts));
329
+ copies.push(
330
+ ...copyTree(binSrc, join2(cwd, "qa", "bin"), {
331
+ ...copyOpts,
332
+ filter: (rel2) => rel2 !== "qualiow"
333
+ })
334
+ );
255
335
  if (existsSync2(binSrc)) {
256
336
  const versionPath = join2(cwd, "qa", "bin", "VERSION");
257
337
  const version = `${getPackageVersion(pkgRoot)}
@@ -270,6 +350,32 @@ async function runInit(options, ctx) {
270
350
  copies.push(copyEntry(envExampleSrc, join2(cwd, "qa", ".env.example"), copyOpts));
271
351
  }
272
352
  }
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;
370
+ }
371
+ }
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
+ }
273
379
  for (const dir of ["output/sessions", "output/bugs", "output/context", ".auth", "qa"]) {
274
380
  const full = join2(cwd, dir);
275
381
  if (!existsSync2(full)) {
@@ -313,12 +419,20 @@ async function runInit(options, ctx) {
313
419
  log(
314
420
  gitignoreUpdated ? chalk.green(" \u2713 Updated .gitignore (Qualiow block)") : chalk.cyan(" \u25CB .gitignore already up to date")
315
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
+ }
316
427
  log("");
317
428
  log(chalk.cyan.bold(options.dryRun ? "Dry run complete." : "Qualiow initialized."));
318
429
  log("");
319
430
  log(chalk.white("Next steps:"));
320
431
  log(chalk.white(" 1. npx playwright-cli install --skills # official Playwright skill, next to qualiow"));
321
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
+ }
322
436
  log(chalk.white(" 3. /qa-target-setup or /qa-explore https://your-app.com"));
323
437
  log(chalk.white(" 4. mobile: qa/bin/doctor-mobile.sh # then /qa-explore-mobile --target <id>"));
324
438
  log("");
@@ -596,7 +710,10 @@ var KnowledgeManifestEntrySchema = z4.object({
596
710
  var LoadingStrategySchema = z4.object({
597
711
  always: z4.array(z4.string()),
598
712
  by_domain: z4.record(z4.string(), z4.array(z4.string())),
599
- by_tag: 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()
600
717
  });
601
718
  var KnowledgeManifestSchema = z4.object({
602
719
  version: z4.string().min(1),
@@ -860,7 +977,8 @@ function validateKnowledgeBase(dataDir) {
860
977
  const allRefs = [
861
978
  ...ls.always,
862
979
  ...Object.values(ls.by_domain).flat(),
863
- ...Object.values(ls.by_tag).flat()
980
+ ...Object.values(ls.by_tag).flat(),
981
+ ...Object.values(ls.by_skill ?? {}).flat()
864
982
  ];
865
983
  for (const id of allRefs) {
866
984
  if (!registryIds.has(id)) {
@@ -1061,9 +1179,9 @@ function parseSessionDirName(name) {
1061
1179
 
1062
1180
  // src/cli/commands/list.ts
1063
1181
  function listCommand() {
1064
- 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) => {
1065
1183
  try {
1066
- await runList(type, process.cwd());
1184
+ await runList(type, process.cwd(), options);
1067
1185
  } catch (err) {
1068
1186
  console.error(chalk3.red("Error:"), err instanceof Error ? err.message : err);
1069
1187
  process.exit(1);
@@ -1071,13 +1189,13 @@ function listCommand() {
1071
1189
  });
1072
1190
  return cmd;
1073
1191
  }
1074
- async function runList(type, cwd) {
1192
+ async function runList(type, cwd, options = {}, log = (line) => console.log(line)) {
1075
1193
  switch (type) {
1076
1194
  case "sessions":
1077
1195
  listSessions(cwd);
1078
1196
  break;
1079
1197
  case "knowledge":
1080
- listKnowledge(cwd);
1198
+ listKnowledge(cwd, options, log);
1081
1199
  break;
1082
1200
  case "targets":
1083
1201
  listTargets(cwd);
@@ -1143,40 +1261,128 @@ function listSessions(cwd) {
1143
1261
  console.log(chalk3.white(` Total: ${rows.length} session(s)` + (unindexed.length ? chalk3.gray(` (+${unindexed.length} unindexed)`) : "")));
1144
1262
  console.log("");
1145
1263
  }
1146
- function listKnowledge(cwd) {
1147
- const knowledgeDir = resolve5(cwd, "data", "knowledge");
1264
+ function listKnowledge(cwd, options, log) {
1265
+ const dataDir = resolveDataDir(cwd, options.data);
1266
+ const knowledgeDir = join6(dataDir, "knowledge");
1148
1267
  const manifestPath = join6(knowledgeDir, "manifest.yml");
1149
1268
  if (!existsSync6(manifestPath)) {
1150
- console.log(chalk3.yellow("No knowledge base found. Run `npx qualiow init` first."));
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);
1151
1285
  return;
1152
1286
  }
1153
- const manifest = parseYaml3(readFileSync5(manifestPath, "utf-8"));
1154
1287
  const filesOnDisk = globSync4(join6(knowledgeDir, "releases", "*", "entries", "*.yml")).length;
1155
- console.log(chalk3.cyan.bold("\nKnowledge Base:"));
1156
- console.log(chalk3.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
1288
+ log(chalk3.cyan.bold("\nKnowledge Base:"));
1289
+ log(chalk3.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
1157
1290
  if (filesOnDisk !== manifest.entries.length || manifest.stats.total_entries !== filesOnDisk) {
1158
- console.log(
1291
+ log(
1159
1292
  chalk3.yellow(
1160
1293
  ` \u26A0 Registry (${manifest.entries.length}) / stats (${manifest.stats.total_entries}) disagree with ${filesOnDisk} entry files \u2014 run: npx qualiow kb sync`
1161
1294
  )
1162
1295
  );
1163
1296
  }
1164
- console.log("");
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("");
1311
+ return;
1312
+ }
1165
1313
  const grouped = /* @__PURE__ */ new Map();
1166
- for (const entry of manifest.entries) {
1314
+ for (const entry of entries) {
1167
1315
  const list = grouped.get(entry.type) ?? [];
1168
1316
  list.push(entry);
1169
1317
  grouped.set(entry.type, list);
1170
1318
  }
1171
- for (const [type, entries] of grouped) {
1172
- console.log(chalk3.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${entries.length}):`));
1173
- 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) {
1174
1322
  const priorityColor = entry.priority === "high" ? chalk3.red : entry.priority === "medium" ? chalk3.yellow : chalk3.white;
1175
1323
  const tags = entry.tags.map((t) => chalk3.gray(t)).join(", ");
1176
- console.log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk3.gray("tags:")} ${tags}`);
1324
+ log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk3.gray("tags:")} ${tags}`);
1177
1325
  }
1178
- 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("");
1360
+ }
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}`);
1179
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("");
1180
1386
  }
1181
1387
  function listTargets(cwd) {
1182
1388
  const targetsDir = resolve5(cwd, "data", "targets");
@@ -1488,12 +1694,12 @@ var RULES = [
1488
1694
  {
1489
1695
  name: "Authorization header",
1490
1696
  pattern: /(authorization)(\s*[:=]\s*)(\S[^\n\r]*)/gi,
1491
- replace: (m, k, sep, value) => /_REDACTED\]/.test(value) ? m : `${k}${sep}[REDACTED]`
1697
+ replace: (m, k, sep2, value) => /_REDACTED\]/.test(value) ? m : `${k}${sep2}[REDACTED]`
1492
1698
  },
1493
1699
  {
1494
1700
  name: "Cookie header",
1495
1701
  pattern: /^(set-cookie|cookie)(\s*:\s*).+$/gim,
1496
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1702
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1497
1703
  },
1498
1704
  {
1499
1705
  name: "AWS access key id",
@@ -1503,7 +1709,7 @@ var RULES = [
1503
1709
  {
1504
1710
  name: "AWS secret access key",
1505
1711
  pattern: /(aws_secret_access_key)(\s*[:=]\s*)\S+/gi,
1506
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1712
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1507
1713
  },
1508
1714
  {
1509
1715
  name: "OpenAI-style key",
@@ -1523,22 +1729,22 @@ var RULES = [
1523
1729
  {
1524
1730
  name: "API key",
1525
1731
  pattern: /(x-api-key|api[_-]?key)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
1526
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1732
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1527
1733
  },
1528
1734
  {
1529
1735
  name: "Password",
1530
1736
  pattern: /(password|passwd|pwd)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
1531
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1737
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1532
1738
  },
1533
1739
  {
1534
1740
  name: "Token",
1535
1741
  pattern: /(access[_-]?token|refresh[_-]?token|token)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
1536
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1742
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1537
1743
  },
1538
1744
  {
1539
1745
  name: "Secret",
1540
1746
  pattern: /([a-z_]*secret)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
1541
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1747
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1542
1748
  },
1543
1749
  {
1544
1750
  name: "SSN",
@@ -1581,6 +1787,9 @@ function redact(text, opts = {}) {
1581
1787
  }
1582
1788
  return { text: result, redactions: [...redactions] };
1583
1789
  }
1790
+ function containsSecrets(text) {
1791
+ return redact(text).redactions.length > 0;
1792
+ }
1584
1793
  var REDACTION_CATEGORIES = RULES.map((r) => r.name).concat("Email");
1585
1794
 
1586
1795
  // src/formatters/common.ts
@@ -1675,6 +1884,11 @@ var CONFIDENTIALITY_HEADER_MD = CONFIDENTIALITY_LINES.map(
1675
1884
  (l) => `> ${l}`
1676
1885
  ).join("\n");
1677
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
+ }
1678
1892
 
1679
1893
  // src/formatters/html-report.ts
1680
1894
  var HTML_TEMPLATE = `<!DOCTYPE html>
@@ -2540,7 +2754,7 @@ ${details}`);
2540
2754
  log(chalk5.white(` Time box: ${minutes} min`));
2541
2755
  return { sessionDir };
2542
2756
  }
2543
- for (const sub of ["", "screenshots", "bugs", "videos"]) {
2757
+ for (const sub of ["", "screenshots", "bugs", "videos", "snapshots"]) {
2544
2758
  mkdirSync3(join10(sessionDir, sub), { recursive: true });
2545
2759
  }
2546
2760
  const date = now.toISOString().slice(0, 10);
@@ -2591,9 +2805,13 @@ ${details}`);
2591
2805
 
2592
2806
  // src/cli/commands/kb.ts
2593
2807
  import { Command as Command6 } from "commander";
2594
- import { resolve as resolve8 } from "path";
2595
- import { existsSync as existsSync11 } from "fs";
2808
+ import { resolve as resolve8, join as join11 } from "path";
2809
+ import { existsSync as existsSync11, readFileSync as readFileSync9, readdirSync as readdirSync6 } from "fs";
2596
2810
  import chalk6 from "chalk";
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;
2597
2815
  function kbCommand() {
2598
2816
  const cmd = new Command6("kb").description("Knowledge-base maintenance");
2599
2817
  cmd.command("sync").description("Regenerate data/knowledge/manifest.yml entries and stats from the release files").action(() => {
@@ -2620,6 +2838,14 @@ function kbCommand() {
2620
2838
  process.exit(1);
2621
2839
  }
2622
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) => {
2842
+ try {
2843
+ console.log(runKbDigest(options, process.cwd()));
2844
+ } catch (err) {
2845
+ console.error(chalk6.red("Error:"), err instanceof Error ? err.message : err);
2846
+ process.exit(1);
2847
+ }
2848
+ });
2623
2849
  return cmd;
2624
2850
  }
2625
2851
  function runKb(mode, cwd) {
@@ -2629,13 +2855,620 @@ function runKb(mode, cwd) {
2629
2855
  }
2630
2856
  return syncKnowledgeManifest(dataDir, { check: mode === "check" });
2631
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
+ );
2903
+ }
2904
+ skillAdded = add(bySkill[options.for]);
2905
+ }
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
+ );
2911
+ }
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
+ );
2936
+ }
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");
3181
+ } else {
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
+ }
3203
+ }
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 };
3281
+ }
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
+ }
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));
3463
+ }
2632
3464
 
2633
3465
  // src/cli/index.ts
2634
- var program = new Command7().name("qualiow").description("qualiow \u2014 AI-powered exploratory testing (web, mobile, backend)").version(getPackageVersion());
3466
+ var program = new Command8().name("qualiow").description("qualiow \u2014 AI-powered exploratory testing (web, mobile, backend)").version(getPackageVersion());
2635
3467
  program.addCommand(initCommand());
2636
3468
  program.addCommand(validateCommand());
2637
3469
  program.addCommand(listCommand());
2638
3470
  program.addCommand(reportCommand());
2639
3471
  program.addCommand(exploreCommand());
2640
3472
  program.addCommand(kbCommand());
3473
+ program.addCommand(sessionCommand());
2641
3474
  program.parse();