sniff-qa 0.7.0 → 0.8.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 (71) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/CHANGELOG.md +70 -0
  3. package/NOTICE +1 -1
  4. package/README.md +109 -380
  5. package/dist/assert-budget-NBF3JYM7.js +9 -0
  6. package/dist/caps-G3ZGJI7B.js +21 -0
  7. package/dist/caps-G3ZGJI7B.js.map +1 -0
  8. package/dist/{chunk-LJYT4MD5.js → chunk-7ZOFYET5.js} +18 -97
  9. package/dist/chunk-7ZOFYET5.js.map +1 -0
  10. package/dist/chunk-EGANHIIE.js +91 -0
  11. package/dist/chunk-EGANHIIE.js.map +1 -0
  12. package/dist/chunk-GV27IOMC.js +106 -0
  13. package/dist/chunk-GV27IOMC.js.map +1 -0
  14. package/dist/chunk-GX36BPK7.js +161 -0
  15. package/dist/chunk-GX36BPK7.js.map +1 -0
  16. package/dist/chunk-NG2IGCAK.js +45 -0
  17. package/dist/chunk-NG2IGCAK.js.map +1 -0
  18. package/dist/cli/index.js +27 -16
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/crawl-ZXZRF4Q7.js +15 -0
  21. package/dist/crawl-ZXZRF4Q7.js.map +1 -0
  22. package/dist/crawl-command-RDWGHZC4.js +76 -0
  23. package/dist/crawl-command-RDWGHZC4.js.map +1 -0
  24. package/dist/{discover-Q363YJ5X.js → discover-QKGMYPHK.js} +15 -7
  25. package/dist/discover-QKGMYPHK.js.map +1 -0
  26. package/dist/{domain-NNL2PPRK.js → domain-UQ34YE4B.js} +1 -1
  27. package/dist/index.d.ts +15 -0
  28. package/dist/index.js +6 -2
  29. package/dist/index.js.map +1 -1
  30. package/dist/{loader-UG2XADG7.js → loader-Z2DUGG5Z.js} +18 -2
  31. package/dist/loader-Z2DUGG5Z.js.map +1 -0
  32. package/dist/mcp/server.d.ts +20 -1
  33. package/dist/mcp/server.js +37 -28
  34. package/dist/mcp/server.js.map +1 -1
  35. package/dist/{model-2DTSAX7T.js → model-SP6HJN6J.js} +4 -2
  36. package/dist/model-SP6HJN6J.js.map +1 -0
  37. package/dist/{persistence-RHUFBQAY.js → persistence-XLFJ5EY4.js} +6 -2
  38. package/dist/persistence-XLFJ5EY4.js.map +1 -0
  39. package/dist/{quality-run-LLBZZI7X.js → quality-run-YAURB242.js} +6 -5
  40. package/dist/{quality-run-LLBZZI7X.js.map → quality-run-YAURB242.js.map} +1 -1
  41. package/dist/redaction-CHAIVPCF.js +30 -0
  42. package/dist/redaction-CHAIVPCF.js.map +1 -0
  43. package/dist/{repo-analyzer-WK5WP7NT.js → repo-analyzer-4OURSITY.js} +1 -1
  44. package/dist/{report-IKRVVIW4.js → report-7FQFH4HW.js} +3 -3
  45. package/dist/{runner-HFJDHS2I.js → runner-QHSYX7J2.js} +1 -1
  46. package/dist/{runner-II7BPB63.js → runner-RDVVIGBU.js} +7 -2
  47. package/dist/runner-RDVVIGBU.js.map +1 -0
  48. package/dist/{unified-67Z6YA64.js → unified-YSOTPG5B.js} +12 -10
  49. package/dist/{unified-67Z6YA64.js.map → unified-YSOTPG5B.js.map} +1 -1
  50. package/dist/{update-baselines-UCAW3SDN.js → update-baselines-JYKUUIZG.js} +2 -2
  51. package/dist/write-report-6RJWN54I.js +31 -0
  52. package/dist/write-report-6RJWN54I.js.map +1 -0
  53. package/package.json +5 -4
  54. package/skills/sniff/SKILL.md +10 -10
  55. package/skills/sniff-fix/SKILL.md +3 -0
  56. package/skills/sniff-report/SKILL.md +3 -0
  57. package/dist/chunk-LJYT4MD5.js.map +0 -1
  58. package/dist/crawl-666NLYDC.js +0 -11
  59. package/dist/crawl-command-3OB4IUBU.js +0 -54
  60. package/dist/crawl-command-3OB4IUBU.js.map +0 -1
  61. package/dist/discover-Q363YJ5X.js.map +0 -1
  62. package/dist/loader-UG2XADG7.js.map +0 -1
  63. package/dist/model-2DTSAX7T.js.map +0 -1
  64. package/dist/persistence-RHUFBQAY.js.map +0 -1
  65. package/dist/runner-II7BPB63.js.map +0 -1
  66. /package/dist/{crawl-666NLYDC.js.map → assert-budget-NBF3JYM7.js.map} +0 -0
  67. /package/dist/{domain-NNL2PPRK.js.map → domain-UQ34YE4B.js.map} +0 -0
  68. /package/dist/{repo-analyzer-WK5WP7NT.js.map → repo-analyzer-4OURSITY.js.map} +0 -0
  69. /package/dist/{report-IKRVVIW4.js.map → report-7FQFH4HW.js.map} +0 -0
  70. /package/dist/{runner-HFJDHS2I.js.map → runner-QHSYX7J2.js.map} +0 -0
  71. /package/dist/{update-baselines-UCAW3SDN.js.map → update-baselines-JYKUUIZG.js.map} +0 -0
