qualiow-exploratory-testing 2.0.0 → 2.2.1

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 +83 -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 +49 -0
  10. package/data/knowledge/manifest.yml +22 -0
  11. package/dist/cli/index.js +1111 -62
  12. package/dist/index.d.ts +91 -2
  13. package/dist/index.js +532 -48
  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(
@@ -106,6 +119,22 @@ var ALL_BUGS_MD_HEADER = table(
106
119
  "_Consolidated index across all exploratory testing sessions._",
107
120
  ALL_BUGS_COLUMNS
108
121
  );
122
+ function keysOf(columns) {
123
+ return columns.map((c) => c.trim().toLowerCase());
124
+ }
125
+ function headersMatchColumns(headers, columns) {
126
+ const a = keysOf(headers);
127
+ const b = keysOf(columns);
128
+ return a.length === b.length && a.every((h, i) => h === b[i]);
129
+ }
130
+ function missingColumns(headers, columns) {
131
+ const present = new Set(keysOf(headers));
132
+ return columns.filter((c) => !present.has(c.trim().toLowerCase()));
133
+ }
134
+ function buildTableRow(headers, values) {
135
+ const cells = keysOf(headers).map((key) => values[key] ?? "");
136
+ return `| ${cells.join(" | ")} |`;
137
+ }
109
138
 
110
139
  // src/utils/gitignore.ts
111
140
  var QUALIOW_GITIGNORE_HEADER = "# Qualiow";
@@ -139,9 +168,71 @@ function mergeGitignore(existing) {
139
168
  return existing + prefix + leadingBlank + block.join("\n") + "\n";
140
169
  }
141
170
 
171
+ // src/utils/settings-merge.ts
172
+ var QUALIOW_HOOK_ENTRIES = [
173
+ { matcher: "Read", command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/read-guard.mjs"' },
174
+ {
175
+ matcher: "Write|Edit|MultiEdit",
176
+ command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/write-guard.mjs"'
177
+ }
178
+ ];
179
+ var QUALIOW_PERMISSION_ALLOW = [
180
+ "Bash(playwright-cli:*)",
181
+ "Bash(npx playwright-cli:*)",
182
+ "Bash(qualiow:*)"
183
+ ];
184
+ function isRecord(v) {
185
+ return typeof v === "object" && v !== null && !Array.isArray(v);
186
+ }
187
+ function existingHookCommands(settings) {
188
+ const commands = /* @__PURE__ */ new Set();
189
+ const hooks = settings.hooks;
190
+ if (!isRecord(hooks)) return commands;
191
+ const preToolUse = hooks.PreToolUse;
192
+ if (!Array.isArray(preToolUse)) return commands;
193
+ for (const entry of preToolUse) {
194
+ if (!isRecord(entry) || !Array.isArray(entry.hooks)) continue;
195
+ for (const h of entry.hooks) {
196
+ if (isRecord(h) && typeof h.command === "string") commands.add(h.command);
197
+ }
198
+ }
199
+ return commands;
200
+ }
201
+ function mergeQualiowHookSettings(existing) {
202
+ const settings = isRecord(existing) ? { ...existing } : {};
203
+ let changed = false;
204
+ const hooksSection = isRecord(settings.hooks) ? { ...settings.hooks } : {};
205
+ const preToolUse = Array.isArray(hooksSection.PreToolUse) ? [...hooksSection.PreToolUse] : [];
206
+ const haveCommands = existingHookCommands(settings);
207
+ for (const { matcher, command } of QUALIOW_HOOK_ENTRIES) {
208
+ if (haveCommands.has(command)) continue;
209
+ preToolUse.push({ matcher, hooks: [{ type: "command", command }] });
210
+ haveCommands.add(command);
211
+ changed = true;
212
+ }
213
+ hooksSection.PreToolUse = preToolUse;
214
+ settings.hooks = hooksSection;
215
+ const permissions = isRecord(settings.permissions) ? { ...settings.permissions } : {};
216
+ const allow = Array.isArray(permissions.allow) ? [...permissions.allow] : [];
217
+ const allowSet = new Set(allow.filter((a) => typeof a === "string"));
218
+ for (const rule of QUALIOW_PERMISSION_ALLOW) {
219
+ if (allowSet.has(rule)) continue;
220
+ allow.push(rule);
221
+ allowSet.add(rule);
222
+ changed = true;
223
+ }
224
+ permissions.allow = allow;
225
+ settings.permissions = permissions;
226
+ return { settings, changed };
227
+ }
228
+
142
229
  // src/cli/commands/init.ts
143
230
  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) => {
231
+ 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(
232
+ "--hooks",
233
+ "Install the PreToolUse guard hooks into qa/hooks/ and wire them into .claude/settings.json",
234
+ false
235
+ ).action(async (options) => {
145
236
  try {
146
237
  await runInit(options, { cwd: process.cwd() });
147
238
  } catch (err) {
@@ -218,14 +309,14 @@ async function runInit(options, ctx) {
218
309
  filter: (rel2) => rel2.startsWith("qa-")
219
310
  })
220
311
  );
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) {
312
+ const agentsCandidates = [join2(pkgRoot, "agents"), join2(pkgRoot, ".claude", "agents")];
313
+ const agentsSrc = agentsCandidates.find((p) => existsSync2(p));
314
+ if (agentsSrc) {
227
315
  copies.push(
228
- copyEntry(agentSrc, join2(cwd, ".claude", "agents", "qa-gather-agent.md"), copyOpts)
316
+ ...copyTree(agentsSrc, join2(cwd, ".claude", "agents"), {
317
+ ...copyOpts,
318
+ filter: (rel2) => rel2.endsWith(".md")
319
+ })
229
320
  );
230
321
  }
231
322
  const dataSrc = join2(pkgRoot, "data");
@@ -251,7 +342,12 @@ async function runInit(options, ctx) {
251
342
  })
252
343
  );
253
344
  const binSrc = join2(pkgRoot, "bin");
254
- copies.push(...copyTree(binSrc, join2(cwd, "qa", "bin"), copyOpts));
345
+ copies.push(
346
+ ...copyTree(binSrc, join2(cwd, "qa", "bin"), {
347
+ ...copyOpts,
348
+ filter: (rel2) => rel2 !== "qualiow"
349
+ })
350
+ );
255
351
  if (existsSync2(binSrc)) {
256
352
  const versionPath = join2(cwd, "qa", "bin", "VERSION");
257
353
  const version = `${getPackageVersion(pkgRoot)}
@@ -270,6 +366,32 @@ async function runInit(options, ctx) {
270
366
  copies.push(copyEntry(envExampleSrc, join2(cwd, "qa", ".env.example"), copyOpts));
271
367
  }
272
368
  }
369
+ let hooksSettingsChanged = false;
370
+ if (options.hooks) {
371
+ const hooksScriptsSrc = join2(pkgRoot, "hooks", "scripts");
372
+ copies.push(
373
+ ...copyTree(hooksScriptsSrc, join2(cwd, "qa", "hooks"), {
374
+ ...copyOpts,
375
+ filter: (rel2) => rel2.endsWith(".mjs")
376
+ })
377
+ );
378
+ const settingsPath = join2(cwd, ".claude", "settings.json");
379
+ const settingsExisted = existsSync2(settingsPath);
380
+ let existingSettings;
381
+ if (settingsExisted) {
382
+ try {
383
+ existingSettings = JSON.parse(readFileSync2(settingsPath, "utf-8"));
384
+ } catch {
385
+ existingSettings = void 0;
386
+ }
387
+ }
388
+ const { settings, changed } = mergeQualiowHookSettings(existingSettings);
389
+ hooksSettingsChanged = changed || !settingsExisted;
390
+ if (!options.dryRun) {
391
+ mkdirSync(dirname2(settingsPath), { recursive: true });
392
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
393
+ }
394
+ }
273
395
  for (const dir of ["output/sessions", "output/bugs", "output/context", ".auth", "qa"]) {
274
396
  const full = join2(cwd, dir);
275
397
  if (!existsSync2(full)) {
@@ -313,12 +435,20 @@ async function runInit(options, ctx) {
313
435
  log(
314
436
  gitignoreUpdated ? chalk.green(" \u2713 Updated .gitignore (Qualiow block)") : chalk.cyan(" \u25CB .gitignore already up to date")
315
437
  );
438
+ if (options.hooks) {
439
+ log(
440
+ hooksSettingsChanged ? chalk.green(" \u2713 Wired hooks into .claude/settings.json") : chalk.cyan(" \u25CB .claude/settings.json hooks already up to date")
441
+ );
442
+ }
316
443
  log("");
317
444
  log(chalk.cyan.bold(options.dryRun ? "Dry run complete." : "Qualiow initialized."));
318
445
  log("");
319
446
  log(chalk.white("Next steps:"));
320
447
  log(chalk.white(" 1. npx playwright-cli install --skills # official Playwright skill, next to qualiow"));
321
448
  log(chalk.white(" 2. cp qa/.env.example qa/.env # credentials by env var name only"));
449
+ if (options.hooks) {
450
+ log(chalk.white(' QUALIOW_HOOKS=off or QUALIOW_READ_MAX_LINES=<n> under "env" in .claude/settings.json tune the guards'));
451
+ }
322
452
  log(chalk.white(" 3. /qa-target-setup or /qa-explore https://your-app.com"));
323
453
  log(chalk.white(" 4. mobile: qa/bin/doctor-mobile.sh # then /qa-explore-mobile --target <id>"));
324
454
  log("");
@@ -596,7 +726,10 @@ var KnowledgeManifestEntrySchema = z4.object({
596
726
  var LoadingStrategySchema = z4.object({
597
727
  always: z4.array(z4.string()),
598
728
  by_domain: z4.record(z4.string(), z4.array(z4.string())),
599
- by_tag: z4.record(z4.string(), z4.array(z4.string()))
729
+ by_tag: z4.record(z4.string(), z4.array(z4.string())),
730
+ /** Per-skill selection used by `qualiow kb digest --for <skill>`. Optional so
731
+ * a manifest written before this key still validates. */
732
+ by_skill: z4.record(z4.string(), z4.array(z4.string())).optional()
600
733
  });
601
734
  var KnowledgeManifestSchema = z4.object({
602
735
  version: z4.string().min(1),
@@ -860,7 +993,8 @@ function validateKnowledgeBase(dataDir) {
860
993
  const allRefs = [
861
994
  ...ls.always,
862
995
  ...Object.values(ls.by_domain).flat(),
863
- ...Object.values(ls.by_tag).flat()
996
+ ...Object.values(ls.by_tag).flat(),
997
+ ...Object.values(ls.by_skill ?? {}).flat()
864
998
  ];
865
999
  for (const id of allRefs) {
866
1000
  if (!registryIds.has(id)) {
@@ -1033,6 +1167,7 @@ function parseMarkdownTable(md, opts = {}) {
1033
1167
 
1034
1168
  // src/utils/session-dir.ts
1035
1169
  var SESSION_DIR_RE = /^(\d{4}-\d{2}-\d{2}-\d{4})-(explore|quick|mobile|backend)-([a-z0-9][a-z0-9-]*)$/;
1170
+ var LEGACY_SESSION_DIR_RE = /^\d{4}-\d{2}-\d{2}(?:-\d{4})?-.+/;
1036
1171
  function slugify(input) {
1037
1172
  let s = (input ?? "").trim();
1038
1173
  try {
@@ -1058,12 +1193,23 @@ function parseSessionDirName(name) {
1058
1193
  if (!m) return null;
1059
1194
  return { timestamp: m[1], kind: m[2], slug: m[3] };
1060
1195
  }
1196
+ var DATE_PREFIX_RE = /^(\d{4})-(\d{2})-(\d{2})(?:-(\d{2})(\d{2}))?(?=-|$)/;
1197
+ function describeSessionDir(name) {
1198
+ const parsed = parseSessionDirName(name);
1199
+ const legacy = !parsed;
1200
+ if (!parsed && !LEGACY_SESSION_DIR_RE.test(name)) return null;
1201
+ const m = DATE_PREFIX_RE.exec(name);
1202
+ if (!m) return null;
1203
+ const [, y, mo, d, h, mi] = m;
1204
+ const timestamp = new Date(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0));
1205
+ return { name, timestamp, legacy };
1206
+ }
1061
1207
 
1062
1208
  // src/cli/commands/list.ts
1063
1209
  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) => {
1210
+ 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
1211
  try {
1066
- await runList(type, process.cwd());
1212
+ await runList(type, process.cwd(), options);
1067
1213
  } catch (err) {
1068
1214
  console.error(chalk3.red("Error:"), err instanceof Error ? err.message : err);
1069
1215
  process.exit(1);
@@ -1071,13 +1217,13 @@ function listCommand() {
1071
1217
  });
1072
1218
  return cmd;
1073
1219
  }
1074
- async function runList(type, cwd) {
1220
+ async function runList(type, cwd, options = {}, log = (line) => console.log(line)) {
1075
1221
  switch (type) {
1076
1222
  case "sessions":
1077
- listSessions(cwd);
1223
+ listSessions(cwd, log);
1078
1224
  break;
1079
1225
  case "knowledge":
1080
- listKnowledge(cwd);
1226
+ listKnowledge(cwd, options, log);
1081
1227
  break;
1082
1228
  case "targets":
1083
1229
  listTargets(cwd);
@@ -1109,74 +1255,168 @@ function readSessionIndex(indexPath) {
1109
1255
  }
1110
1256
  return rows;
1111
1257
  }
1112
- function listSessions(cwd) {
1258
+ function reportDirName(report) {
1259
+ const link = /\]\(([^)]+)\)/.exec(report);
1260
+ const path = (link ? link[1] : report).trim();
1261
+ return basename4(path.replace(/\/session-report\.md$/, ""));
1262
+ }
1263
+ function listSessions(cwd, log) {
1113
1264
  const sessionsDir = resolve5(cwd, "output", "sessions");
1114
1265
  const indexPath = join6(sessionsDir, "INDEX.md");
1115
1266
  if (!existsSync6(sessionsDir)) {
1116
- console.log(chalk3.yellow("No sessions directory. Run `npx qualiow init` first, then start a session."));
1267
+ log(chalk3.yellow("No sessions directory. Run `npx qualiow init` first, then start a session."));
1117
1268
  return;
1118
1269
  }
1119
1270
  const rows = readSessionIndex(indexPath);
1120
- const indexedDirs = new Set(rows.map((r) => basename4(r.report.replace(/\/session-report\.md$/, ""))));
1121
- 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();
1122
- console.log(chalk3.cyan.bold("\nSessions:"));
1123
- console.log("");
1271
+ const indexedDirs = new Set(rows.map((r) => reportDirName(r.report)));
1272
+ const unindexed = readdirSync3(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => describeSessionDir(d.name)).filter((d) => d !== null && !indexedDirs.has(d.name)).sort((a, b) => a.name.localeCompare(b.name));
1273
+ log(chalk3.cyan.bold("\nSessions:"));
1274
+ log("");
1124
1275
  if (rows.length === 0 && unindexed.length === 0) {
1125
- console.log(chalk3.yellow(" No sessions recorded yet."));
1126
- console.log(chalk3.white(" Start one with: /qa-explore <url>"));
1127
- console.log("");
1276
+ log(chalk3.yellow(" No sessions recorded yet."));
1277
+ log(chalk3.white(" Start one with: /qa-explore <url>"));
1278
+ log("");
1128
1279
  return;
1129
1280
  }
1130
- const widths = [16, 8, 22, 5, 9, 12];
1281
+ const widths = [16, 8, 22, 5, 9, 18];
1131
1282
  const header = INDEX_COLUMNS.map((c, i) => i < widths.length ? pad2(c, widths[i]) : c).join(" ");
1132
- console.log(chalk3.bold(` ${header}`));
1133
- console.log(` ${widths.map((w) => "\u2500".repeat(w)).join(" ")} ${"\u2500".repeat(30)}`);
1283
+ log(chalk3.bold(` ${header}`));
1284
+ log(` ${widths.map((w) => "\u2500".repeat(w)).join(" ")} ${"\u2500".repeat(30)}`);
1134
1285
  for (const r of rows) {
1135
- console.log(
1136
- ` ${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}`
1286
+ log(
1287
+ ` ${pad2(r.date, 16)} ${pad2(r.kind, 8)} ${pad2(r.target, 22)} ${pad2(r.bugs, 5)} ${pad2(r.duration, 9)} ${pad2(r.status, 18)} ${r.report}`
1137
1288
  );
1138
1289
  }
1139
1290
  for (const d of unindexed) {
1140
- console.log(chalk3.gray(` ${pad2(d.slice(0, 15), 16)} ${pad2("", 8)} ${pad2("", 22)} ${pad2("", 5)} ${pad2("", 9)} ${pad2("unindexed", 12)} ${d}`));
1291
+ const status = d.legacy ? "unindexed (legacy)" : "unindexed";
1292
+ log(chalk3.gray(` ${pad2(d.name.slice(0, 15), 16)} ${pad2("", 8)} ${pad2("", 22)} ${pad2("", 5)} ${pad2("", 9)} ${pad2(status, 18)} ${d.name}`));
1141
1293
  }
1142
- console.log("");
1143
- console.log(chalk3.white(` Total: ${rows.length} session(s)` + (unindexed.length ? chalk3.gray(` (+${unindexed.length} unindexed)`) : "")));
1144
- console.log("");
1294
+ log("");
1295
+ log(chalk3.white(` Total: ${rows.length} session(s)` + (unindexed.length ? chalk3.gray(` (+${unindexed.length} unindexed)`) : "")));
1296
+ log("");
1145
1297
  }
1146
- function listKnowledge(cwd) {
1147
- const knowledgeDir = resolve5(cwd, "data", "knowledge");
1298
+ function listKnowledge(cwd, options, log) {
1299
+ const dataDir = resolveDataDir(cwd, options.data);
1300
+ const knowledgeDir = join6(dataDir, "knowledge");
1148
1301
  const manifestPath = join6(knowledgeDir, "manifest.yml");
1149
1302
  if (!existsSync6(manifestPath)) {
1150
- console.log(chalk3.yellow("No knowledge base found. Run `npx qualiow init` first."));
1303
+ log(chalk3.yellow(`No knowledge base at ${manifestPath}. Run \`npx qualiow init\` first.`));
1304
+ return;
1305
+ }
1306
+ const manifest = KnowledgeManifestSchema.parse(
1307
+ parseYaml3(readFileSync5(manifestPath, "utf-8"))
1308
+ );
1309
+ if (options.entry) {
1310
+ log(readEntryFile(knowledgeDir, manifest.entries, options.entry));
1311
+ return;
1312
+ }
1313
+ if (options.changelog) {
1314
+ printKnowledgeChangelog(knowledgeDir, log);
1315
+ return;
1316
+ }
1317
+ if (options.stats) {
1318
+ printKnowledgeStats(manifest, log);
1151
1319
  return;
1152
1320
  }
