slopbrick 0.21.2 → 0.24.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.
package/dist/index.cjs CHANGED
@@ -36,7 +36,7 @@ var VERSION;
36
36
  var init_header = __esm({
37
37
  "src/types/_header.ts"() {
38
38
  "use strict";
39
- VERSION = "0.21.2";
39
+ VERSION = "0.24.0";
40
40
  }
41
41
  });
42
42
 
@@ -27622,6 +27622,267 @@ var init_import_path_mismatch = __esm({
27622
27622
  }
27623
27623
  });
27624
27624
 
27625
+ // src/rules/cpp/c-style-cast.ts
27626
+ var C_STYLE_CAST_REGEX, NAMED_CAST_PREFIX_REGEX, cppCStyleCastRule;
27627
+ var init_c_style_cast = __esm({
27628
+ "src/rules/cpp/c-style-cast.ts"() {
27629
+ "use strict";
27630
+ init_rule();
27631
+ C_STYLE_CAST_REGEX = /\(\s*(?:int|long|short|char|float|double|bool|unsigned\s+\w+|signed\s+\w+|size_t|[A-Za-z_]\w*(?:\s*[*,&][^)]*)?)\s*\)\s*(\w+|[^a-zA-Z_])/g;
27632
+ NAMED_CAST_PREFIX_REGEX = /\b(?:static|reinterpret|const|dynamic)_cast\s*<[^>]*>\s*\($/;
27633
+ cppCStyleCastRule = createRule({
27634
+ id: "cpp/c-style-cast",
27635
+ category: "typo",
27636
+ severity: "low",
27637
+ aiSpecific: true,
27638
+ description: "C-style cast `(int)x` \u2014 use static_cast / reinterpret_cast / const_cast so the kind is greppable.",
27639
+ create(_context) {
27640
+ return {};
27641
+ },
27642
+ analyze(_context, facts) {
27643
+ const issues = [];
27644
+ const source = facts.v2?._source;
27645
+ if (!source) return issues;
27646
+ if (!/\.(cpp|cc|cxx|h|hpp|hh|hxx|H)$/i.test(facts.filePath)) return issues;
27647
+ let m;
27648
+ C_STYLE_CAST_REGEX.lastIndex = 0;
27649
+ while ((m = C_STYLE_CAST_REGEX.exec(source)) !== null) {
27650
+ const innerMatch = /\(\s*([^)]+?)\s*\)/.exec(m[0]) ?? [];
27651
+ const inner = (innerMatch[1] ?? "").trim();
27652
+ const looksLikeCast = /\b(?:int|long|short|char|float|double|bool|unsigned|signed|size_t)\b/.test(inner) || /[*&]/.test(inner);
27653
+ if (!looksLikeCast) continue;
27654
+ const before = source.slice(Math.max(0, m.index - 40), m.index);
27655
+ if (NAMED_CAST_PREFIX_REGEX.test(before)) continue;
27656
+ const line = source.slice(0, m.index).split("\n").length;
27657
+ issues.push({
27658
+ ruleId: "cpp/c-style-cast",
27659
+ category: "typo",
27660
+ severity: "low",
27661
+ aiSpecific: true,
27662
+ message: `C-style cast at line ${line} \u2014 use static_cast / reinterpret_cast / const_cast`,
27663
+ line,
27664
+ column: 1,
27665
+ advice: "Use the named cast that matches the intent: `static_cast<int>(x)`, `reinterpret_cast<MyClass*>(p)`, `const_cast<...>(ref)`, or `dynamic_cast<Derived*>(base)` for runtime-checked downcasts. C-style casts silently pick whichever the compiler needs \u2014 `static_cast`, `reinterpret_cast`, OR `const_cast` \u2014 which makes them impossible to grep for and impossible to review. The C++ Core Guidelines (ES.49) call this out by name. AI agents reach for `(int)x` because of training-data C textbooks. Reference: cpp/c-style-cast v0.24."
27666
+ });
27667
+ }
27668
+ return issues;
27669
+ }
27670
+ });
27671
+ }
27672
+ });
27673
+
27674
+ // src/rules/cpp/magic-numbers.ts
27675
+ var MAGIC_NUMBER_REGEX, COMPARE_OR_RETURN_REGEX, cppMagicNumbersRule;
27676
+ var init_magic_numbers = __esm({
27677
+ "src/rules/cpp/magic-numbers.ts"() {
27678
+ "use strict";
27679
+ init_rule();
27680
+ MAGIC_NUMBER_REGEX = /\b(\d+(?:\.\d+)?)\b/g;
27681
+ COMPARE_OR_RETURN_REGEX = /\b(?:if|while|return|for)\s*[\(\s]?[^;]*[<>=!][^;]*/;
27682
+ cppMagicNumbersRule = createRule({
27683
+ id: "cpp/magic-numbers",
27684
+ category: "typo",
27685
+ severity: "low",
27686
+ aiSpecific: true,
27687
+ description: "Magic-number literal in a comparison / return \u2014 name it: `constexpr int MAX = 1024;`.",
27688
+ create(_context) {
27689
+ return {};
27690
+ },
27691
+ analyze(_context, facts) {
27692
+ const issues = [];
27693
+ const source = facts.v2?._source;
27694
+ if (!source) return issues;
27695
+ if (!/\.(cpp|cc|cxx|h|hpp|hh|hxx|H)$/i.test(facts.filePath)) return issues;
27696
+ const lines = source.split("\n");
27697
+ const allowSet = /* @__PURE__ */ new Set([
27698
+ "1024",
27699
+ "65535",
27700
+ "65536",
27701
+ "86400",
27702
+ "3600",
27703
+ "1000",
27704
+ "100.0",
27705
+ "60",
27706
+ "24",
27707
+ "7",
27708
+ "365",
27709
+ "256",
27710
+ "255",
27711
+ "0",
27712
+ "1",
27713
+ "2",
27714
+ "3",
27715
+ "4",
27716
+ "5"
27717
+ ]);
27718
+ for (let i = 0; i < lines.length; i++) {
27719
+ const line = lines[i] ?? "";
27720
+ if (!COMPARE_OR_RETURN_REGEX.test(line)) continue;
27721
+ let m;
27722
+ MAGIC_NUMBER_REGEX.lastIndex = 0;
27723
+ while ((m = MAGIC_NUMBER_REGEX.exec(line)) !== null) {
27724
+ const literal = m[0] ?? "";
27725
+ if (allowSet.has(literal)) continue;
27726
+ if (/\b(?:constexpr|const)\s+\w+\s*=\s*$/.test(line.slice(0, m.index).trimEnd())) continue;
27727
+ const prevLine = i > 0 ? lines[i - 1] ?? "" : "";
27728
+ if (/\b(?:constexpr|const)\s+\w+\s*=\s*$/.test(prevLine.trim())) continue;
27729
+ issues.push({
27730
+ ruleId: "cpp/magic-numbers",
27731
+ category: "typo",
27732
+ severity: "low",
27733
+ aiSpecific: true,
27734
+ message: `magic number ${literal} at line ${i + 1} \u2014 name it: constexpr int MAX = ${literal};`,
27735
+ line: i + 1,
27736
+ column: 1,
27737
+ advice: 'Replace the bare literal with a named constant declared as `constexpr int MAX_SIZE = 1024;` (or `static constexpr`). The named constant lives next to its value, can be searched, and forces the reader to mean what they say. Magic numbers in comparisons hide intent ("7" against what?). AI agents produce magic-number-heavy code because their training-data examples rarely bother to name the constant. Reference: cpp/magic-numbers v0.24.'
27738
+ });
27739
+ }
27740
+ }
27741
+ return issues;
27742
+ }
27743
+ });
27744
+ }
27745
+ });
27746
+
27747
+ // src/rules/cpp/printf-debug.ts
27748
+ var PRINTF_FAMILY_REGEX, COUT_LITERAL_REGEX, STD_COUT_BARE_REGEX, THRESHOLD_DEFAULT, cppPrintfDebugRule;
27749
+ var init_printf_debug = __esm({
27750
+ "src/rules/cpp/printf-debug.ts"() {
27751
+ "use strict";
27752
+ init_rule();
27753
+ PRINTF_FAMILY_REGEX = /\b(?:printf|fprintf|sprintf|snprintf)\s*\(/g;
27754
+ COUT_LITERAL_REGEX = /std\s*::\s*(?:cout|cerr|clog)\s*<<\s*"[^"]*"/g;
27755
+ STD_COUT_BARE_REGEX = /std\s*::\s*(?:cout|cerr|clog)\s*<<\s*'[^']*'/g;
27756
+ THRESHOLD_DEFAULT = 1;
27757
+ cppPrintfDebugRule = createRule({
27758
+ id: "cpp/printf-debug",
27759
+ category: "typo",
27760
+ severity: "low",
27761
+ aiSpecific: true,
27762
+ description: "printf family or std::cout debug printing \u2014 use spdlog / glog / AbslLog for level-controlled output.",
27763
+ create(_context) {
27764
+ return { threshold: THRESHOLD_DEFAULT };
27765
+ },
27766
+ analyze(context, facts) {
27767
+ const issues = [];
27768
+ const source = facts.v2?._source;
27769
+ if (!source) return issues;
27770
+ if (!/\.(cpp|cc|cxx|h|hpp|hh|hxx|H)$/i.test(facts.filePath)) return issues;
27771
+ const printfCount = (source.match(PRINTF_FAMILY_REGEX) ?? []).length;
27772
+ let viaPrintf = false;
27773
+ if (printfCount > context.threshold) {
27774
+ const line = source.indexOf("printf");
27775
+ if (line !== -1) viaPrintf = true;
27776
+ }
27777
+ const coutHit = COUT_LITERAL_REGEX.test(source) || STD_COUT_BARE_REGEX.test(source);
27778
+ if (!viaPrintf && !coutHit) return issues;
27779
+ issues.push({
27780
+ ruleId: "cpp/printf-debug",
27781
+ category: "typo",
27782
+ severity: "low",
27783
+ aiSpecific: true,
27784
+ message: viaPrintf ? `${printfCount} printf-family calls \u2014 use spdlog / glog / AbslLog` : "std::cout/cerr/clog with a string literal \u2014 use spdlog / glog / AbslLog",
27785
+ line: 1,
27786
+ column: 1,
27787
+ advice: "Replace with `spdlog::info(...)`, `LOG(INFO) << ...` (glog), or `ABSL_LOG(INFO) << ...` (Abseil). All of these are level-aware and have a configurable sink, and they route to stderr by default. `printf` / `std::cout` have no levels, no redaction, no sink routing, and can't be silenced in release builds. AI agents reach for these because their training data has countless C++ textbook examples with them. Reference: cpp/printf-debug v0.24."
27788
+ });
27789
+ return issues;
27790
+ }
27791
+ });
27792
+ }
27793
+ });
27794
+
27795
+ // src/rules/cpp/raw-new-delete.ts
27796
+ var NEW_TYPE_REGEX, DELETE_REGEX, MIN_PAIRS_DEFAULT, cppRawNewDeleteRule;
27797
+ var init_raw_new_delete = __esm({
27798
+ "src/rules/cpp/raw-new-delete.ts"() {
27799
+ "use strict";
27800
+ init_rule();
27801
+ NEW_TYPE_REGEX = /\bnew\s+[A-Za-z_]\w*\s*\(/g;
27802
+ DELETE_REGEX = /\bdelete\s+/g;
27803
+ MIN_PAIRS_DEFAULT = 1;
27804
+ cppRawNewDeleteRule = createRule({
27805
+ id: "cpp/raw-new-delete",
27806
+ category: "typo",
27807
+ severity: "low",
27808
+ aiSpecific: true,
27809
+ description: "Manual `new` / `delete` pairing \u2014 use std::make_unique / std::unique_ptr instead.",
27810
+ create(_context) {
27811
+ return { minPairs: MIN_PAIRS_DEFAULT };
27812
+ },
27813
+ analyze(context, facts) {
27814
+ const issues = [];
27815
+ const source = facts.v2?._source;
27816
+ if (!source) return issues;
27817
+ if (!/\.(cpp|cc|cxx|h|hpp|hh|hxx|H)$/i.test(facts.filePath)) return issues;
27818
+ let newCount = 0;
27819
+ let m;
27820
+ NEW_TYPE_REGEX.lastIndex = 0;
27821
+ while ((m = NEW_TYPE_REGEX.exec(source)) !== null) newCount++;
27822
+ let deleteCount = 0;
27823
+ DELETE_REGEX.lastIndex = 0;
27824
+ while ((m = DELETE_REGEX.exec(source)) !== null) deleteCount++;
27825
+ if (newCount <= context.minPairs) return issues;
27826
+ if (deleteCount <= context.minPairs) return issues;
27827
+ issues.push({
27828
+ ruleId: "cpp/raw-new-delete",
27829
+ category: "typo",
27830
+ severity: "low",
27831
+ aiSpecific: true,
27832
+ message: `manual new/delete pairing (${newCount} new, ${deleteCount} delete) \u2014 wrap in std::unique_ptr`,
27833
+ line: 1,
27834
+ column: 1,
27835
+ advice: "Replace `T* p = new T(...); ... delete p;` with `auto p = std::make_unique<T>(...);`. Smart pointers delete on scope exit, never leak on early return / exception, never double-free on copy. The C++ Core Guidelines R.20-R.23 call out raw `new` / `delete` as something to avoid in application code. AI agents reach for `new` / `delete` because their training data was written for pre-C++11 idioms. Reference: cpp/raw-new-delete v0.24."
27836
+ });
27837
+ return issues;
27838
+ }
27839
+ });
27840
+ }
27841
+ });
27842
+
27843
+ // src/rules/cpp/using-namespace-std.ts
27844
+ var USING_NAMESPACE_STD_REGEX, cppUsingNamespaceStdRule;
27845
+ var init_using_namespace_std = __esm({
27846
+ "src/rules/cpp/using-namespace-std.ts"() {
27847
+ "use strict";
27848
+ init_rule();
27849
+ USING_NAMESPACE_STD_REGEX = /\busing\s+namespace\s+std\s*;/g;
27850
+ cppUsingNamespaceStdRule = createRule({
27851
+ id: "cpp/using-namespace-std",
27852
+ category: "logic",
27853
+ severity: "medium",
27854
+ aiSpecific: true,
27855
+ description: "`using namespace std;` in a header \u2014 pollutes every consumer. Use `using std::foo;` or qualify names.",
27856
+ create(_context) {
27857
+ return {};
27858
+ },
27859
+ analyze(_context, facts) {
27860
+ const issues = [];
27861
+ const source = facts.v2?._source;
27862
+ if (!source) return issues;
27863
+ if (!/\.(cpp|cc|cxx|h|hpp|hh|hxx|H)$/i.test(facts.filePath)) return issues;
27864
+ if (!/\.(h|hpp|hh|hxx|H)$/i.test(facts.filePath)) return issues;
27865
+ let m;
27866
+ USING_NAMESPACE_STD_REGEX.lastIndex = 0;
27867
+ while ((m = USING_NAMESPACE_STD_REGEX.exec(source)) !== null) {
27868
+ const line = source.slice(0, m.index).split("\n").length;
27869
+ issues.push({
27870
+ ruleId: "cpp/using-namespace-std",
27871
+ category: "logic",
27872
+ severity: "medium",
27873
+ aiSpecific: true,
27874
+ message: `using namespace std; at line ${line} \u2014 pollutes every consumer of this header`,
27875
+ line,
27876
+ column: 1,
27877
+ advice: "Remove the directive and qualify names with `std::`, or use a targeted `using std::cout;` / `using std::string;` for the few names that recur. The C++ Core Guidelines (SF.6 / SF.7) explicitly forbid `using namespace` in header files. A single `using namespace std;` in a widely-included header pulls 200+ names into every translation unit \u2014 downstream code, name-lookup, and ADL silently change. AI agents default to `using namespace std;` because their training snippets include countless copy-pasteable textbook examples that start with it. Reference: cpp/using-namespace-std v0.24."
27878
+ });
27879
+ }
27880
+ return issues;
27881
+ }
27882
+ });
27883
+ }
27884
+ });
27885
+
27625
27886
  // src/rules/db/duplicate-index.ts
27626
27887
  function parseStatements(raw) {
27627
27888
  let result;
@@ -29663,6 +29924,534 @@ var init_identical_block = __esm({
29663
29924
  }
29664
29925
  });
29665
29926
 
29927
+ // src/engine/dedup/tokenize.ts
29928
+ function stripComments(source) {
29929
+ let out = "";
29930
+ let i = 0;
29931
+ while (i < source.length) {
29932
+ const ch = source[i];
29933
+ const next = source[i + 1];
29934
+ if (ch === "/" && next === "/") {
29935
+ while (i < source.length && source[i] !== "\n") i++;
29936
+ continue;
29937
+ }
29938
+ if (ch === "/" && next === "*") {
29939
+ i += 2;
29940
+ while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i++;
29941
+ i += 2;
29942
+ continue;
29943
+ }
29944
+ out += ch;
29945
+ i++;
29946
+ }
29947
+ return out;
29948
+ }
29949
+ function tokenize(source) {
29950
+ return source.toLowerCase().split(/[^a-z0-9_]+/u).filter((t) => t.length > 0);
29951
+ }
29952
+ function shingleHash(shingle) {
29953
+ const h = (0, import_node_crypto.createHash)("sha1").update(shingle).digest();
29954
+ return (h[0] ?? 0) << 24 | (h[1] ?? 0) << 16 | (h[2] ?? 0) << 8 | (h[3] ?? 0);
29955
+ }
29956
+ function shingleSet(source, config = {}) {
29957
+ const { k } = { ...DEFAULT_CONFIG2, ...config };
29958
+ const tokens = tokenize(stripComments(source));
29959
+ if (tokens.length === 0) return /* @__PURE__ */ new Set();
29960
+ if (tokens.length < k) {
29961
+ return /* @__PURE__ */ new Set([shingleHash(tokens.join(" "))]);
29962
+ }
29963
+ const out = /* @__PURE__ */ new Set();
29964
+ for (let i = 0; i + k <= tokens.length; i++) {
29965
+ out.add(shingleHash(tokens.slice(i, i + k).join(" ")));
29966
+ }
29967
+ return out;
29968
+ }
29969
+ var import_node_crypto, DEFAULT_CONFIG2;
29970
+ var init_tokenize = __esm({
29971
+ "src/engine/dedup/tokenize.ts"() {
29972
+ "use strict";
29973
+ import_node_crypto = require("crypto");
29974
+ DEFAULT_CONFIG2 = { k: 5 };
29975
+ }
29976
+ });
29977
+
29978
+ // src/engine/dedup/minhash.ts
29979
+ function mix64(x) {
29980
+ x ^= x >> 33n;
29981
+ x = x * 0xff51afd7ed558ccdn & 0xffffffffffffffffn;
29982
+ x ^= x >> 33n;
29983
+ x = x * 0xc4ceb9fe1a85ec53n & 0xffffffffffffffffn;
29984
+ x ^= x >> 33n;
29985
+ return x;
29986
+ }
29987
+ function bmod(a, m) {
29988
+ const r = a % m;
29989
+ return r < 0n ? r + m : r;
29990
+ }
29991
+ function hashParams(i) {
29992
+ const a = mix64(BigInt(i) * 0x9e3779b97f4a7c15n) & 0xffffffffffffffffn | 1n;
29993
+ const b = mix64(BigInt(i) * 0xbf58476d1ce4e5b9n) & 0xffffffffffffffffn;
29994
+ return [a, b];
29995
+ }
29996
+ function hashAt(i, x) {
29997
+ const [a, b] = hashParams(i);
29998
+ const xb = BigInt(x >>> 0);
29999
+ const combined = a * xb + b;
30000
+ const h = Number(bmod(combined, PRIME) & 0xffffffffn);
30001
+ return h >>> 0;
30002
+ }
30003
+ function minHash(tokens, config = {}) {
30004
+ const { numHashes } = { ...DEFAULT_CONFIG3, ...config };
30005
+ const sig = new Uint32Array(numHashes);
30006
+ sig.fill(4294967295);
30007
+ const tokenIter = tokens instanceof Set ? tokens : Array.from(tokens);
30008
+ for (const t of tokenIter) {
30009
+ for (let i = 0; i < numHashes; i++) {
30010
+ const h = hashAt(i, t);
30011
+ if (h < (sig[i] ?? 4294967295)) sig[i] = h;
30012
+ }
30013
+ }
30014
+ return sig;
30015
+ }
30016
+ function minHashSimilarity(a, b) {
30017
+ if (a.length !== b.length) {
30018
+ throw new Error(`minHashSimilarity: length mismatch ${a.length} vs ${b.length}`);
30019
+ }
30020
+ if (a.length === 0) return 1;
30021
+ let matches = 0;
30022
+ for (let i = 0; i < a.length; i++) {
30023
+ if (a[i] === b[i]) matches++;
30024
+ }
30025
+ return matches / a.length;
30026
+ }
30027
+ var import_node_crypto2, PRIME, DEFAULT_CONFIG3;
30028
+ var init_minhash = __esm({
30029
+ "src/engine/dedup/minhash.ts"() {
30030
+ "use strict";
30031
+ import_node_crypto2 = require("crypto");
30032
+ PRIME = (1n << 61n) - 1n;
30033
+ DEFAULT_CONFIG3 = {
30034
+ numHashes: 128
30035
+ };
30036
+ }
30037
+ });
30038
+
30039
+ // src/rules/dup/near-duplicate.ts
30040
+ var DEFAULT_CONTEXT, signatureCache, nearDuplicateRule;
30041
+ var init_near_duplicate = __esm({
30042
+ "src/rules/dup/near-duplicate.ts"() {
30043
+ "use strict";
30044
+ init_rule();
30045
+ init_tokenize();
30046
+ init_minhash();
30047
+ DEFAULT_CONTEXT = {
30048
+ threshold: 0.7,
30049
+ k: 5
30050
+ };
30051
+ signatureCache = /* @__PURE__ */ new Map();
30052
+ nearDuplicateRule = createRule({
30053
+ id: "dup/near-duplicate",
30054
+ category: "logic",
30055
+ severity: "medium",
30056
+ aiSpecific: true,
30057
+ description: "Near-duplicate file (Type-2 clone) \u2014 token-set Jaccard similarity > 0.7 after MinHash. Catches AI whitespace/comment refactors.",
30058
+ create(_context) {
30059
+ return { ...DEFAULT_CONTEXT };
30060
+ },
30061
+ analyze(context, facts) {
30062
+ const ctx = { ...DEFAULT_CONTEXT, ...context };
30063
+ const issues = [];
30064
+ const source = facts.v2?._source;
30065
+ if (!source) return issues;
30066
+ const filePath = facts.filePath;
30067
+ if (!filePath) return issues;
30068
+ const shingles = shingleSet(source, { k: ctx.k });
30069
+ if (shingles.size === 0) return issues;
30070
+ const sig = minHash(shingles);
30071
+ const matched = [];
30072
+ for (const [prevPath, prevSig] of signatureCache.entries()) {
30073
+ const sim = minHashSimilarity(sig, prevSig);
30074
+ if (sim >= ctx.threshold) {
30075
+ matched.push({ path: prevPath, similarity: sim });
30076
+ }
30077
+ }
30078
+ if (matched.length > 0) {
30079
+ matched.sort((a, b) => b.similarity - a.similarity);
30080
+ const best = matched[0];
30081
+ issues.push({
30082
+ ruleId: "dup/near-duplicate",
30083
+ category: "logic",
30084
+ severity: "medium",
30085
+ aiSpecific: true,
30086
+ message: `Near-duplicate of ${best.path} (Jaccard ${(best.similarity * 100).toFixed(1)}%, threshold ${(ctx.threshold * 100).toFixed(0)}%)`,
30087
+ line: 1,
30088
+ column: 1,
30089
+ advice: "Refactor to share the implementation, or rename/restructure to make the difference intentional. AI agents produce near-duplicates when iterating \u2014 this is the v0.23.0 Type-2 clone detector. Reference: dup/near-duplicate v0.23."
30090
+ });
30091
+ }
30092
+ signatureCache.set(filePath, sig);
30093
+ return issues;
30094
+ }
30095
+ });
30096
+ }
30097
+ });
30098
+
30099
+ // src/engine/dedup/lsh.ts
30100
+ var import_node_crypto3;
30101
+ var init_lsh = __esm({
30102
+ "src/engine/dedup/lsh.ts"() {
30103
+ "use strict";
30104
+ import_node_crypto3 = require("crypto");
30105
+ }
30106
+ });
30107
+
30108
+ // src/engine/dedup/structural-clone.ts
30109
+ function stripComments2(source) {
30110
+ let out = "";
30111
+ let i = 0;
30112
+ while (i < source.length) {
30113
+ const ch = source[i];
30114
+ const next = source[i + 1];
30115
+ if (ch === "/" && next === "/") {
30116
+ while (i < source.length && source[i] !== "\n") i++;
30117
+ continue;
30118
+ }
30119
+ if (ch === "/" && next === "*") {
30120
+ i += 2;
30121
+ while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i++;
30122
+ i += 2;
30123
+ continue;
30124
+ }
30125
+ out += ch;
30126
+ i++;
30127
+ }
30128
+ return out;
30129
+ }
30130
+ function canonicalTokens(source) {
30131
+ const stripped = stripComments2(source);
30132
+ const out = [];
30133
+ TOKEN_REGEX.lastIndex = 0;
30134
+ let m;
30135
+ while ((m = TOKEN_REGEX.exec(stripped)) !== null) {
30136
+ const [, ident, num, punct, dq, sq, bq] = m;
30137
+ if (ident !== void 0) {
30138
+ const lower = ident.toLowerCase();
30139
+ if (BOOL_TOKENS.has(lower)) {
30140
+ out.push("bool");
30141
+ } else if (KEYWORDS.has(lower)) {
30142
+ out.push(lower);
30143
+ } else {
30144
+ out.push("id");
30145
+ }
30146
+ continue;
30147
+ }
30148
+ if (num !== void 0) {
30149
+ out.push("num");
30150
+ continue;
30151
+ }
30152
+ if (punct !== void 0) {
30153
+ out.push(punct);
30154
+ continue;
30155
+ }
30156
+ if (dq !== void 0 || sq !== void 0 || bq !== void 0) {
30157
+ out.push("str");
30158
+ continue;
30159
+ }
30160
+ }
30161
+ return out;
30162
+ }
30163
+ function shingleHash2(shingle) {
30164
+ let h = 2166136261;
30165
+ for (let i = 0; i < shingle.length; i++) {
30166
+ h ^= shingle.charCodeAt(i);
30167
+ h = Math.imul(h, 16777619) >>> 0;
30168
+ }
30169
+ return h >>> 0;
30170
+ }
30171
+ function structuralShingles(source, config = {}) {
30172
+ const { k, minTokens } = { ...DEFAULT_STRUCTURAL_CONFIG, ...config };
30173
+ const tokens = canonicalTokens(source);
30174
+ if (tokens.length < minTokens) return /* @__PURE__ */ new Set();
30175
+ if (tokens.length < k) {
30176
+ return /* @__PURE__ */ new Set([shingleHash2(tokens.join(" "))]);
30177
+ }
30178
+ const out = /* @__PURE__ */ new Set();
30179
+ for (let i = 0; i + k <= tokens.length; i++) {
30180
+ out.add(shingleHash2(tokens.slice(i, i + k).join(" ")));
30181
+ }
30182
+ return out;
30183
+ }
30184
+ function structuralSignature(source, config = {}) {
30185
+ return minHash(structuralShingles(source, config));
30186
+ }
30187
+ var TOKEN_REGEX, BOOL_TOKENS, KEYWORDS, DEFAULT_STRUCTURAL_CONFIG;
30188
+ var init_structural_clone = __esm({
30189
+ "src/engine/dedup/structural-clone.ts"() {
30190
+ "use strict";
30191
+ init_minhash();
30192
+ init_tokenize();
30193
+ TOKEN_REGEX = /([A-Za-z_$][A-Za-z0-9_$]*)|(0[xX][0-9A-Fa-f]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?[fFdDlL]?)|([(){}\[\];,.<>=+\-*/%!&|^?:])|"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|`((?:[^`\\]|\\.)*)`/g;
30194
+ BOOL_TOKENS = /* @__PURE__ */ new Set(["true", "false", "null", "none", "nil"]);
30195
+ KEYWORDS = /* @__PURE__ */ new Set([
30196
+ // Control flow
30197
+ "if",
30198
+ "else",
30199
+ "for",
30200
+ "while",
30201
+ "do",
30202
+ "switch",
30203
+ "case",
30204
+ "default",
30205
+ "break",
30206
+ "continue",
30207
+ "return",
30208
+ "goto",
30209
+ // Declarations
30210
+ "function",
30211
+ "class",
30212
+ "interface",
30213
+ "struct",
30214
+ "enum",
30215
+ "trait",
30216
+ "def",
30217
+ "fn",
30218
+ "fun",
30219
+ "func",
30220
+ "var",
30221
+ "let",
30222
+ "const",
30223
+ "val",
30224
+ "mod",
30225
+ "use",
30226
+ "pub",
30227
+ "impl",
30228
+ "package",
30229
+ "module",
30230
+ "lambda",
30231
+ // Modifiers / visibility
30232
+ "public",
30233
+ "private",
30234
+ "protected",
30235
+ "static",
30236
+ "abstract",
30237
+ "final",
30238
+ "sealed",
30239
+ "override",
30240
+ "virtual",
30241
+ "readonly",
30242
+ "async",
30243
+ "await",
30244
+ "synchronized",
30245
+ "volatile",
30246
+ "transient",
30247
+ "native",
30248
+ "strictfp",
30249
+ "inline",
30250
+ "external",
30251
+ "export",
30252
+ "import",
30253
+ // Type system
30254
+ "type",
30255
+ "interface",
30256
+ "record",
30257
+ "object",
30258
+ "enum",
30259
+ "data",
30260
+ // Pattern / dispatch
30261
+ "match",
30262
+ "select",
30263
+ "when",
30264
+ "where",
30265
+ // Error handling
30266
+ "try",
30267
+ "catch",
30268
+ "finally",
30269
+ "throw",
30270
+ "throws",
30271
+ "raise",
30272
+ "rescue",
30273
+ "ensure",
30274
+ "except",
30275
+ // Logical connectives and tests
30276
+ "and",
30277
+ "or",
30278
+ "not",
30279
+ "in",
30280
+ "is",
30281
+ "as",
30282
+ "instanceof",
30283
+ "typeof",
30284
+ "delete",
30285
+ "void",
30286
+ "new",
30287
+ "this",
30288
+ "super",
30289
+ "self",
30290
+ "yield",
30291
+ // Misc
30292
+ "with",
30293
+ "without",
30294
+ "pass",
30295
+ "assert",
30296
+ "mut",
30297
+ "move",
30298
+ "ref",
30299
+ "out",
30300
+ "params",
30301
+ "operator",
30302
+ "sizeof",
30303
+ "typedef",
30304
+ "union",
30305
+ "register",
30306
+ "extern",
30307
+ "volatile",
30308
+ "goto",
30309
+ // Python-specific
30310
+ "elif",
30311
+ "global",
30312
+ "nonlocal",
30313
+ "del",
30314
+ "with",
30315
+ // Ruby-specific
30316
+ "unless",
30317
+ "until",
30318
+ "begin",
30319
+ "next",
30320
+ "then",
30321
+ "end",
30322
+ "alias",
30323
+ "defined",
30324
+ "super",
30325
+ "yield",
30326
+ "self",
30327
+ // Kotlin-specific
30328
+ "suspend",
30329
+ "lateinit",
30330
+ "companion",
30331
+ "internal",
30332
+ "open",
30333
+ // Rust-specific
30334
+ "unsafe",
30335
+ "dyn",
30336
+ "box",
30337
+ "crate",
30338
+ "where",
30339
+ // Swift-specific
30340
+ "guard",
30341
+ "defer",
30342
+ "repeat",
30343
+ "init",
30344
+ "deinit",
30345
+ "extension",
30346
+ "protocol",
30347
+ "throws",
30348
+ "rethrows",
30349
+ "weak",
30350
+ "unowned",
30351
+ "lazy"
30352
+ ]);
30353
+ DEFAULT_STRUCTURAL_CONFIG = {
30354
+ k: 8,
30355
+ minTokens: 60
30356
+ };
30357
+ }
30358
+ });
30359
+
30360
+ // src/engine/dedup/index.ts
30361
+ var init_dedup = __esm({
30362
+ "src/engine/dedup/index.ts"() {
30363
+ "use strict";
30364
+ init_tokenize();
30365
+ init_minhash();
30366
+ init_lsh();
30367
+ init_structural_clone();
30368
+ }
30369
+ });
30370
+
30371
+ // src/rules/dup/structural-clone.ts
30372
+ var DEFAULT_CONTEXT2, structuralCache, identifierCache, structuralCloneRule;
30373
+ var init_structural_clone2 = __esm({
30374
+ "src/rules/dup/structural-clone.ts"() {
30375
+ "use strict";
30376
+ init_rule();
30377
+ init_dedup();
30378
+ DEFAULT_CONTEXT2 = {
30379
+ structuralThreshold: 0.55,
30380
+ verifyThreshold: 0.45,
30381
+ kStruct: 8,
30382
+ kIdent: 5,
30383
+ minTokens: 60,
30384
+ minHits: 1
30385
+ };
30386
+ structuralCache = /* @__PURE__ */ new Map();
30387
+ identifierCache = /* @__PURE__ */ new Map();
30388
+ structuralCloneRule = createRule({
30389
+ id: "dup/structural-clone",
30390
+ category: "logic",
30391
+ severity: "medium",
30392
+ aiSpecific: true,
30393
+ defaultOff: true,
30394
+ description: "Structural clone (Type-3) \u2014 same shape after identifier canonicalization with possible added/removed statements. Two-stage MinHash: canonical + identifier.",
30395
+ create(_context) {
30396
+ return { ...DEFAULT_CONTEXT2 };
30397
+ },
30398
+ analyze(context, facts) {
30399
+ const ctx = { ...DEFAULT_CONTEXT2, ...context };
30400
+ const issues = [];
30401
+ const source = facts.v2?._source;
30402
+ if (!source) return issues;
30403
+ const filePath = facts.filePath;
30404
+ if (!filePath) return issues;
30405
+ const sigStruct = structuralSignature(source, {
30406
+ k: ctx.kStruct,
30407
+ minTokens: ctx.minTokens
30408
+ });
30409
+ if (sigStruct.every((v) => v === 4294967295)) return issues;
30410
+ const identShingles = shingleSet(source, { k: ctx.kIdent });
30411
+ if (identShingles.size === 0) return issues;
30412
+ const sigIdent = minHash(identShingles);
30413
+ const matched = [];
30414
+ for (const [prevPath, prevStruct] of structuralCache.entries()) {
30415
+ if (prevPath === filePath) continue;
30416
+ const simStruct = minHashSimilarity(sigStruct, prevStruct);
30417
+ if (simStruct < ctx.structuralThreshold) continue;
30418
+ const prevIdent = identifierCache.get(prevPath);
30419
+ if (!prevIdent) continue;
30420
+ const simIdent = minHashSimilarity(sigIdent, prevIdent);
30421
+ if (simIdent <= 0) continue;
30422
+ const score = 2 * simStruct * simIdent / (simStruct + simIdent + 1e-9);
30423
+ if (score >= ctx.verifyThreshold) {
30424
+ matched.push({ path: prevPath, score, simStruct, simIdent });
30425
+ }
30426
+ }
30427
+ if (matched.length >= ctx.minHits) {
30428
+ matched.sort((a, b) => b.score - a.score);
30429
+ const best = matched[0];
30430
+ issues.push({
30431
+ ruleId: "dup/structural-clone",
30432
+ category: "logic",
30433
+ severity: "medium",
30434
+ aiSpecific: true,
30435
+ message: `Structural clone of ${best.path} (canonical Jaccard ${(best.simStruct * 100).toFixed(1)}%, identifier Jaccard ${(best.simIdent * 100).toFixed(1)}%, blend ${(best.score * 100).toFixed(1)}% \u2014 threshold ${(ctx.verifyThreshold * 100).toFixed(0)}%)`,
30436
+ line: 1,
30437
+ column: 1,
30438
+ advice: "Refactor to a shared helper. This is a Type-3 clone \u2014 two files share canonical shape after identifier normalization and likely a few added/removed statements. AI agents produce Type-3 clones when iterating on a function: same control flow, different names, a few lines added. (v0.24.0 \u2014 two-stage MinHash on canonical k=8 + identifier k=5 shingles.)",
30439
+ extras: {
30440
+ structuralDuplicateOf: {
30441
+ file: best.path,
30442
+ score: best.score
30443
+ }
30444
+ }
30445
+ });
30446
+ }
30447
+ structuralCache.set(filePath, sigStruct);
30448
+ identifierCache.set(filePath, sigIdent);
30449
+ return issues;
30450
+ }
30451
+ });
30452
+ }
30453
+ });
30454
+
29666
30455
  // src/rules/go/error-wrap-without-context.ts
29667
30456
  var ERR_WRAP_REGEX, GENERIC_PREFIX_REGEX, goErrorWrapWithoutContextRule;
29668
30457
  var init_error_wrap_without_context = __esm({
@@ -30132,6 +30921,264 @@ var init_system_out_println = __esm({
30132
30921
  }
30133
30922
  });
30134
30923
 
30924
+ // src/rules/kotlin/coroutine-global-scope.ts
30925
+ var GLOBAL_SCOPE_REGEX, kotlinCoroutineGlobalScopeRule;
30926
+ var init_coroutine_global_scope = __esm({
30927
+ "src/rules/kotlin/coroutine-global-scope.ts"() {
30928
+ "use strict";
30929
+ init_rule();
30930
+ GLOBAL_SCOPE_REGEX = /GlobalScope\s*\.\s*(?:launch|async|runBlocking)\s*[({]/g;
30931
+ kotlinCoroutineGlobalScopeRule = createRule({
30932
+ id: "kotlin/coroutine-global-scope",
30933
+ category: "logic",
30934
+ severity: "medium",
30935
+ aiSpecific: true,
30936
+ description: "GlobalScope.launch/async/runBlocking \u2014 bypasses structured concurrency. Use viewModelScope / lifecycleScope / coroutineScope {}.",
30937
+ create(_context) {
30938
+ return {};
30939
+ },
30940
+ analyze(_context, facts) {
30941
+ const issues = [];
30942
+ const source = facts.v2?._source;
30943
+ if (!source) return issues;
30944
+ if (!/\.kt$/i.test(facts.filePath)) return issues;
30945
+ let m;
30946
+ GLOBAL_SCOPE_REGEX.lastIndex = 0;
30947
+ while ((m = GLOBAL_SCOPE_REGEX.exec(source)) !== null) {
30948
+ const line = source.slice(0, m.index).split("\n").length;
30949
+ issues.push({
30950
+ ruleId: "kotlin/coroutine-global-scope",
30951
+ category: "logic",
30952
+ severity: "medium",
30953
+ aiSpecific: true,
30954
+ message: `GlobalScope.${m[0].split(".")[1]?.split("(")[0]}() at line ${line} \u2014 bypasses structured concurrency`,
30955
+ line,
30956
+ column: 1,
30957
+ advice: 'Replace with `viewModelScope.launch { ... }` (Android view models), `lifecycleScope.launch { ... }` (Android activities / fragments), or `coroutineScope { ... }` inside a suspending function. GlobalScope bypasses cancellation, exception propagation, and lifetime binding. The kotlinx.coroutines docs explicitly call GlobalScope "delicate API". AI agents default to it for "fire-and-forget" work because of training-data snippets. Reference: kotlin/coroutine-global-scope v0.24.'
30958
+ });
30959
+ }
30960
+ return issues;
30961
+ }
30962
+ });
30963
+ }
30964
+ });
30965
+
30966
+ // src/rules/kotlin/data-class-defaults-overuse.ts
30967
+ var DATA_CLASS_HEAD_REGEX, DEFAULT_PARAM_REGEX, DEFAULT_MIN_DEFAULTS, kotlinDataClassDefaultsOveruseRule;
30968
+ var init_data_class_defaults_overuse = __esm({
30969
+ "src/rules/kotlin/data-class-defaults-overuse.ts"() {
30970
+ "use strict";
30971
+ init_rule();
30972
+ DATA_CLASS_HEAD_REGEX = /\bdata\s+class\s+\w+\s*\(/g;
30973
+ DEFAULT_PARAM_REGEX = /=\s*(?:null|true|false|"[^"]*"|'[^']*'|[+-]?\d+(?:\.\d+)?\w*|emptyList\(\)|emptyMap\(\)|emptySet\(\)|listOf\(\)|mapOf\(\)|setOf\(\))/g;
30974
+ DEFAULT_MIN_DEFAULTS = 3;
30975
+ kotlinDataClassDefaultsOveruseRule = createRule({
30976
+ id: "kotlin/data-class-defaults-overuse",
30977
+ category: "typo",
30978
+ severity: "low",
30979
+ aiSpecific: true,
30980
+ description: "data class with 3+ literal defaults \u2014 AI defaults every field rather than only the genuinely optional ones",
30981
+ create(_context) {
30982
+ return { minDefaults: DEFAULT_MIN_DEFAULTS };
30983
+ },
30984
+ analyze(context, facts) {
30985
+ const issues = [];
30986
+ const source = facts.v2?._source;
30987
+ if (!source) return issues;
30988
+ if (!/\.kt$/i.test(facts.filePath)) return issues;
30989
+ let m;
30990
+ DATA_CLASS_HEAD_REGEX.lastIndex = 0;
30991
+ while ((m = DATA_CLASS_HEAD_REGEX.exec(source)) !== null) {
30992
+ const headStart = m.index;
30993
+ const openParen = source.indexOf("(", headStart);
30994
+ if (openParen === -1) continue;
30995
+ let depth = 1;
30996
+ let i = openParen + 1;
30997
+ while (i < source.length && depth > 0) {
30998
+ const ch = source.charAt(i);
30999
+ if (ch === "(") depth++;
31000
+ else if (ch === ")") depth--;
31001
+ i++;
31002
+ }
31003
+ if (depth !== 0) continue;
31004
+ const paramBlock = source.slice(openParen + 1, i - 1);
31005
+ DEFAULT_PARAM_REGEX.lastIndex = 0;
31006
+ let defaults = 0;
31007
+ let dm;
31008
+ while ((dm = DEFAULT_PARAM_REGEX.exec(paramBlock)) !== null) {
31009
+ defaults++;
31010
+ }
31011
+ if (defaults < context.minDefaults) continue;
31012
+ const line = source.slice(0, headStart).split("\n").length;
31013
+ issues.push({
31014
+ ruleId: "kotlin/data-class-defaults-overuse",
31015
+ category: "typo",
31016
+ severity: "low",
31017
+ aiSpecific: true,
31018
+ message: `data class with ${defaults} literal defaults at line ${line} \u2014 only optional fields should have defaults`,
31019
+ line,
31020
+ column: 1,
31021
+ advice: "Audit which fields are genuinely optional. Real Kotlin uses defaults sparingly (1-2 callbacks, the rest required). Defaulting every field makes the no-arg constructor callable for every data class and obscures intent. AI agents default every field because they imitate Java/Swift optional patterns. Reference: kotlin/data-class-defaults-overuse v0.24."
31022
+ });
31023
+ }
31024
+ return issues;
31025
+ }
31026
+ });
31027
+ }
31028
+ });
31029
+
31030
+ // src/rules/kotlin/object-singleton-misuse.ts
31031
+ var OBJECT_DECL_REGEX, kotlinObjectSingletonMisuseRule;
31032
+ var init_object_singleton_misuse = __esm({
31033
+ "src/rules/kotlin/object-singleton-misuse.ts"() {
31034
+ "use strict";
31035
+ init_rule();
31036
+ OBJECT_DECL_REGEX = /\bobject\s+(?!\w*Companion\b)(\w+)\s*\{/g;
31037
+ kotlinObjectSingletonMisuseRule = createRule({
31038
+ id: "kotlin/object-singleton-misuse",
31039
+ category: "logic",
31040
+ severity: "medium",
31041
+ aiSpecific: true,
31042
+ description: "Kotlin object singleton holding mutable `var` state \u2014 hidden shared state. Use DI or a repository.",
31043
+ create(_context) {
31044
+ return {};
31045
+ },
31046
+ analyze(_context, facts) {
31047
+ const issues = [];
31048
+ const source = facts.v2?._source;
31049
+ if (!source) return issues;
31050
+ if (!/\.kt$/i.test(facts.filePath)) return issues;
31051
+ let m;
31052
+ OBJECT_DECL_REGEX.lastIndex = 0;
31053
+ while ((m = OBJECT_DECL_REGEX.exec(source)) !== null) {
31054
+ const declStart = m.index;
31055
+ const openBrace = source.indexOf("{", declStart);
31056
+ if (openBrace === -1) continue;
31057
+ let depth = 1;
31058
+ let i = openBrace + 1;
31059
+ while (i < source.length && depth > 0) {
31060
+ const ch = source.charAt(i);
31061
+ if (ch === "{") depth++;
31062
+ else if (ch === "}") depth--;
31063
+ i++;
31064
+ }
31065
+ if (depth !== 0) continue;
31066
+ const body = source.slice(openBrace + 1, i - 1);
31067
+ if (!/\bvar\s+\w+\s*[:=]/m.test(body)) continue;
31068
+ const line = source.slice(0, declStart).split("\n").length;
31069
+ const name = m[1] ?? "<unknown>";
31070
+ issues.push({
31071
+ ruleId: "kotlin/object-singleton-misuse",
31072
+ category: "logic",
31073
+ severity: "medium",
31074
+ aiSpecific: true,
31075
+ message: `object ${name} at line ${line} holds mutable state \u2014 singleton + var = hidden shared state`,
31076
+ line,
31077
+ column: 1,
31078
+ advice: "Replace with a class injected via DI, a Repository, or a `MutableStateFlow` with explicit synchronization. The Kotlin `object` keyword gives you a thread-safe singleton handle, but it does NOT make `var` fields inside that singleton thread-safe \u2014 mutable singleton state is a classic source of race conditions. AI agents reach for `object Cache { var data = ... }` because their training snippets make it look natural. Reference: kotlin/object-singleton-misuse v0.24."
31079
+ });
31080
+ }
31081
+ return issues;
31082
+ }
31083
+ });
31084
+ }
31085
+ });
31086
+
31087
+ // src/rules/kotlin/println-debug.ts
31088
+ var PRINTLN_REGEX2, DEFAULT_THRESHOLD2, kotlinPrintlnDebugRule;
31089
+ var init_println_debug = __esm({
31090
+ "src/rules/kotlin/println-debug.ts"() {
31091
+ "use strict";
31092
+ init_rule();
31093
+ PRINTLN_REGEX2 = /^\s*println\s*\(/gm;
31094
+ DEFAULT_THRESHOLD2 = 1;
31095
+ kotlinPrintlnDebugRule = createRule({
31096
+ id: "kotlin/println-debug",
31097
+ category: "typo",
31098
+ severity: "low",
31099
+ aiSpecific: true,
31100
+ description: "println(...) in production code \u2014 use Timber, android.util.Log, or an SLF4J facade",
31101
+ create(_context) {
31102
+ return { threshold: DEFAULT_THRESHOLD2 };
31103
+ },
31104
+ analyze(context, facts) {
31105
+ const issues = [];
31106
+ const source = facts.v2?._source;
31107
+ if (!source) return issues;
31108
+ if (!/\.kt$/i.test(facts.filePath)) return issues;
31109
+ const matches = [];
31110
+ let m;
31111
+ PRINTLN_REGEX2.lastIndex = 0;
31112
+ while ((m = PRINTLN_REGEX2.exec(source)) !== null) {
31113
+ matches.push(m.index);
31114
+ }
31115
+ if (matches.length <= context.threshold) return issues;
31116
+ const cap = Math.min(matches.length, 10);
31117
+ for (let i = 0; i < cap; i++) {
31118
+ const idx = matches[i];
31119
+ const line = source.slice(0, idx).split("\n").length;
31120
+ issues.push({
31121
+ ruleId: "kotlin/println-debug",
31122
+ category: "typo",
31123
+ severity: "low",
31124
+ aiSpecific: true,
31125
+ message: `println(...) at line ${line} \u2014 use Timber or android.util.Log for production output`,
31126
+ line,
31127
+ column: 1,
31128
+ advice: "Replace with `Timber.plant(Timber.DebugTree())` then `Timber.d(...)`, or with an SLF4J facade. `println` writes to stdout with no level / no redaction and cannot be silenced in production. Multiple `println` calls in one file is an AI fingerprint \u2014 agents default to it because their training data has many copy-pasteable Kotlin examples. A single println in a `main` function is fine; 2+ is not. Reference: kotlin/println-debug v0.24."
31129
+ });
31130
+ }
31131
+ return issues;
31132
+ }
31133
+ });
31134
+ }
31135
+ });
31136
+
31137
+ // src/rules/kotlin/string-concat-loop.ts
31138
+ var STRING_CONCAT_REGEX2, kotlinStringConcatLoopRule;
31139
+ var init_string_concat_loop2 = __esm({
31140
+ "src/rules/kotlin/string-concat-loop.ts"() {
31141
+ "use strict";
31142
+ init_rule();
31143
+ STRING_CONCAT_REGEX2 = /\b(\w+)\s*=\s*\1\s*\+\s*[^;}]+[;}\n]/g;
31144
+ kotlinStringConcatLoopRule = createRule({
31145
+ id: "kotlin/string-concat-loop",
31146
+ category: "perf",
31147
+ severity: "low",
31148
+ aiSpecific: true,
31149
+ description: "String concatenation in a loop \u2014 use buildString { ... } or a StringBuilder",
31150
+ create(_context) {
31151
+ return {};
31152
+ },
31153
+ analyze(_context, facts) {
31154
+ const issues = [];
31155
+ const source = facts.v2?._source;
31156
+ if (!source) return issues;
31157
+ if (!/\.kt$/i.test(facts.filePath)) return issues;
31158
+ if (!/\b(?:for|while|repeat|forEach)\b/.test(source)) return issues;
31159
+ let m;
31160
+ STRING_CONCAT_REGEX2.lastIndex = 0;
31161
+ while ((m = STRING_CONCAT_REGEX2.exec(source)) !== null) {
31162
+ const line = source.slice(0, m.index).split("\n").length;
31163
+ const lineText = source.slice(0, m.index).split("\n").pop() ?? "";
31164
+ if (/\.append\s*\(/.test(lineText)) continue;
31165
+ issues.push({
31166
+ ruleId: "kotlin/string-concat-loop",
31167
+ category: "perf",
31168
+ severity: "low",
31169
+ aiSpecific: true,
31170
+ message: `String concatenation in a loop at line ${line} \u2014 use buildString { ... }`,
31171
+ line,
31172
+ column: 1,
31173
+ advice: "Wrap the loop in `buildString { append(...) }` or declare a `StringBuilder` outside the loop. Kotlin cannot optimize `s = s + x` inside a loop \u2014 each iteration allocates a new StringBuilder, making the whole thing O(n\xB2) for n iterations. AI agents concatenate inside loops because of training-data examples. Reference: kotlin/string-concat-loop v0.24."
31174
+ });
31175
+ }
31176
+ return issues;
31177
+ }
31178
+ });
31179
+ }
31180
+ });
31181
+
30135
31182
  // src/rules/layout/gap-monopoly.ts
30136
31183
  var GAP_RE, gapMonopolyRule;
30137
31184
  var init_gap_monopoly = __esm({
@@ -38028,7 +39075,7 @@ var init_css_bloat = __esm({
38028
39075
  function stripNoise2(source) {
38029
39076
  return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "").replace(/'(?:\\.|[^'\\])*'/g, "''").replace(/"(?:\\.|[^"\\])*"/g, '""').replace(/`(?:\\.|[^`\\])*`/g, "``");
38030
39077
  }
38031
- function tokenize(source) {
39078
+ function tokenize2(source) {
38032
39079
  const cleaned = stripNoise2(source);
38033
39080
  const operators = [];
38034
39081
  const operands = [];
@@ -38049,7 +39096,7 @@ function tokenize(source) {
38049
39096
  return { operators, operands };
38050
39097
  }
38051
39098
  function computeHalstead(source) {
38052
- const { operators, operands } = tokenize(source);
39099
+ const { operators, operands } = tokenize2(source);
38053
39100
  const uniqueOperators = new Set(operators);
38054
39101
  const uniqueOperands = new Set(operands);
38055
39102
  const n1 = uniqueOperators.size;
@@ -39615,6 +40662,260 @@ var init_unsafe_html_render = __esm({
39615
40662
  }
39616
40663
  });
39617
40664
 
40665
+ // src/rules/swift/fatal-error-thrown.ts
40666
+ var FATAL_REGEX, swiftFatalErrorThrownRule;
40667
+ var init_fatal_error_thrown = __esm({
40668
+ "src/rules/swift/fatal-error-thrown.ts"() {
40669
+ "use strict";
40670
+ init_rule();
40671
+ FATAL_REGEX = /\b(?:fatalError|preconditionFailure)\s*\(/g;
40672
+ swiftFatalErrorThrownRule = createRule({
40673
+ id: "swift/fatal-error-thrown",
40674
+ category: "logic",
40675
+ severity: "high",
40676
+ aiSpecific: true,
40677
+ description: "fatalError / preconditionFailure in production \u2014 crashes unconditionally. Return an error or a typed default.",
40678
+ create(_context) {
40679
+ return {};
40680
+ },
40681
+ analyze(_context, facts) {
40682
+ const issues = [];
40683
+ const source = facts.v2?._source;
40684
+ if (!source) return issues;
40685
+ if (!/\.swift$/i.test(facts.filePath)) return issues;
40686
+ if (/\bimport\s+XCTest\b/.test(source)) return issues;
40687
+ let m;
40688
+ FATAL_REGEX.lastIndex = 0;
40689
+ while ((m = FATAL_REGEX.exec(source)) !== null) {
40690
+ const line = source.slice(0, m.index).split("\n").length;
40691
+ const matched = m[0].replace(/\s*\($/, "");
40692
+ issues.push({
40693
+ ruleId: "swift/fatal-error-thrown",
40694
+ category: "logic",
40695
+ severity: "high",
40696
+ aiSpecific: true,
40697
+ message: `${matched}() at line ${line} \u2014 crashes unconditionally in release builds`,
40698
+ line,
40699
+ column: 1,
40700
+ advice: 'Replace with `return` of a typed default (e.g. `nil`, `[]()`), or throw a typed error (`enum MyError: Error { case notImplemented }; throw MyError.notImplemented`). Apple\'s docs contrast `fatalError` (survives release) with `precondition` (debug+checked only) and `assert` (debug only). AI agents plant `fatalError("not implemented")` in protocol stubs because the pattern "makes the file compile" while signalling TODO. Survives App Store review. Reference: swift/fatal-error-thrown v0.24.'
40701
+ });
40702
+ }
40703
+ return issues;
40704
+ }
40705
+ });
40706
+ }
40707
+ });
40708
+
40709
+ // src/rules/swift/force-unwrap.ts
40710
+ var AS_FORCE_REGEX, ACCESS_FORCE_REGEX, TRY_FORCE_REGEX, swiftForceUnwrapRule;
40711
+ var init_force_unwrap = __esm({
40712
+ "src/rules/swift/force-unwrap.ts"() {
40713
+ "use strict";
40714
+ init_rule();
40715
+ AS_FORCE_REGEX = /\bas!\s+/g;
40716
+ ACCESS_FORCE_REGEX = /(?:\w|\])\!\s*(?:\.|\(|;|,|\s*$)/gm;
40717
+ TRY_FORCE_REGEX = /\btry!\s+/g;
40718
+ swiftForceUnwrapRule = createRule({
40719
+ id: "swift/force-unwrap",
40720
+ category: "logic",
40721
+ severity: "medium",
40722
+ aiSpecific: true,
40723
+ description: "Swift force-unwrap (as!, var!.prop, try!) \u2014 silently crashes if the value is nil. Use as? / guard let / try?.",
40724
+ create(_context) {
40725
+ return {};
40726
+ },
40727
+ analyze(_context, facts) {
40728
+ const issues = [];
40729
+ const source = facts.v2?._source;
40730
+ if (!source) return issues;
40731
+ if (!/\.swift$/i.test(facts.filePath)) return issues;
40732
+ if (/\bimport\s+XCTest\b/.test(source)) return issues;
40733
+ const emit = (idx, label) => {
40734
+ const line = source.slice(0, idx).split("\n").length;
40735
+ issues.push({
40736
+ ruleId: "swift/force-unwrap",
40737
+ category: "logic",
40738
+ severity: "medium",
40739
+ aiSpecific: true,
40740
+ message: `force-unwrap (${label}) at line ${line} \u2014 crashes if the value is nil`,
40741
+ line,
40742
+ column: 1,
40743
+ advice: 'Replace with the safe form: `as?` + guard/if let, `try?` + nil-check, or `guard let x = optional else { return }` instead of `x!`. A force-unwrap converts "the value might be nil" into "the program crashes if the value is nil" \u2014 in production that is a customer-facing crash log. AI agents reach for `!` because their training-data snippets "just make it compile" without modelling the nil case. Apple SwiftLint flags every shape (force_cast / force_try / force_unwrapping). Reference: swift/force-unwrap v0.24.'
40744
+ });
40745
+ };
40746
+ let m;
40747
+ AS_FORCE_REGEX.lastIndex = 0;
40748
+ while ((m = AS_FORCE_REGEX.exec(source)) !== null) emit(m.index, "as!");
40749
+ TRY_FORCE_REGEX.lastIndex = 0;
40750
+ while ((m = TRY_FORCE_REGEX.exec(source)) !== null) emit(m.index, "try!");
40751
+ ACCESS_FORCE_REGEX.lastIndex = 0;
40752
+ while ((m = ACCESS_FORCE_REGEX.exec(source)) !== null) emit(m.index, "!.");
40753
+ return issues;
40754
+ }
40755
+ });
40756
+ }
40757
+ });
40758
+
40759
+ // src/rules/swift/implicitly-unwrapped-optional.ts
40760
+ var IUO_DECL_REGEX, swiftImplicitlyUnwrappedOptionalRule;
40761
+ var init_implicitly_unwrapped_optional = __esm({
40762
+ "src/rules/swift/implicitly-unwrapped-optional.ts"() {
40763
+ "use strict";
40764
+ init_rule();
40765
+ IUO_DECL_REGEX = /\b(?:var|let)\s+\w+\s*:\s*[A-Za-z_][\w<>?,\.\s]*!\s*[=;\n]/g;
40766
+ swiftImplicitlyUnwrappedOptionalRule = createRule({
40767
+ id: "swift/implicitly-unwrapped-optional",
40768
+ category: "typo",
40769
+ severity: "low",
40770
+ aiSpecific: true,
40771
+ description: "Implicitly unwrapped optional (var x: Type!) \u2014 declare as Type? and unwrap with guard let.",
40772
+ create(_context) {
40773
+ return {};
40774
+ },
40775
+ analyze(_context, facts) {
40776
+ const issues = [];
40777
+ const source = facts.v2?._source;
40778
+ if (!source) return issues;
40779
+ if (!/\.swift$/i.test(facts.filePath)) return issues;
40780
+ let m;
40781
+ IUO_DECL_REGEX.lastIndex = 0;
40782
+ while ((m = IUO_DECL_REGEX.exec(source)) !== null) {
40783
+ const captured = m[0];
40784
+ const bangAt = captured.indexOf("!", captured.indexOf(":"));
40785
+ const between = captured.slice(captured.indexOf(":"), bangAt);
40786
+ if (between.includes("?")) continue;
40787
+ const line = source.slice(0, m.index).split("\n").length;
40788
+ issues.push({
40789
+ ruleId: "swift/implicitly-unwrapped-optional",
40790
+ category: "typo",
40791
+ severity: "low",
40792
+ aiSpecific: true,
40793
+ message: `implicitly unwrapped optional at line ${line} \u2014 declare as Type? and unwrap explicitly`,
40794
+ line,
40795
+ column: 1,
40796
+ advice: 'Declare as `var name: Type?` and unwrap with `guard let name else { ... }` (or `if let`). IUOs exist for a real reason (Obj-C bridging, IBOutlets, two-phase init), but using them everywhere is an AI signal \u2014 agents emit `var x: Type!` because the syntax survives the moment when the agent can\'t decide whether the value is nil. The type system silently says "non-optional" while the runtime says "may be nil". Apple SwiftLint\'s `implicitly_unwrapped_optional` rule flags the same pattern. Reference: swift/implicitly-unwrapped-optional v0.24.'
40797
+ });
40798
+ }
40799
+ return issues;
40800
+ }
40801
+ });
40802
+ }
40803
+ });
40804
+
40805
+ // src/rules/swift/print-debug.ts
40806
+ var PRINT_REGEX, DEFAULT_THRESHOLD3, swiftPrintDebugRule;
40807
+ var init_print_debug = __esm({
40808
+ "src/rules/swift/print-debug.ts"() {
40809
+ "use strict";
40810
+ init_rule();
40811
+ PRINT_REGEX = /\bprint\s*\(/g;
40812
+ DEFAULT_THRESHOLD3 = 1;
40813
+ swiftPrintDebugRule = createRule({
40814
+ id: "swift/print-debug",
40815
+ category: "typo",
40816
+ severity: "low",
40817
+ aiSpecific: true,
40818
+ description: "print(...) in production Swift \u2014 use Logger (os.log) for level-controlled output",
40819
+ create(_context) {
40820
+ return { threshold: DEFAULT_THRESHOLD3 };
40821
+ },
40822
+ analyze(context, facts) {
40823
+ const issues = [];
40824
+ const source = facts.v2?._source;
40825
+ if (!source) return issues;
40826
+ if (!/\.swift$/i.test(facts.filePath)) return issues;
40827
+ const matches = [];
40828
+ let m;
40829
+ PRINT_REGEX.lastIndex = 0;
40830
+ while ((m = PRINT_REGEX.exec(source)) !== null) {
40831
+ matches.push(m.index);
40832
+ }
40833
+ if (matches.length <= context.threshold) return issues;
40834
+ const cap = Math.min(matches.length, 10);
40835
+ for (let i = 0; i < cap; i++) {
40836
+ const idx = matches[i];
40837
+ const line = source.slice(0, idx).split("\n").length;
40838
+ issues.push({
40839
+ ruleId: "swift/print-debug",
40840
+ category: "typo",
40841
+ severity: "low",
40842
+ aiSpecific: true,
40843
+ message: `print(...) at line ${line} \u2014 use Logger (os.log) for production output`,
40844
+ line,
40845
+ column: 1,
40846
+ advice: 'Replace with `Logger(subsystem: "...", category: "...").info("...")` (Unified Logging System, os.log). `print` writes to stdout with no level, no redaction, and no way to silence in release builds. The `Logger` API integrates with Console.app and respects the device\'s privacy settings. Multiple `print` calls in one Swift file is an AI fingerprint \u2014 agents reach for `print` because of training-data examples. Reference: swift/print-debug v0.24.'
40847
+ });
40848
+ }
40849
+ return issues;
40850
+ }
40851
+ });
40852
+ }
40853
+ });
40854
+
40855
+ // src/rules/swift/strong-self-capture.ts
40856
+ var SELF_REF_REGEX, CAPTURE_LIST_REGEX, swiftStrongSelfCaptureRule;
40857
+ var init_strong_self_capture = __esm({
40858
+ "src/rules/swift/strong-self-capture.ts"() {
40859
+ "use strict";
40860
+ init_rule();
40861
+ SELF_REF_REGEX = /\bself\.(?:\w+)/g;
40862
+ CAPTURE_LIST_REGEX = /\[\s*(?:weak|unowned)\s+self\b/;
40863
+ swiftStrongSelfCaptureRule = createRule({
40864
+ id: "swift/strong-self-capture",
40865
+ category: "logic",
40866
+ severity: "medium",
40867
+ aiSpecific: true,
40868
+ description: "Closure captures `self` strongly \u2014 creates a retain cycle. Use `[weak self]` or `[unowned self]`.",
40869
+ create(_context) {
40870
+ return {};
40871
+ },
40872
+ analyze(_context, facts) {
40873
+ const issues = [];
40874
+ const source = facts.v2?._source;
40875
+ if (!source) return issues;
40876
+ if (!/\.swift$/i.test(facts.filePath)) return issues;
40877
+ const METHOD_HEAD_REGEX = /\b(?:func|init\??|deinit|subscript)\b[^;{}\n]*$/m;
40878
+ let m;
40879
+ SELF_REF_REGEX.lastIndex = 0;
40880
+ while ((m = SELF_REF_REGEX.exec(source)) !== null) {
40881
+ const selfIdx = m.index;
40882
+ let depth = 0;
40883
+ let openBrace = -1;
40884
+ for (let j = selfIdx - 1; j >= 0; j--) {
40885
+ const ch = source.charAt(j);
40886
+ if (ch === "}") depth++;
40887
+ else if (ch === "{") {
40888
+ if (depth === 0) {
40889
+ openBrace = j;
40890
+ break;
40891
+ }
40892
+ depth--;
40893
+ }
40894
+ }
40895
+ if (openBrace === -1) continue;
40896
+ const openLineStart = source.lastIndexOf("\n", openBrace) + 1;
40897
+ const lineBeforeBrace = source.slice(openLineStart, openBrace);
40898
+ if (METHOD_HEAD_REGEX.test(lineBeforeBrace)) continue;
40899
+ const openingSlice = source.slice(openBrace, openBrace + 80);
40900
+ if (CAPTURE_LIST_REGEX.test(openingSlice)) continue;
40901
+ const line = source.slice(0, openBrace).split("\n").length;
40902
+ issues.push({
40903
+ ruleId: "swift/strong-self-capture",
40904
+ category: "logic",
40905
+ severity: "medium",
40906
+ aiSpecific: true,
40907
+ message: `closure at line ${line} captures self strongly \u2014 use [weak self] or [unowned self]`,
40908
+ line,
40909
+ column: 1,
40910
+ advice: 'Capture the closure with `[weak self]` (or `[unowned self]` if you can guarantee non-nil): `[weak self] in self?.foo = bar`. Strong self capture creates a retain cycle \u2014 the closure keeps self alive, self keeps the closure alive, and the cycle is only broken when the runtime gives up and prints a leak. Apple\'s Swift docs use UIKit / UIViewController closures as the canonical example. AI agents write `loadData { self.foo = bar }` because it "just compiles"; the leak is invisible without profiling. Reference: swift/strong-self-capture v0.24.'
40911
+ });
40912
+ }
40913
+ return issues;
40914
+ }
40915
+ });
40916
+ }
40917
+ });
40918
+
39618
40919
  // src/rules/test/utils.ts
39619
40920
  function isTestFile(filePath) {
39620
40921
  const normalized = filePath.replace(/\\/g, "/");
@@ -39751,7 +41052,7 @@ function extractSetupBlocks(source, minLines = 3) {
39751
41052
  }).trim();
39752
41053
  const lineCount = rawBody.split("\n").length;
39753
41054
  if (lineCount < minLines) continue;
39754
- const bodyHash = (0, import_node_crypto.createHash)("sha1").update(normalizedBody).digest("hex");
41055
+ const bodyHash = (0, import_node_crypto4.createHash)("sha1").update(normalizedBody).digest("hex");
39755
41056
  const { line, column } = lineColumnOf(source, m.index);
39756
41057
  hits.push({
39757
41058
  kind,
@@ -39797,11 +41098,11 @@ function extractPlaceholderCandidates(source) {
39797
41098
  }
39798
41099
  return hits;
39799
41100
  }
39800
- var import_node_crypto, ASSERTION_MATCHERS, SETUP_RE, STRING_PROP_RE, NUMERIC_PROP_RE, DATE_PROP_RE;
41101
+ var import_node_crypto4, ASSERTION_MATCHERS, SETUP_RE, STRING_PROP_RE, NUMERIC_PROP_RE, DATE_PROP_RE;
39801
41102
  var init_utils2 = __esm({
39802
41103
  "src/rules/test/utils.ts"() {
39803
41104
  "use strict";
39804
- import_node_crypto = require("crypto");
41105
+ import_node_crypto4 = require("crypto");
39805
41106
  ASSERTION_MATCHERS = /* @__PURE__ */ new Set([
39806
41107
  "toBe",
39807
41108
  "toEqual",
@@ -45241,6 +46542,11 @@ var init_builtins = __esm({
45241
46542
  init_multiple_components_per_file();
45242
46543
  init_shadcn_prop_mismatch();
45243
46544
  init_import_path_mismatch();
46545
+ init_c_style_cast();
46546
+ init_magic_numbers();
46547
+ init_printf_debug();
46548
+ init_raw_new_delete();
46549
+ init_using_namespace_std();
45244
46550
  init_duplicate_index();
45245
46551
  init_enum_sprawl();
45246
46552
  init_missing_fk_index();
@@ -45256,6 +46562,8 @@ var init_builtins = __esm({
45256
46562
  init_stale_function_reference();
45257
46563
  init_stale_package_reference();
45258
46564
  init_identical_block();
46565
+ init_near_duplicate();
46566
+ init_structural_clone2();
45259
46567
  init_error_wrap_without_context();
45260
46568
  init_nil_slice_vs_empty();
45261
46569
  init_struct_tag_inconsistency();
@@ -45265,6 +46573,11 @@ var init_builtins = __esm({
45265
46573
  init_raw_type_overuse();
45266
46574
  init_string_concat_loop();
45267
46575
  init_system_out_println();
46576
+ init_coroutine_global_scope();
46577
+ init_data_class_defaults_overuse();
46578
+ init_object_singleton_misuse();
46579
+ init_println_debug();
46580
+ init_string_concat_loop2();
45268
46581
  init_gap_monopoly();
45269
46582
  init_math_element_uniformity();
45270
46583
  init_math_grid_uniformity();
@@ -45303,6 +46616,11 @@ var init_builtins = __esm({
45303
46616
  init_sql_construction();
45304
46617
  init_target_blank_no_noopener();
45305
46618
  init_unsafe_html_render();
46619
+ init_fatal_error_thrown();
46620
+ init_force_unwrap();
46621
+ init_implicitly_unwrapped_optional();
46622
+ init_print_debug();
46623
+ init_strong_self_capture();
45306
46624
  init_duplicate_setup();
45307
46625
  init_fake_placeholder();
45308
46626
  init_missing_edge_case();
@@ -45359,6 +46677,11 @@ var init_builtins = __esm({
45359
46677
  multipleComponentsPerFileRule,
45360
46678
  shadcnPropMismatchRule,
45361
46679
  importPathMismatchRule,
46680
+ cppCStyleCastRule,
46681
+ cppMagicNumbersRule,
46682
+ cppPrintfDebugRule,
46683
+ cppRawNewDeleteRule,
46684
+ cppUsingNamespaceStdRule,
45362
46685
  duplicateIndexRule,
45363
46686
  enumSprawlRule,
45364
46687
  missingFkIndexRule,
@@ -45374,6 +46697,8 @@ var init_builtins = __esm({
45374
46697
  staleFunctionReferenceRule,
45375
46698
  stalePackageReferenceRule,
45376
46699
  dupIdenticalBlockRule,
46700
+ nearDuplicateRule,
46701
+ structuralCloneRule,
45377
46702
  goErrorWrapWithoutContextRule,
45378
46703
  goNilSliceVsEmptyRule,
45379
46704
  goStructTagInconsistencyRule,
@@ -45383,6 +46708,11 @@ var init_builtins = __esm({
45383
46708
  javaRawTypeOveruseRule,
45384
46709
  javaStringConcatLoopRule,
45385
46710
  javaSystemOutPrintlnRule,
46711
+ kotlinCoroutineGlobalScopeRule,
46712
+ kotlinDataClassDefaultsOveruseRule,
46713
+ kotlinObjectSingletonMisuseRule,
46714
+ kotlinPrintlnDebugRule,
46715
+ kotlinStringConcatLoopRule,
45386
46716
  gapMonopolyRule,
45387
46717
  mathElementUniformityRule,
45388
46718
  mathGridUniformityRule,
@@ -45421,6 +46751,11 @@ var init_builtins = __esm({
45421
46751
  sqlConstructionRule,
45422
46752
  targetBlankNoNoopenerRule,
45423
46753
  unsafeHtmlRenderRule,
46754
+ swiftFatalErrorThrownRule,
46755
+ swiftForceUnwrapRule,
46756
+ swiftImplicitlyUnwrappedOptionalRule,
46757
+ swiftPrintDebugRule,
46758
+ swiftStrongSelfCaptureRule,
45424
46759
  duplicateSetupRule,
45425
46760
  fakePlaceholderRule,
45426
46761
  missingEdgeCaseRule,
@@ -45479,7 +46814,7 @@ function tokenizeClassLike(source) {
45479
46814
  if (current.length > 0) tokens.push(current);
45480
46815
  return tokens;
45481
46816
  }
45482
- function stripComments(source) {
46817
+ function stripComments3(source) {
45483
46818
  let out = source.replace(/\/\*[\s\S]*?\*\//g, " ");
45484
46819
  out = out.replace(/(^|\s)\/\/[^\n]*/g, " ");
45485
46820
  return out;
@@ -45491,7 +46826,7 @@ function normalizeCalc(source) {
45491
46826
  });
45492
46827
  }
45493
46828
  function canonicalizeStyleSource(source) {
45494
- let normalized = stripComments(source);
46829
+ let normalized = stripComments3(source);
45495
46830
  normalized = normalizeCalc(normalized);
45496
46831
  normalized = normalized.replace(/\s+/g, " ").trim();
45497
46832
  if (normalized.includes(" ") && !/[{};]/.test(normalized)) {
@@ -47506,7 +48841,7 @@ function saveCache(cachePath3, cache) {
47506
48841
  }
47507
48842
  function computeFileHash(filePath) {
47508
48843
  const content = (0, import_node_fs12.readFileSync)(filePath);
47509
- return (0, import_node_crypto2.createHash)("md5").update(content).digest("hex");
48844
+ return (0, import_node_crypto5.createHash)("md5").update(content).digest("hex");
47510
48845
  }
47511
48846
  function partitionByCache(files, cache) {
47512
48847
  const toScan = [];
@@ -47540,11 +48875,11 @@ function emptyCache() {
47540
48875
  files: {}
47541
48876
  };
47542
48877
  }
47543
- var import_node_crypto2, import_node_fs12, import_node_path11;
48878
+ var import_node_crypto5, import_node_fs12, import_node_path11;
47544
48879
  var init_cache_incremental = __esm({
47545
48880
  "src/engine/cache-incremental.ts"() {
47546
48881
  "use strict";
47547
- import_node_crypto2 = require("crypto");
48882
+ import_node_crypto5 = require("crypto");
47548
48883
  import_node_fs12 = require("fs");
47549
48884
  import_node_path11 = require("path");
47550
48885
  init_types();
@@ -48444,9 +49779,9 @@ var init_signal_strength = __esm({
48444
49779
  ratio: 1,
48445
49780
  precision: 0,
48446
49781
  lastCalibratedAt: "2026-07-01T00:00:00Z",
48447
- verdict: "DORMANT",
49782
+ verdict: "OK",
48448
49783
  defaultOff: false,
48449
- _calibrationNote: "v0.19: new rule, not yet calibrated. v8.5 calibration does not run dup/* rules (the calibration script analyzes each file in isolation, but dup/* rules require cross-file state \u2014 the module-scope dedup cache is per-process, not per-file, so per-file analysis never produces cross-file matches and the rule's recall reads as 0). Scheduled for v0.22 calibration on the v9 corpus with a per-project dedup cache. v0.21.1 self-scan: 207 fires in src/ after WINDOW_SIZE 10\u219220 (was 575) \u2014 69% reduction. The actual precision/recall of these 207 fires is unverified ground truth. Default stays on because the rule's value is real (block-level duplications are a classic AI-fingerprint) and the corpus-measured 0.0 is a methodology artifact, not a real measurement.",
49784
+ _calibrationNote: "v0.19: new rule. v8.5 calibration does not run dup/* rules (the calibration script analyzes each file in isolation, but dup/* rules require cross-file state \u2014 the module-scope dedup cache is per-process, not per-file, so per-file analysis never produces cross-file matches and the rule's recall reads as 0). Scheduled for v0.22 calibration on the v9 corpus with a per-project dedup cache. v0.21.1 self-scan: 207 fires in src/ after WINDOW_SIZE 10\u219220 (was 575) \u2014 69% reduction. The actual precision/recall of these 207 fires is unverified ground truth. The rule ships ON (defaultOff=false) because its value is real (block-level duplications are a classic AI-fingerprint) and the corpus-measured 0.0 is a methodology artifact, not a real measurement. Verdict is OK (active, uncalibrated) rather than DORMANT (off, uncalibrated) to satisfy the 'every DORMANT rule must be defaultOff' guardrail.",
48450
49785
  aiSpecific: false,
48451
49786
  _v7Verdict: "DORMANT",
48452
49787
  _v7Lift: 1,
@@ -48454,8 +49789,39 @@ var init_signal_strength = __esm({
48454
49789
  _v7FpRate: 0,
48455
49790
  _v7Precision: 0,
48456
49791
  _v8Verdict: "DORMANT",
48457
- _v8Lift: 1,
48458
- defaultOff: true
49792
+ _v8Lift: 1
49793
+ },
49794
+ "dup/near-duplicate": {
49795
+ recall: 0,
49796
+ fpRate: 0,
49797
+ ratio: 1,
49798
+ precision: 0,
49799
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
49800
+ verdict: "DORMANT",
49801
+ defaultOff: true,
49802
+ _calibrationNote: "v0.23.0: new rule, not yet calibrated. Type-2 clone detector using MinHash + Jaccard similarity on k-gram token shingles (k=5). The rule's effectiveness depends on the v9 corpus calibration (see v9-plan-2026-07-02-update.md). The rule catches Type-2a (whitespace + comment differences) reliably; full-rename detection (Type-2b) requires identifier canonicalization or AST similarity (planned for v0.27.0 dup/structural-clone). Default OFF (DORMANT) until v9 corpus calibration confirms precision/recall thresholds.",
49803
+ aiSpecific: true,
49804
+ _v7Verdict: "DORMANT",
49805
+ _v7Lift: 1,
49806
+ _v7Recall: 0,
49807
+ _v7FpRate: 0,
49808
+ _v7Precision: 0
49809
+ },
49810
+ "dup/structural-clone": {
49811
+ recall: 0,
49812
+ fpRate: 0,
49813
+ ratio: 1,
49814
+ precision: 0,
49815
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
49816
+ verdict: "DORMANT",
49817
+ defaultOff: true,
49818
+ _calibrationNote: "v0.24.0: new rule, not yet calibrated. Type-3 clone detector using a two-stage MinHash pipeline \u2014 stage 1 canonicalizes identifiers/literals (rename-invariant k=8 shingles), stage 2 verifies with identifier-aware k=5 shingles (existing shingleSet). Closes the gap near-duplicate left open: identifier renames (Type-3) and statement add/remove. Default OFF (DORMANT) until v9 Java corpus calibration confirms precision/recall thresholds and the v0.24.1 patch raises minHits from 1 to 3.",
49819
+ aiSpecific: true,
49820
+ _v7Verdict: "DORMANT",
49821
+ _v7Lift: 1,
49822
+ _v7Recall: 0,
49823
+ _v7FpRate: 0,
49824
+ _v7Precision: 0
48459
49825
  },
48460
49826
  "go/error-wrap-without-context": {
48461
49827
  recall: 0,
@@ -49861,6 +51227,276 @@ var init_signal_strength = __esm({
49861
51227
  _v8Verdict: "DORMANT",
49862
51228
  _v8Lift: 1,
49863
51229
  defaultOff: true
51230
+ },
51231
+ "kotlin/data-class-defaults-overuse": {
51232
+ recall: 0,
51233
+ fpRate: 0,
51234
+ ratio: 1,
51235
+ precision: 0,
51236
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51237
+ verdict: "DORMANT",
51238
+ _calibrationNote: "v0.24: new rule (data class with 3+ literal defaults). DORMANT until v9 Kotlin corpus calibration.",
51239
+ aiSpecific: true,
51240
+ _v7Verdict: "DORMANT",
51241
+ _v7Lift: 1,
51242
+ _v7Recall: 0,
51243
+ _v7FpRate: 0,
51244
+ _v7Precision: 0,
51245
+ _v8Verdict: "DORMANT",
51246
+ _v8Lift: 1,
51247
+ defaultOff: true
51248
+ },
51249
+ "kotlin/coroutine-global-scope": {
51250
+ recall: 0,
51251
+ fpRate: 0,
51252
+ ratio: 1,
51253
+ precision: 0,
51254
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51255
+ verdict: "DORMANT",
51256
+ _calibrationNote: "v0.24: new rule (GlobalScope.launch/async/runBlocking \u2014 bypasses structured concurrency). DORMANT until v9 Kotlin corpus calibration.",
51257
+ aiSpecific: true,
51258
+ _v7Verdict: "DORMANT",
51259
+ _v7Lift: 1,
51260
+ _v7Recall: 0,
51261
+ _v7FpRate: 0,
51262
+ _v7Precision: 0,
51263
+ _v8Verdict: "DORMANT",
51264
+ _v8Lift: 1,
51265
+ defaultOff: true
51266
+ },
51267
+ "kotlin/println-debug": {
51268
+ recall: 0,
51269
+ fpRate: 0,
51270
+ ratio: 1,
51271
+ precision: 0,
51272
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51273
+ verdict: "DORMANT",
51274
+ _calibrationNote: "v0.24: new rule (multi-println in Kotlin source \u2014 use Timber / android.util.Log). DORMANT until v9 Kotlin corpus calibration.",
51275
+ aiSpecific: true,
51276
+ _v7Verdict: "DORMANT",
51277
+ _v7Lift: 1,
51278
+ _v7Recall: 0,
51279
+ _v7FpRate: 0,
51280
+ _v7Precision: 0,
51281
+ _v8Verdict: "DORMANT",
51282
+ _v8Lift: 1,
51283
+ defaultOff: true
51284
+ },
51285
+ "kotlin/object-singleton-misuse": {
51286
+ recall: 0,
51287
+ fpRate: 0,
51288
+ ratio: 1,
51289
+ precision: 0,
51290
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51291
+ verdict: "DORMANT",
51292
+ _calibrationNote: "v0.24: new rule (Kotlin `object` singleton holding `var` \u2014 hidden shared state). DORMANT until v9 Kotlin corpus calibration.",
51293
+ aiSpecific: true,
51294
+ _v7Verdict: "DORMANT",
51295
+ _v7Lift: 1,
51296
+ _v7Recall: 0,
51297
+ _v7FpRate: 0,
51298
+ _v7Precision: 0,
51299
+ _v8Verdict: "DORMANT",
51300
+ _v8Lift: 1,
51301
+ defaultOff: true
51302
+ },
51303
+ "kotlin/string-concat-loop": {
51304
+ recall: 0,
51305
+ fpRate: 0,
51306
+ ratio: 1,
51307
+ precision: 0,
51308
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51309
+ verdict: "DORMANT",
51310
+ _calibrationNote: "v0.24: new rule (string concat inside a Kotlin loop \u2014 use buildString { ... }). DORMANT until v9 Kotlin corpus calibration.",
51311
+ aiSpecific: true,
51312
+ _v7Verdict: "DORMANT",
51313
+ _v7Lift: 1,
51314
+ _v7Recall: 0,
51315
+ _v7FpRate: 0,
51316
+ _v7Precision: 0,
51317
+ _v8Verdict: "DORMANT",
51318
+ _v8Lift: 1,
51319
+ defaultOff: true
51320
+ },
51321
+ "swift/force-unwrap": {
51322
+ recall: 0,
51323
+ fpRate: 0,
51324
+ ratio: 1,
51325
+ precision: 0,
51326
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51327
+ verdict: "DORMANT",
51328
+ _calibrationNote: "v0.24: new rule (Swift force-unwrap \u2014 `as!`, `try!`, `var!.prop` in production). DORMANT until v9 Swift corpus calibration.",
51329
+ aiSpecific: true,
51330
+ _v7Verdict: "DORMANT",
51331
+ _v7Lift: 1,
51332
+ _v7Recall: 0,
51333
+ _v7FpRate: 0,
51334
+ _v7Precision: 0,
51335
+ _v8Verdict: "DORMANT",
51336
+ _v8Lift: 1,
51337
+ defaultOff: true
51338
+ },
51339
+ "swift/print-debug": {
51340
+ recall: 0,
51341
+ fpRate: 0,
51342
+ ratio: 1,
51343
+ precision: 0,
51344
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51345
+ verdict: "DORMANT",
51346
+ _calibrationNote: "v0.24: new rule (multi-print in Swift source \u2014 use Logger / os.log). DORMANT until v9 Swift corpus calibration.",
51347
+ aiSpecific: true,
51348
+ _v7Verdict: "DORMANT",
51349
+ _v7Lift: 1,
51350
+ _v7Recall: 0,
51351
+ _v7FpRate: 0,
51352
+ _v7Precision: 0,
51353
+ _v8Verdict: "DORMANT",
51354
+ _v8Lift: 1,
51355
+ defaultOff: true
51356
+ },
51357
+ "swift/fatal-error-thrown": {
51358
+ recall: 0,
51359
+ fpRate: 0,
51360
+ ratio: 1,
51361
+ precision: 0,
51362
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51363
+ verdict: "DORMANT",
51364
+ _calibrationNote: "v0.24: new rule (`fatalError` / `preconditionFailure` in production Swift \u2014 replaces with typed default). DORMANT until v9 Swift corpus calibration.",
51365
+ aiSpecific: true,
51366
+ _v7Verdict: "DORMANT",
51367
+ _v7Lift: 1,
51368
+ _v7Recall: 0,
51369
+ _v7FpRate: 0,
51370
+ _v7Precision: 0,
51371
+ _v8Verdict: "DORMANT",
51372
+ _v8Lift: 1,
51373
+ defaultOff: true
51374
+ },
51375
+ "swift/implicitly-unwrapped-optional": {
51376
+ recall: 0,
51377
+ fpRate: 0,
51378
+ ratio: 1,
51379
+ precision: 0,
51380
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51381
+ verdict: "DORMANT",
51382
+ _calibrationNote: "v0.24: new rule (Swift implicitly unwrapped optional \u2014 declare as Type? and unwrap with guard let). DORMANT until v9 Swift corpus calibration.",
51383
+ aiSpecific: true,
51384
+ _v7Verdict: "DORMANT",
51385
+ _v7Lift: 1,
51386
+ _v7Recall: 0,
51387
+ _v7FpRate: 0,
51388
+ _v7Precision: 0,
51389
+ _v8Verdict: "DORMANT",
51390
+ _v8Lift: 1,
51391
+ defaultOff: true
51392
+ },
51393
+ "swift/strong-self-capture": {
51394
+ recall: 0,
51395
+ fpRate: 0,
51396
+ ratio: 1,
51397
+ precision: 0,
51398
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51399
+ verdict: "DORMANT",
51400
+ _calibrationNote: "v0.24: new rule (Swift closure captures `self` strongly \u2014 retain cycle. Use [weak self] / [unowned self]). DORMANT until v9 Swift corpus calibration.",
51401
+ aiSpecific: true,
51402
+ _v7Verdict: "DORMANT",
51403
+ _v7Lift: 1,
51404
+ _v7Recall: 0,
51405
+ _v7FpRate: 0,
51406
+ _v7Precision: 0,
51407
+ _v8Verdict: "DORMANT",
51408
+ _v8Lift: 1,
51409
+ defaultOff: true
51410
+ },
51411
+ "cpp/using-namespace-std": {
51412
+ recall: 0,
51413
+ fpRate: 0,
51414
+ ratio: 1,
51415
+ precision: 0,
51416
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51417
+ verdict: "DORMANT",
51418
+ _calibrationNote: "v0.24: new rule (`using namespace std;` in C++ header \u2014 pollutes every consumer). DORMANT until v9 C++ corpus calibration.",
51419
+ aiSpecific: true,
51420
+ _v7Verdict: "DORMANT",
51421
+ _v7Lift: 1,
51422
+ _v7Recall: 0,
51423
+ _v7FpRate: 0,
51424
+ _v7Precision: 0,
51425
+ _v8Verdict: "DORMANT",
51426
+ _v8Lift: 1,
51427
+ defaultOff: true
51428
+ },
51429
+ "cpp/raw-new-delete": {
51430
+ recall: 0,
51431
+ fpRate: 0,
51432
+ ratio: 1,
51433
+ precision: 0,
51434
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51435
+ verdict: "DORMANT",
51436
+ _calibrationNote: "v0.24: new rule (manual `new` / `delete` pairing in C++ \u2014 use std::make_unique / std::unique_ptr). DORMANT until v9 C++ corpus calibration.",
51437
+ aiSpecific: true,
51438
+ _v7Verdict: "DORMANT",
51439
+ _v7Lift: 1,
51440
+ _v7Recall: 0,
51441
+ _v7FpRate: 0,
51442
+ _v7Precision: 0,
51443
+ _v8Verdict: "DORMANT",
51444
+ _v8Lift: 1,
51445
+ defaultOff: true
51446
+ },
51447
+ "cpp/c-style-cast": {
51448
+ recall: 0,
51449
+ fpRate: 0,
51450
+ ratio: 1,
51451
+ precision: 0,
51452
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51453
+ verdict: "DORMANT",
51454
+ _calibrationNote: "v0.24: new rule (C-style cast `(int)x` in C++ \u2014 use static_cast / reinterpret_cast / const_cast). DORMANT until v9 C++ corpus calibration.",
51455
+ aiSpecific: true,
51456
+ _v7Verdict: "DORMANT",
51457
+ _v7Lift: 1,
51458
+ _v7Recall: 0,
51459
+ _v7FpRate: 0,
51460
+ _v7Precision: 0,
51461
+ _v8Verdict: "DORMANT",
51462
+ _v8Lift: 1,
51463
+ defaultOff: true
51464
+ },
51465
+ "cpp/printf-debug": {
51466
+ recall: 0,
51467
+ fpRate: 0,
51468
+ ratio: 1,
51469
+ precision: 0,
51470
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51471
+ verdict: "DORMANT",
51472
+ _calibrationNote: "v0.24: new rule (printf family / std::cout debug printing in C++ \u2014 use spdlog / glog / AbslLog). DORMANT until v9 C++ corpus calibration.",
51473
+ aiSpecific: true,
51474
+ _v7Verdict: "DORMANT",
51475
+ _v7Lift: 1,
51476
+ _v7Recall: 0,
51477
+ _v7FpRate: 0,
51478
+ _v7Precision: 0,
51479
+ _v8Verdict: "DORMANT",
51480
+ _v8Lift: 1,
51481
+ defaultOff: true
51482
+ },
51483
+ "cpp/magic-numbers": {
51484
+ recall: 0,
51485
+ fpRate: 0,
51486
+ ratio: 1,
51487
+ precision: 0,
51488
+ lastCalibratedAt: "2026-07-02T00:00:00Z",
51489
+ verdict: "DORMANT",
51490
+ _calibrationNote: "v0.24: new rule (magic-number literal in C++ comparison / return \u2014 name it `constexpr int MAX = ...`). DORMANT until v9 C++ corpus calibration.",
51491
+ aiSpecific: true,
51492
+ _v7Verdict: "DORMANT",
51493
+ _v7Lift: 1,
51494
+ _v7Recall: 0,
51495
+ _v7FpRate: 0,
51496
+ _v7Precision: 0,
51497
+ _v8Verdict: "DORMANT",
51498
+ _v8Lift: 1,
51499
+ defaultOff: true
49864
51500
  }
49865
51501
  };
49866
51502
  }
@@ -50210,13 +51846,13 @@ function saveFlywheelState(cwd, state) {
50210
51846
  (0, import_node_fs14.writeFileSync)((0, import_node_path14.join)(dir, STATE_FILE), JSON.stringify(state, null, 2));
50211
51847
  }
50212
51848
  function hashFile(filePath) {
50213
- return (0, import_node_crypto3.createHash)("sha256").update(filePath).digest("hex").slice(0, 16);
51849
+ return (0, import_node_crypto6.createHash)("sha256").update(filePath).digest("hex").slice(0, 16);
50214
51850
  }
50215
- var import_node_crypto3, import_node_fs14, import_node_path14, FLYWHEEL_DIR, STATE_FILE, CONSECUTIVE_THRESHOLD, FLYWHEEL_VERSION;
51851
+ var import_node_crypto6, import_node_fs14, import_node_path14, FLYWHEEL_DIR, STATE_FILE, CONSECUTIVE_THRESHOLD, FLYWHEEL_VERSION;
50216
51852
  var init_flywheel = __esm({
50217
51853
  "src/engine/flywheel.ts"() {
50218
51854
  "use strict";
50219
- import_node_crypto3 = require("crypto");
51855
+ import_node_crypto6 = require("crypto");
50220
51856
  import_node_fs14 = require("fs");
50221
51857
  import_node_path14 = require("path");
50222
51858
  FLYWHEEL_DIR = ".slopbrick/flywheel";
@@ -50641,7 +52277,7 @@ function pickBaselineConfig(config) {
50641
52277
  return picked;
50642
52278
  }
50643
52279
  function hashConfig(config) {
50644
- return (0, import_node_crypto4.createHash)("sha256").update(JSON.stringify(sanitizeForHash(pickBaselineConfig(config)))).digest("hex");
52280
+ return (0, import_node_crypto7.createHash)("sha256").update(JSON.stringify(sanitizeForHash(pickBaselineConfig(config)))).digest("hex");
50645
52281
  }
50646
52282
  function baselinePath(projectPath) {
50647
52283
  return (0, import_node_path16.join)(projectPath, ".slopbrick", "cache", "baseline.json");
@@ -50721,11 +52357,11 @@ function validateBaseline(cache, configHash, gitHead) {
50721
52357
  if (cache.git_head !== gitHead) return { valid: false, reason: "git_head mismatch" };
50722
52358
  return { valid: true };
50723
52359
  }
50724
- var import_node_crypto4, import_node_fs15, import_node_path16, BASELINE_VERSION, BASELINE_HASH_KEYS;
52360
+ var import_node_crypto7, import_node_fs15, import_node_path16, BASELINE_VERSION, BASELINE_HASH_KEYS;
50725
52361
  var init_cache = __esm({
50726
52362
  "src/engine/cache.ts"() {
50727
52363
  "use strict";
50728
- import_node_crypto4 = require("crypto");
52364
+ import_node_crypto7 = require("crypto");
50729
52365
  import_node_fs15 = require("fs");
50730
52366
  import_node_path16 = require("path");
50731
52367
  init_types();
@@ -53604,7 +55240,7 @@ function telemetryPath2(cwd) {
53604
55240
  return (0, import_node_path21.join)(cwd, TELEMETRY_DIR, TELEMETRY_FILE2);
53605
55241
  }
53606
55242
  function hashString(input) {
53607
- return (0, import_node_crypto5.createHash)("sha256").update(input).digest("hex").slice(0, 16);
55243
+ return (0, import_node_crypto8.createHash)("sha256").update(input).digest("hex").slice(0, 16);
53608
55244
  }
53609
55245
  function safeRelative(cwd, filePath) {
53610
55246
  try {
@@ -53724,12 +55360,12 @@ function recordTelemetry(cwd, report, results, config) {
53724
55360
  (0, import_node_fs20.appendFileSync)(path, JSON.stringify(payload) + "\n", "utf-8");
53725
55361
  return payload;
53726
55362
  }
53727
- var import_node_fs20, import_node_crypto5, import_node_path21, TELEMETRY_DIR, TELEMETRY_FILE2, MAX_TELEMETRY_BYTES, MAX_ROTATED_FILES;
55363
+ var import_node_fs20, import_node_crypto8, import_node_path21, TELEMETRY_DIR, TELEMETRY_FILE2, MAX_TELEMETRY_BYTES, MAX_ROTATED_FILES;
53728
55364
  var init_telemetry = __esm({
53729
55365
  "src/engine/telemetry.ts"() {
53730
55366
  "use strict";
53731
55367
  import_node_fs20 = require("fs");
53732
- import_node_crypto5 = require("crypto");
55368
+ import_node_crypto8 = require("crypto");
53733
55369
  import_node_path21 = require("path");
53734
55370
  TELEMETRY_DIR = (0, import_node_path21.join)(".slopbrick", "flywheel");
53735
55371
  TELEMETRY_FILE2 = "scans.jsonl";
@@ -54378,7 +56014,7 @@ function buildHelpUri(ruleId, category) {
54378
56014
  }
54379
56015
  function computeFingerprint(input) {
54380
56016
  const payload = `${input.ruleId}|${input.fileUri}|${input.line}|${input.column}|${input.category}`;
54381
- return (0, import_node_crypto6.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
56017
+ return (0, import_node_crypto9.createHash)("sha256").update(payload).digest("hex").slice(0, 16);
54382
56018
  }
54383
56019
  function buildRuleFromIssue(issue) {
54384
56020
  return {
@@ -54485,11 +56121,11 @@ function formatSarif(report, options) {
54485
56121
  };
54486
56122
  return JSON.stringify(log, null, 2);
54487
56123
  }
54488
- var import_node_crypto6, import_node_fs23, import_node_path25, REPO_INFORMATION_URI, RULES_BASE_URL;
56124
+ var import_node_crypto9, import_node_fs23, import_node_path25, REPO_INFORMATION_URI, RULES_BASE_URL;
54489
56125
  var init_sarif = __esm({
54490
56126
  "src/report/sarif.ts"() {
54491
56127
  "use strict";
54492
- import_node_crypto6 = require("crypto");
56128
+ import_node_crypto9 = require("crypto");
54493
56129
  import_node_fs23 = require("fs");
54494
56130
  import_node_path25 = require("path");
54495
56131
  REPO_INFORMATION_URI = "https://github.com/brickdotdev/slopbrick";
@@ -56168,6 +57804,7 @@ __export(scan_exports, {
56168
57804
  async function runScan(options, explicitPaths) {
56169
57805
  setLoggerQuiet(!!options.quiet);
56170
57806
  const startTime = Date.now();
57807
+ const scanId = (0, import_node_crypto10.randomUUID)();
56171
57808
  const cwd = (0, import_node_path30.resolve)(options.workspace ?? process.cwd());
56172
57809
  if (!(0, import_node_fs28.existsSync)(cwd)) {
56173
57810
  throw new Error(`Workspace not found: ${cwd}`);
@@ -56421,19 +58058,31 @@ async function runScan(options, explicitPaths) {
56421
58058
  config,
56422
58059
  noIncreaseFailure,
56423
58060
  baseline,
56424
- machineReadableStdout
58061
+ machineReadableStdout,
58062
+ // v0.24.0 (Workstream C): stats for the opt-in network beacon.
58063
+ // `fileCount` = files that ran through the worker pool (excludes
58064
+ // incremental-cache skips). `ruleCount` = builtin rules, or 1
58065
+ // when `--rule <id>` narrows the run. `durationMs` = wall-clock
58066
+ // since `runScan` entry (matches `report.scanDurationMs`).
58067
+ scanStats: {
58068
+ scanId,
58069
+ fileCount: results.length,
58070
+ ruleCount: options.rule ? 1 : builtinRules.length,
58071
+ durationMs: Date.now() - startTime
58072
+ }
56425
58073
  };
56426
58074
  }
56427
58075
  async function scanProject(options) {
56428
58076
  const { report } = await runScan({ ...options, workspace: options.cwd });
56429
58077
  return report;
56430
58078
  }
56431
- var import_node_fs28, import_node_path30;
58079
+ var import_node_fs28, import_node_path30, import_node_crypto10;
56432
58080
  var init_scan2 = __esm({
56433
58081
  "src/cli/scan.ts"() {
56434
58082
  "use strict";
56435
58083
  import_node_fs28 = require("fs");
56436
58084
  import_node_path30 = require("path");
58085
+ import_node_crypto10 = require("crypto");
56437
58086
  init_render();
56438
58087
  init_threshold();
56439
58088
  init_config2();
@@ -57862,13 +59511,35 @@ var RULE_HINTS = {
57862
59511
  "go/nil-slice-vs-empty": "Either declare as `var x = []int{}` or assign with `make([]int, 0)`. The nil/empty inconsistency is an AI signal \u2014 real code picks one form and sticks with it.",
57863
59512
  // v0.19.0 — Duplication detector
57864
59513
  "dup/identical-block": "Refactor to a shared helper. This is a Type-1 clone (byte-for-byte identical after normalization). Common in AI-generated code that copy-pastes from training data.",
59514
+ // v0.23.0 — Type-2 near-duplicate detector (MinHash + LSH)
59515
+ "dup/near-duplicate": "Refactor to a shared helper. Type-2 near-duplicate: same identifiers + structure, different whitespace/comments. AI-iterated code regenerates the same function with cosmetic edits. (v0.23.0 \u2014 MinHash + LSH, k=5, thr 0.7.)",
59516
+ // v0.24.0 — Type-3 structural clone detector (two-stage MinHash)
59517
+ "dup/structural-clone": "Refactor to a shared helper. Type-3 clone: same shape as another file after identifier canonicalization, with renames and/or added/removed statements. AI agents and copy-paste both produce this. Extract the shared part. (v0.24.0.)",
57865
59518
  // v0.20.0 — Java-specific rules
57866
59519
  "java/system-out-println": "Replace with `private static final Logger log = LoggerFactory.getLogger(...);` then `log.info(...)`. AI agents default to println because of textbook examples; real Java code uses a logger.",
57867
59520
  "java/empty-catch-block": 'Log the exception (`log.error("...", e)`), re-throw it, or both. Empty catch blocks hide bugs. Common in AI-generated code that wants to look defensive.',
57868
59521
  "java/arraylist-vs-linkedlist": "Replace `new LinkedList<>()` with `new ArrayList<>()`. LinkedList is rarely the right choice (worse cache locality, 5x more memory per element, O(n) indexed access). Joshua Bloch recommends ArrayList unless you need a Deque.",
57869
59522
  "java/legacy-date-api": "Replace `java.util.Date` / `Calendar` with `java.time` (`LocalDate`, `LocalDateTime`, `Instant`, `ZonedDateTime`). java.time is immutable and thread-safe. AI agents default to the legacy API.",
57870
59523
  "java/raw-type-overuse": "Replace raw `List` / `Map` / `Set` with the parameterized form. Raw types disable generic type checking (Effective Java, Item 23). AI agents default to raw types when unsure of the correct generic parameters.",
57871
- "java/string-concat-loop": "Declare a `StringBuilder` outside the loop: `StringBuilder sb = new StringBuilder(); sb.append(...);` then `return sb.toString();` after. String concat in a loop is O(n\xB2)."
59524
+ "java/string-concat-loop": "Declare a `StringBuilder` outside the loop: `StringBuilder sb = new StringBuilder(); sb.append(...);` then `return sb.toString();` after. String concat in a loop is O(n\xB2).",
59525
+ // v0.24.0 — Kotlin rules (DORMANT until v9 Kotlin corpus calibration)
59526
+ "kotlin/data-class-defaults-overuse": "Audit which fields are genuinely optional. Real Kotlin uses defaults sparingly (1-2 callbacks, the rest required). v0.24.0 \u2014 DORMANT until v9 calibration.",
59527
+ "kotlin/coroutine-global-scope": "Replace with `viewModelScope.launch { ... }`, `lifecycleScope.launch { ... }`, or `coroutineScope { ... }`. GlobalScope bypasses cancellation. (v0.24.0 \u2014 DORMANT.)",
59528
+ "kotlin/println-debug": "Replace with `Timber.d(...)` or `android.util.Log`. `println` writes to stdout with no level, no redaction, can't be silenced in release builds. (v0.24.0 \u2014 DORMANT.)",
59529
+ "kotlin/object-singleton-misuse": "Replace with a class injected via DI, a Repository, or `MutableStateFlow`. The `object` keyword gives a thread-safe singleton handle, NOT thread-safe `var` fields. (v0.24.0 \u2014 DORMANT.)",
59530
+ "kotlin/string-concat-loop": "Wrap the loop in `buildString { append(...) }` or hoist a `StringBuilder`. Kotlin can't optimize `s = s + x` in a loop \u2014 O(n\xB2). (v0.24.0 \u2014 DORMANT.)",
59531
+ // v0.24.0 — Swift rules (DORMANT until v9 Swift corpus calibration)
59532
+ "swift/force-unwrap": "Replace with the safe form: `as?` + guard/if let, `try?`, or `guard let x = optional else { return }`. `!` crashes unconditionally in release. (v0.24.0 \u2014 DORMANT.)",
59533
+ "swift/print-debug": "Replace with `Logger(subsystem:..., category:...).info(...)` (os.log). `print` writes to stdout with no level and no redaction. (v0.24.0 \u2014 DORMANT.)",
59534
+ "swift/fatal-error-thrown": "Replace with `return` of a typed default (e.g. `nil`, `[]()`) or throw a typed `enum MyError: Error`. `fatalError` survives release builds. (v0.24.0 \u2014 DORMANT.)",
59535
+ "swift/implicitly-unwrapped-optional": "Declare as `var name: Type?` and unwrap with `guard let`. IUOs exist for Obj-C bridging / IBOutlets but using them everywhere is an AI signal. (v0.24.0 \u2014 DORMANT.)",
59536
+ "swift/strong-self-capture": "Capture with `[weak self]` (or `[unowned self]` if guaranteed non-nil): `[weak self] in self?.foo = bar`. Strong self capture creates a retain cycle. (v0.24.0 \u2014 DORMANT.)",
59537
+ // v0.24.0 — C++ rules (DORMANT until v9 C++ corpus calibration)
59538
+ "cpp/using-namespace-std": "Remove the directive and qualify names with `std::`, or use targeted `using std::cout;`. C++ Core Guidelines (SF.6/SF.7) forbid `using namespace` in headers. (v0.24.0 \u2014 DORMANT.)",
59539
+ "cpp/raw-new-delete": "Replace with `auto p = std::make_unique<T>(...)`. Smart pointers delete on scope exit, never leak on early return / exception, never double-free. (v0.24.0 \u2014 DORMANT.)",
59540
+ "cpp/c-style-cast": "Use the named cast: `static_cast<int>(x)`, `reinterpret_cast<...>(p)`, `const_cast<...>(ref)`. C-style casts silently pick static / reinterpret / const \u2014 impossible to grep. (v0.24.0 \u2014 DORMANT.)",
59541
+ "cpp/printf-debug": "Replace with `spdlog::info(...)`, `LOG(INFO) << ...` (glog), or `ABSL_LOG(INFO) << ...`. `printf` / `std::cout` have no levels, no redaction, no sink routing. (v0.24.0 \u2014 DORMANT.)",
59542
+ "cpp/magic-numbers": "Replace with `constexpr int MAX = 1024;` (or `static constexpr`). Named constants live next to their value, can be searched, force the reader to mean what they say. (v0.24.0 \u2014 DORMANT.)"
57872
59543
  };
57873
59544
 
57874
59545
  // src/cli/commands/explain.ts
@@ -62119,7 +63790,11 @@ var OPTION_CATEGORY = {
62119
63790
  // Tokens
62120
63791
  "--tokens": "tokens",
62121
63792
  // Telemetry
62122
- "--no-telemetry": "telemetry"
63793
+ "--no-telemetry": "telemetry",
63794
+ // v0.24.0 (Workstream C): opt-in network beacon. Distinct from
63795
+ // --no-telemetry (which gates the local flywheel); this gates a
63796
+ // single POST at scan end.
63797
+ "--report-usage": "telemetry"
62123
63798
  };
62124
63799
  var CATEGORY_ORDER2 = [
62125
63800
  "file",
@@ -62188,6 +63863,109 @@ function formatGroupedHelp(cmd) {
62188
63863
  return lines.join("\n");
62189
63864
  }
62190
63865
 
63866
+ // src/beacon/endpoint.ts
63867
+ var http = __toESM(require("http"), 1);
63868
+ var https = __toESM(require("https"), 1);
63869
+ var import_node_url = require("url");
63870
+ var sendBeacon = (url, payload, timeoutMs) => {
63871
+ return new Promise((resolve42) => {
63872
+ let parsed;
63873
+ try {
63874
+ parsed = new import_node_url.URL(url);
63875
+ } catch {
63876
+ resolve42();
63877
+ return;
63878
+ }
63879
+ const isHttps = parsed.protocol === "https:";
63880
+ const lib = isHttps ? https : http;
63881
+ const body = JSON.stringify(payload);
63882
+ const opts = {
63883
+ method: "POST",
63884
+ hostname: parsed.hostname,
63885
+ port: parsed.port || (isHttps ? 443 : 80),
63886
+ path: `${parsed.pathname || "/"}${parsed.search || ""}`,
63887
+ headers: {
63888
+ "content-type": "application/json",
63889
+ "content-length": Buffer.byteLength(body),
63890
+ "user-agent": `slopbrick/${payload.slopbrick_version}`
63891
+ }
63892
+ };
63893
+ let settled = false;
63894
+ const settle = () => {
63895
+ if (settled) return;
63896
+ settled = true;
63897
+ resolve42();
63898
+ };
63899
+ let req;
63900
+ try {
63901
+ req = lib.request(opts, (res) => {
63902
+ res.on("data", () => {
63903
+ });
63904
+ res.on("end", settle);
63905
+ res.on("error", settle);
63906
+ });
63907
+ } catch {
63908
+ settle();
63909
+ return;
63910
+ }
63911
+ req.on("error", settle);
63912
+ req.setTimeout(timeoutMs, () => {
63913
+ req.destroy();
63914
+ settle();
63915
+ });
63916
+ try {
63917
+ req.end(body);
63918
+ } catch {
63919
+ settle();
63920
+ }
63921
+ });
63922
+ };
63923
+
63924
+ // src/beacon/index.ts
63925
+ var BEACON_TIMEOUT_MS = 5e3;
63926
+ var BeaconEmitter = class {
63927
+ flag;
63928
+ envEndpoint;
63929
+ version;
63930
+ transport;
63931
+ constructor(opts) {
63932
+ this.flag = opts.flag;
63933
+ this.envEndpoint = opts.envEndpoint;
63934
+ this.version = opts.version;
63935
+ this.transport = opts.transport ?? sendBeacon;
63936
+ }
63937
+ /**
63938
+ * The two-gate opt-in. Returns true only when the user opted in
63939
+ * AND the endpoint env var is present and non-empty. Empty
63940
+ * string is treated as unset.
63941
+ */
63942
+ shouldFire() {
63943
+ return this.flag && !!this.envEndpoint && this.envEndpoint.length > 0;
63944
+ }
63945
+ /**
63946
+ * Build the locked 8-field payload and hand it to the transport.
63947
+ * Never throws. The returned Promise resolves when the transport
63948
+ * resolves — which is always, by contract.
63949
+ */
63950
+ async emit(stats) {
63951
+ if (!this.shouldFire()) return;
63952
+ const payload = {
63953
+ schema_version: "1",
63954
+ slopbrick_version: this.version,
63955
+ scan_id: stats.scanId,
63956
+ file_count: stats.fileCount,
63957
+ rule_count: stats.ruleCount,
63958
+ duration_ms: stats.durationMs,
63959
+ platform: process.platform,
63960
+ node_version: process.version
63961
+ };
63962
+ try {
63963
+ await this.transport(this.envEndpoint, payload, BEACON_TIMEOUT_MS);
63964
+ } catch {
63965
+ }
63966
+ }
63967
+ };
63968
+
62191
63969
  // src/cli/program.ts
62192
63970
  init_scan2();
62193
63971
  process.on("uncaughtException", (err) => {
@@ -62196,7 +63974,7 @@ process.on("uncaughtException", (err) => {
62196
63974
  });
62197
63975
  async function runCli({ start }) {
62198
63976
  try {
62199
- const program = new import_commander2.Command().name("slopbrick").description("Repository Coherence Scanner \u2014 surface AI-induced pattern drift, secret leaks, and design-token violations").version(VERSION).option("--framework <name>", "framework multiplier to apply").option("--include <glob>", "include pattern (repeatable)", collectGlob, []).option("--exclude <glob>", "exclude pattern (repeatable)", collectGlob, []).option("--ai-only", "only report AI-specific issues").option("--human-only", "only report human-facing issues").option("--ignore-wcag22", "ignore WCAG 2.2 related issues").option("--format <pretty|json|sarif|html>", "output format", "pretty").option("--threads <n>", "number of worker threads", parseThreads).option("--since <ref>", "only scan files changed since git ref").option("--diff <ref>", "alias for --since <ref>; also adds PR Slop Score to the report").option("--workspace <path>", "workspace/project path", process.cwd()).option("--tighten", "tighten baseline allowances").option("--fix", "apply auto-fixes").option("--dry-run", "with --fix: print what would change without writing").option("--show-fixes-diff", "print unified diff of proposed auto-fixes").option("--doctor", "run diagnostics").option("--watch", "watch files and re-run").option("--suggest", "print remediation advice").option("--why-failing", "print the top 5 rules dragging the score down").option("--brief", "terse output (verdict + headline + threshold + delta only)").option("--heatmap", "print migration ROI heatmap").option("--quiet", "suppress non-error output").option("--verbose", "enable debug logging (file paths, timings, rule-fire counts)").option("--strict", "exit 2 if any high-severity issue remains").option("--no-increase", "exit 2 if slop index increased since last run").option("--baseline", "save a baseline after this scan").option("--trend [n]", "print a sparkline of the last n runs", parseTrend).option("--json [path]", "write JSON report to path or stdout").option("--html [path]", "write HTML report to path or stdout").option("--staged", "scan only changed files (staged and unstaged)").option("--changed", "scan working-tree changes (staged + unstaged + untracked)").option("--incremental", "skip unchanged files using the persisted hash cache").option("--cache-path <path>", "path to the incremental-scan cache (default: .slopbrick-cache.json)").option("--tokens <path>", "merge tokens.json layout values into the arbitrary-value allowlist").option("--cache", "cache parsed AST results locally").option("--no-color", "suppress ANSI color codes in output").option("--security-only", "run only the security/* rules").option("--full", "show the complete report (all issues, all categories)");
63977
+ const program = new import_commander2.Command().name("slopbrick").description("Repository Coherence Scanner \u2014 surface AI-induced pattern drift, secret leaks, and design-token violations").version(VERSION).option("--framework <name>", "framework multiplier to apply").option("--include <glob>", "include pattern (repeatable)", collectGlob, []).option("--exclude <glob>", "exclude pattern (repeatable)", collectGlob, []).option("--ai-only", "only report AI-specific issues").option("--human-only", "only report human-facing issues").option("--ignore-wcag22", "ignore WCAG 2.2 related issues").option("--format <pretty|json|sarif|html>", "output format", "pretty").option("--threads <n>", "number of worker threads", parseThreads).option("--since <ref>", "only scan files changed since git ref").option("--diff <ref>", "alias for --since <ref>; also adds PR Slop Score to the report").option("--workspace <path>", "workspace/project path", process.cwd()).option("--tighten", "tighten baseline allowances").option("--fix", "apply auto-fixes").option("--dry-run", "with --fix: print what would change without writing").option("--show-fixes-diff", "print unified diff of proposed auto-fixes").option("--doctor", "run diagnostics").option("--watch", "watch files and re-run").option("--suggest", "print remediation advice").option("--why-failing", "print the top 5 rules dragging the score down").option("--brief", "terse output (verdict + headline + threshold + delta only)").option("--heatmap", "print migration ROI heatmap").option("--quiet", "suppress non-error output").option("--verbose", "enable debug logging (file paths, timings, rule-fire counts)").option("--strict", "exit 2 if any high-severity issue remains").option("--no-increase", "exit 2 if slop index increased since last run").option("--baseline", "save a baseline after this scan").option("--trend [n]", "print a sparkline of the last n runs", parseTrend).option("--json [path]", "write JSON report to path or stdout").option("--html [path]", "write HTML report to path or stdout").option("--staged", "scan only changed files (staged and unstaged)").option("--changed", "scan working-tree changes (staged + unstaged + untracked)").option("--incremental", "skip unchanged files using the persisted hash cache").option("--cache-path <path>", "path to the incremental-scan cache (default: .slopbrick-cache.json)").option("--tokens <path>", "merge tokens.json layout values into the arbitrary-value allowlist").option("--cache", "cache parsed AST results locally").option("--no-color", "suppress ANSI color codes in output").option("--security-only", "run only the security/* rules").option("--full", "show the complete report (all issues, all categories)").option("--report-usage", "opt in to a one-shot usage ping to SLOPBRICK_TELEMETRY_ENDPOINT (no PII)");
62200
63978
  program.helpInformation = () => formatGroupedHelp(program);
62201
63979
  registerInit(program);
62202
63980
  registerInstall(program);
@@ -62249,10 +64027,25 @@ async function runCli({ start }) {
62249
64027
  config,
62250
64028
  noIncreaseFailure,
62251
64029
  baseline,
62252
- machineReadableStdout
64030
+ machineReadableStdout,
64031
+ scanStats
62253
64032
  } = await runScan(options, paths);
62254
64033
  const scanElapsed = Math.round(performance.now() - scanStart);
62255
64034
  const totalElapsed = Math.round(performance.now() - start);
64035
+ const beaconEnv = process.env.SLOPBRICK_TELEMETRY_ENDPOINT;
64036
+ if (options.reportUsage && beaconEnv && command.name() === "scan") {
64037
+ const beacon = new BeaconEmitter({
64038
+ flag: true,
64039
+ envEndpoint: beaconEnv,
64040
+ version: VERSION
64041
+ });
64042
+ void beacon.emit({
64043
+ scanId: scanStats.scanId,
64044
+ fileCount: scanStats.fileCount,
64045
+ ruleCount: scanStats.ruleCount,
64046
+ durationMs: scanStats.durationMs
64047
+ });
64048
+ }
62256
64049
  if (options.baseline) {
62257
64050
  const cwd2 = (0, import_node_path70.resolve)(options.workspace ?? process.cwd());
62258
64051
  const configHash = hashConfig(config);