@@ -0,0 +1,106 @@
1
+ // src/mcp/caps.ts
2
+ var CAPABILITIES = ["scan", "walk", "discover", "report", "install"];
3
+ var UNIFIED_MODES = ["walk", "scan", "run", "discover", "report"];
4
+ var MODE_CAPABILITY = {
5
+ walk: "walk",
6
+ scan: "scan",
7
+ run: "walk",
8
+ discover: "discover",
9
+ report: "report"
10
+ };
11
+ var CAPABILITY_TOOL = {
12
+ scan: "sniff_scan",
13
+ walk: "sniff_run",
14
+ discover: "sniff_discover",
15
+ report: "sniff_report",
16
+ install: "sniff_install"
17
+ };
18
+ var TOOL_ORDER = [
19
+ "sniff",
20
+ "sniff_scan",
21
+ "sniff_run",
22
+ "sniff_discover",
23
+ "sniff_install",
24
+ "sniff_report"
25
+ ];
26
+ var UNIFIED_CAPABILITIES = ["scan", "walk", "discover", "report"];
27
+ var IMPLIES = {
28
+ walk: ["scan"]
29
+ };
30
+ function expandCaps(caps) {
31
+ const out = [];
32
+ const add = (c) => {
33
+ if (out.includes(c)) return;
34
+ out.push(c);
35
+ for (const implied of IMPLIES[c] ?? []) add(implied);
36
+ };
37
+ for (const c of caps) add(c);
38
+ return out;
39
+ }
40
+ var CapsError = class extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "CapsError";
44
+ }
45
+ };
46
+ function isCapability(value) {
47
+ return CAPABILITIES.includes(value);
48
+ }
49
+ function parseCaps(argv) {
50
+ let raw;
51
+ for (let i = 0; i < argv.length; i += 1) {
52
+ const arg = argv[i];
53
+ if (arg === "--caps") {
54
+ raw = argv[i + 1];
55
+ if (raw === void 0 || raw.startsWith("-")) {
56
+ throw new CapsError("--caps needs a comma-separated list, for example --caps scan,report");
57
+ }
58
+ break;
59
+ }
60
+ if (arg.startsWith("--caps=")) {
61
+ raw = arg.slice("--caps=".length);
62
+ break;
63
+ }
64
+ }
65
+ if (raw === void 0) return [...CAPABILITIES];
66
+ const names = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
67
+ if (names.length === 0) {
68
+ throw new CapsError("--caps was empty. Known capabilities: " + CAPABILITIES.join(", "));
69
+ }
70
+ const unknown = names.filter((n) => !isCapability(n));
71
+ if (unknown.length > 0) {
72
+ throw new CapsError(
73
+ `Unknown capability: ${unknown.join(", ")}. Known capabilities: ${CAPABILITIES.join(", ")}`
74
+ );
75
+ }
76
+ const granted = [];
77
+ for (const n of names) {
78
+ if (isCapability(n) && !granted.includes(n)) granted.push(n);
79
+ }
80
+ return granted;
81
+ }
82
+ function resolveTools(caps) {
83
+ const expanded = expandCaps(caps);
84
+ const granted = new Set(expanded);
85
+ const modes = UNIFIED_MODES.filter((m) => granted.has(MODE_CAPABILITY[m]));
86
+ const wantsUnified = UNIFIED_CAPABILITIES.some((c) => granted.has(c));
87
+ const registered = /* @__PURE__ */ new Set();
88
+ if (wantsUnified) registered.add("sniff");
89
+ for (const cap of expanded) registered.add(CAPABILITY_TOOL[cap]);
90
+ return {
91
+ tools: TOOL_ORDER.filter((t) => registered.has(t)),
92
+ modes: [...modes]
93
+ };
94
+ }
95
+
96
+ export {
97
+ CAPABILITIES,
98
+ UNIFIED_MODES,
99
+ MODE_CAPABILITY,
100
+ CAPABILITY_TOOL,
101
+ expandCaps,
102
+ CapsError,
103
+ parseCaps,
104
+ resolveTools
105
+ };
106
+ //# sourceMappingURL=chunk-GV27IOMC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/caps.ts"],"sourcesContent":["/**\n * Capability gating for the MCP server (`--caps`).\n *\n * This module is deliberately side-effect free. `src/cli/index.ts` runs the\n * whole commander CLI at import time, so the parser cannot live there: a test\n * importing it would execute the CLI. Both `src/cli/index.ts` and\n * `src/mcp/server.ts` import from here instead.\n */\n\n/** Every capability name accepted by `--caps`. */\nexport const CAPABILITIES = ['scan', 'walk', 'discover', 'report', 'install'] as const;\n\nexport type Capability = (typeof CAPABILITIES)[number];\n\n/** Modes accepted by the unified `sniff` tool, in the order the enum declares them. */\nexport const UNIFIED_MODES = ['walk', 'scan', 'run', 'discover', 'report'] as const;\n\nexport type UnifiedMode = (typeof UNIFIED_MODES)[number];\n\n/**\n * The capability each unified mode needs. `run` is the legacy alias for a\n * browser audit, so it shares the `walk` capability: without it, neither the\n * unified `walk`/`run` modes nor the `sniff_run` tool are reachable.\n */\nexport const MODE_CAPABILITY: Readonly<Record<UnifiedMode, Capability>> = {\n walk: 'walk',\n scan: 'scan',\n run: 'walk',\n discover: 'discover',\n report: 'report',\n};\n\n/** The narrow tool each capability registers. */\nexport const CAPABILITY_TOOL: Readonly<Record<Capability, string>> = {\n scan: 'sniff_scan',\n walk: 'sniff_run',\n discover: 'sniff_discover',\n report: 'sniff_report',\n install: 'sniff_install',\n};\n\n/**\n * Registration order, matching what the server has always registered so the\n * default (no `--caps`) tool list stays byte-identical to earlier versions.\n */\nconst TOOL_ORDER: readonly string[] = [\n 'sniff',\n 'sniff_scan',\n 'sniff_run',\n 'sniff_discover',\n 'sniff_install',\n 'sniff_report',\n];\n\n/** Capabilities that make the unified `sniff` tool worth registering. */\nconst UNIFIED_CAPABILITIES: readonly Capability[] = ['scan', 'walk', 'discover', 'report'];\n\n/**\n * Capabilities implied by another capability.\n *\n * `walk` implies `scan`: `handleSniffWalk` degrades to a source scan when no\n * dev server is reachable (`src/mcp/handlers.ts`), and the legacy `run` mode\n * does the same. Granting `walk` therefore already grants source-scan\n * authority, so the capability set says so rather than pretending otherwise.\n */\nconst IMPLIES: Readonly<Partial<Record<Capability, readonly Capability[]>>> = {\n walk: ['scan'],\n};\n\n/** Add every capability implied by the ones granted. */\nexport function expandCaps(caps: readonly Capability[]): Capability[] {\n const out: Capability[] = [];\n const add = (c: Capability): void => {\n if (out.includes(c)) return;\n out.push(c);\n for (const implied of IMPLIES[c] ?? []) add(implied);\n };\n for (const c of caps) add(c);\n return out;\n}\n\n/** Thrown for a malformed `--caps` value, so the server can exit loudly. */\nexport class CapsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CapsError';\n }\n}\n\nfunction isCapability(value: string): value is Capability {\n return (CAPABILITIES as readonly string[]).includes(value);\n}\n\n/**\n * Read `--caps` out of an argv array. Accepts `--caps a,b` and `--caps=a,b`.\n * Returns every capability when the flag is absent, so an existing MCP config\n * keeps the tool list it has today.\n *\n * Throws `CapsError` on an unknown name or an empty list: a typo in an MCP\n * config would otherwise silently grant nothing, which is worse than a crash.\n */\nexport function parseCaps(argv: readonly string[]): Capability[] {\n let raw: string | undefined;\n\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i] as string;\n if (arg === '--caps') {\n raw = argv[i + 1];\n if (raw === undefined || raw.startsWith('-')) {\n throw new CapsError('--caps needs a comma-separated list, for example --caps scan,report');\n }\n break;\n }\n if (arg.startsWith('--caps=')) {\n raw = arg.slice('--caps='.length);\n break;\n }\n }\n\n if (raw === undefined) return [...CAPABILITIES];\n\n const names = raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);\n if (names.length === 0) {\n throw new CapsError('--caps was empty. Known capabilities: ' + CAPABILITIES.join(', '));\n }\n\n const unknown = names.filter((n) => !isCapability(n));\n if (unknown.length > 0) {\n throw new CapsError(\n `Unknown capability: ${unknown.join(', ')}. Known capabilities: ${CAPABILITIES.join(', ')}`,\n );\n }\n\n const granted: Capability[] = [];\n for (const n of names) {\n if (isCapability(n) && !granted.includes(n)) granted.push(n);\n }\n return granted;\n}\n\n/**\n * Turn a granted capability list into the tools to register and the modes the\n * unified `sniff` tool may accept.\n */\nexport function resolveTools(caps: readonly Capability[]): {\n tools: string[];\n modes: UnifiedMode[];\n} {\n const expanded = expandCaps(caps);\n const granted = new Set(expanded);\n const modes = UNIFIED_MODES.filter((m) => granted.has(MODE_CAPABILITY[m]));\n const wantsUnified = UNIFIED_CAPABILITIES.some((c) => granted.has(c));\n\n const registered = new Set<string>();\n if (wantsUnified) registered.add('sniff');\n for (const cap of expanded) registered.add(CAPABILITY_TOOL[cap]);\n\n return {\n tools: TOOL_ORDER.filter((t) => registered.has(t)),\n modes: [...modes],\n };\n}\n"],"mappings":";AAUO,IAAM,eAAe,CAAC,QAAQ,QAAQ,YAAY,UAAU,SAAS;AAKrE,IAAM,gBAAgB,CAAC,QAAQ,QAAQ,OAAO,YAAY,QAAQ;AASlE,IAAM,kBAA6D;AAAA,EACxE,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAK;AAAA,EACL,UAAU;AAAA,EACV,QAAQ;AACV;AAGO,IAAM,kBAAwD;AAAA,EACnE,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,SAAS;AACX;AAMA,IAAM,aAAgC;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,uBAA8C,CAAC,QAAQ,QAAQ,YAAY,QAAQ;AAUzF,IAAM,UAAwE;AAAA,EAC5E,MAAM,CAAC,MAAM;AACf;AAGO,SAAS,WAAW,MAA2C;AACpE,QAAM,MAAoB,CAAC;AAC3B,QAAM,MAAM,CAAC,MAAwB;AACnC,QAAI,IAAI,SAAS,CAAC,EAAG;AACrB,QAAI,KAAK,CAAC;AACV,eAAW,WAAW,QAAQ,CAAC,KAAK,CAAC,EAAG,KAAI,OAAO;AAAA,EACrD;AACA,aAAW,KAAK,KAAM,KAAI,CAAC;AAC3B,SAAO;AACT;AAGO,IAA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A,QAAM,WAAW,WAAW,IAAI;AAChC,QAAM,UAAU,IAAI,IAAI,QAAQ;AAChC,QAAM,QAAQ,cAAc,OAAO,CAAC,MAAM,QAAQ,IAAI,gBAAgB,CAAC,CAAC,CAAC;AACzE,QAAM,eAAe,qBAAqB,KAAK,CAAC,MAAM,QAAQ,IAAI,CAAC,CAAC;AAEpE,QAAM,aAAa,oBAAI,IAAY;AACnC,MAAI,aAAc,YAAW,IAAI,OAAO;AACxC,aAAW,OAAO,SAAU,YAAW,IAAI,gBAAgB,GAAG,CAAC;AAE/D,SAAO;AAAA,IACL,OAAO,WAAW,OAAO,CAAC,MAAM,WAAW,IAAI,CAAC,CAAC;AAAA,IACjD,OAAO,CAAC,GAAG,KAAK;AAAA,EAClB;AACF;","names":[]}
@@ -0,0 +1,161 @@
1
+ import {
2
+ SniffError
3
+ } from "./chunk-IXDUD2UG.js";
4
+
5
+ // src/core/redaction.ts
6
+ import { readFile } from "fs/promises";
7
+ var REDACTED = "[redacted]";
8
+ var MIN_SECRET_LENGTH = 4;
9
+ var MAX_JSON_DEPTH = 4;
10
+ var AUTH_HEADER = /(\bauthorization\b["']?\s*[:=]\s*["']?)((?:bearer|basic|token|jwt)\s+)?([^\s"'`,;)\]}]+)/gi;
11
+ function collectStrings(value, out, depth) {
12
+ if (depth > MAX_JSON_DEPTH) return;
13
+ if (typeof value === "string") {
14
+ addSecret(value, out, depth);
15
+ return;
16
+ }
17
+ if (Array.isArray(value)) {
18
+ for (const item of value) collectStrings(item, out, depth);
19
+ return;
20
+ }
21
+ if (value && typeof value === "object") {
22
+ for (const item of Object.values(value)) {
23
+ collectStrings(item, out, depth);
24
+ }
25
+ }
26
+ }
27
+ function addSecret(value, out, depth) {
28
+ const v = value.trim();
29
+ if (v.length < MIN_SECRET_LENGTH) return;
30
+ out.add(v);
31
+ const encoded = encodeURIComponent(v);
32
+ if (encoded !== v && encoded.length >= MIN_SECRET_LENGTH) out.add(encoded);
33
+ if (depth >= MAX_JSON_DEPTH) return;
34
+ const trimmed = v.trimStart();
35
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return;
36
+ try {
37
+ collectStrings(JSON.parse(v), out, depth + 1);
38
+ } catch {
39
+ }
40
+ }
41
+ function collectStorageStateSecrets(state) {
42
+ const out = /* @__PURE__ */ new Set();
43
+ if (!state || typeof state !== "object") return [];
44
+ const doc = state;
45
+ if (Array.isArray(doc.cookies)) {
46
+ for (const cookie of doc.cookies) {
47
+ if (cookie && typeof cookie === "object") {
48
+ addSecret(String(cookie.value ?? ""), out, 0);
49
+ }
50
+ }
51
+ }
52
+ if (Array.isArray(doc.origins)) {
53
+ for (const origin of doc.origins) {
54
+ if (!origin || typeof origin !== "object") continue;
55
+ const o = origin;
56
+ if (Array.isArray(o.localStorage)) {
57
+ for (const entry of o.localStorage) {
58
+ if (entry && typeof entry === "object") {
59
+ addSecret(String(entry.value ?? ""), out, 0);
60
+ }
61
+ }
62
+ }
63
+ if (o.indexedDB !== void 0) collectStrings(o.indexedDB, out, 1);
64
+ }
65
+ }
66
+ return [...out].filter((s) => s.length >= MIN_SECRET_LENGTH);
67
+ }
68
+ function createRedactor(secrets) {
69
+ const ordered = [...new Set(secrets)].filter((s) => s.length >= MIN_SECRET_LENGTH).sort((a, b) => b.length - a.length);
70
+ return (text) => {
71
+ if (typeof text !== "string" || text.length === 0) return text;
72
+ let out = text;
73
+ for (const secret of ordered) {
74
+ if (out.includes(secret)) out = out.split(secret).join(REDACTED);
75
+ }
76
+ return out.replace(AUTH_HEADER, (_m, prefix, scheme) => `${prefix}${scheme ?? ""}${REDACTED}`);
77
+ };
78
+ }
79
+ function redactDeep(value, redact) {
80
+ if (typeof value === "string") return redact(value);
81
+ if (Array.isArray(value)) {
82
+ return value.map((item) => redactDeep(item, redact));
83
+ }
84
+ if (value && typeof value === "object") {
85
+ const out = {};
86
+ for (const [k, v] of Object.entries(value)) {
87
+ out[k] = redactDeep(v, redact);
88
+ }
89
+ return out;
90
+ }
91
+ return value;
92
+ }
93
+ var active = null;
94
+ var loaded = /* @__PURE__ */ new Map();
95
+ function installRedactor(secrets) {
96
+ active = secrets.length > 0 ? createRedactor(secrets) : null;
97
+ }
98
+ function clearRedactor() {
99
+ active = null;
100
+ loaded.clear();
101
+ }
102
+ function isRedactorInstalled() {
103
+ return active !== null;
104
+ }
105
+ function redactText(text) {
106
+ return active ? active(text) : text;
107
+ }
108
+ function redactValue(value) {
109
+ return active ? redactDeep(value, active) : value;
110
+ }
111
+ async function loadStorageState(path) {
112
+ let raw;
113
+ try {
114
+ raw = await readFile(path, "utf8");
115
+ } catch (err) {
116
+ throw new SniffError(
117
+ "STORAGE_STATE_UNREADABLE",
118
+ `Cannot read the storage state at ${path}: ${err instanceof Error ? err.message : String(err)}`
119
+ );
120
+ }
121
+ let parsed;
122
+ try {
123
+ parsed = JSON.parse(raw);
124
+ } catch (err) {
125
+ throw new SniffError(
126
+ "STORAGE_STATE_INVALID",
127
+ `The storage state at ${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}. Generate one with playwright: context.storageState({ path: "auth.json" }).`
128
+ );
129
+ }
130
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
131
+ throw new SniffError(
132
+ "STORAGE_STATE_INVALID",
133
+ `The storage state at ${path} is not a Playwright storage-state object (expected { cookies, origins }).`
134
+ );
135
+ }
136
+ return parsed;
137
+ }
138
+ async function useStorageState(path) {
139
+ const cached = loaded.get(path);
140
+ if (cached) return cached;
141
+ const state = await loadStorageState(path);
142
+ loaded.set(path, state);
143
+ installRedactor(collectStorageStateSecrets(state));
144
+ return state;
145
+ }
146
+
147
+ export {
148
+ REDACTED,
149
+ MIN_SECRET_LENGTH,
150
+ collectStorageStateSecrets,
151
+ createRedactor,
152
+ redactDeep,
153
+ installRedactor,
154
+ clearRedactor,
155
+ isRedactorInstalled,
156
+ redactText,
157
+ redactValue,
158
+ loadStorageState,
159
+ useStorageState
160
+ };
161
+ //# sourceMappingURL=chunk-GX36BPK7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/redaction.ts"],"sourcesContent":["/**\n * Credential redaction for reports written after an authenticated walk.\n *\n * `--storage-state` loads a Playwright storage-state file so sniff can walk a\n * logged-in app. That file holds session cookies and bearer tokens, and sniff\n * writes HTML and JSON reports plus progress lines that quote captured URLs and\n * console text. Without this module a crawl of a logged-in app can serialize a\n * live credential into a file the user then commits.\n *\n * What this guarantees, exactly: every string of {@link MIN_SECRET_LENGTH} or\n * more characters found in the storage state (cookie values, localStorage\n * values, indexedDB values), every string leaf of any of those values that is\n * itself JSON, and the percent-encoded form of each, is replaced with\n * `[redacted]` in every text artifact sniff writes. Values shorter than the\n * floor are left alone, because replacing a two-character string would corrupt\n * unrelated report text.\n *\n * What it does not cover: screenshot pixels. A logged-in crawl renders session\n * UI into the PNGs under the report directory by design, and no string filter\n * can change that.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { SniffError } from './errors.js';\n\nexport const REDACTED = '[redacted]';\n\n/** Shorter values are skipped: redacting them would mangle unrelated text. */\nexport const MIN_SECRET_LENGTH = 4;\n\n/** Depth cap for unwrapping JSON nested inside a storage-state value. */\nconst MAX_JSON_DEPTH = 4;\n\n/**\n * `Authorization: Bearer <token>` and its JSON form. Defence in depth for a\n * header echoed into console output, whose value never passed through the\n * storage-state file and so is not in the literal set.\n */\nconst AUTH_HEADER =\n /(\\bauthorization\\b[\"']?\\s*[:=]\\s*[\"']?)((?:bearer|basic|token|jwt)\\s+)?([^\\s\"'`,;)\\]}]+)/gi;\n\n/** A parsed Playwright storage-state document. */\nexport interface StorageState {\n cookies?: unknown;\n origins?: unknown;\n}\n\nfunction collectStrings(value: unknown, out: Set<string>, depth: number): void {\n if (depth > MAX_JSON_DEPTH) return;\n if (typeof value === 'string') {\n addSecret(value, out, depth);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectStrings(item, out, depth);\n return;\n }\n if (value && typeof value === 'object') {\n for (const item of Object.values(value as Record<string, unknown>)) {\n collectStrings(item, out, depth);\n }\n }\n}\n\nfunction addSecret(value: string, out: Set<string>, depth: number): void {\n const v = value.trim();\n if (v.length < MIN_SECRET_LENGTH) return;\n out.add(v);\n\n const encoded = encodeURIComponent(v);\n if (encoded !== v && encoded.length >= MIN_SECRET_LENGTH) out.add(encoded);\n\n // A localStorage value is very often stringified JSON such as\n // {\"accessToken\":\"...\"}. The app reads the token out and uses it bare, so the\n // whole-value literal would never match what lands in a URL or a log line.\n if (depth >= MAX_JSON_DEPTH) return;\n const trimmed = v.trimStart();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return;\n try {\n collectStrings(JSON.parse(v), out, depth + 1);\n } catch {\n // Not JSON. The whole-value literal is already registered.\n }\n}\n\n/**\n * Gather every credential-bearing string from a parsed storage state.\n * Only value positions are read: cookie and origin *names*, domains and paths\n * are structural, and redacting them would mangle report text for no gain.\n */\nexport function collectStorageStateSecrets(state: unknown): string[] {\n const out = new Set<string>();\n if (!state || typeof state !== 'object') return [];\n const doc = state as StorageState;\n\n if (Array.isArray(doc.cookies)) {\n for (const cookie of doc.cookies) {\n if (cookie && typeof cookie === 'object') {\n addSecret(String((cookie as Record<string, unknown>).value ?? ''), out, 0);\n }\n }\n }\n\n if (Array.isArray(doc.origins)) {\n for (const origin of doc.origins) {\n if (!origin || typeof origin !== 'object') continue;\n const o = origin as Record<string, unknown>;\n if (Array.isArray(o.localStorage)) {\n for (const entry of o.localStorage) {\n if (entry && typeof entry === 'object') {\n addSecret(String((entry as Record<string, unknown>).value ?? ''), out, 0);\n }\n }\n }\n // Playwright can also persist indexedDB. Its shape is nested and\n // version-dependent, so walk it rather than naming fields.\n if (o.indexedDB !== undefined) collectStrings(o.indexedDB, out, 1);\n }\n }\n\n return [...out].filter((s) => s.length >= MIN_SECRET_LENGTH);\n}\n\n/**\n * Build a redactor over a secret list. Longer secrets are replaced first so a\n * value that contains another value cannot leave a fragment behind.\n */\nexport function createRedactor(secrets: readonly string[]): (text: string) => string {\n const ordered = [...new Set(secrets)]\n .filter((s) => s.length >= MIN_SECRET_LENGTH)\n .sort((a, b) => b.length - a.length);\n\n return (text: string): string => {\n if (typeof text !== 'string' || text.length === 0) return text;\n let out = text;\n for (const secret of ordered) {\n if (out.includes(secret)) out = out.split(secret).join(REDACTED);\n }\n return out.replace(AUTH_HEADER, (_m, prefix: string, scheme: string | undefined) =>\n `${prefix}${scheme ?? ''}${REDACTED}`);\n };\n}\n\n/** Deep-map every string in a JSON-shaped value through `redact`. */\nexport function redactDeep<T>(value: T, redact: (text: string) => string): T {\n if (typeof value === 'string') return redact(value) as unknown as T;\n if (Array.isArray(value)) {\n return value.map((item) => redactDeep(item, redact)) as unknown as T;\n }\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = redactDeep(v, redact);\n }\n return out as unknown as T;\n }\n return value;\n}\n\n// ── Process-level redactor ────────────────────────────────────────────────\n// Installed once when a storage state is loaded, then consulted by every\n// writer. A no-op until something is installed, so the default run is\n// untouched.\n\nlet active: ((text: string) => string) | null = null;\nconst loaded = new Map<string, StorageState>();\n\nexport function installRedactor(secrets: readonly string[]): void {\n active = secrets.length > 0 ? createRedactor(secrets) : null;\n}\n\n/** Test helper: forget the installed redactor and any cached storage state. */\nexport function clearRedactor(): void {\n active = null;\n loaded.clear();\n}\n\nexport function isRedactorInstalled(): boolean {\n return active !== null;\n}\n\n/** Redact a string. Returns it unchanged when no redactor is installed. */\nexport function redactText(text: string): string {\n return active ? active(text) : text;\n}\n\n/** Redact every string in a JSON-shaped value. No-op with no redactor. */\nexport function redactValue<T>(value: T): T {\n return active ? redactDeep(value, active) : value;\n}\n\n/**\n * Read and parse a Playwright storage-state file.\n *\n * Fails loudly on a missing or unparseable file: silently continuing would\n * produce an unauthenticated crawl that reports every page as a login wall.\n * It cannot tell an expired or wrong-domain session from a live one, and does\n * not claim to.\n */\nexport async function loadStorageState(path: string): Promise<StorageState> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n throw new SniffError(\n 'STORAGE_STATE_UNREADABLE',\n `Cannot read the storage state at ${path}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new SniffError(\n 'STORAGE_STATE_INVALID',\n `The storage state at ${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}. ` +\n 'Generate one with playwright: context.storageState({ path: \"auth.json\" }).',\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new SniffError(\n 'STORAGE_STATE_INVALID',\n `The storage state at ${path} is not a Playwright storage-state object (expected { cookies, origins }).`,\n );\n }\n return parsed as StorageState;\n}\n\n/**\n * Load a storage state once per path, install the redactor from that same\n * parsed object, and return it. Parsing once and deriving both the browser\n * context state and the secret list from the same object avoids a second read\n * that could see different bytes.\n */\nexport async function useStorageState(path: string): Promise<StorageState> {\n const cached = loaded.get(path);\n if (cached) return cached;\n const state = await loadStorageState(path);\n loaded.set(path, state);\n installRedactor(collectStorageStateSecrets(state));\n return state;\n}\n"],"mappings":";;;;;AAsBA,SAAS,gBAAgB;AAGlB,IAAM,WAAW;AAGjB,IAAM,oBAAoB;AAGjC,IAAM,iBAAiB;AAOvB,IAAM,cACJ;AAQF,SAAS,eAAe,OAAgB,KAAkB,OAAqB;AAC7E,MAAI,QAAQ,eAAgB;AAC5B,MAAI,OAAO,UAAU,UAAU;AAC7B,cAAU,OAAO,KAAK,KAAK;AAC3B;AAAA,EACF;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAW,QAAQ,MAAO,gBAAe,MAAM,KAAK,KAAK;AACzD;AAAA,EACF;AACA,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,eAAW,QAAQ,OAAO,OAAO,KAAgC,GAAG;AAClE,qBAAe,MAAM,KAAK,KAAK;AAAA,IACjC;AAAA,EACF;AACF;AAEA,SAAS,UAAU,OAAe,KAAkB,OAAq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S,OAAO,IAAI,IAAI;AACjC;AAGO,SAAS,YAAe,OAAa;AAC1C,SAAO,SAAS,WAAW,OAAO,MAAM,IAAI;AAC9C;AAUA,eAAsB,iBAAiB,MAAqC;AAC1E,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,MAAM,MAAM;AAAA,EACnC,SAAS,KAAK;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,MACA,oCAAoC,IAAI,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAC/F;AAAA,EACF;AACA,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,SAAS,KAAK;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,MACA,wBAAwB,IAAI,uBAAuB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAErG;AAAA,EACF;AACA,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAAG;AAClE,UAAM,IAAI;AAAA,MACR;AAAA,MACA,wBAAwB,IAAI;AAAA,IAC9B;AAAA,EACF;AACA,SAAO;AACT;AAQA,eAAsB,gBAAgB,MAAqC;AACzE,QAAM,SAAS,OAAO,IAAI,IAAI;AAC9B,MAAI,OAAQ,QAAO;AACnB,QAAM,QAAQ,MAAM,iBAAiB,IAAI;AACzC,SAAO,IAAI,MAAM,KAAK;AACtB,kBAAgB,2BAA2B,KAAK,CAAC;AACjD,SAAO;AACT;","names":[]}
@@ -0,0 +1,45 @@
1
+ // src/core/assert-budget.ts
2
+ var SEVERITY_KEYS = [
3
+ ["critical", "maxCritical"],
4
+ ["high", "maxHigh"],
5
+ ["medium", "maxMedium"],
6
+ ["low", "maxLow"],
7
+ ["info", "maxInfo"]
8
+ ];
9
+ var PASSED = { passed: true, violations: [] };
10
+ function evaluateSeverityBudget(findings, budget) {
11
+ if (!budget) return PASSED;
12
+ const counts = {};
13
+ for (const f of findings) {
14
+ counts[f.severity] = (counts[f.severity] ?? 0) + 1;
15
+ }
16
+ const violations = [];
17
+ for (const [severity, key] of SEVERITY_KEYS) {
18
+ const limit = budget[key];
19
+ if (limit === void 0) continue;
20
+ const actual = counts[severity] ?? 0;
21
+ if (actual > limit) {
22
+ violations.push(
23
+ `assert.${String(key)}: ${actual} ${severity} finding${actual === 1 ? "" : "s"}, budget ${limit}`
24
+ );
25
+ }
26
+ }
27
+ if (budget.maxTotal !== void 0 && findings.length > budget.maxTotal) {
28
+ violations.push(
29
+ `assert.maxTotal: ${findings.length} finding${findings.length === 1 ? "" : "s"}, budget ${budget.maxTotal}`
30
+ );
31
+ }
32
+ return violations.length === 0 ? PASSED : { passed: false, violations };
33
+ }
34
+ function printBudgetViolations(result) {
35
+ for (const line of result.violations) {
36
+ console.error(`Budget exceeded: ${line}`);
37
+ }
38
+ return result.violations.length > 0;
39
+ }
40
+
41
+ export {
42
+ evaluateSeverityBudget,
43
+ printBudgetViolations
44
+ };
45
+ //# sourceMappingURL=chunk-NG2IGCAK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/assert-budget.ts"],"sourcesContent":["import type { Severity } from './types.js';\nimport type { AssertConfig } from '../config/schema.js';\n\n/** Anything with a severity: source findings, crawl findings, scenario findings. */\nexport interface SeverityBearing {\n severity: Severity;\n}\n\nexport interface BudgetResult {\n passed: boolean;\n /** One human-readable line per breached budget, in severity order. */\n violations: string[];\n}\n\nconst SEVERITY_KEYS: ReadonlyArray<readonly [Severity, keyof AssertConfig]> = [\n ['critical', 'maxCritical'],\n ['high', 'maxHigh'],\n ['medium', 'maxMedium'],\n ['low', 'maxLow'],\n ['info', 'maxInfo'],\n];\n\nconst PASSED: BudgetResult = { passed: true, violations: [] };\n\n/**\n * Check a set of findings against the optional `assert` block from config.\n *\n * The block is additive: it can only turn a passing run into a failing one, so\n * a project without an `assert` key behaves exactly as it did before. An empty\n * block is also a pass, which keeps a partially-filled config from failing a\n * run for a key nobody set.\n */\nexport function evaluateSeverityBudget(\n findings: readonly SeverityBearing[],\n budget: AssertConfig | undefined,\n): BudgetResult {\n if (!budget) return PASSED;\n\n const counts: Partial<Record<Severity, number>> = {};\n for (const f of findings) {\n counts[f.severity] = (counts[f.severity] ?? 0) + 1;\n }\n\n const violations: string[] = [];\n\n for (const [severity, key] of SEVERITY_KEYS) {\n const limit = budget[key];\n if (limit === undefined) continue;\n const actual = counts[severity] ?? 0;\n if (actual > limit) {\n violations.push(\n `assert.${String(key)}: ${actual} ${severity} finding${actual === 1 ? '' : 's'}, budget ${limit}`,\n );\n }\n }\n\n if (budget.maxTotal !== undefined && findings.length > budget.maxTotal) {\n violations.push(\n `assert.maxTotal: ${findings.length} finding${findings.length === 1 ? '' : 's'}, budget ${budget.maxTotal}`,\n );\n }\n\n return violations.length === 0 ? PASSED : { passed: false, violations };\n}\n\n/**\n * Print each breached budget on its own line, so a CI log says exactly which\n * one blew. Returns whether anything was printed, which is the caller's cue to\n * fail the run.\n */\nexport function printBudgetViolations(result: BudgetResult): boolean {\n for (const line of result.violations) {\n console.error(`Budget exceeded: ${line}`);\n }\n return result.violations.length > 0;\n}\n"],"mappings":";AAcA,IAAM,gBAAwE;AAAA,EAC5E,CAAC,YAAY,aAAa;AAAA,EAC1B,CAAC,QAAQ,SAAS;AAAA,EAClB,CAAC,UAAU,WAAW;AAAA,EACtB,CAAC,OAAO,QAAQ;AAAA,EAChB,CAAC,QAAQ,SAAS;AACpB;AAEA,IAAM,SAAuB,EAAE,QAAQ,MAAM,YAAY,CAAC,EAAE;AAUrD,SAAS,uBACd,UACA,QACc;AACd,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,SAA4C,CAAC;AACnD,aAAW,KAAK,UAAU;AACxB,WAAO,EAAE,QAAQ,KAAK,OAAO,EAAE,QAAQ,KAAK,KAAK;AAAA,EACnD;AAEA,QAAM,aAAuB,CAAC;AAE9B,aAAW,CAAC,UAAU,GAAG,KAAK,eAAe;AAC3C,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,UAAU,OAAW;AACzB,UAAM,SAAS,OAAO,QAAQ,KAAK;AACnC,QAAI,SAAS,OAAO;AAClB,iBAAW;AAAA,QACT,UAAU,OAAO,GAAG,CAAC,KAAK,MAAM,IAAI,QAAQ,WAAW,WAAW,IAAI,KAAK,GAAG,YAAY,KAAK;AAAA,MACjG;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,aAAa,UAAa,SAAS,SAAS,OAAO,UAAU;AACtE,eAAW;AAAA,MACT,oBAAoB,SAAS,MAAM,WAAW,SAAS,WAAW,IAAI,KAAK,GAAG,YAAY,OAAO,QAAQ;AAAA,IAC3G;AAAA,EACF;AAEA,SAAO,WAAW,WAAW,IAAI,SAAS,EAAE,QAAQ,OAAO,WAAW;AACxE;AAOO,SAAS,sBAAsB,QAA+B;AACnE,aAAW,QAAQ,OAAO,YAAY;AACpC,YAAQ,MAAM,oBAAoB,IAAI,EAAE;AAAA,EAC1C;AACA,SAAO,OAAO,WAAW,SAAS;AACpC;","names":[]}
package/dist/cli/index.js CHANGED
@@ -2,23 +2,31 @@
2
2
 
3
3
  // src/cli/index.ts
4
4
  if (process.argv.includes("--mcp")) {
5
+ const { parseCaps, CapsError } = await import("../caps-G3ZGJI7B.js");
6
+ let caps;
7
+ try {
8
+ caps = parseCaps(process.argv);
9
+ } catch (err) {
10
+ console.error(err instanceof CapsError ? err.message : String(err));
11
+ process.exit(1);
12
+ }
5
13
  const { startMcpServer } = await import("../mcp/server.js");
6
- await startMcpServer();
14
+ await startMcpServer(caps);
7
15
  } else {
8
16
  const { Command } = await import("commander");
9
17
  const { ensurePlaywrightBrowsers } = await import("../ensure-browsers-AYKMLUHV.js");
10
18
  const { getVersion } = await import("../version-FLE7ZHDX.js");
11
19
  const program = new Command();
12
20
  program.name("sniff").description("AI-powered QA testing framework").version(getVersion());
13
- program.argument("[target]", "Project directory to scan (default: current directory)").option("--url <url>", "Target URL \u2014 enables full browser audit (a11y, visual, perf, runtime hooks)").option("--ci", "CI mode: headless, JUnit XML, flakiness tracking, no AI exploration").option("--no-browser", "Force source-only scan even if URL is configured").option("--explore", "Run optional AI exploration after browser checks", false).option("--no-explore", "Skip AI exploration (kept for compatibility; exploration is off by default)").option("--max-steps <n>", "Cap AI exploration steps when --explore is used (default: 50)").option("--headed", "Show the browser window (alias for --no-headless)").option("--no-headless", "Show the browser window").option("--format <formats>", "Report formats: html, json, junit (comma-separated)").option("--fail-on <severities>", "Exit non-zero on these severities (default: critical,high)", "critical,high").option("--json", "Output results as JSON").option("--report", "Write a self-contained HTML report to sniff-reports/sniff-report.html").option("--all", "Show low-confidence findings too (hidden by default)").option("--max-pages <n>", "Max pages to crawl during the flow-walk (default: 25)").option("--no-mobile", "Skip the mobile (375px) responsive pass").option("--track-flakes", "Track test flakiness across runs").option("--discover", "Run autonomous E2E discovery (scenarios + edge cases)").option("--max-scenarios <n>", "Cap total scenarios for discovery (default: 50)").option("--max-variants-per-scenario <n>", "Cap edge variants per scenario (default: 3)").option("--max-variants-per-run <n>", "Cap edge variants per run (default: 40)").option("--realism <profile>", "Discovery realism: robot, careful-user, casual-user, frustrated-user, power-user").option("--seed <n>", "Replay a specific random seed").option("--only <filter>", "Filter discovery scenarios by id substring or app type").option("--app-type <types>", "Filter discovery app types (comma-separated) \u2014 only generates scenarios for these types if the classifier matches them").option("--force-app-type <type>", "Force a single app type, bypassing the classifier entirely (use when classification returns blank)").option("--no-llm", "Disable LLM-backed discovery polish").option("--non-interactive", "Non-interactive mode for discovery (skips prompts and countdown)").option("--regenerate", "Regenerate sniff-scenarios/ before running (prompts on hand-edits)").option("--regenerate-only", "Regenerate sniff-scenarios/ and exit without running").option("--force-regenerate", "Regenerate sniff-scenarios/ and overwrite hand-edits").option("--verbose", "Print classification breakdown (top 3 guesses + matched signals per dimension)").option("--dry-run", "Discover: generate scenarios + classify without running browser or writing reports").action(async (target, options) => {
21
+ program.argument("[target]", "Project directory to scan (default: current directory)").option("--url <url>", "Target URL, enables full browser audit (a11y, visual, perf, runtime hooks)").option("--ci", "CI mode: headless, JUnit XML, flakiness tracking, no AI exploration").option("--no-browser", "Force source-only scan even if URL is configured").option("--explore", "Run optional AI exploration after browser checks", false).option("--no-explore", "Skip AI exploration (kept for compatibility; exploration is off by default)").option("--max-steps <n>", "Cap AI exploration steps when --explore is used (default: 50)").option("--headed", "Show the browser window (alias for --no-headless)").option("--no-headless", "Show the browser window").option("--format <formats>", "Report formats: html, json, junit (comma-separated)").option("--fail-on <severities>", "Exit non-zero on these severities (default: critical,high)", "critical,high").option("--json", "Output results as JSON").option("--report", "Write a self-contained HTML report to sniff-reports/sniff-report.html").option("--all", "Show low-confidence findings too (hidden by default)").option("--max-pages <n>", "Max pages to crawl during the flow-walk (default: 25)").option("--no-mobile", "Skip the mobile (375px) responsive pass").option("--storage-state <path>", "Playwright storage-state JSON, so the walk runs as a logged-in user. Cookie and token values from it are redacted from every written report.").option("--track-flakes", "Track test flakiness across runs").option("--discover", "Run autonomous E2E discovery (scenarios + edge cases)").option("--max-scenarios <n>", "Cap total scenarios for discovery (default: 50)").option("--max-variants-per-scenario <n>", "Cap edge variants per scenario (default: 3)").option("--max-variants-per-run <n>", "Cap edge variants per run (default: 40)").option("--realism <profile>", "Discovery realism: robot, careful-user, casual-user, frustrated-user, power-user").option("--seed <n>", "Replay a specific random seed").option("--only <filter>", "Filter discovery scenarios by id substring or app type").option("--app-type <types>", "Filter discovery app types (comma-separated); only generates scenarios for these types if the classifier matches them").option("--force-app-type <type>", "Force a single app type, bypassing the classifier entirely (use when classification returns blank)").option("--no-llm", "Disable LLM-backed discovery polish").option("--non-interactive", "Non-interactive mode for discovery (skips prompts and countdown)").option("--regenerate", "Regenerate sniff-scenarios/ before running (prompts on hand-edits)").option("--regenerate-only", "Regenerate sniff-scenarios/ and exit without running").option("--force-regenerate", "Regenerate sniff-scenarios/ and overwrite hand-edits").option("--verbose", "Print classification breakdown (top 3 guesses + matched signals per dimension)").option("--dry-run", "Discover: generate scenarios + classify without running browser or writing reports").action(async (target, options) => {
14
22
  const rootDir = target ? (await import("path")).resolve(target) : process.cwd();
15
23
  if (options.discover || options.regenerate || options.regenerateOnly || options.forceRegenerate || options.dryRun) {
16
- const { loadConfig: loadConfig2 } = await import("../loader-UG2XADG7.js");
24
+ const { loadConfig: loadConfig2 } = await import("../loader-Z2DUGG5Z.js");
17
25
  const config2 = await loadConfig2(rootDir);
18
26
  if (!options.regenerateOnly && !options.dryRun) {
19
27
  await ensurePlaywrightBrowsers(config2.browser?.projects);
20
28
  }
21
- const { discoverCommand } = await import("../discover-Q363YJ5X.js");
29
+ const { discoverCommand } = await import("../discover-QKGMYPHK.js");
22
30
  const appTypes = typeof options.appType === "string" ? options.appType.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
23
31
  const result = await discoverCommand({
24
32
  rootDir,
@@ -45,8 +53,8 @@ if (process.argv.includes("--mcp")) {
45
53
  });
46
54
  process.exit(result.exitCode);
47
55
  }
48
- const { unifiedCommand } = await import("../unified-67Z6YA64.js");
49
- const { loadConfig } = await import("../loader-UG2XADG7.js");
56
+ const { unifiedCommand } = await import("../unified-YSOTPG5B.js");
57
+ const { loadConfig } = await import("../loader-Z2DUGG5Z.js");
50
58
  const config = await loadConfig(rootDir);
51
59
  let url = options.url ?? config.browser?.baseUrl;
52
60
  if (!url && options.browser !== false) {
@@ -66,10 +74,13 @@ if (process.argv.includes("--mcp")) {
66
74
  const pc = (await import("picocolors")).default;
67
75
  if (wantsBrowser) {
68
76
  await ensurePlaywrightBrowsers(config.browser?.projects);
69
- const { crawlCommand } = await import("../crawl-command-3OB4IUBU.js");
77
+ const { crawlCommand } = await import("../crawl-command-RDWGHZC4.js");
78
+ const storageState = options.storageState ? (await import("path")).resolve(options.storageState) : config.browser?.storageState;
70
79
  const code = await crawlCommand({
71
80
  rootDir,
72
81
  url,
82
+ ...storageState ? { storageState } : {},
83
+ ...config.assert ? { assert: config.assert } : {},
73
84
  headless: options.headed ? false : options.headless,
74
85
  json: options.json,
75
86
  report: options.report,
@@ -84,7 +95,7 @@ if (process.argv.includes("--mcp")) {
84
95
  if (!options.json) {
85
96
  const { getDevCommand } = await import("../dev-server-detector-XQ5AYPDT.js");
86
97
  const devCmd = await getDevCommand(rootDir).catch(() => null);
87
- console.log(`${pc.yellow("No running app detected")} \u2014 no --url and no dev server.`);
98
+ console.log(`${pc.yellow("No running app detected")}: no --url and no dev server.`);
88
99
  console.log(pc.dim("Running a source-only scan. For the full flow-walk that finds real bugs,"));
89
100
  console.log(`${pc.dim(`start your app${devCmd ? ` (${devCmd})` : ""} then re-run, or pass`)} ${pc.bold("--url <url>")}${pc.dim(".")} ${pc.dim("See")} ${pc.bold("sniff doctor")}${pc.dim(".")}
90
101
  `);
@@ -109,28 +120,28 @@ if (process.argv.includes("--mcp")) {
109
120
  const { ciCommand } = await import("../ci-ISCWZJD3.js");
110
121
  await ciCommand(options);
111
122
  });
112
- program.command("scan").description("Source-only scan (no browser) \u2014 placeholder/TODO/console.log/dead links/etc.").argument("[target]", "Project directory (default: current directory)").option("--json", "Output results as JSON").option("--fail-on <severities>", "Exit non-zero on these severities (default: critical,high)", "critical,high").action(async (target, options) => {
123
+ program.command("scan").description("Source-only scan (no browser): placeholder/TODO/console.log/dead links/etc.").argument("[target]", "Project directory (default: current directory)").option("--json", "Output results as JSON").option("--fail-on <severities>", "Exit non-zero on these severities (default: critical,high)", "critical,high").action(async (target, options) => {
113
124
  const rootDir = target ? (await import("path")).resolve(target) : process.cwd();
114
- const { unifiedCommand } = await import("../unified-67Z6YA64.js");
125
+ const { unifiedCommand } = await import("../unified-YSOTPG5B.js");
115
126
  await unifiedCommand({ rootDir, explore: false, json: options.json, failOn: options.failOn });
116
127
  });
117
128
  program.command("report").description("View last scan results").option("--json", "Output as JSON").option("--format <formats>", "Regenerate report in specified formats (comma-separated: html,json,junit)").option("--output <dir>", "Output directory for regenerated reports").action(async (options) => {
118
- const { reportCommand } = await import("../report-IKRVVIW4.js");
129
+ const { reportCommand } = await import("../report-7FQFH4HW.js");
119
130
  await reportCommand(options);
120
131
  });
121
132
  program.command("update-baselines").description("Update visual regression baselines").option("--yes", "Skip confirmation prompt").action(async (options) => {
122
- const { updateBaselinesCommand } = await import("../update-baselines-UCAW3SDN.js");
133
+ const { updateBaselinesCommand } = await import("../update-baselines-JYKUUIZG.js");
123
134
  await updateBaselinesCommand(options);
124
135
  });
125
- program.command("discover").description("Run autonomous E2E discovery (scenarios + edge cases)").argument("[target]", "Project directory (default: current directory)").option("--url <url>", "Target URL (default: auto-detect dev server)").option("--ci", "CI mode: headless, robot realism, no countdown, JUnit output").option("--headed", "Show the browser window (alias for --no-headless)").option("--no-headless", "Show the browser window").option("--format <formats>", "Report formats: html, json, junit (comma-separated)").option("--json", "Output results as JSON").option("--max-scenarios <n>", "Cap total scenarios (default: 50)").option("--max-variants-per-scenario <n>", "Cap edge variants per scenario (default: 3)").option("--max-variants-per-run <n>", "Cap edge variants per run (default: 40)").option("--realism <profile>", "Realism: robot, careful-user, casual-user, frustrated-user, power-user").option("--seed <n>", "Replay a specific random seed").option("--only <filter>", "Filter scenarios by id substring or app type").option("--app-type <types>", "Filter discovery app types (comma-separated) \u2014 only generates scenarios for these types if the classifier matches them").option("--force-app-type <type>", "Force a single app type, bypassing the classifier entirely (use when classification returns blank)").option("--no-llm", "Disable LLM-backed polish").option("--non-interactive", "Skip prompts and the production-URL countdown").option("--regenerate", "Regenerate sniff-scenarios/ before running (prompts on hand-edits)").option("--regenerate-only", "Regenerate sniff-scenarios/ and exit without running").option("--force-regenerate", "Regenerate sniff-scenarios/ and overwrite hand-edits").option("--verbose", "Print classification breakdown (top 3 guesses + matched signals per dimension)").option("--dry-run", "Generate scenarios + classify without running browser or writing reports").action(async (target, options) => {
136
+ program.command("discover").description("Run autonomous E2E discovery (scenarios + edge cases)").argument("[target]", "Project directory (default: current directory)").option("--url <url>", "Target URL (default: auto-detect dev server)").option("--ci", "CI mode: headless, robot realism, no countdown, JUnit output").option("--headed", "Show the browser window (alias for --no-headless)").option("--no-headless", "Show the browser window").option("--format <formats>", "Report formats: html, json, junit (comma-separated)").option("--json", "Output results as JSON").option("--max-scenarios <n>", "Cap total scenarios (default: 50)").option("--max-variants-per-scenario <n>", "Cap edge variants per scenario (default: 3)").option("--max-variants-per-run <n>", "Cap edge variants per run (default: 40)").option("--realism <profile>", "Realism: robot, careful-user, casual-user, frustrated-user, power-user").option("--seed <n>", "Replay a specific random seed").option("--only <filter>", "Filter scenarios by id substring or app type").option("--app-type <types>", "Filter discovery app types (comma-separated); only generates scenarios for these types if the classifier matches them").option("--force-app-type <type>", "Force a single app type, bypassing the classifier entirely (use when classification returns blank)").option("--no-llm", "Disable LLM-backed polish").option("--non-interactive", "Skip prompts and the production-URL countdown").option("--regenerate", "Regenerate sniff-scenarios/ before running (prompts on hand-edits)").option("--regenerate-only", "Regenerate sniff-scenarios/ and exit without running").option("--force-regenerate", "Regenerate sniff-scenarios/ and overwrite hand-edits").option("--verbose", "Print classification breakdown (top 3 guesses + matched signals per dimension)").option("--dry-run", "Generate scenarios + classify without running browser or writing reports").action(async (target, options) => {
126
137
  if (!options.regenerateOnly && !options.dryRun) {
127
- const { loadConfig } = await import("../loader-UG2XADG7.js");
138
+ const { loadConfig } = await import("../loader-Z2DUGG5Z.js");
128
139
  const rootDir2 = target ? (await import("path")).resolve(target) : process.cwd();
129
140
  const config = await loadConfig(rootDir2);
130
141
  await ensurePlaywrightBrowsers(config.browser?.projects);
131
142
  }
132
143
  const rootDir = target ? (await import("path")).resolve(target) : process.cwd();
133
- const { discoverCommand } = await import("../discover-Q363YJ5X.js");
144
+ const { discoverCommand } = await import("../discover-QKGMYPHK.js");
134
145
  const appTypes = typeof options.appType === "string" ? options.appType.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
135
146
  const result = await discoverCommand({
136
147
  rootDir,
@@ -183,7 +194,7 @@ ${pc.bold("sniff doctor")}
183
194
  } catch {
184
195
  }
185
196
  console.log(` ${playwrightOk ? pc.green("OK") : pc.yellow("--")} Playwright ${playwrightOk ? "installed" : "not installed (auto-installs on first browser scan)"}`);
186
- const { loadConfig } = await import("../loader-UG2XADG7.js");
197
+ const { loadConfig } = await import("../loader-Z2DUGG5Z.js");
187
198
  let hasConfig = false;
188
199
  try {
189
200
  const config = await loadConfig(rootDir);