1153
- const manifest = parseYaml3(readFileSync5(manifestPath, "utf-8"));
1154
1321
  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}`));
1322
+ log(chalk3.cyan.bold("\nKnowledge Base:"));
1323
+ log(chalk3.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
1157
1324
  if (filesOnDisk !== manifest.entries.length || manifest.stats.total_entries !== filesOnDisk) {
1158
- console.log(
1325
+ log(
1159
1326
  chalk3.yellow(
1160
1327
  ` \u26A0 Registry (${manifest.entries.length}) / stats (${manifest.stats.total_entries}) disagree with ${filesOnDisk} entry files \u2014 run: npx qualiow kb sync`
1161
1328
  )
1162
1329
  );
1163
1330
  }
1164
- console.log("");
1331
+ const filters = [];
1332
+ if (options.domain) filters.push(`domain ${options.domain}`);
1333
+ if (options.tag) filters.push(`tag ${options.tag}`);
1334
+ if (options.type) filters.push(`type ${options.type}`);
1335
+ const entries = manifest.entries.filter(
1336
+ (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)
1337
+ );
1338
+ if (filters.length) {
1339
+ log(chalk3.white(` Filter: ${filters.join(", ")} \u2192 ${entries.length} entries`));
1340
+ }
1341
+ log("");
1342
+ if (entries.length === 0) {
1343
+ log(chalk3.yellow(" No entries match that filter."));
1344
+ log("");
1345
+ return;
1346
+ }
1165
1347
  const grouped = /* @__PURE__ */ new Map();
1166
- for (const entry of manifest.entries) {
1348
+ for (const entry of entries) {
1167
1349
  const list = grouped.get(entry.type) ?? [];
1168
1350
  list.push(entry);
1169
1351
  grouped.set(entry.type, list);
1170
1352
  }
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) {
1353
+ for (const [type, group] of grouped) {
1354
+ log(chalk3.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${group.length}):`));
1355
+ for (const entry of group) {
1174
1356
  const priorityColor = entry.priority === "high" ? chalk3.red : entry.priority === "medium" ? chalk3.yellow : chalk3.white;
1175
1357
  const tags = entry.tags.map((t) => chalk3.gray(t)).join(", ");
1176
- console.log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk3.gray("tags:")} ${tags}`);
1358
+ log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk3.gray("tags:")} ${tags}`);
1177
1359
  }
