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/index.js CHANGED
@@ -231,7 +231,10 @@ var KnowledgeManifestEntrySchema = z3.object({
231
231
  var LoadingStrategySchema = z3.object({
232
232
  always: z3.array(z3.string()),
233
233
  by_domain: z3.record(z3.string(), z3.array(z3.string())),
234
- by_tag: z3.record(z3.string(), z3.array(z3.string()))
234
+ by_tag: z3.record(z3.string(), z3.array(z3.string())),
235
+ /** Per-skill selection used by `qualiow kb digest --for <skill>`. Optional so
236
+ * a manifest written before this key still validates. */
237
+ by_skill: z3.record(z3.string(), z3.array(z3.string())).optional()
235
238
  });
236
239
  var KnowledgeManifestSchema = z3.object({
237
240
  version: z3.string().min(1),
@@ -684,7 +687,8 @@ function validateKnowledgeBase(dataDir) {
684
687
  const allRefs = [
685
688
  ...ls.always,
686
689
  ...Object.values(ls.by_domain).flat(),
687
- ...Object.values(ls.by_tag).flat()
690
+ ...Object.values(ls.by_tag).flat(),
691
+ ...Object.values(ls.by_skill ?? {}).flat()
688
692
  ];
689
693
  for (const id of allRefs) {
690
694
  if (!registryIds.has(id)) {
@@ -1003,6 +1007,19 @@ function resolveTargetPath(cwd, name, pkgRoot = getPackageRoot()) {
1003
1007
  if (existsSync4(cwdDefault)) return cwdDefault;
1004
1008
  return resolve2(pkgRoot, "data", "targets", "_default.yml");
1005
1009
  }
1010
+ function resolveDataDir(cwd, explicit, pkgRoot = getPackageRoot()) {
1011
+ if (explicit) return resolve2(cwd, explicit);
1012
+ const projectLocal = resolve2(cwd, "data");
1013
+ if (existsSync4(join4(projectLocal, "knowledge", "manifest.yml"))) {
1014
+ return projectLocal;
1015
+ }
1016
+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
1017
+ if (pluginRoot) {
1018
+ const pluginData = resolve2(pluginRoot, "data");
1019
+ if (existsSync4(pluginData)) return pluginData;
1020
+ }
1021
+ return resolve2(pkgRoot, "data");
1022
+ }
1006
1023
  function resolveDomainPath(dataDir, id) {
1007
1024
  const direct = join4(dataDir, "domains", `${id}.yml`);
1008
1025
  if (existsSync4(direct)) return direct;
@@ -1933,6 +1950,66 @@ import {
1933
1950
  chmodSync
1934
1951
  } from "fs";
1935
1952
  import chalk from "chalk";
1953
+
1954
+ // src/utils/settings-merge.ts
1955
+ var QUALIOW_HOOK_ENTRIES = [
1956
+ { matcher: "Read", command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/read-guard.mjs"' },
1957
+ {
1958
+ matcher: "Write|Edit|MultiEdit",
1959
+ command: 'node "$CLAUDE_PROJECT_DIR/qa/hooks/write-guard.mjs"'
1960
+ }
1961
+ ];
1962
+ var QUALIOW_PERMISSION_ALLOW = [
1963
+ "Bash(playwright-cli:*)",
1964
+ "Bash(npx playwright-cli:*)",
1965
+ "Bash(qualiow:*)"
1966
+ ];
1967
+ function isRecord(v) {
1968
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1969
+ }
1970
+ function existingHookCommands(settings) {
1971
+ const commands = /* @__PURE__ */ new Set();
1972
+ const hooks = settings.hooks;
1973
+ if (!isRecord(hooks)) return commands;
1974
+ const preToolUse = hooks.PreToolUse;
1975
+ if (!Array.isArray(preToolUse)) return commands;
1976
+ for (const entry of preToolUse) {
1977
+ if (!isRecord(entry) || !Array.isArray(entry.hooks)) continue;
1978
+ for (const h of entry.hooks) {
1979
+ if (isRecord(h) && typeof h.command === "string") commands.add(h.command);
1980
+ }
1981
+ }
1982
+ return commands;
1983
+ }
1984
+ function mergeQualiowHookSettings(existing) {
1985
+ const settings = isRecord(existing) ? { ...existing } : {};
1986
+ let changed = false;
1987
+ const hooksSection = isRecord(settings.hooks) ? { ...settings.hooks } : {};
1988
+ const preToolUse = Array.isArray(hooksSection.PreToolUse) ? [...hooksSection.PreToolUse] : [];
1989
+ const haveCommands = existingHookCommands(settings);
1990
+ for (const { matcher, command } of QUALIOW_HOOK_ENTRIES) {
1991
+ if (haveCommands.has(command)) continue;
1992
+ preToolUse.push({ matcher, hooks: [{ type: "command", command }] });
1993
+ haveCommands.add(command);
1994
+ changed = true;
1995
+ }
1996
+ hooksSection.PreToolUse = preToolUse;
1997
+ settings.hooks = hooksSection;
1998
+ const permissions = isRecord(settings.permissions) ? { ...settings.permissions } : {};
1999
+ const allow = Array.isArray(permissions.allow) ? [...permissions.allow] : [];
2000
+ const allowSet = new Set(allow.filter((a) => typeof a === "string"));
2001
+ for (const rule of QUALIOW_PERMISSION_ALLOW) {
2002
+ if (allowSet.has(rule)) continue;
2003
+ allow.push(rule);
2004
+ allowSet.add(rule);
2005
+ changed = true;
2006
+ }
2007
+ permissions.allow = allow;
2008
+ settings.permissions = permissions;
2009
+ return { settings, changed };
2010
+ }
2011
+
2012
+ // src/cli/commands/init.ts
1936
2013
  function sameContent(a, b) {
1937
2014
  try {
1938
2015
  return readFileSync6(a).equals(readFileSync6(b));
@@ -2000,14 +2077,14 @@ async function runInit(options, ctx) {
2000
2077
  filter: (rel2) => rel2.startsWith("qa-")
2001
2078
  })
2002
2079
  );
2003
- const agentCandidates = [
2004
- join6(pkgRoot, "agents", "qa-gather-agent.md"),
2005
- join6(pkgRoot, ".claude", "agents", "qa-gather-agent.md")
2006
- ];
2007
- const agentSrc = agentCandidates.find((p) => existsSync6(p));
2008
- if (agentSrc) {
2080
+ const agentsCandidates = [join6(pkgRoot, "agents"), join6(pkgRoot, ".claude", "agents")];
2081
+ const agentsSrc = agentsCandidates.find((p) => existsSync6(p));
2082
+ if (agentsSrc) {
2009
2083
  copies.push(
2010
- copyEntry(agentSrc, join6(cwd, ".claude", "agents", "qa-gather-agent.md"), copyOpts)
2084
+ ...copyTree(agentsSrc, join6(cwd, ".claude", "agents"), {
2085
+ ...copyOpts,
2086
+ filter: (rel2) => rel2.endsWith(".md")
2087
+ })
2011
2088
  );
2012
2089
  }
2013
2090
  const dataSrc = join6(pkgRoot, "data");
@@ -2033,7 +2110,12 @@ async function runInit(options, ctx) {
2033
2110
  })
2034
2111
  );
2035
2112
  const binSrc = join6(pkgRoot, "bin");
2036
- copies.push(...copyTree(binSrc, join6(cwd, "qa", "bin"), copyOpts));
2113
+ copies.push(
2114
+ ...copyTree(binSrc, join6(cwd, "qa", "bin"), {
2115
+ ...copyOpts,
2116
+ filter: (rel2) => rel2 !== "qualiow"
2117
+ })
2118
+ );
2037
2119
  if (existsSync6(binSrc)) {
2038
2120
  const versionPath = join6(cwd, "qa", "bin", "VERSION");
2039
2121
  const version = `${getPackageVersion(pkgRoot)}
@@ -2052,6 +2134,32 @@ async function runInit(options, ctx) {
2052
2134
  copies.push(copyEntry(envExampleSrc, join6(cwd, "qa", ".env.example"), copyOpts));
2053
2135
  }
2054
2136
  }
2137
+ let hooksSettingsChanged = false;
2138
+ if (options.hooks) {
2139
+ const hooksScriptsSrc = join6(pkgRoot, "hooks", "scripts");
2140
+ copies.push(
2141
+ ...copyTree(hooksScriptsSrc, join6(cwd, "qa", "hooks"), {
2142
+ ...copyOpts,
2143
+ filter: (rel2) => rel2.endsWith(".mjs")
2144
+ })
2145
+ );
2146
+ const settingsPath = join6(cwd, ".claude", "settings.json");
2147
+ const settingsExisted = existsSync6(settingsPath);
2148
+ let existingSettings;
2149
+ if (settingsExisted) {
2150
+ try {
2151
+ existingSettings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
2152
+ } catch {
2153
+ existingSettings = void 0;
2154
+ }
2155
+ }
2156
+ const { settings, changed } = mergeQualiowHookSettings(existingSettings);
2157
+ hooksSettingsChanged = changed || !settingsExisted;
2158
+ if (!options.dryRun) {
2159
+ mkdirSync2(dirname3(settingsPath), { recursive: true });
2160
+ writeFileSync2(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2161
+ }
2162
+ }
2055
2163
  for (const dir of ["output/sessions", "output/bugs", "output/context", ".auth", "qa"]) {
2056
2164
  const full = join6(cwd, dir);
2057
2165
  if (!existsSync6(full)) {
@@ -2095,12 +2203,20 @@ async function runInit(options, ctx) {
2095
2203
  log(
2096
2204
  gitignoreUpdated ? chalk.green(" \u2713 Updated .gitignore (Qualiow block)") : chalk.cyan(" \u25CB .gitignore already up to date")
2097
2205
  );
2206
+ if (options.hooks) {
2207
+ log(
2208
+ hooksSettingsChanged ? chalk.green(" \u2713 Wired hooks into .claude/settings.json") : chalk.cyan(" \u25CB .claude/settings.json hooks already up to date")
2209
+ );
2210
+ }
2098
2211
  log("");
2099
2212
  log(chalk.cyan.bold(options.dryRun ? "Dry run complete." : "Qualiow initialized."));
2100
2213
  log("");
2101
2214
  log(chalk.white("Next steps:"));
2102
2215
  log(chalk.white(" 1. npx playwright-cli install --skills # official Playwright skill, next to qualiow"));
2103
2216
  log(chalk.white(" 2. cp qa/.env.example qa/.env # credentials by env var name only"));
2217
+ if (options.hooks) {
2218
+ log(chalk.white(' QUALIOW_HOOKS=off or QUALIOW_READ_MAX_LINES=<n> under "env" in .claude/settings.json tune the guards'));
2219
+ }
2104
2220
  log(chalk.white(" 3. /qa-target-setup or /qa-explore https://your-app.com"));
2105
2221
  log(chalk.white(" 4. mobile: qa/bin/doctor-mobile.sh # then /qa-explore-mobile --target <id>"));
2106
2222
  log("");
@@ -2172,7 +2288,7 @@ ${details}`);
2172
2288
  log(chalk2.white(` Time box: ${minutes} min`));
2173
2289
  return { sessionDir };
2174
2290
  }
2175
- for (const sub of ["", "screenshots", "bugs", "videos"]) {
2291
+ for (const sub of ["", "screenshots", "bugs", "videos", "snapshots"]) {
2176
2292
  mkdirSync3(join7(sessionDir, sub), { recursive: true });
2177
2293
  }
2178
2294
  const date = now.toISOString().slice(0, 10);
@@ -2309,13 +2425,13 @@ import { existsSync as existsSync9, readFileSync as readFileSync8, readdirSync a
2309
2425
  import { parse as parseYaml3 } from "yaml";
2310
2426
  import { globSync as globSync3 } from "glob";
2311
2427
  import chalk4 from "chalk";
2312
- async function runList(type, cwd) {
2428
+ async function runList(type, cwd, options = {}, log = (line) => console.log(line)) {
2313
2429
  switch (type) {
2314
2430
  case "sessions":
2315
2431
  listSessions(cwd);
2316
2432
  break;
2317
2433
  case "knowledge":
2318
- listKnowledge(cwd);
2434
+ listKnowledge(cwd, options, log);
2319
2435
  break;
2320
2436
  case "targets":
2321
2437
  listTargets(cwd);
@@ -2381,41 +2497,129 @@ function listSessions(cwd) {
2381
2497
  console.log(chalk4.white(` Total: ${rows.length} session(s)` + (unindexed.length ? chalk4.gray(` (+${unindexed.length} unindexed)`) : "")));
2382
2498
  console.log("");
2383
2499
  }
2384
- function listKnowledge(cwd) {
2385
- const knowledgeDir = resolve6(cwd, "data", "knowledge");
2500
+ function listKnowledge(cwd, options, log) {
2501
+ const dataDir = resolveDataDir(cwd, options.data);
2502
+ const knowledgeDir = join9(dataDir, "knowledge");
2386
2503
  const manifestPath = join9(knowledgeDir, "manifest.yml");
2387
2504
  if (!existsSync9(manifestPath)) {
2388
- console.log(chalk4.yellow("No knowledge base found. Run `npx qualiow init` first."));
2505
+ log(chalk4.yellow(`No knowledge base at ${manifestPath}. Run \`npx qualiow init\` first.`));
2506
+ return;
2507
+ }
2508
+ const manifest = KnowledgeManifestSchema.parse(
2509
+ parseYaml3(readFileSync8(manifestPath, "utf-8"))
2510
+ );
2511
+ if (options.entry) {
2512
+ log(readEntryFile(knowledgeDir, manifest.entries, options.entry));
2513
+ return;
2514
+ }
2515
+ if (options.changelog) {
2516
+ printKnowledgeChangelog(knowledgeDir, log);
2517
+ return;
2518
+ }
2519
+ if (options.stats) {
2520
+ printKnowledgeStats(manifest, log);
2389
2521
  return;
2390
2522
  }
2391
- const manifest = parseYaml3(readFileSync8(manifestPath, "utf-8"));
2392
2523
  const filesOnDisk = globSync3(join9(knowledgeDir, "releases", "*", "entries", "*.yml")).length;
2393
- console.log(chalk4.cyan.bold("\nKnowledge Base:"));
2394
- console.log(chalk4.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
2524
+ log(chalk4.cyan.bold("\nKnowledge Base:"));
2525
+ log(chalk4.white(` Version: ${manifest.version} | Entries: ${manifest.entries.length}`));
2395
2526
  if (filesOnDisk !== manifest.entries.length || manifest.stats.total_entries !== filesOnDisk) {
2396
- console.log(
2527
+ log(
2397
2528
  chalk4.yellow(
2398
2529
  ` \u26A0 Registry (${manifest.entries.length}) / stats (${manifest.stats.total_entries}) disagree with ${filesOnDisk} entry files \u2014 run: npx qualiow kb sync`
2399
2530
  )
2400
2531
  );
2401
2532
  }
2402
- console.log("");
2533
+ const filters = [];
2534
+ if (options.domain) filters.push(`domain ${options.domain}`);
2535
+ if (options.tag) filters.push(`tag ${options.tag}`);
2536
+ if (options.type) filters.push(`type ${options.type}`);
2537
+ const entries = manifest.entries.filter(
2538
+ (e) => (!options.domain || e.domains.includes(options.domain) || e.domains.includes("all")) && (!options.tag || e.tags.includes(options.tag)) && (!options.type || e.type === options.type)
2539
+ );
2540
+ if (filters.length) {
2541
+ log(chalk4.white(` Filter: ${filters.join(", ")} \u2192 ${entries.length} entries`));
2542
+ }
2543
+ log("");
2544
+ if (entries.length === 0) {
2545
+ log(chalk4.yellow(" No entries match that filter."));
2546
+ log("");
2547
+ return;
2548
+ }
2403
2549
  const grouped = /* @__PURE__ */ new Map();
2404
- for (const entry of manifest.entries) {
2550
+ for (const entry of entries) {
2405
2551
  const list = grouped.get(entry.type) ?? [];
2406
2552
  list.push(entry);
2407
2553
  grouped.set(entry.type, list);
2408
2554
  }
2409
- for (const [type, entries] of grouped) {
2410
- console.log(chalk4.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${entries.length}):`));
2411
- for (const entry of entries) {
2555
+ for (const [type, group] of grouped) {
2556
+ log(chalk4.cyan(` ${type.charAt(0).toUpperCase() + type.slice(1)}s (${group.length}):`));
2557
+ for (const entry of group) {
2412
2558
  const priorityColor = entry.priority === "high" ? chalk4.red : entry.priority === "medium" ? chalk4.yellow : chalk4.white;
2413
2559
  const tags = entry.tags.map((t) => chalk4.gray(t)).join(", ");
2414
- console.log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk4.gray("tags:")} ${tags}`);
2560
+ log(` ${priorityColor(`[${entry.priority}]`)} ${entry.id} ${chalk4.gray("tags:")} ${tags}`);
2415
2561
  }
2416
- console.log("");
2562
+ log("");
2563
+ }
2564
+ }
2565
+ function readEntryFile(knowledgeDir, entries, id) {
2566
+ const meta = entries.find((e) => e.id === id);
2567
+ const path = meta ? join9(knowledgeDir, meta.file) : join9(knowledgeDir, "custom", `${id}.yml`);
2568
+ if (!existsSync9(path)) {
2569
+ throw new Error(`Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`);
2570
+ }
2571
+ return readFileSync8(path, "utf-8").trimEnd();
2572
+ }
2573
+ function printKnowledgeChangelog(knowledgeDir, log) {
2574
+ const changelogPath = join9(knowledgeDir, "changelog.yml");
2575
+ if (!existsSync9(changelogPath)) {
2576
+ log(chalk4.yellow(`No changelog at ${changelogPath}.`));
2577
+ return;
2578
+ }
2579
+ const changelog = KnowledgeChangelogSchema.parse(
2580
+ parseYaml3(readFileSync8(changelogPath, "utf-8"))
2581
+ );
2582
+ log(chalk4.cyan.bold("\nKnowledge Base Changelog:"));
2583
+ log("");
2584
+ for (const release of changelog.releases) {
2585
+ log(` ${chalk4.bold(`v${release.version}`)} ${chalk4.gray(`\xB7 ${release.date}`)}`);
2586
+ log(` ${release.summary}`);
2587
+ const added = release.entries_added.map((e) => e.id);
2588
+ if (added.length) log(` ${chalk4.gray("added:")} ${added.join(", ")}`);
2589
+ if (release.entries_modified.length) {
2590
+ log(` ${chalk4.gray("modified:")} ${release.entries_modified.join(", ")}`);
2591
+ }
2592
+ if (release.entries_removed.length) {
2593
+ log(` ${chalk4.gray("removed:")} ${release.entries_removed.join(", ")}`);
2594
+ }
2595
+ log("");
2417
2596
  }
2418
2597
  }
2598
+ function printKnowledgeStats(manifest, log) {
2599
+ log(chalk4.cyan.bold("\nKnowledge Base Stats:"));
2600
+ log(chalk4.white(` Version: ${manifest.version}`));
2601
+ log("");
2602
+ for (const [key, value] of Object.entries(manifest.stats)) {
2603
+ log(` ${pad2(key.replace(/_/g, " "), 18)} ${value}`);
2604
+ }
2605
+ log("");
2606
+ log(chalk4.cyan(` Active releases (${manifest.active_releases.length}):`));
2607
+ log(` ${manifest.active_releases.join(", ")}`);
2608
+ log("");
2609
+ const ls = manifest.loading_strategy;
2610
+ log(chalk4.cyan(" Loading strategy:"));
2611
+ log(` ${pad2("always", 12)} ${ls.always.length} entries`);
2612
+ for (const [bucket, map] of [
2613
+ ["by_domain", ls.by_domain],
2614
+ ["by_tag", ls.by_tag],
2615
+ ["by_skill", ls.by_skill ?? {}]
2616
+ ]) {
2617
+ const keys = Object.keys(map);
2618
+ const total = Object.values(map).reduce((n, ids) => n + ids.length, 0);
2619
+ log(` ${pad2(bucket, 12)} ${keys.length} keys, ${total} references`);
2620
+ }
2621
+ log("");
2622
+ }
2419
2623
  function listTargets(cwd) {
2420
2624
  const targetsDir = resolve6(cwd, "data", "targets");
2421
2625
  if (!existsSync9(targetsDir)) {
@@ -2561,9 +2765,13 @@ function printResult(result, cwd) {
2561
2765
 
2562
2766
  // src/cli/commands/kb.ts
2563
2767
  import { Command as Command6 } from "commander";
2564
- import { resolve as resolve8 } from "path";
2565
- import { existsSync as existsSync11 } from "fs";
2768
+ import { resolve as resolve8, join as join11 } from "path";
2769
+ import { existsSync as existsSync11, readFileSync as readFileSync9, readdirSync as readdirSync6 } from "fs";
2566
2770
  import chalk6 from "chalk";
2771
+ import { parse as parseYaml4 } from "yaml";
2772
+ var DEFAULT_MAX_LINES = 12;
2773
+ var WRAP_COLUMN = 100;
2774
+ var WHEN_TO_USE_ITEMS = 3;
2567
2775
  function runKb(mode, cwd) {
2568
2776
  const dataDir = resolve8(cwd, "data");
2569
2777
  if (!existsSync11(resolve8(dataDir, "knowledge", "manifest.yml"))) {
@@ -2571,6 +2779,241 @@ function runKb(mode, cwd) {
2571
2779
  }
2572
2780
  return syncKnowledgeManifest(dataDir, { check: mode === "check" });
2573
2781
  }
2782
+ function runKbDigest(options, cwd) {
2783
+ const dataDir = resolveDataDir(cwd, options.data);
2784
+ const knowledgeDir = join11(dataDir, "knowledge");
2785
+ const manifestPath = join11(knowledgeDir, "manifest.yml");
2786
+ if (!existsSync11(manifestPath)) {
2787
+ throw new Error(
2788
+ `No knowledge manifest at ${manifestPath}. Pass --data <dir>, or run \`npx qualiow init\` first.`
2789
+ );
2790
+ }
2791
+ const manifest = KnowledgeManifestSchema.parse(
2792
+ parseYaml4(readFileSync9(manifestPath, "utf-8"))
2793
+ );
2794
+ const byId = new Map(manifest.entries.map((e) => [e.id, e]));
2795
+ const maxLines = Math.max(1, options.maxLines ?? DEFAULT_MAX_LINES);
2796
+ if (options.entry) {
2797
+ return readWholeEntry(knowledgeDir, byId, options.entry);
2798
+ }
2799
+ const ls = manifest.loading_strategy;
2800
+ const selected = [];
2801
+ const add = (ids) => {
2802
+ let added = 0;
2803
+ for (const id of ids ?? []) {
2804
+ if (selected.includes(id)) continue;
2805
+ selected.push(id);
2806
+ added++;
2807
+ }
2808
+ return added;
2809
+ };
2810
+ add(ls.always);
2811
+ const domainAdded = options.domain ? add(ls.by_domain[options.domain]) : 0;
2812
+ const tags = options.tag ?? [];
2813
+ let tagAdded = 0;
2814
+ for (const tag of tags) tagAdded += add(ls.by_tag[tag]);
2815
+ let skillAdded = 0;
2816
+ if (options.for) {
2817
+ const bySkill = ls.by_skill;
2818
+ if (!bySkill) {
2819
+ throw new Error(
2820
+ "This manifest has no loading_strategy.by_skill, so --for has nothing to select."
2821
+ );
2822
+ }
2823
+ if (!Object.prototype.hasOwnProperty.call(bySkill, options.for)) {
2824
+ throw new Error(
2825
+ `Unknown skill "${options.for}". Known: ${Object.keys(bySkill).sort().join(", ")}.`
2826
+ );
2827
+ }
2828
+ skillAdded = add(bySkill[options.for]);
2829
+ }
2830
+ const unknown = selected.filter((id) => !byId.has(id));
2831
+ if (unknown.length) {
2832
+ throw new Error(
2833
+ `loading_strategy references ${unknown.length} unknown entry id(s): ${unknown.join(", ")}. Run \`qualiow kb sync\` and \`qualiow validate --kb\`.`
2834
+ );
2835
+ }
2836
+ const header = [
2837
+ `# Knowledge digest v${manifest.version}`,
2838
+ `${selected.length} entries`,
2839
+ `always ${ls.always.length}`
2840
+ ];
2841
+ if (options.domain) header.push(`domain ${options.domain} +${domainAdded}`);
2842
+ if (tags.length) header.push(`tags ${tags.join(", ")} +${tagAdded}`);
2843
+ if (options.for) header.push(`skill ${options.for} +${skillAdded}`);
2844
+ const lines = [header.join(" \xB7 ")];
2845
+ for (const id of selected) {
2846
+ const meta = byId.get(id);
2847
+ lines.push(...entryBlock(join11(knowledgeDir, meta.file), meta, maxLines));
2848
+ }
2849
+ lines.push(...customSection(knowledgeDir, maxLines));
2850
+ lines.push(...learnedPatternsSection(cwd, knowledgeDir));
2851
+ return lines.join("\n");
2852
+ }
2853
+ function readWholeEntry(knowledgeDir, byId, id) {
2854
+ const meta = byId.get(id);
2855
+ const path = meta ? join11(knowledgeDir, meta.file) : join11(knowledgeDir, "custom", `${id}.yml`);
2856
+ if (!existsSync11(path)) {
2857
+ throw new Error(
2858
+ `Unknown entry "${id}". Run \`qualiow list knowledge\` to see the available ids.`
2859
+ );
2860
+ }
2861
+ return readFileSync9(path, "utf-8").trimEnd();
2862
+ }
2863
+ function entryBlock(file, meta, maxLines, custom = false) {
2864
+ if (!existsSync11(file)) {
2865
+ throw new Error(`Entry "${meta.id}" is registered but its file is missing: ${file}`);
2866
+ }
2867
+ const entry = KnowledgeEntrySchema.parse(parseYaml4(readFileSync9(file, "utf-8")));
2868
+ const content = entry.content;
2869
+ const marker = custom ? " [custom]" : "";
2870
+ const out = [
2871
+ `- ${meta.id} [${meta.type}/${meta.priority}]${marker} tags: ${meta.tags.join(", ")}`
2872
+ ];
2873
+ out.push(...wrap(collapse(entry.content.summary)));
2874
+ for (const [key, items] of namedArrays(content)) {
2875
+ const rendered = items.map((item) => {
2876
+ const lead = subItemLead(item);
2877
+ return lead ? `${item.name} \u2014 ${lead}` : item.name;
2878
+ }).join("; ");
2879
+ out.push(...wrap(`${humanise(key)}: ${rendered}`));
2880
+ }
2881
+ const whenToUse = content["when_to_use"];
2882
+ if (Array.isArray(whenToUse) && whenToUse.length) {
2883
+ const items = whenToUse.slice(0, WHEN_TO_USE_ITEMS).filter((v) => typeof v === "string").map(collapse);
2884
+ if (items.length) out.push(...wrap(`when to use: ${items.join("; ")}`));
2885
+ }
2886
+ return capLines(out, maxLines);
2887
+ }
2888
+ function customSection(knowledgeDir, maxLines) {
2889
+ const customDir = join11(knowledgeDir, "custom");
2890
+ if (!existsSync11(customDir)) return [];
2891
+ const files = readdirSync6(customDir).filter((f) => f.endsWith(".yml")).sort();
2892
+ if (!files.length) return [];
2893
+ const lines = ["", "## Custom entries"];
2894
+ for (const file of files) {
2895
+ const path = join11(customDir, file);
2896
+ const parsed = parseYaml4(readFileSync9(path, "utf-8"));
2897
+ lines.push(
2898
+ ...entryBlock(
2899
+ path,
2900
+ {
2901
+ id: parsed.id ?? file.replace(/\.yml$/, ""),
2902
+ type: parsed.type ?? "custom",
2903
+ priority: parsed.priority ?? "medium",
2904
+ tags: parsed.tags ?? []
2905
+ },
2906
+ maxLines,
2907
+ true
2908
+ )
2909
+ );
2910
+ }
2911
+ return lines;
2912
+ }
2913
+ function learnedPatternsSection(cwd, knowledgeDir) {
2914
+ const candidates = [
2915
+ resolve8(cwd, "data", "knowledge", "learned-patterns.md"),
2916
+ join11(knowledgeDir, "learned-patterns.md")
2917
+ ];
2918
+ const path = candidates.find((p) => existsSync11(p));
2919
+ if (!path) return [];
2920
+ const sections = learnedPatternLeadIns(readFileSync9(path, "utf-8"));
2921
+ if (!sections.length) return [];
2922
+ const lines = ["", "## Learned patterns", "Grep the file for the full entry."];
2923
+ for (const section of sections) {
2924
+ lines.push(...wrap(`${section.heading}: ${section.items.join("; ")}`));
2925
+ }
2926
+ return lines;
2927
+ }
2928
+ function learnedPatternLeadIns(markdown) {
2929
+ const sections = [];
2930
+ let current = null;
2931
+ let bullet = null;
2932
+ const flush = () => {
2933
+ if (bullet !== null && current) {
2934
+ const match = /^\*\*([\s\S]+?)\*\*/.exec(bullet);
2935
+ if (match) current.items.push(collapse(match[1]));
2936
+ }
2937
+ bullet = null;
2938
+ };
2939
+ for (const raw of markdown.split("\n")) {
2940
+ const heading = /^#{2,}\s+(.+)$/.exec(raw);
2941
+ if (heading) {
2942
+ flush();
2943
+ current = { heading: heading[1].trim(), items: [] };
2944
+ sections.push(current);
2945
+ continue;
2946
+ }
2947
+ const start = /^[-*]\s+(.*)$/.exec(raw);
2948
+ if (start) {
2949
+ flush();
2950
+ bullet = start[1];
2951
+ continue;
2952
+ }
2953
+ if (bullet !== null) {
2954
+ if (raw.trim() === "") flush();
2955
+ else bullet += ` ${raw.trim()}`;
2956
+ }
2957
+ }
2958
+ flush();
2959
+ return sections.filter((s) => s.items.length > 0);
2960
+ }
2961
+ function namedArrays(content) {
2962
+ const found = [];
2963
+ for (const [key, value] of Object.entries(content)) {
2964
+ if (key === "summary" || key === "when_to_use") continue;
2965
+ if (!Array.isArray(value) || value.length === 0) continue;
2966
+ const items = value.filter(
2967
+ (v) => typeof v === "object" && v !== null && typeof v.name === "string"
2968
+ );
2969
+ if (items.length === value.length) found.push([key, items]);
2970
+ }
2971
+ return found;
2972
+ }
2973
+ function subItemLead(item) {
2974
+ const questions = item["questions"];
2975
+ if (Array.isArray(questions) && typeof questions[0] === "string") {
2976
+ return truncate(collapse(questions[0]));
2977
+ }
2978
+ const description = item["description"];
2979
+ if (typeof description === "string") return truncate(collapse(description));
2980
+ return "";
2981
+ }
2982
+ function collapse(text) {
2983
+ return text.replace(/\s+/g, " ").trim();
2984
+ }
2985
+ function truncate(text, limit = WRAP_COLUMN) {
2986
+ if (text.length <= limit) return text;
2987
+ const cut = text.slice(0, limit - 1);
2988
+ const lastSpace = cut.lastIndexOf(" ");
2989
+ return `${(lastSpace > limit / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
2990
+ }
2991
+ function humanise(key) {
2992
+ const spaced = key.replace(/_/g, " ");
2993
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
2994
+ }
2995
+ function wrap(text, width = WRAP_COLUMN, indent = " ", hanging = " ") {
2996
+ const words = collapse(text).split(" ").filter(Boolean);
2997
+ if (!words.length) return [];
2998
+ const out = [];
2999
+ let line = indent + words[0];
3000
+ for (const word of words.slice(1)) {
3001
+ if (line.length + 1 + word.length > width) {
3002
+ out.push(line);
3003
+ line = hanging + word;
3004
+ } else {
3005
+ line += ` ${word}`;
3006
+ }
3007
+ }
3008
+ out.push(line);
3009
+ return out;
3010
+ }
3011
+ function capLines(lines, maxLines) {
3012
+ if (lines.length <= maxLines) return lines;
3013
+ const kept = lines.slice(0, maxLines);
3014
+ kept[kept.length - 1] = `${kept[kept.length - 1]} \u2026`;
3015
+ return kept;
3016
+ }
2574
3017
  export {
2575
3018
  ALL_BUGS_COLUMNS,
2576
3019
  ALL_BUGS_MD_HEADER,
@@ -2635,6 +3078,7 @@ export {
2635
3078
  readAllMetrics,
2636
3079
  readSessionIndex,
2637
3080
  redact,
3081
+ resolveDataDir,
2638
3082
  resolveDomainPath,
2639
3083
  resolveSessionDir,
2640
3084
  resolveSkillsSource,
@@ -2642,6 +3086,7 @@ export {
2642
3086
  runExplore,
2643
3087
  runInit,
2644
3088
  runKb,
3089
+ runKbDigest,
2645
3090
  runList,
2646
3091
  runReport,
2647
3092
  runValidate,