1178
- console.log("");
1360
+ log("");
1361
+ }
1362
+ }
1363
+ function readEntryFile(knowledgeDir, entries, id) {
1364
+ const meta = entries.find((e) => e.id === id);
1365
+ const path = meta ? join6(knowledgeDir, meta.file) : join6(knowledgeDir, "custom", `${id}.yml`);
1366
+ if (!existsSync6(path)) {
1367
+ throw new Error(`Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`);
1179
1368
  }
1369
+ return readFileSync5(path, "utf-8").trimEnd();
1370
+ }
1371
+ function printKnowledgeChangelog(knowledgeDir, log) {
1372
+ const changelogPath = join6(knowledgeDir, "changelog.yml");
1373
+ if (!existsSync6(changelogPath)) {
1374
+ log(chalk3.yellow(`No changelog at ${changelogPath}.`));
1375
+ return;
1376
+ }
1377
+ const changelog = KnowledgeChangelogSchema.parse(
1378
+ parseYaml3(readFileSync5(changelogPath, "utf-8"))
1379
+ );
1380
+ log(chalk3.cyan.bold("\nKnowledge Base Changelog:"));
1381
+ log("");
1382
+ for (const release of changelog.releases) {
1383
+ log(` ${chalk3.bold(`v${release.version}`)} ${chalk3.gray(`\xB7 ${release.date}`)}`);
1384
+ log(` ${release.summary}`);
1385
+ const added = release.entries_added.map((e) => e.id);
1386
+ if (added.length) log(` ${chalk3.gray("added:")} ${added.join(", ")}`);
1387
+ if (release.entries_modified.length) {
1388
+ log(` ${chalk3.gray("modified:")} ${release.entries_modified.join(", ")}`);
1389
+ }
1390
+ if (release.entries_removed.length) {
1391
+ log(` ${chalk3.gray("removed:")} ${release.entries_removed.join(", ")}`);
1392
+ }
1393
+ log("");
1394
+ }
1395
+ }
1396
+ function printKnowledgeStats(manifest, log) {
1397
+ log(chalk3.cyan.bold("\nKnowledge Base Stats:"));
1398
+ log(chalk3.white(` Version: ${manifest.version}`));
1399
+ log("");
1400
+ for (const [key, value] of Object.entries(manifest.stats)) {
1401
+ log(` ${pad2(key.replace(/_/g, " "), 18)} ${value}`);
1402
+ }
1403
+ log("");
1404
+ log(chalk3.cyan(` Active releases (${manifest.active_releases.length}):`));
1405
+ log(` ${manifest.active_releases.join(", ")}`);
1406
+ log("");
1407
+ const ls = manifest.loading_strategy;
1408
+ log(chalk3.cyan(" Loading strategy:"));
1409
+ log(` ${pad2("always", 12)} ${ls.always.length} entries`);
1410
+ for (const [bucket, map] of [
1411
+ ["by_domain", ls.by_domain],
1412
+ ["by_tag", ls.by_tag],
1413
+ ["by_skill", ls.by_skill ?? {}]
1414
+ ]) {
1415
+ const keys = Object.keys(map);
1416
+ const total = Object.values(map).reduce((n, ids) => n + ids.length, 0);
1417
+ log(` ${pad2(bucket, 12)} ${keys.length} keys, ${total} references`);
1418
+ }
1419
+ log("");
1180
1420
  }
1181
1421
  function listTargets(cwd) {
1182
1422
  const targetsDir = resolve5(cwd, "data", "targets");
@@ -1488,12 +1728,12 @@ var RULES = [
1488
1728
  {
1489
1729
  name: "Authorization header",
1490
1730
  pattern: /(authorization)(\s*[:=]\s*)(\S[^\n\r]*)/gi,
1491
- replace: (m, k, sep, value) => /_REDACTED\]/.test(value) ? m : `${k}${sep}[REDACTED]`
1731
+ replace: (m, k, sep2, value) => /_REDACTED\]/.test(value) ? m : `${k}${sep2}[REDACTED]`
1492
1732
  },
1493
1733
  {
1494
1734
  name: "Cookie header",
1495
1735
  pattern: /^(set-cookie|cookie)(\s*:\s*).+$/gim,
1496
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1736
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1497
1737
  },
1498
1738
  {
1499
1739
  name: "AWS access key id",
@@ -1503,7 +1743,7 @@ var RULES = [
1503
1743
  {
1504
1744
  name: "AWS secret access key",
1505
1745
  pattern: /(aws_secret_access_key)(\s*[:=]\s*)\S+/gi,
1506
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1746
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1507
1747
  },
1508
1748
  {
1509
1749
  name: "OpenAI-style key",
@@ -1523,22 +1763,22 @@ var RULES = [
1523
1763
  {
1524
1764
  name: "API key",
1525
1765
  pattern: /(x-api-key|api[_-]?key)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
1526
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1766
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1527
1767
  },
1528
1768
  {
1529
1769
  name: "Password",
1530
1770
  pattern: /(password|passwd|pwd)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
1531
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1771
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1532
1772
  },
1533
1773
  {
1534
1774
  name: "Token",
1535
1775
  pattern: /(access[_-]?token|refresh[_-]?token|token)(\s*[:=]\s*)["']?[A-Za-z0-9._-]{8,}["']?/gi,
1536
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1776
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1537
1777
  },
1538
1778
  {
1539
1779
  name: "Secret",
1540
1780
  pattern: /([a-z_]*secret)(\s*[:=]\s*)["']?[^\s,}"']+["']?/gi,
1541
- replace: (_m, k, sep) => `${k}${sep}[REDACTED]`
1781
+ replace: (_m, k, sep2) => `${k}${sep2}[REDACTED]`
1542
1782
  },
1543
1783
  {
1544
1784
  name: "SSN",
@@ -1581,6 +1821,9 @@ function redact(text, opts = {}) {
1581
1821
  }
1582
1822
  return { text: result, redactions: [...redactions] };
1583
1823
  }
1824
+ function containsSecrets(text) {
1825
+ return redact(text).redactions.length > 0;
1826
+ }
1584
1827
  var REDACTION_CATEGORIES = RULES.map((r) => r.name).concat("Email");
1585
1828
 
1586
1829
  // src/formatters/common.ts
@@ -1675,6 +1918,11 @@ var CONFIDENTIALITY_HEADER_MD = CONFIDENTIALITY_LINES.map(
1675
1918
  (l) => `> ${l}`
1676
1919
  ).join("\n");
1677
1920
  var CONFIDENTIALITY_NOTICE = CONFIDENTIALITY_LINES.join(" ");
1921
+ function hasConfidentialityHeader(text) {
1922
+ return /CONFIDENTIAL:\s*This report may contain internal URLs/i.test(
1923
+ text.slice(0, 400)
1924
+ );
1925
+ }
1678
1926
 
1679
1927
  // src/formatters/html-report.ts
1680
1928
  var HTML_TEMPLATE = `<!DOCTYPE html>
@@ -2540,7 +2788,7 @@ ${details}`);
2540
2788
  log(chalk5.white(` Time box: ${minutes} min`));
2541
2789
  return { sessionDir };
2542
2790
  }
2543
- for (const sub of ["", "screenshots", "bugs", "videos"]) {
2791
+ for (const sub of ["", "screenshots", "bugs", "videos", "snapshots"]) {
2544
2792
  mkdirSync3(join10(sessionDir, sub), { recursive: true });
2545
2793
  }
2546
2794
  const date = now.toISOString().slice(0, 10);
@@ -2591,9 +2839,13 @@ ${details}`);
2591
2839
 
2592
2840
  // src/cli/commands/kb.ts
2593
2841
  import { Command as Command6 } from "commander";
2594
- import { resolve as resolve8 } from "path";
2595
- import { existsSync as existsSync11 } from "fs";
2842
+ import { resolve as resolve8, join as join11 } from "path";
2843
+ import { existsSync as existsSync11, readFileSync as readFileSync9, readdirSync as readdirSync6 } from "fs";
2596
2844
  import chalk6 from "chalk";
2845
+ import { parse as parseYaml4 } from "yaml";
2846
+ var DEFAULT_MAX_LINES = 12;
2847
+ var WRAP_COLUMN = 100;
2848
+ var WHEN_TO_USE_ITEMS = 3;
2597
2849
  function kbCommand() {
2598
2850
  const cmd = new Command6("kb").description("Knowledge-base maintenance");
2599
2851
  cmd.command("sync").description("Regenerate data/knowledge/manifest.yml entries and stats from the release files").action(() => {
@@ -2620,6 +2872,14 @@ function kbCommand() {
2620
2872
  process.exit(1);
2621
2873
  }
2622
2874
  });
2875
+ 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) => {
2876
+ try {
2877
+ console.log(runKbDigest(options, process.cwd()));
2878
+ } catch (err) {
2879
+ console.error(chalk6.red("Error:"), err instanceof Error ? err.message : err);
2880
+ process.exit(1);
2881
+ }
2882
+ });
2623
2883
  return cmd;
2624
2884
  }
2625
2885
  function runKb(mode, cwd) {
@@ -2629,13 +2889,802 @@ function runKb(mode, cwd) {
2629
2889
  }
2630
2890
  return syncKnowledgeManifest(dataDir, { check: mode === "check" });
2631
2891
  }
2892
+ function runKbDigest(options, cwd) {
2893
+ const dataDir = resolveDataDir(cwd, options.data);
2894
+ const knowledgeDir = join11(dataDir, "knowledge");
2895
+ const manifestPath = join11(knowledgeDir, "manifest.yml");
2896
+ if (!existsSync11(manifestPath)) {
2897
+ throw new Error(
2898
+ `No knowledge manifest at ${manifestPath}. Pass --data <dir>, or run \`npx qualiow init\` first.`
2899
+ );
2900
+ }
2901
+ const manifest = KnowledgeManifestSchema.parse(
2902
+ parseYaml4(readFileSync9(manifestPath, "utf-8"))
2903
+ );
2904
+ const byId = new Map(manifest.entries.map((e) => [e.id, e]));
2905
+ const maxLines = Math.max(1, options.maxLines ?? DEFAULT_MAX_LINES);
2906
+ if (options.entry) {
2907
+ return readWholeEntry(knowledgeDir, byId, options.entry);
2908
+ }
2909
+ const ls = manifest.loading_strategy;
2910
+ const selected = [];
2911
+ const add = (ids) => {
2912
+ let added = 0;
2913
+ for (const id of ids ?? []) {
2914
+ if (selected.includes(id)) continue;
2915
+ selected.push(id);
2916
+ added++;
2917
+ }
2918
+ return added;
2919
+ };
2920
+ add(ls.always);
2921
+ const domainAdded = options.domain ? add(ls.by_domain[options.domain]) : 0;
2922
+ const tags = options.tag ?? [];
2923
+ let tagAdded = 0;
2924
+ for (const tag of tags) tagAdded += add(ls.by_tag[tag]);
2925
+ let skillAdded = 0;
2926
+ if (options.for) {
2927
+ const bySkill = ls.by_skill;
2928
+ if (!bySkill) {
2929
+ throw new Error(
2930
+ "This manifest has no loading_strategy.by_skill, so --for has nothing to select."
2931
+ );
2932
+ }
2933
+ if (!Object.prototype.hasOwnProperty.call(bySkill, options.for)) {
2934
+ throw new Error(
2935
+ `Unknown skill "${options.for}". Known: ${Object.keys(bySkill).sort().join(", ")}.`
2936
+ );
2937
+ }
2938
+ skillAdded = add(bySkill[options.for]);
2939
+ }
2940
+ const unknown = selected.filter((id) => !byId.has(id));
2941
+ if (unknown.length) {
2942
+ throw new Error(
2943
+ `loading_strategy references ${unknown.length} unknown entry id(s): ${unknown.join(", ")}. Run \`qualiow kb sync\` and \`qualiow validate --kb\`.`
2944
+ );
2945
+ }
2946
+ const header = [
2947
+ `# Knowledge digest v${manifest.version}`,
2948
+ `${selected.length} entries`,
2949
+ `always ${ls.always.length}`
2950
+ ];
2951
+ if (options.domain) header.push(`domain ${options.domain} +${domainAdded}`);
2952
+ if (tags.length) header.push(`tags ${tags.join(", ")} +${tagAdded}`);
2953
+ if (options.for) header.push(`skill ${options.for} +${skillAdded}`);
2954
+ const lines = [header.join(" \xB7 ")];
2955
+ for (const id of selected) {
2956
+ const meta = byId.get(id);
2957
+ lines.push(...entryBlock(join11(knowledgeDir, meta.file), meta, maxLines));
2958
+ }
2959
+ lines.push(...customSection(knowledgeDir, maxLines));
2960
+ lines.push(...learnedPatternsSection(cwd, knowledgeDir));
2961
+ return lines.join("\n");
2962
+ }
2963
+ function readWholeEntry(knowledgeDir, byId, id) {
2964
+ const meta = byId.get(id);
2965
+ const path = meta ? join11(knowledgeDir, meta.file) : join11(knowledgeDir, "custom", `${id}.yml`);
2966
+ if (!existsSync11(path)) {
2967
+ throw new Error(
2968
+ `Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`
2969
+ );
2970
+ }
2971
+ return readFileSync9(path, "utf-8").trimEnd();
2972
+ }
2973
+ function entryBlock(file, meta, maxLines, custom = false) {
2974
+ if (!existsSync11(file)) {
2975
+ throw new Error(`Entry "${meta.id}" is registered but its file is missing: ${file}`);
2976
+ }
2977
+ const entry = KnowledgeEntrySchema.parse(parseYaml4(readFileSync9(file, "utf-8")));
2978
+ const content = entry.content;
2979
+ const marker = custom ? " [custom]" : "";
2980
+ const out = [
2981
+ `- ${meta.id} [${meta.type}/${meta.priority}]${marker} tags: ${meta.tags.join(", ")}`
2982
+ ];
2983
+ out.push(...wrap(collapse(entry.content.summary)));
2984
+ for (const [key, items] of namedArrays(content)) {
2985
+ const rendered = items.map((item) => {
2986
+ const lead = subItemLead(item);
2987
+ return lead ? `${item.name} \u2014 ${lead}` : item.name;
2988
+ }).join("; ");
2989
+ out.push(...wrap(`${humanise(key)}: ${rendered}`));
2990
+ }
2991
+ const whenToUse = content["when_to_use"];
2992
+ if (Array.isArray(whenToUse) && whenToUse.length) {
2993
+ const items = whenToUse.slice(0, WHEN_TO_USE_ITEMS).filter((v) => typeof v === "string").map(collapse);
2994
+ if (items.length) out.push(...wrap(`when to use: ${items.join("; ")}`));
2995
+ }
2996
+ return capLines(out, maxLines);
2997
+ }
2998
+ function customSection(knowledgeDir, maxLines) {
2999
+ const customDir = join11(knowledgeDir, "custom");
3000
+ if (!existsSync11(customDir)) return [];
3001
+ const files = readdirSync6(customDir).filter((f) => f.endsWith(".yml")).sort();
3002
+ if (!files.length) return [];
3003
+ const lines = ["", "## Custom entries"];
3004
+ for (const file of files) {
3005
+ const path = join11(customDir, file);
3006
+ const parsed = parseYaml4(readFileSync9(path, "utf-8"));
3007
+ lines.push(
3008
+ ...entryBlock(
3009
+ path,
3010
+ {
3011
+ id: parsed.id ?? file.replace(/\.yml$/, ""),
3012
+ type: parsed.type ?? "custom",
3013
+ priority: parsed.priority ?? "medium",
3014
+ tags: parsed.tags ?? []
3015
+ },
3016
+ maxLines,
3017
+ true
3018
+ )
3019
+ );
3020
+ }
3021
+ return lines;
3022
+ }
3023
+ function learnedPatternsSection(cwd, knowledgeDir) {
3024
+ const candidates = [
3025
+ resolve8(cwd, "data", "knowledge", "learned-patterns.md"),
3026
+ join11(knowledgeDir, "learned-patterns.md")
3027
+ ];
3028
+ const path = candidates.find((p) => existsSync11(p));
3029
+ if (!path) return [];
3030
+ const sections = learnedPatternLeadIns(readFileSync9(path, "utf-8"));
3031
+ if (!sections.length) return [];
3032
+ const lines = ["", "## Learned patterns", "Grep the file for the full entry."];
3033
+ for (const section of sections) {
3034
+ lines.push(...wrap(`${section.heading}: ${section.items.join("; ")}`));
3035
+ }
3036
+ return lines;
3037
+ }
3038
+ function learnedPatternLeadIns(markdown) {
3039
+ const sections = [];
3040
+ let current = null;
3041
+ let bullet = null;
3042
+ const flush = () => {
3043
+ if (bullet !== null && current) {
3044
+ const match = /^\*\*([\s\S]+?)\*\*/.exec(bullet);
3045
+ if (match) current.items.push(collapse(match[1]));
3046
+ }
3047
+ bullet = null;
3048
+ };
3049
+ for (const raw of markdown.split("\n")) {
3050
+ const heading = /^#{2,}\s+(.+)$/.exec(raw);
3051
+ if (heading) {
3052
+ flush();
3053
+ current = { heading: heading[1].trim(), items: [] };
3054
+ sections.push(current);
3055
+ continue;
3056
+ }
3057
+ const start = /^[-*]\s+(.*)$/.exec(raw);
3058
+ if (start) {
3059
+ flush();
3060
+ bullet = start[1];
3061
+ continue;
3062
+ }
3063
+ if (bullet !== null) {
3064
+ if (raw.trim() === "") flush();
3065
+ else bullet += ` ${raw.trim()}`;
3066
+ }
3067
+ }
3068
+ flush();
3069
+ return sections.filter((s) => s.items.length > 0);
3070
+ }
3071
+ function namedArrays(content) {
3072
+ const found = [];
3073
+ for (const [key, value] of Object.entries(content)) {
3074
+ if (key === "summary" || key === "when_to_use") continue;
3075
+ if (!Array.isArray(value) || value.length === 0) continue;
3076
+ const items = value.filter(
3077
+ (v) => typeof v === "object" && v !== null && typeof v.name === "string"
3078
+ );
3079
+ if (items.length === value.length) found.push([key, items]);
3080
+ }
3081
+ return found;
3082
+ }
3083
+ function subItemLead(item) {
3084
+ const questions = item["questions"];
3085
+ if (Array.isArray(questions) && typeof questions[0] === "string") {
3086
+ return truncate(collapse(questions[0]));
3087
+ }
3088
+ const description = item["description"];
3089
+ if (typeof description === "string") return truncate(collapse(description));
3090
+ return "";
3091
+ }
3092
+ function collapse(text) {
3093
+ return text.replace(/\s+/g, " ").trim();
3094
+ }
3095
+ function truncate(text, limit = WRAP_COLUMN) {
3096
+ if (text.length <= limit) return text;
3097
+ const cut = text.slice(0, limit - 1);
3098
+ const lastSpace = cut.lastIndexOf(" ");
3099
+ return `${(lastSpace > limit / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
3100
+ }
3101
+ function humanise(key) {
3102
+ const spaced = key.replace(/_/g, " ");
3103
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
3104
+ }
3105
+ function wrap(text, width = WRAP_COLUMN, indent = " ", hanging = " ") {
3106
+ const words = collapse(text).split(" ").filter(Boolean);
3107
+ if (!words.length) return [];
3108
+ const out = [];
3109
+ let line = indent + words[0];
3110
+ for (const word of words.slice(1)) {
3111
+ if (line.length + 1 + word.length > width) {
3112
+ out.push(line);
3113
+ line = hanging + word;
3114
+ } else {
3115
+ line += ` ${word}`;
3116
+ }
3117
+ }
3118
+ out.push(line);
3119
+ return out;
3120
+ }
3121
+ function capLines(lines, maxLines) {
3122
+ if (lines.length <= maxLines) return lines;
3123
+ const kept = lines.slice(0, maxLines);
3124
+ kept[kept.length - 1] = `${kept[kept.length - 1]} \u2026`;
3125
+ return kept;
3126
+ }
3127
+
3128
+ // src/cli/commands/session.ts
3129
+ import { Command as Command7 } from "commander";
3130
+ import { execFileSync } from "child_process";
3131
+ import {
3132
+ appendFileSync as appendFileSync2,
3133
+ existsSync as existsSync12,
3134
+ mkdirSync as mkdirSync4,
3135
+ readFileSync as readFileSync10,
3136
+ readdirSync as readdirSync7,
3137
+ rmSync,
3138
+ statSync as statSync2,
3139
+ writeFileSync as writeFileSync5
3140
+ } from "fs";
3141
+ import { basename as basename7, dirname as dirname4, join as join12, relative as relative6, resolve as resolve9, sep } from "path";
3142
+ import chalk7 from "chalk";
3143
+ var defaultLog = (line) => console.log(line);
3144
+ function sessionCommand() {
3145
+ const cmd = new Command7("session").description(
3146
+ "Manage exploratory testing session output: finalize, list, archive, delete, prune"
3147
+ );
3148
+ cmd.command("finalize").description(
3149
+ "Validate a session (confidentiality header, no secrets, stats.json shape) and append its INDEX.md / all-bugs.md rows"
3150
+ ).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) => {
3151
+ try {
3152
+ const result = await runSessionFinalize(dir, options, { cwd: process.cwd() });
3153
+ if (!result.ok) {
3154
+ console.error(chalk7.red(`
3155
+ ${result.violations.length} violation(s):`));
3156
+ result.violations.forEach((v, i) => console.error(chalk7.red(` ${i + 1}. ${v}`)));
3157
+ console.error("");
3158
+ process.exit(1);
3159
+ }
3160
+ } catch (err) {
3161
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3162
+ process.exit(1);
3163
+ }
3164
+ });
3165
+ cmd.command("list").description("List sessions (same as `qualiow list sessions`)").action(async () => {
3166
+ try {
3167
+ await runList("sessions", process.cwd());
3168
+ } catch (err) {
3169
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3170
+ process.exit(1);
3171
+ }
3172
+ });
3173
+ 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) => {
3174
+ try {
3175
+ runSessionArchive(dir, options, { cwd: process.cwd() });
3176
+ } catch (err) {
3177
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3178
+ process.exit(1);
3179
+ }
3180
+ });
3181
+ 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) => {
3182
+ try {
3183
+ runSessionDelete(dir, options, { cwd: process.cwd() });
3184
+ } catch (err) {
3185
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3186
+ process.exit(1);
3187
+ }
3188
+ });
3189
+ cmd.command("repair-index").description(
3190
+ "Merge an INDEX.md / all-bugs.md table split into blocks by blank lines between its rows (dry run unless --yes)"
3191
+ ).option("--yes", "Rewrite the files instead of a dry run", false).action((options) => {
3192
+ try {
3193
+ runSessionRepairIndex(options, { cwd: process.cwd() });
3194
+ } catch (err) {
3195
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3196
+ process.exit(1);
3197
+ }
3198
+ });
3199
+ 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) => {
3200
+ try {
3201
+ runSessionPrune(options, { cwd: process.cwd() });
3202
+ } catch (err) {
3203
+ console.error(chalk7.red("Error:"), err instanceof Error ? err.message : err);
3204
+ process.exit(1);
3205
+ }
3206
+ });
3207
+ return cmd;
3208
+ }
3209
+ async function runSessionFinalize(dir, options, ctx) {
3210
+ const cwd = ctx.cwd;
3211
+ const log = ctx.log ?? defaultLog;
3212
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3213
+ if (!existsSync12(sessionsDir)) {
3214
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3215
+ }
3216
+ const sessionDir = resolveSessionDir(sessionsDir, dir);
3217
+ const dirName = basename7(sessionDir);
3218
+ const parsedDirName = parseSessionDirName(dirName);
3219
+ const violations = [];
3220
+ const redactedFiles = [];
3221
+ let stats;
3222
+ const statsPath = join12(sessionDir, "stats.json");
3223
+ if (!existsSync12(statsPath)) {
3224
+ violations.push("stats.json is missing");
3225
+ } else {
3226
+ let raw;
3227
+ try {
3228
+ raw = JSON.parse(readFileSync10(statsPath, "utf-8"));
3229
+ } catch (err) {
3230
+ violations.push(`stats.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
3231
+ }
3232
+ if (raw) {
3233
+ const effective = { ...raw };
3234
+ if (effective.kind === void 0 && parsedDirName) {
3235
+ effective.kind = parsedDirName.kind;
3236
+ }
3237
+ const result = SessionMetricsSchema.strict().safeParse(effective);
3238
+ if (!result.success) {
3239
+ for (const issue of result.error.issues) {
3240
+ const path = issue.path.length ? issue.path.join(".") : "(root)";
3241
+ violations.push(`stats.json: ${path} \u2014 ${issue.message}`);
3242
+ }
3243
+ } else {
3244
+ stats = result.data;
3245
+ }
3246
+ }
3247
+ }
3248
+ const allFiles = listFilesRecursive(sessionDir);
3249
+ for (const file of allFiles) {
3250
+ if (!file.toLowerCase().endsWith(".md")) continue;
3251
+ const content = readFileSync10(file, "utf-8");
3252
+ if (!hasConfidentialityHeader(content)) {
3253
+ violations.push(`${relative6(sessionDir, file)} is missing the confidentiality header`);
3254
+ }
3255
+ }
3256
+ const scannedExtRe = /\.(md|json|log|ya?ml)$/i;
3257
+ for (const file of allFiles) {
3258
+ if (!scannedExtRe.test(file)) continue;
3259
+ const rel = relative6(sessionDir, file);
3260
+ if (rel.split(sep).includes("snapshots")) continue;
3261
+ const content = readFileSync10(file, "utf-8");
3262
+ if (!containsSecrets(content)) continue;
3263
+ const { text, redactions } = redact(content);
3264
+ if (options.redact) {
3265
+ writeFileSync5(file, text);
3266
+ redactedFiles.push({ file: rel, categories: redactions });
3267
+ log(chalk7.yellow(` \u26A0 Redacted ${rel}: ${redactions.join(", ")}`));
3268
+ } else {
3269
+ violations.push(`${rel} contains a secret: ${redactions.join(", ")} (run with --redact to fix)`);
3270
+ }
3271
+ }
3272
+ if (violations.length > 0) {
3273
+ return { ok: false, violations, sessionDir, redactedFiles };
3274
+ }
3275
+ if (options.check) {
3276
+ log(chalk7.green(` \u2713 ${dirName} passes finalize checks (--check \u2014 nothing written)`));
3277
+ return { ok: true, violations: [], sessionDir, redactedFiles };
3278
+ }
3279
+ const finalStats = stats;
3280
+ const kind = finalStats.kind ?? parsedDirName?.kind ?? "";
3281
+ const indexPath = join12(sessionsDir, "INDEX.md");
3282
+ ensureFileWithHeader(indexPath, INDEX_MD_HEADER);
3283
+ const bugsOutputDir = resolve9(cwd, "output", "bugs");
3284
+ mkdirSync4(bugsOutputDir, { recursive: true });
3285
+ const allBugsPath = join12(bugsOutputDir, "all-bugs.md");
3286
+ ensureFileWithHeader(allBugsPath, ALL_BUGS_MD_HEADER);
3287
+ const appendIndexRow = tableRowAppender(indexPath, INDEX_COLUMNS, "INDEX.md", log);
3288
+ let indexRowAdded = false;
3289
+ if (!tableRowsText(indexPath).some((t) => t.includes(`${dirName}/`))) {
3290
+ appendIndexRow({
3291
+ date: finalStats.date,
3292
+ kind,
3293
+ target: finalStats.target,
3294
+ bugs: String(finalStats.bugs_found),
3295
+ duration: `${finalStats.duration_min} min`,
3296
+ status: "complete",
3297
+ report: `${dirName}/session-report.md`
3298
+ });
3299
+ indexRowAdded = true;
3300
+ }
3301
+ const parsedSession = await parseSession(sessionDir);
3302
+ const bugs = [...parsedSession.bugs].sort((a, b) => a.id.localeCompare(b.id));
3303
+ const existingBugRows = readAllBugsRows(allBugsPath);
3304
+ const existingBugRowsText = tableRowsText(allBugsPath);
3305
+ const appendBugRow = tableRowAppender(allBugsPath, ALL_BUGS_COLUMNS, "all-bugs.md", log);
3306
+ const bugRowsAdded = [];
3307
+ for (const bug of bugs) {
3308
+ const reportPath = `${dirName}/bugs/${bug.id}.md`;
3309
+ if (existingBugRows.some((r) => r.id === bug.id && r.session === dirName)) continue;
3310
+ if (existingBugRowsText.some((t) => t.includes(reportPath))) continue;
3311
+ const title = bug.component ? `[${bug.component}] ${bug.title}` : bug.title;
3312
+ const severity = bug.severity.charAt(0).toUpperCase() + bug.severity.slice(1);
3313
+ appendBugRow({
3314
+ id: bug.id,
3315
+ session: dirName,
3316
+ title,
3317
+ severity,
3318
+ status: "open",
3319
+ report: reportPath
3320
+ });
3321
+ bugRowsAdded.push(bug.id);
3322
+ }
3323
+ warnSplitTable(indexPath, "INDEX.md", log);
3324
+ warnSplitTable(allBugsPath, "all-bugs.md", log);
3325
+ if (appendSessionMetricsDeduped(resolve9(cwd, "output"), finalStats)) {
3326
+ log(chalk7.green(" \u2713 Metrics appended to output/metrics.jsonl"));
3327
+ }
3328
+ const progressPath = join12(sessionDir, "progress.json");
3329
+ if (existsSync12(progressPath)) {
3330
+ try {
3331
+ const progress = JSON.parse(readFileSync10(progressPath, "utf-8"));
3332
+ progress.status = "complete";
3333
+ writeFileSync5(progressPath, `${JSON.stringify(progress, null, 2)}
3334
+ `);
3335
+ } catch {
3336
+ }
3337
+ }
3338
+ log(chalk7.green(` \u2713 ${dirName} finalized`));
3339
+ if (indexRowAdded) log(chalk7.white(" INDEX.md row appended"));
3340
+ if (bugRowsAdded.length) log(chalk7.white(` all-bugs.md rows appended: ${bugRowsAdded.join(", ")}`));
3341
+ return { ok: true, violations: [], sessionDir, redactedFiles, indexRowAdded, bugRowsAdded };
3342
+ }
3343
+ function ensureFileWithHeader(path, header) {
3344
+ if (existsSync12(path)) return;
3345
+ mkdirSync4(dirname4(path), { recursive: true });
3346
+ writeFileSync5(path, header);
3347
+ }
3348
+ function readTableHeaders(path) {
3349
+ if (!existsSync12(path)) return null;
3350
+ return parseMarkdownTable(readFileSync10(path, "utf-8"))?.headers ?? null;
3351
+ }
3352
+ function isTableLine(line) {
3353
+ return line.trim().startsWith("|");
3354
+ }
3355
+ function isSeparatorLine(line) {
3356
+ const t = line.trim();
3357
+ return t.startsWith("|") && /^[|\s:-]+$/.test(t) && t.includes("--");
3358
+ }
3359
+ function isEmptyRowLine(line) {
3360
+ return /^[|\s]+$/.test(line.trim());
3361
+ }
3362
+ function tableBounds(lines) {
3363
+ let headerIdx = -1;
3364
+ for (let i = 0; i < lines.length - 1; i++) {
3365
+ if (isTableLine(lines[i]) && isSeparatorLine(lines[i + 1])) {
3366
+ headerIdx = i;
3367
+ break;
3368
+ }
3369
+ }
3370
+ if (headerIdx === -1) return { headerIdx, endIdx: lines.length };
3371
+ let endIdx = lines.length;
3372
+ for (let i = headerIdx + 2; i < lines.length; i++) {
3373
+ if (/^#{1,6}\s/.test(lines[i])) {
3374
+ endIdx = i;
3375
+ break;
3376
+ }
3377
+ }
3378
+ return { headerIdx, endIdx };
3379
+ }
3380
+ function tableRowLines(lines) {
3381
+ const { headerIdx, endIdx } = tableBounds(lines);
3382
+ if (headerIdx === -1) return [];
3383
+ const out = [];
3384
+ for (let i = headerIdx + 1; i < endIdx; i++) {
3385
+ const line = lines[i];
3386
+ if (!isTableLine(line) || isSeparatorLine(line) || isEmptyRowLine(line)) continue;
3387
+ out.push({ index: i, text: line });
3388
+ }
3389
+ return out;
3390
+ }
3391
+ function tableRowsText(path) {
3392
+ if (!existsSync12(path)) return [];
3393
+ return tableRowLines(readFileSync10(path, "utf-8").split("\n")).map((r) => r.text);
3394
+ }
3395
+ function tableRowAppender(path, columns, label, log) {
3396
+ let headers;
3397
+ return (values) => {
3398
+ if (!headers) {
3399
+ headers = readTableHeaders(path) ?? [...columns];
3400
+ if (!headersMatchColumns(headers, columns)) {
3401
+ const missing = missingColumns(headers, columns);
3402
+ const detail = missing.length ? `an older column set (no ${missing.join(", ")})` : "a different column set";
3403
+ log(chalk7.yellow(` \u25CB ${label} uses ${detail}; row written in that layout`));
3404
+ }
3405
+ }
3406
+ insertTableRow(path, buildTableRow(headers, values));
3407
+ };
3408
+ }
3409
+ function insertTableRow(path, row) {
3410
+ if (!existsSync12(path)) {
3411
+ appendFileSync2(path, `${row}
3412
+ `);
3413
+ return;
3414
+ }
3415
+ const lines = readFileSync10(path, "utf-8").split("\n");
3416
+ const { headerIdx, endIdx } = tableBounds(lines);
3417
+ let last = -1;
3418
+ for (let i = headerIdx === -1 ? 0 : headerIdx; i < endIdx; i++) {
3419
+ if (isTableLine(lines[i])) last = i;
3420
+ }
3421
+ if (last === -1) {
3422
+ appendFileSync2(path, `${row}
3423
+ `);
3424
+ return;
3425
+ }
3426
+ lines.splice(last + 1, 0, row);
3427
+ writeFileSync5(path, lines.join("\n"));
3428
+ }
3429
+ function nonBlankNeighbour(lines, from, step) {
3430
+ for (let i = from + step; i >= 0 && i < lines.length; i += step) {
3431
+ if (lines[i].trim() !== "") return i;
3432
+ }
3433
+ return -1;
3434
+ }
3435
+ function analyseTable(content) {
3436
+ const lines = content.split("\n");
3437
+ const { headerIdx, endIdx } = tableBounds(lines);
3438
+ if (headerIdx === -1) return { total: 0, visible: 0, blankLines: [] };
3439
+ const blankLines = [];
3440
+ for (let i = headerIdx + 1; i < endIdx; i++) {
3441
+ if (lines[i].trim() !== "") continue;
3442
+ const prev = nonBlankNeighbour(lines, i, -1);
3443
+ const next = nonBlankNeighbour(lines, i, 1);
3444
+ if (prev >= headerIdx && next !== -1 && isTableLine(lines[prev]) && isTableLine(lines[next])) {
3445
+ blankLines.push(i);
3446
+ }
3447
+ }
3448
+ return {
3449
+ total: tableRowLines(lines).length,
3450
+ visible: parseMarkdownTable(content)?.rows.length ?? 0,
3451
+ blankLines
3452
+ };
3453
+ }
3454
+ function warnSplitTable(path, label, log) {
3455
+ if (!existsSync12(path)) return;
3456
+ const report = analyseTable(readFileSync10(path, "utf-8"));
3457
+ const hidden = report.total - report.visible;
3458
+ if (hidden <= 0) return;
3459
+ log(
3460
+ chalk7.yellow(
3461
+ ` \u25CB ${label} has ${hidden} row(s) outside the first table block (blank lines split it); readers see ${report.visible} of ${report.total} \u2014 run \`qualiow session repair-index\``
3462
+ )
3463
+ );
3464
+ }
3465
+ function runSessionRepairIndex(options, ctx) {
3466
+ const cwd = ctx.cwd;
3467
+ const log = ctx.log ?? defaultLog;
3468
+ const targets = [
3469
+ { path: resolve9(cwd, "output", "sessions", "INDEX.md"), label: "INDEX.md" },
3470
+ { path: resolve9(cwd, "output", "bugs", "all-bugs.md"), label: "all-bugs.md" }
3471
+ ];
3472
+ const files = [];
3473
+ for (const { path, label } of targets) {
3474
+ if (!existsSync12(path)) continue;
3475
+ const content = readFileSync10(path, "utf-8");
3476
+ const report = analyseTable(content);
3477
+ const hiddenRows = Math.max(report.total - report.visible, 0);
3478
+ const blankLines = report.blankLines.length;
3479
+ if (blankLines === 0) {
3480
+ log(chalk7.green(` \u2713 ${label}: nothing to repair`));
3481
+ files.push({ file: label, blankLines, hiddenRows: 0, repaired: false });
3482
+ continue;
3483
+ }
3484
+ if (!options.yes) {
3485
+ log(
3486
+ chalk7.cyan(
3487
+ ` ${label}: ${blankLines} blank line(s) between table rows; ${hiddenRows} row(s) would become visible`
3488
+ )
3489
+ );
3490
+ files.push({ file: label, blankLines, hiddenRows, repaired: false });
3491
+ continue;
3492
+ }
3493
+ const drop = new Set(report.blankLines);
3494
+ writeFileSync5(path, content.split("\n").filter((_, i) => !drop.has(i)).join("\n"));
3495
+ log(
3496
+ chalk7.green(
3497
+ ` \u2713 ${label}: removed ${blankLines} blank line(s) between table rows; ${hiddenRows} row(s) now visible`
3498
+ )
3499
+ );
3500
+ files.push({ file: label, blankLines, hiddenRows, repaired: true });
3501
+ }
3502
+ if (files.length === 0) {
3503
+ log(chalk7.yellow(" No output/sessions/INDEX.md or output/bugs/all-bugs.md found."));
3504
+ } else if (!options.yes && files.some((f) => f.blankLines > 0)) {
3505
+ log(chalk7.white(" Re-run with --yes to rewrite."));
3506
+ }
3507
+ return { ok: true, dryRun: !options.yes, files };
3508
+ }
3509
+ function readAllBugsRows(path) {
3510
+ if (!existsSync12(path)) return [];
3511
+ const table2 = parseMarkdownTable(readFileSync10(path, "utf-8"));
3512
+ if (!table2) return [];
3513
+ return table2.rows.map((r) => ({
3514
+ id: r["id"] ?? "",
3515
+ session: r["session"] ?? "",
3516
+ title: r["title"] ?? "",
3517
+ severity: r["severity"] ?? "",
3518
+ status: r["status"] ?? "",
3519
+ report: r["report"] ?? ""
3520
+ })).filter((r) => r.id);
3521
+ }
3522
+ function listFilesRecursive(dir) {
3523
+ const out = [];
3524
+ for (const entry of readdirSync7(dir, { withFileTypes: true })) {
3525
+ const full = join12(dir, entry.name);
3526
+ if (entry.isDirectory()) {
3527
+ out.push(...listFilesRecursive(full));
3528
+ } else if (entry.isFile()) {
3529
+ out.push(full);
3530
+ }
3531
+ }
3532
+ return out;
3533
+ }
3534
+ function runSessionArchive(dir, options, ctx) {
3535
+ const cwd = ctx.cwd;
3536
+ const log = ctx.log ?? defaultLog;
3537
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3538
+ if (!existsSync12(sessionsDir)) {
3539
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3540
+ }
3541
+ const sessionDir = resolveSessionDir(sessionsDir, dir);
3542
+ const dirName = basename7(sessionDir);
3543
+ const tarPath = join12(sessionsDir, `${dirName}.tar.gz`);
3544
+ execFileSync("tar", ["-czf", tarPath, "-C", sessionsDir, dirName]);
3545
+ log(chalk7.green(` \u2713 Archived ${dirName} \u2192 ${relative6(cwd, tarPath)}`));
3546
+ let removed = false;
3547
+ if (options.remove) {
3548
+ rmSync(sessionDir, { recursive: true, force: true });
3549
+ setIndexRowStatus(join12(sessionsDir, "INDEX.md"), dirName, "archived");
3550
+ removed = true;
3551
+ log(chalk7.green(` \u2713 Removed ${dirName} (INDEX.md row marked archived)`));
3552
+ }
3553
+ return { ok: true, sessionDir, tarPath, removed };
3554
+ }
3555
+ function setIndexRowStatus(indexPath, dirName, status) {
3556
+ if (!existsSync12(indexPath)) return;
3557
+ const headers = readTableHeaders(indexPath) ?? [...INDEX_COLUMNS];
3558
+ const statusIdx = headers.findIndex((h) => h.trim().toLowerCase() === "status");
3559
+ if (statusIdx === -1) return;
3560
+ const lines = readFileSync10(indexPath, "utf-8").split("\n");
3561
+ const updated = lines.map((line) => {
3562
+ if (!line.trim().startsWith("|")) return line;
3563
+ if (!line.includes(`${dirName}/`)) return line;
3564
+ const cells = line.split("|");
3565
+ if (cells.length < 3) return line;
3566
+ const inner = cells.slice(1, -1).map((c) => c.trim());
3567
+ if (inner.length <= statusIdx) return line;
3568
+ inner[statusIdx] = status;
3569
+ return `| ${inner.join(" | ")} |`;
3570
+ });
3571
+ writeFileSync5(indexPath, updated.join("\n"));
3572
+ }
3573
+ function runSessionDelete(dir, options, ctx) {
3574
+ const cwd = ctx.cwd;
3575
+ const log = ctx.log ?? defaultLog;
3576
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3577
+ if (!existsSync12(sessionsDir)) {
3578
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3579
+ }
3580
+ const sessionDir = resolveSessionDir(sessionsDir, dir);
3581
+ const dirName = basename7(sessionDir);
3582
+ const { fileCount, totalBytes } = dirStats(sessionDir);
3583
+ const indexPath = join12(sessionsDir, "INDEX.md");
3584
+ const allBugsPath = resolve9(cwd, "output", "bugs", "all-bugs.md");
3585
+ const indexRows = tableRowsText(indexPath).filter((t) => t.includes(`${dirName}/`));
3586
+ const bugRows = tableRowsText(allBugsPath).filter((t) => t.includes(`${dirName}/bugs/`));
3587
+ if (!options.yes) {
3588
+ log(chalk7.cyan(`
3589
+ Dry run \u2014 would delete ${dirName}`));
3590
+ log(chalk7.white(` Files: ${fileCount} Size: ${formatBytes(totalBytes)}`));
3591
+ log(chalk7.white(` INDEX.md rows to remove: ${indexRows.length}`));
3592
+ log(chalk7.white(` all-bugs.md rows to remove: ${bugRows.length}`));
3593
+ log(chalk7.white(" Re-run with --yes to delete.\n"));
3594
+ return {
3595
+ ok: true,
3596
+ dryRun: true,
3597
+ sessionDir,
3598
+ fileCount,
3599
+ totalBytes,
3600
+ indexRows: indexRows.length,
3601
+ bugRows: bugRows.length
3602
+ };
3603
+ }
3604
+ performDelete(cwd, sessionDir);
3605
+ log(chalk7.green(` \u2713 Deleted ${dirName} (${fileCount} files, ${formatBytes(totalBytes)})`));
3606
+ return {
3607
+ ok: true,
3608
+ dryRun: false,
3609
+ sessionDir,
3610
+ fileCount,
3611
+ totalBytes,
3612
+ indexRows: indexRows.length,
3613
+ bugRows: bugRows.length
3614
+ };
3615
+ }
3616
+ function performDelete(cwd, sessionDir) {
3617
+ const dirName = basename7(sessionDir);
3618
+ rmSync(sessionDir, { recursive: true, force: true });
3619
+ removeTableRows(
3620
+ join12(cwd, "output", "sessions", "INDEX.md"),
3621
+ (line) => line.includes(`${dirName}/session-report.md`)
3622
+ );
3623
+ removeTableRows(join12(cwd, "output", "bugs", "all-bugs.md"), (line) => line.includes(`${dirName}/bugs/`));
3624
+ }
3625
+ function removeTableRows(filePath, matches) {
3626
+ if (!existsSync12(filePath)) return;
3627
+ const lines = readFileSync10(filePath, "utf-8").split("\n");
3628
+ const sepIdx = lines.findIndex((l) => /^\|(\s*:?-{2,}\s*\|)+\s*$/.test(l.trim()));
3629
+ if (sepIdx === -1) return;
3630
+ const head = lines.slice(0, sepIdx + 1);
3631
+ const rest = lines.slice(sepIdx + 1).filter((l) => !matches(l));
3632
+ writeFileSync5(filePath, [...head, ...rest].join("\n"));
3633
+ }
3634
+ function dirStats(dir) {
3635
+ let fileCount = 0;
3636
+ let totalBytes = 0;
3637
+ for (const file of listFilesRecursive(dir)) {
3638
+ fileCount++;
3639
+ totalBytes += statSync2(file).size;
3640
+ }
3641
+ return { fileCount, totalBytes };
3642
+ }
3643
+ function formatBytes(n) {
3644
+ if (n < 1024) return `${n} B`;
3645
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
3646
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
3647
+ }
3648
+ function runSessionPrune(options, ctx) {
3649
+ const cwd = ctx.cwd;
3650
+ const log = ctx.log ?? defaultLog;
3651
+ const now = ctx.now ?? /* @__PURE__ */ new Date();
3652
+ const days = typeof options.olderThan === "string" ? Number(options.olderThan) : options.olderThan;
3653
+ if (!Number.isFinite(days) || days < 0) {
3654
+ throw new Error(`--older-than must be a non-negative number of days (got "${options.olderThan}")`);
3655
+ }
3656
+ const sessionsDir = resolve9(cwd, "output", "sessions");
3657
+ if (!existsSync12(sessionsDir)) {
3658
+ throw new Error("No output/sessions directory found. Run `npx qualiow init` first.");
3659
+ }
3660
+ const thresholdMs = days * 24 * 60 * 60 * 1e3;
3661
+ const dirs = readdirSync7(sessionsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => describeSessionDir(d.name)).filter((d) => d !== null).sort((a, b) => a.name.localeCompare(b.name));
3662
+ const selected = dirs.filter((d) => now.getTime() - d.timestamp.getTime() > thresholdMs);
3663
+ const candidates = selected.map((d) => d.name);
3664
+ if (!options.yes) {
3665
+ log(chalk7.cyan(`
3666
+ Dry run \u2014 ${candidates.length} session(s) older than ${days} day(s):`));
3667
+ for (const d of selected) {
3668
+ log(chalk7.white(` ${d.name}${d.legacy ? " (legacy name)" : ""}`));
3669
+ }
3670
+ if (!candidates.length) log(chalk7.white(" (none)"));
3671
+ log("");
3672
+ return { ok: true, dryRun: true, candidates };
3673
+ }
3674
+ for (const d of selected) {
3675
+ performDelete(cwd, join12(sessionsDir, d.name));
3676
+ log(chalk7.green(` \u2713 Deleted ${d.name}${d.legacy ? " (legacy name)" : ""}`));
3677
+ }
3678
+ return { ok: true, dryRun: false, candidates };
3679
+ }
2632
3680
 
2633
3681
  // src/cli/index.ts
2634
- var program = new Command7().name("qualiow").description("qualiow \u2014 AI-powered exploratory testing (web, mobile, backend)").version(getPackageVersion());
3682
+ var program = new Command8().name("qualiow").description("qualiow \u2014 AI-powered exploratory testing (web, mobile, backend)").version(getPackageVersion());
2635
3683
  program.addCommand(initCommand());
2636
3684
  program.addCommand(validateCommand());
2637
3685
  program.addCommand(listCommand());
2638
3686
  program.addCommand(reportCommand());
2639
3687
  program.addCommand(exploreCommand());
2640
3688
  program.addCommand(kbCommand());
3689
+ program.addCommand(sessionCommand());
2641
3690
  program.parse();