code-gauge 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +156 -106
  2. package/dist/cli.cjs +3 -3
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +3 -3
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cliConfig.cjs +1 -1
  7. package/dist/cliConfig.cjs.map +1 -1
  8. package/dist/cliConfig.d.ts +27 -84
  9. package/dist/cliConfig.js +1 -1
  10. package/dist/cliConfig.js.map +1 -1
  11. package/dist/crossFileDuplication.cjs +1 -1
  12. package/dist/crossFileDuplication.cjs.map +1 -1
  13. package/dist/crossFileDuplication.d.ts +9 -0
  14. package/dist/crossFileDuplication.js +1 -1
  15. package/dist/crossFileDuplication.js.map +1 -1
  16. package/dist/depDegree.cjs +2 -0
  17. package/dist/depDegree.cjs.map +1 -0
  18. package/dist/depDegree.d.ts +12 -0
  19. package/dist/depDegree.js +2 -0
  20. package/dist/depDegree.js.map +1 -0
  21. package/dist/diffCommand.cjs +5 -0
  22. package/dist/diffCommand.cjs.map +1 -0
  23. package/dist/diffCommand.d.ts +17 -0
  24. package/dist/diffCommand.js +5 -0
  25. package/dist/diffCommand.js.map +1 -0
  26. package/dist/duplication.cjs +1 -1
  27. package/dist/duplication.cjs.map +1 -1
  28. package/dist/duplication.d.ts +23 -2
  29. package/dist/duplication.js +1 -1
  30. package/dist/duplication.js.map +1 -1
  31. package/dist/git.cjs +2 -0
  32. package/dist/git.cjs.map +1 -0
  33. package/dist/git.d.ts +27 -0
  34. package/dist/git.js +2 -0
  35. package/dist/git.js.map +1 -0
  36. package/dist/index.cjs +1 -1
  37. package/dist/index.d.ts +4 -2
  38. package/dist/index.js +1 -1
  39. package/dist/languages.cjs +1 -1
  40. package/dist/languages.cjs.map +1 -1
  41. package/dist/languages.js +1 -1
  42. package/dist/languages.js.map +1 -1
  43. package/dist/metrics.cjs +1 -2
  44. package/dist/metrics.cjs.map +1 -1
  45. package/dist/metrics.d.ts +11 -0
  46. package/dist/metrics.js +1 -2
  47. package/dist/metrics.js.map +1 -1
  48. package/dist/nativeMetrics.cjs +1 -1
  49. package/dist/nativeMetrics.cjs.map +1 -1
  50. package/dist/nativeMetrics.d.ts +7 -3
  51. package/dist/nativeMetrics.js +1 -1
  52. package/dist/nativeMetrics.js.map +1 -1
  53. package/dist/regressionGate.cjs +2 -0
  54. package/dist/regressionGate.cjs.map +1 -0
  55. package/dist/regressionGate.d.ts +106 -0
  56. package/dist/regressionGate.js +2 -0
  57. package/dist/regressionGate.js.map +1 -0
  58. package/dist/scan.cjs +2 -0
  59. package/dist/scan.cjs.map +1 -0
  60. package/dist/scan.d.ts +55 -0
  61. package/dist/scan.js +2 -0
  62. package/dist/scan.js.map +1 -0
  63. package/dist/types.d.ts +24 -76
  64. package/package.json +7 -5
  65. package/dist/architectureMetrics.cjs +0 -2
  66. package/dist/architectureMetrics.cjs.map +0 -1
  67. package/dist/architectureMetrics.d.ts +0 -41
  68. package/dist/architectureMetrics.js +0 -2
  69. package/dist/architectureMetrics.js.map +0 -1
  70. package/dist/typescriptProject.cjs +0 -3
  71. package/dist/typescriptProject.cjs.map +0 -1
  72. package/dist/typescriptProject.d.ts +0 -24
  73. package/dist/typescriptProject.js +0 -3
  74. package/dist/typescriptProject.js.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./languages.cjs");let t=require("node:module");const n=new Map(e.defaultLanguages.map(e=>[e.name,e]));let r=!1,i;function a(e,t,r){if(!s()||n.get(t.name)!==t||!e.isWellFormed())return;let i=c();if(i)try{return JSON.parse(i.measureCodeNative(e,t.name,r))}catch(e){if(process.env.CODE_GAUGE_NATIVE_STRICT===`1`)throw e;return}}function o(){return s()&&c()!==void 0}function s(){return process.env.CODE_GAUGE_NATIVE!==`0`}function c(){if(r)return i;r=!0;try{i=(0,t.createRequire)(require("url").pathToFileURL(__filename).href)(`../native/code-gauge.node`)}catch{}return i}exports.isNativeBackendAvailable=o,exports.measureWithNativeBackend=a;
1
+ "use strict";const e=require("./languages.cjs");let t=require("node:module");const n=new Map(e.defaultLanguages.map(e=>[e.name,e]));let r=!1,i;function a(e,t,r){if(!s()||n.get(t.name)!==t||!e.isWellFormed())return;let i=c();if(i)try{return JSON.parse(i.measureCodeNative(e,t.name,r))}catch(e){if(process.env.CODE_GAUGE_NATIVE_STRICT===`1`)throw e;return}}function o(){return s()&&c()!==void 0}function s(){return process.env.CODE_GAUGE_NATIVE!==`0`}function c(){if(r)return i;r=!0;try{let e=(0,t.createRequire)(require("url").pathToFileURL(__filename).href)(`../native/code-gauge.node`);e.payloadVersion?.()===3&&(i=e)}catch{}return i}exports.isNativeBackendAvailable=o,exports.measureWithNativeBackend=a;
2
2
  //# sourceMappingURL=nativeMetrics.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"nativeMetrics.cjs","names":["defaultLanguages","createRequire"],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { defaultLanguages } from './languages.js';\nimport type { CodeMetrics, LanguageDefinition } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, difficulty, ...) are\n * computed in TypeScript because V8 and Rust disagree on the last bit of log/log2 results, and\n * the native backend must be bit-identical to the TypeScript one.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'maintainabilityIndex' | 'syntaxTree'> {\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n}\n\ninterface NativeBinding {\n measureCodeNative(code: string, language: string, includeSyntaxTree: boolean): string;\n}\n\nconst defaultLanguageByName = new Map(defaultLanguages.map((language) => [language.name, language]));\n\nlet bindingLoadAttempted = false;\nlet cachedBinding: NativeBinding | undefined;\n\n/**\n * Measures via the Rust addon when it is built and applicable, or returns undefined so the caller\n * falls back to the TypeScript implementation. Custom-registered languages always fall back: the\n * addon only embeds the built-in grammars.\n */\nexport function measureWithNativeBackend(\n code: string,\n language: LanguageDefinition,\n includeSyntaxTree: boolean\n): NativeMetricsPayload | undefined {\n if (!isNativeBackendEnabled() || defaultLanguageByName.get(language.name) !== language) {\n return undefined;\n }\n\n // Lone surrogates cannot cross the N-API boundary losslessly (they become U+FFFD), so\n // ill-formed strings measure through the TypeScript backend, which sees them as-is.\n if (!code.isWellFormed()) {\n return undefined;\n }\n\n const binding = loadBinding();\n if (!binding) {\n return undefined;\n }\n\n try {\n return JSON.parse(binding.measureCodeNative(code, language.name, includeSyntaxTree)) as NativeMetricsPayload;\n } catch (error) {\n // Parity tests set the strict flag: without it, a binding that starts throwing would silently\n // degrade the \"native\" side of every comparison into a TypeScript-vs-TypeScript check.\n if (process.env.CODE_GAUGE_NATIVE_STRICT === '1') {\n throw error;\n }\n // A native failure (e.g. the tree-depth guard on pathological input) falls back to the\n // TypeScript backend instead of turning measureCode into a throwing API.\n return undefined;\n }\n}\n\n/** Whether measureCode currently uses the native backend for built-in languages. */\nexport function isNativeBackendAvailable(): boolean {\n return isNativeBackendEnabled() && loadBinding() !== undefined;\n}\n\n/** Checked per call (not cached) so tests can flip backends within one process. */\nfunction isNativeBackendEnabled(): boolean {\n return process.env.CODE_GAUGE_NATIVE !== '0';\n}\n\nfunction loadBinding(): NativeBinding | undefined {\n if (bindingLoadAttempted) {\n return cachedBinding;\n }\n bindingLoadAttempted = true;\n\n try {\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find native/.\n const requireNative = createRequire(import.meta.url);\n cachedBinding = requireNative('../native/code-gauge.node') as NativeBinding;\n } catch {\n // The addon has not been built (or this platform/module format cannot load it).\n }\n return cachedBinding;\n}\n"],"mappings":"6EAyBA,MAAM,EAAwB,IAAI,IAAIA,EAAAA,iBAAiB,IAAK,GAAa,CAAC,EAAS,KAAM,CAAQ,CAAC,CAAC,EAEnG,IAAI,EAAuB,GACvB,EAOJ,SAAgB,EACd,EACA,EACA,EACkC,CAOlC,GANI,CAAC,EAAuB,GAAK,EAAsB,IAAI,EAAS,IAAI,IAAM,GAM1E,CAAC,EAAK,aAAa,EACrB,OAGF,IAAM,EAAU,EAAY,EACvB,KAIL,GAAI,CACF,OAAO,KAAK,MAAM,EAAQ,kBAAkB,EAAM,EAAS,KAAM,CAAiB,CAAC,CACrF,OAAS,EAAO,CAGd,GAAI,QAAQ,IAAI,2BAA6B,IAC3C,MAAM,EAIR,MACF,CACF,CAGA,SAAgB,GAAoC,CAClD,OAAO,EAAuB,GAAK,EAAY,IAAM,IAAA,EACvD,CAGA,SAAS,GAAkC,CACzC,OAAO,QAAQ,IAAI,oBAAsB,GAC3C,CAEA,SAAS,GAAyC,CAChD,GAAI,EACF,OAAO,EAET,EAAuB,GAEvB,GAAI,CAGF,GAAA,EADsBC,EAAAA,cAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,IACM,CAAC,CAAC,2BAA2B,CAC3D,MAAQ,CAER,CACA,OAAO,CACT"}
1
+ {"version":3,"file":"nativeMetrics.cjs","names":["defaultLanguages","createRequire"],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { defaultLanguages } from './languages.js';\nimport type { CodeMetrics, FunctionMetrics, LanguageDefinition } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, effort, ...) are\n * computed in TypeScript because V8 and Rust disagree on the last bit of log/log2 results, and\n * the native backend must be bit-identical to the TypeScript one.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeFunctionMetricsPayload extends Omit<FunctionMetrics, 'halstead'> {\n halsteadCounts: NativeHalsteadCounts;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'functions' | 'syntaxTree'> {\n functions: NativeFunctionMetricsPayload[];\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n}\n\ninterface NativeBinding {\n measureCodeNative(code: string, language: string, includeSyntaxTree: boolean): string;\n /** Absent on stale builds that predate payload versioning. */\n payloadVersion?(): number;\n}\n\n/**\n * Must equal `payload_version` in native/src/lib.rs. A previously built addon survives a\n * `git pull` untouched, so without this handshake it would silently return payloads missing\n * newer fields (e.g. duplication.duplicateLineNumbers) instead of falling back to the\n * TypeScript backend.\n */\nconst expectedPayloadVersion = 3;\n\nconst defaultLanguageByName = new Map(defaultLanguages.map((language) => [language.name, language]));\n\nlet bindingLoadAttempted = false;\nlet cachedBinding: NativeBinding | undefined;\n\n/**\n * Measures via the Rust addon when it is built and applicable, or returns undefined so the caller\n * falls back to the TypeScript implementation. Custom-registered languages always fall back: the\n * addon only embeds the built-in grammars.\n */\nexport function measureWithNativeBackend(\n code: string,\n language: LanguageDefinition,\n includeSyntaxTree: boolean\n): NativeMetricsPayload | undefined {\n if (!isNativeBackendEnabled() || defaultLanguageByName.get(language.name) !== language) {\n return undefined;\n }\n\n // Lone surrogates cannot cross the N-API boundary losslessly (they become U+FFFD), so\n // ill-formed strings measure through the TypeScript backend, which sees them as-is.\n if (!code.isWellFormed()) {\n return undefined;\n }\n\n const binding = loadBinding();\n if (!binding) {\n return undefined;\n }\n\n try {\n return JSON.parse(binding.measureCodeNative(code, language.name, includeSyntaxTree)) as NativeMetricsPayload;\n } catch (error) {\n // Parity tests set the strict flag: without it, a binding that starts throwing would silently\n // degrade the \"native\" side of every comparison into a TypeScript-vs-TypeScript check.\n if (process.env.CODE_GAUGE_NATIVE_STRICT === '1') {\n throw error;\n }\n // A native failure (e.g. the tree-depth guard on pathological input) falls back to the\n // TypeScript backend instead of turning measureCode into a throwing API.\n return undefined;\n }\n}\n\n/** Whether measureCode currently uses the native backend for built-in languages. */\nexport function isNativeBackendAvailable(): boolean {\n return isNativeBackendEnabled() && loadBinding() !== undefined;\n}\n\n/** Checked per call (not cached) so tests can flip backends within one process. */\nfunction isNativeBackendEnabled(): boolean {\n return process.env.CODE_GAUGE_NATIVE !== '0';\n}\n\nfunction loadBinding(): NativeBinding | undefined {\n if (bindingLoadAttempted) {\n return cachedBinding;\n }\n bindingLoadAttempted = true;\n\n try {\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find native/.\n const requireNative = createRequire(import.meta.url);\n const binding = requireNative('../native/code-gauge.node') as NativeBinding;\n if (binding.payloadVersion?.() === expectedPayloadVersion) {\n cachedBinding = binding;\n }\n // A version mismatch (or a build too old to report one) leaves the binding unused, like a\n // missing addon: rebuild with `yarn build-native` to re-enable the native backend.\n } catch {\n // The addon has not been built (or this platform/module format cannot load it).\n }\n return cachedBinding;\n}\n"],"mappings":"6EAsCA,MAEM,EAAwB,IAAI,IAAIA,EAAAA,iBAAiB,IAAK,GAAa,CAAC,EAAS,KAAM,CAAQ,CAAC,CAAC,EAEnG,IAAI,EAAuB,GACvB,EAOJ,SAAgB,EACd,EACA,EACA,EACkC,CAOlC,GANI,CAAC,EAAuB,GAAK,EAAsB,IAAI,EAAS,IAAI,IAAM,GAM1E,CAAC,EAAK,aAAa,EACrB,OAGF,IAAM,EAAU,EAAY,EACvB,KAIL,GAAI,CACF,OAAO,KAAK,MAAM,EAAQ,kBAAkB,EAAM,EAAS,KAAM,CAAiB,CAAC,CACrF,OAAS,EAAO,CAGd,GAAI,QAAQ,IAAI,2BAA6B,IAC3C,MAAM,EAIR,MACF,CACF,CAGA,SAAgB,GAAoC,CAClD,OAAO,EAAuB,GAAK,EAAY,IAAM,IAAA,EACvD,CAGA,SAAS,GAAkC,CACzC,OAAO,QAAQ,IAAI,oBAAsB,GAC3C,CAEA,SAAS,GAAyC,CAChD,GAAI,EACF,OAAO,EAET,EAAuB,GAEvB,GAAI,CAGF,IAAM,GAAA,EADgBC,EAAAA,cAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,IACM,CAAC,CAAC,2BAA2B,EACrD,EAAQ,iBAAiB,IAAM,IACjC,EAAgB,EAIpB,MAAQ,CAER,CACA,OAAO,CACT"}
@@ -1,6 +1,6 @@
1
- import type { CodeMetrics, LanguageDefinition } from './types.js';
1
+ import type { CodeMetrics, FunctionMetrics, LanguageDefinition } from './types.js';
2
2
  /**
3
- * Halstead counts measured natively; the derived float metrics (volume, difficulty, ...) are
3
+ * Halstead counts measured natively; the derived float metrics (volume, effort, ...) are
4
4
  * computed in TypeScript because V8 and Rust disagree on the last bit of log/log2 results, and
5
5
  * the native backend must be bit-identical to the TypeScript one.
6
6
  */
@@ -10,7 +10,11 @@ export interface NativeHalsteadCounts {
10
10
  totalOperators: number;
11
11
  totalOperands: number;
12
12
  }
13
- export interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'maintainabilityIndex' | 'syntaxTree'> {
13
+ export interface NativeFunctionMetricsPayload extends Omit<FunctionMetrics, 'halstead'> {
14
+ halsteadCounts: NativeHalsteadCounts;
15
+ }
16
+ export interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'functions' | 'syntaxTree'> {
17
+ functions: NativeFunctionMetricsPayload[];
14
18
  halsteadCounts: NativeHalsteadCounts;
15
19
  syntaxTree?: string;
16
20
  }
@@ -1,2 +1,2 @@
1
- import{defaultLanguages as e}from"./languages.js";import{createRequire as t}from"node:module";const n=new Map(e.map(e=>[e.name,e]));let r=!1,i;function a(e,t,r){if(!s()||n.get(t.name)!==t||!e.isWellFormed())return;let i=c();if(i)try{return JSON.parse(i.measureCodeNative(e,t.name,r))}catch(e){if(process.env.CODE_GAUGE_NATIVE_STRICT===`1`)throw e;return}}function o(){return s()&&c()!==void 0}function s(){return process.env.CODE_GAUGE_NATIVE!==`0`}function c(){if(r)return i;r=!0;try{i=t(import.meta.url)(`../native/code-gauge.node`)}catch{}return i}export{o as isNativeBackendAvailable,a as measureWithNativeBackend};
1
+ import{defaultLanguages as e}from"./languages.js";import{createRequire as t}from"node:module";const n=new Map(e.map(e=>[e.name,e]));let r=!1,i;function a(e,t,r){if(!s()||n.get(t.name)!==t||!e.isWellFormed())return;let i=c();if(i)try{return JSON.parse(i.measureCodeNative(e,t.name,r))}catch(e){if(process.env.CODE_GAUGE_NATIVE_STRICT===`1`)throw e;return}}function o(){return s()&&c()!==void 0}function s(){return process.env.CODE_GAUGE_NATIVE!==`0`}function c(){if(r)return i;r=!0;try{let e=t(import.meta.url)(`../native/code-gauge.node`);e.payloadVersion?.()===3&&(i=e)}catch{}return i}export{o as isNativeBackendAvailable,a as measureWithNativeBackend};
2
2
  //# sourceMappingURL=nativeMetrics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"nativeMetrics.js","names":[],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { defaultLanguages } from './languages.js';\nimport type { CodeMetrics, LanguageDefinition } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, difficulty, ...) are\n * computed in TypeScript because V8 and Rust disagree on the last bit of log/log2 results, and\n * the native backend must be bit-identical to the TypeScript one.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'maintainabilityIndex' | 'syntaxTree'> {\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n}\n\ninterface NativeBinding {\n measureCodeNative(code: string, language: string, includeSyntaxTree: boolean): string;\n}\n\nconst defaultLanguageByName = new Map(defaultLanguages.map((language) => [language.name, language]));\n\nlet bindingLoadAttempted = false;\nlet cachedBinding: NativeBinding | undefined;\n\n/**\n * Measures via the Rust addon when it is built and applicable, or returns undefined so the caller\n * falls back to the TypeScript implementation. Custom-registered languages always fall back: the\n * addon only embeds the built-in grammars.\n */\nexport function measureWithNativeBackend(\n code: string,\n language: LanguageDefinition,\n includeSyntaxTree: boolean\n): NativeMetricsPayload | undefined {\n if (!isNativeBackendEnabled() || defaultLanguageByName.get(language.name) !== language) {\n return undefined;\n }\n\n // Lone surrogates cannot cross the N-API boundary losslessly (they become U+FFFD), so\n // ill-formed strings measure through the TypeScript backend, which sees them as-is.\n if (!code.isWellFormed()) {\n return undefined;\n }\n\n const binding = loadBinding();\n if (!binding) {\n return undefined;\n }\n\n try {\n return JSON.parse(binding.measureCodeNative(code, language.name, includeSyntaxTree)) as NativeMetricsPayload;\n } catch (error) {\n // Parity tests set the strict flag: without it, a binding that starts throwing would silently\n // degrade the \"native\" side of every comparison into a TypeScript-vs-TypeScript check.\n if (process.env.CODE_GAUGE_NATIVE_STRICT === '1') {\n throw error;\n }\n // A native failure (e.g. the tree-depth guard on pathological input) falls back to the\n // TypeScript backend instead of turning measureCode into a throwing API.\n return undefined;\n }\n}\n\n/** Whether measureCode currently uses the native backend for built-in languages. */\nexport function isNativeBackendAvailable(): boolean {\n return isNativeBackendEnabled() && loadBinding() !== undefined;\n}\n\n/** Checked per call (not cached) so tests can flip backends within one process. */\nfunction isNativeBackendEnabled(): boolean {\n return process.env.CODE_GAUGE_NATIVE !== '0';\n}\n\nfunction loadBinding(): NativeBinding | undefined {\n if (bindingLoadAttempted) {\n return cachedBinding;\n }\n bindingLoadAttempted = true;\n\n try {\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find native/.\n const requireNative = createRequire(import.meta.url);\n cachedBinding = requireNative('../native/code-gauge.node') as NativeBinding;\n } catch {\n // The addon has not been built (or this platform/module format cannot load it).\n }\n return cachedBinding;\n}\n"],"mappings":"8FAyBA,MAAM,EAAwB,IAAI,IAAI,EAAiB,IAAK,GAAa,CAAC,EAAS,KAAM,CAAQ,CAAC,CAAC,EAEnG,IAAI,EAAuB,GACvB,EAOJ,SAAgB,EACd,EACA,EACA,EACkC,CAOlC,GANI,CAAC,EAAuB,GAAK,EAAsB,IAAI,EAAS,IAAI,IAAM,GAM1E,CAAC,EAAK,aAAa,EACrB,OAGF,IAAM,EAAU,EAAY,EACvB,KAIL,GAAI,CACF,OAAO,KAAK,MAAM,EAAQ,kBAAkB,EAAM,EAAS,KAAM,CAAiB,CAAC,CACrF,OAAS,EAAO,CAGd,GAAI,QAAQ,IAAI,2BAA6B,IAC3C,MAAM,EAIR,MACF,CACF,CAGA,SAAgB,GAAoC,CAClD,OAAO,EAAuB,GAAK,EAAY,IAAM,IAAA,EACvD,CAGA,SAAS,GAAkC,CACzC,OAAO,QAAQ,IAAI,oBAAsB,GAC3C,CAEA,SAAS,GAAyC,CAChD,GAAI,EACF,OAAO,EAET,EAAuB,GAEvB,GAAI,CAGF,EADsB,EAAc,YAAY,GACpB,CAAC,CAAC,2BAA2B,CAC3D,MAAQ,CAER,CACA,OAAO,CACT"}
1
+ {"version":3,"file":"nativeMetrics.js","names":[],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { defaultLanguages } from './languages.js';\nimport type { CodeMetrics, FunctionMetrics, LanguageDefinition } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, effort, ...) are\n * computed in TypeScript because V8 and Rust disagree on the last bit of log/log2 results, and\n * the native backend must be bit-identical to the TypeScript one.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeFunctionMetricsPayload extends Omit<FunctionMetrics, 'halstead'> {\n halsteadCounts: NativeHalsteadCounts;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'functions' | 'syntaxTree'> {\n functions: NativeFunctionMetricsPayload[];\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n}\n\ninterface NativeBinding {\n measureCodeNative(code: string, language: string, includeSyntaxTree: boolean): string;\n /** Absent on stale builds that predate payload versioning. */\n payloadVersion?(): number;\n}\n\n/**\n * Must equal `payload_version` in native/src/lib.rs. A previously built addon survives a\n * `git pull` untouched, so without this handshake it would silently return payloads missing\n * newer fields (e.g. duplication.duplicateLineNumbers) instead of falling back to the\n * TypeScript backend.\n */\nconst expectedPayloadVersion = 3;\n\nconst defaultLanguageByName = new Map(defaultLanguages.map((language) => [language.name, language]));\n\nlet bindingLoadAttempted = false;\nlet cachedBinding: NativeBinding | undefined;\n\n/**\n * Measures via the Rust addon when it is built and applicable, or returns undefined so the caller\n * falls back to the TypeScript implementation. Custom-registered languages always fall back: the\n * addon only embeds the built-in grammars.\n */\nexport function measureWithNativeBackend(\n code: string,\n language: LanguageDefinition,\n includeSyntaxTree: boolean\n): NativeMetricsPayload | undefined {\n if (!isNativeBackendEnabled() || defaultLanguageByName.get(language.name) !== language) {\n return undefined;\n }\n\n // Lone surrogates cannot cross the N-API boundary losslessly (they become U+FFFD), so\n // ill-formed strings measure through the TypeScript backend, which sees them as-is.\n if (!code.isWellFormed()) {\n return undefined;\n }\n\n const binding = loadBinding();\n if (!binding) {\n return undefined;\n }\n\n try {\n return JSON.parse(binding.measureCodeNative(code, language.name, includeSyntaxTree)) as NativeMetricsPayload;\n } catch (error) {\n // Parity tests set the strict flag: without it, a binding that starts throwing would silently\n // degrade the \"native\" side of every comparison into a TypeScript-vs-TypeScript check.\n if (process.env.CODE_GAUGE_NATIVE_STRICT === '1') {\n throw error;\n }\n // A native failure (e.g. the tree-depth guard on pathological input) falls back to the\n // TypeScript backend instead of turning measureCode into a throwing API.\n return undefined;\n }\n}\n\n/** Whether measureCode currently uses the native backend for built-in languages. */\nexport function isNativeBackendAvailable(): boolean {\n return isNativeBackendEnabled() && loadBinding() !== undefined;\n}\n\n/** Checked per call (not cached) so tests can flip backends within one process. */\nfunction isNativeBackendEnabled(): boolean {\n return process.env.CODE_GAUGE_NATIVE !== '0';\n}\n\nfunction loadBinding(): NativeBinding | undefined {\n if (bindingLoadAttempted) {\n return cachedBinding;\n }\n bindingLoadAttempted = true;\n\n try {\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find native/.\n const requireNative = createRequire(import.meta.url);\n const binding = requireNative('../native/code-gauge.node') as NativeBinding;\n if (binding.payloadVersion?.() === expectedPayloadVersion) {\n cachedBinding = binding;\n }\n // A version mismatch (or a build too old to report one) leaves the binding unused, like a\n // missing addon: rebuild with `yarn build-native` to re-enable the native backend.\n } catch {\n // The addon has not been built (or this platform/module format cannot load it).\n }\n return cachedBinding;\n}\n"],"mappings":"8FAsCA,MAEM,EAAwB,IAAI,IAAI,EAAiB,IAAK,GAAa,CAAC,EAAS,KAAM,CAAQ,CAAC,CAAC,EAEnG,IAAI,EAAuB,GACvB,EAOJ,SAAgB,EACd,EACA,EACA,EACkC,CAOlC,GANI,CAAC,EAAuB,GAAK,EAAsB,IAAI,EAAS,IAAI,IAAM,GAM1E,CAAC,EAAK,aAAa,EACrB,OAGF,IAAM,EAAU,EAAY,EACvB,KAIL,GAAI,CACF,OAAO,KAAK,MAAM,EAAQ,kBAAkB,EAAM,EAAS,KAAM,CAAiB,CAAC,CACrF,OAAS,EAAO,CAGd,GAAI,QAAQ,IAAI,2BAA6B,IAC3C,MAAM,EAIR,MACF,CACF,CAGA,SAAgB,GAAoC,CAClD,OAAO,EAAuB,GAAK,EAAY,IAAM,IAAA,EACvD,CAGA,SAAS,GAAkC,CACzC,OAAO,QAAQ,IAAI,oBAAsB,GAC3C,CAEA,SAAS,GAAyC,CAChD,GAAI,EACF,OAAO,EAET,EAAuB,GAEvB,GAAI,CAGF,IAAM,EADgB,EAAc,YAAY,GACpB,CAAC,CAAC,2BAA2B,EACrD,EAAQ,iBAAiB,IAAM,IACjC,EAAgB,EAIpB,MAAQ,CAER,CACA,OAAO,CACT"}
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("./duplication.cjs"),t={newFunction:{maxCognitiveComplexity:15,maxNcss:60,maxNestingDepth:4},tolerance:{cognitiveComplexity:2,ncss:5,nestingDepth:1,depDegree:10,halsteadVolume:150,fileNcss:20,duplicateLines:0},matchSimilarityPercent:70},n=String,r=[{metric:`cognitive complexity`,value:e=>e.cognitiveComplexity,allowance:e=>e.cognitiveComplexity,remediation:`Simplify the added branching or split the function.`,format:n},{metric:`NCSS`,value:e=>e.ncss,allowance:e=>e.ncss,remediation:`Extract the added statements into helper functions or remove them.`,format:n},{metric:`max nesting depth`,value:e=>e.nestingDepth,allowance:e=>e.nestingDepth,remediation:`Flatten the added nesting with early returns or extracted helpers.`,format:n},{metric:`DepDegree`,value:e=>e.depDegree,allowance:e=>e.depDegree,remediation:`Reduce how many earlier definitions the code reads, e.g. by splitting the data flow.`,format:n},{metric:`Halstead volume`,value:e=>e.halstead.volume,allowance:(e,t)=>Math.max(e.halsteadVolume,t*.25),remediation:`Shrink the function: fewer distinct names and operations.`,format:e=>e.toFixed(1)}],i=[{metric:`cognitive complexity`,value:e=>e.cognitiveComplexity,limit:e=>e.maxCognitiveComplexity,remediation:`Split the new function or simplify its branching.`},{metric:`NCSS`,value:e=>e.ncss,limit:e=>e.maxNcss,remediation:`Split the new function into smaller ones.`},{metric:`max nesting depth`,value:e=>e.nestingDepth,limit:e=>e.maxNestingDepth,remediation:`Flatten the new function with early returns or extracted helpers.`}];function a(e,t){let n=l(e,t.matchSimilarityPercent),r=[],i=[],a=0,c=0;for(let o of n.pairs){let n=e[o.headFileIndex];n.gated!==!1&&(a+=1,r.push(...y(n.file,o.base,o.head,t.tolerance)),i.push(s(n.file,o.head,o.base)))}let u=0;for(let[a,l]of e.entries()){if(l.gated===!1)continue;u+=1;let e=l.headMetrics?.functions??[],d=n.headMatched[a];for(let[n,a]of e.entries())d[n]||(c+=1,r.push(...b(l.file,a,t.newFunction)),i.push(s(l.file,a)));r.push(...x(l,o(l,a,n),r,t)),r.push(...C(l,t.tolerance))}return r.sort((e,t)=>e.file.localeCompare(t.file)||e.startLine-t.startLine),i.sort((e,t)=>e.file.localeCompare(t.file)||e.startLine-t.startLine),{violations:r,checkedFileCount:u,checkedFunctionCount:a+c,newFunctionCount:c,checkedFunctions:i}}function o(e,t,n){let r=e.baseMetrics?.functions??[],i=n.baseMatched[t],a=n.headMatched[t],o=r.flatMap((e,t)=>!i[t]&&e.name!==void 0?[t]:[]);if(o.length===0)return!1;let s=(e.headMetrics?.functions??[]).flatMap((e,t)=>a[t]?[]:[t]);return o.length*s.length>f?!1:o.some(t=>s.some(n=>v(e.baseFunctionTokens?.[t],e.headFunctionTokens?.[n],30)>=30))}function s(e,t,n){return{file:e,name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,base:n?c(n):void 0,head:c(t)}}function c(e){return{cognitiveComplexity:e.cognitiveComplexity,ncss:e.ncss,nestingDepth:e.nestingDepth,depDegree:e.depDegree,halsteadVolume:e.halstead.volume}}function l(e,t){let n=e.map(e=>(e.baseMetrics?.functions??[]).map(()=>!1)),r=e.map(e=>(e.headMetrics?.functions??[]).map(()=>!1)),i=[];for(let t of e.keys()){let a=a=>{let o=d(u(e,n,`base`,t),a),s=d(u(e,r,`head`,t),a);for(let[e,t]of o)p(t,s.get(e)??[],n,r,i)};a(e=>e.name===void 0?void 0:`${e.name}\u0000${e.parameterCount}`),a(e=>e.name)}return m(e,n,r,i,t),{pairs:i,baseMatched:n,headMatched:r}}function u(e,t,n,r){let i=[];for(let[a,o]of e.entries()){if(r!==void 0&&a!==r)continue;let e=t[a],s=n===`base`?o.baseMetrics:o.headMetrics,c=n===`base`?o.baseFunctionTokens:o.headFunctionTokens;for(let[t,n]of(s?.functions??[]).entries())e[t]||i.push({fileIndex:a,functionIndex:t,fn:n,tokens:c?.[t]})}return i}function d(e,t){let n=new Map;for(let r of e){let e=t(r.fn);if(e===void 0)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return n}const f=1e4;function p(e,t,n,r,i){let a=e.length+t.length>2&&e.length*t.length<=f,o=[];for(let[n,r]of e.entries())for(let[e,i]of t.entries())o.push({similarity:a?v(r.tokens,i.tokens,0):0,basePosition:n,headPosition:e});h(o,e,t,n,r,i)}function m(e,t,n,r,i){let a=u(e,t,`base`),o=u(e,n,`head`);if(a.length*o.length>f)return;let s=[];for(let[e,t]of a.entries())for(let[n,r]of o.entries()){let a=v(t.tokens,r.tokens,i);a>=i&&s.push({similarity:a,basePosition:e,headPosition:n})}h(s,a,o,t,n,r)}function h(e,t,n,r,i,a){e.sort((e,t)=>t.similarity-e.similarity||e.basePosition-t.basePosition||e.headPosition-t.headPosition);let o=new Map,s=new Map,c=new Set,l=g(e,o,s,c);for(let e of[...o.keys()].toSorted((e,t)=>e-t))l.has(e)||_(e,o,s,c,new Set);for(let[e,o]of[...s.entries()].toSorted((e,t)=>e[0]-t[0])){let s=t[o],c=n[e];r[s.fileIndex][s.functionIndex]=!0,i[c.fileIndex][c.functionIndex]=!0,a.push({base:s.fn,head:c.fn,headFileIndex:c.fileIndex})}}function g(e,t,n,r){let i=new Set;for(let a of e){let e=t.get(a.basePosition)??[];e.push(a.headPosition),t.set(a.basePosition,e),!i.has(a.basePosition)&&!n.has(a.headPosition)&&(n.set(a.headPosition,a.basePosition),i.add(a.basePosition),a.similarity===100&&r.add(a.headPosition))}return i}function _(e,t,n,r,i){for(let a of t.get(e)??[]){if(i.has(a)||r.has(a))continue;i.add(a);let o=n.get(a);if(o===void 0||_(o,t,n,r,i))return n.set(a,e),!0}return!1}function v(t,n,r){if(!t||!n||t.length===0||n.length===0)return 0;let i=Math.max(t.length,n.length);return Math.min(t.length,n.length)*100<r*i?0:e.lcsLength(t,n)*100/i}function y(e,t,n,i){let a=[];for(let o of r){let r=o.value(t),s=o.value(n),c=r+o.allowance(i,r);if(s>c){let t=n.name??`<anonymous>`;a.push({gate:`function-regression`,metric:o.metric,file:e,functionName:t,startLine:n.startLine,endLine:n.endLine,baseValue:r,headValue:s,allowedValue:c,message:`${e}:${n.startLine}-${n.endLine} ${t}: ${o.metric} worsened ${o.format(r)} -> ${o.format(s)} (allowed <= ${o.format(c)}). `+o.remediation})}}return a}function b(e,t,n){let r=[];for(let a of i){let i=a.value(t),o=a.limit(n);if(i>o){let n=t.name??`<anonymous>`;r.push({gate:`new-function`,metric:a.metric,file:e,functionName:n,startLine:t.startLine,endLine:t.endLine,headValue:i,allowedValue:o,message:`${e}:${t.startLine}-${t.endLine} new function ${n}: ${a.metric} ${i} exceeds the new-code limit ${o}. ${a.remediation}`})}}return r}function x(e,t,n,r){let{baseMetrics:i,headMetrics:a}=e;if(!i||!a||!t)return[];let o=[],s=r.tolerance,c=n.some(t=>t.file===e.file&&t.metric===`cognitive complexity`&&(t.gate===`function-regression`||t.gate===`new-function`)&&t.headValue===a.maxCognitiveComplexity),l=i.maxCognitiveComplexity+s.cognitiveComplexity;if(!c&&a.maxCognitiveComplexity>l){let t=S(a.functions),n=t?.startLine??1,r=t?.endLine??a.lines.total;o.push({gate:`file-regression`,metric:`file max cognitive complexity`,file:e.file,functionName:t?.name??void 0,startLine:n,endLine:r,baseValue:i.maxCognitiveComplexity,headValue:a.maxCognitiveComplexity,allowedValue:l,message:`${e.file}:${n}-${r}: the file's max cognitive complexity worsened ${i.maxCognitiveComplexity} -> ${a.maxCognitiveComplexity} (allowed <= ${l}). Simplify or split the most complex function${t?` (${t.name??`<anonymous>`})`:``}.`})}let u=i.ncssCount+s.fileNcss;return a.ncssCount>u&&o.push({gate:`file-regression`,metric:`file NCSS`,file:e.file,startLine:1,endLine:a.lines.total,baseValue:i.ncssCount,headValue:a.ncssCount,allowedValue:u,message:`${e.file}:1-${a.lines.total}: functions were removed or split while the file grew from NCSS ${i.ncssCount} to ${a.ncssCount} (allowed <= ${u}). Remove the added statements or move genuinely new code into its own module.`}),o}function S(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity)&&(t=n);return t}function C(e,t){let n=e.baseDuplicatedLineCount+t.duplicateLines;if(e.headDuplicatedLineCount<=n)return[];let r=e.duplicationPartners.slice(0,3).join(`, `),i=e.headMetrics?.lines.total??1;return[{gate:`duplication`,metric:`duplicated lines`,file:e.file,startLine:1,endLine:i,baseValue:e.baseDuplicatedLineCount,headValue:e.headDuplicatedLineCount,allowedValue:n,message:`${e.file}:1-${i}: duplicated lines increased ${e.baseDuplicatedLineCount} -> ${e.headDuplicatedLineCount} (allowed <= ${n}). Deduplicate${r?` against ${r}`:` the repeated code`} by extracting a shared helper.`}]}exports.defaultGateOptions=t,exports.evaluateRegressionGate=a;
2
+ //# sourceMappingURL=regressionGate.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regressionGate.cjs","names":["lcsLength"],"sources":["../src/regressionGate.ts"],"sourcesContent":["import { lcsLength } from './duplication.js';\nimport type { CodeMetrics, FunctionMetrics } from './types.js';\n\n/**\n * Absolute limits applied only to functions with no base counterpart (SonarQube-style \"Clean as\n * You Code\"): new code is the one place absolute thresholds are required, since there is nothing\n * to ratchet against.\n */\nexport interface NewFunctionThresholds {\n maxCognitiveComplexity: number;\n maxNcss: number;\n maxNestingDepth: number;\n}\n\n/**\n * Allowances added on top of each base value before a ratchet fires, so legitimate refactorings\n * that transiently worsen one number (e.g. an extraction adding a few NCSS lines) don't trap the\n * agent in a loop.\n */\nexport interface GateTolerances {\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n depDegree: number;\n halsteadVolume: number;\n /** File-total NCSS growth allowed when base functions disappeared (the anti-gaming backstop). */\n fileNcss: number;\n /** Duplicated-line growth allowed per changed file. */\n duplicateLines: number;\n}\n\nexport interface GateOptions {\n newFunction: NewFunctionThresholds;\n tolerance: GateTolerances;\n /**\n * Minimum token-LCS similarity percent for re-matching a renamed/moved function to its base\n * counterpart, so renames don't appear as delete+add and hit the new-code thresholds.\n */\n matchSimilarityPercent: number;\n}\n\nexport const defaultGateOptions: GateOptions = {\n // 15 is SonarSource's conventional default; 4 is where the measured cognitive-load response to\n // nesting saturates (Peitek et al. 2021); 60 matches PMD's NcssCount method default.\n newFunction: { maxCognitiveComplexity: 15, maxNcss: 60, maxNestingDepth: 4 },\n // The per-metric allowances are calibrated to admit roughly the same edit: ~5 added statements\n // or one added branch (cognitive 2 ~ nesting 1 ~ ncss 5 ~ depDegree 10 ~ Halstead volume 150;\n // the volume allowance additionally scales with the base value, see ratchetMetrics), so one\n // ratchet cannot block an addition the others deliberately allow.\n tolerance: {\n cognitiveComplexity: 2,\n ncss: 5,\n nestingDepth: 1,\n depDegree: 10,\n halsteadVolume: 150,\n fileNcss: 20,\n duplicateLines: 0,\n },\n matchSimilarityPercent: 70,\n};\n\n/** One changed file with both revisions measured; the caller resolves git and duplication data. */\nexport interface GateFileInput {\n /** Display path (repository-relative head path; base path for deleted files). */\n file: string;\n /** Absent for added files. */\n baseMetrics?: CodeMetrics;\n /** Absent for deleted files. */\n headMetrics?: CodeMetrics;\n /** Token sequences index-parallel to baseMetrics.functions, for similarity re-matching. */\n baseFunctionTokens?: Int32Array[];\n headFunctionTokens?: Int32Array[];\n /** Distinct duplicated lines of this file at the base revision (within-file and cross-file). */\n baseDuplicatedLineCount: number;\n headDuplicatedLineCount: number;\n /** Other files sharing cross-file duplicates with this file at head, as remediation evidence. */\n duplicationPartners: string[];\n /**\n * false: the file only feeds function matching and the duplication universes (it lies outside\n * the gated target directory); no violations are evaluated or reported for it. Default true.\n */\n gated?: boolean;\n}\n\nexport interface GateViolation {\n gate: 'function-regression' | 'new-function' | 'file-regression' | 'duplication';\n metric: string;\n file: string;\n functionName?: string;\n startLine: number;\n endLine: number;\n /** Absent for new-function violations, which have no base value. */\n baseValue?: number;\n headValue: number;\n /** The largest value that would have passed. */\n allowedValue: number;\n /** One-line human/agent-readable statement with the remediation direction. */\n message: string;\n}\n\n/** The gated per-function values of one checked (matched or new) function, for `--full` output. */\nexport interface CheckedFunctionReport {\n /** The head file (a cross-file move is reported where the function now lives). */\n file: string;\n name: string;\n startLine: number;\n endLine: number;\n /** Absent for new functions. */\n base?: GateFunctionValues;\n head: GateFunctionValues;\n}\n\nexport interface GateFunctionValues {\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n depDegree: number;\n halsteadVolume: number;\n}\n\nexport interface GateResult {\n violations: GateViolation[];\n checkedFileCount: number;\n checkedFunctionCount: number;\n newFunctionCount: number;\n /** Every checked function with its gated values, ordered by file and line. */\n checkedFunctions: CheckedFunctionReport[];\n}\n\ninterface RatchetMetric {\n metric: string;\n value: (fn: FunctionMetrics) => number;\n /** The growth allowed on top of the base value before the ratchet fires. */\n allowance: (tolerances: GateTolerances, baseValue: number) => number;\n remediation: string;\n format: (value: number) => string;\n}\n\nconst formatInteger = String;\nconst formatFloat = (value: number): string => value.toFixed(1);\n\n/**\n * Gate-eligible per-function metrics (monotone, stable, actionable): a matched function must not\n * worsen any of them beyond its tolerance. \"Your change made this function worse\" is defensible\n * regardless of metric calibration, so no absolute threshold is involved.\n */\nconst ratchetMetrics: RatchetMetric[] = [\n {\n metric: 'cognitive complexity',\n value: (fn) => fn.cognitiveComplexity,\n allowance: (tolerances) => tolerances.cognitiveComplexity,\n remediation: 'Simplify the added branching or split the function.',\n format: formatInteger,\n },\n {\n metric: 'NCSS',\n value: (fn) => fn.ncss,\n allowance: (tolerances) => tolerances.ncss,\n remediation: 'Extract the added statements into helper functions or remove them.',\n format: formatInteger,\n },\n {\n metric: 'max nesting depth',\n value: (fn) => fn.nestingDepth,\n allowance: (tolerances) => tolerances.nestingDepth,\n remediation: 'Flatten the added nesting with early returns or extracted helpers.',\n format: formatInteger,\n },\n {\n metric: 'DepDegree',\n value: (fn) => fn.depDegree,\n allowance: (tolerances) => tolerances.depDegree,\n remediation: 'Reduce how many earlier definitions the code reads, e.g. by splitting the data flow.',\n format: formatInteger,\n },\n {\n metric: 'Halstead volume',\n value: (fn) => fn.halstead.volume,\n // Volume grows as length * log2(vocabulary), so a flat allowance that admits ~5 statements in\n // a small function admits barely one in a large-vocabulary function; the relative term keeps\n // the ~5-statement calibration at every function size.\n allowance: (tolerances, baseValue) => Math.max(tolerances.halsteadVolume, baseValue * 0.25),\n remediation: 'Shrink the function: fewer distinct names and operations.',\n format: formatFloat,\n },\n];\n\ninterface NewFunctionMetric {\n metric: string;\n value: (fn: FunctionMetrics) => number;\n limit: (thresholds: NewFunctionThresholds) => number;\n remediation: string;\n}\n\nconst newFunctionMetrics: NewFunctionMetric[] = [\n {\n metric: 'cognitive complexity',\n value: (fn) => fn.cognitiveComplexity,\n limit: (thresholds) => thresholds.maxCognitiveComplexity,\n remediation: 'Split the new function or simplify its branching.',\n },\n {\n metric: 'NCSS',\n value: (fn) => fn.ncss,\n limit: (thresholds) => thresholds.maxNcss,\n remediation: 'Split the new function into smaller ones.',\n },\n {\n metric: 'max nesting depth',\n value: (fn) => fn.nestingDepth,\n limit: (thresholds) => thresholds.maxNestingDepth,\n remediation: 'Flatten the new function with early returns or extracted helpers.',\n },\n];\n\n/**\n * Evaluates the regression gate over changed files measured at both revisions. Violations are the\n * whole output contract: everything that passes stays silent, so a clean change costs the\n * consuming agent almost no tokens.\n */\nexport function evaluateRegressionGate(files: GateFileInput[], options: GateOptions): GateResult {\n const matching = matchAllFunctions(files, options.matchSimilarityPercent);\n const violations: GateViolation[] = [];\n const checkedFunctions: CheckedFunctionReport[] = [];\n let checkedPairCount = 0;\n let newFunctionCount = 0;\n\n for (const pair of matching.pairs) {\n const file = files[pair.headFileIndex] as GateFileInput;\n if (file.gated === false) {\n continue;\n }\n checkedPairCount += 1;\n violations.push(...checkRatchets(file.file, pair.base, pair.head, options.tolerance));\n checkedFunctions.push(toFunctionReport(file.file, pair.head, pair.base));\n }\n\n let gatedFileCount = 0;\n for (const [fileIndex, file] of files.entries()) {\n if (file.gated === false) {\n continue;\n }\n gatedFileCount += 1;\n const headFunctions = file.headMetrics?.functions ?? [];\n const headMatched = matching.headMatched[fileIndex] as boolean[];\n for (const [functionIndex, fn] of headFunctions.entries()) {\n if (headMatched[functionIndex]) {\n continue;\n }\n newFunctionCount += 1;\n violations.push(...checkNewFunction(file.file, fn, options.newFunction));\n checkedFunctions.push(toFunctionReport(file.file, fn));\n }\n violations.push(...checkFileBackstops(file, hasSplitEvidence(file, fileIndex, matching), violations, options));\n violations.push(...checkDuplication(file, options.tolerance));\n }\n\n violations.sort((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n checkedFunctions.sort((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n return {\n violations,\n checkedFileCount: gatedFileCount,\n checkedFunctionCount: checkedPairCount + newFunctionCount,\n newFunctionCount,\n checkedFunctions,\n };\n}\n\n/**\n * Similarity below the match threshold but above this marks a removed function's content as\n * reappearing inside unmatched new code — the signature of a split or evasive rewrite.\n */\nconst splitEvidenceSimilarityPercent = 30;\n\n/**\n * Whether a removed NAMED base function's content partially reappears in an unmatched head\n * function of the same file. This is what arms the file-level backstops: splitting a function to\n * hide a worsening behind the (laxer) new-code thresholds leaves its fragments partially similar\n * to the removed original, while an ordinary \"delete a helper, add an unrelated function\" change\n * shares nothing and must not have its brand-new code re-judged against the file's old aggregates.\n */\nfunction hasSplitEvidence(file: GateFileInput, fileIndex: number, matching: FunctionMatching): boolean {\n const baseFunctions = file.baseMetrics?.functions ?? [];\n const baseMatchedFlags = matching.baseMatched[fileIndex] as boolean[];\n const headMatchedFlags = matching.headMatched[fileIndex] as boolean[];\n const removedNamed = baseFunctions.flatMap((fn, index) =>\n !baseMatchedFlags[index] && fn.name !== undefined ? [index] : []\n );\n if (removedNamed.length === 0) {\n return false;\n }\n const unmatchedHead = (file.headMetrics?.functions ?? []).flatMap((_, index) =>\n headMatchedFlags[index] ? [] : [index]\n );\n if (removedNamed.length * unmatchedHead.length > maxSimilarityComparisons) {\n return false;\n }\n return removedNamed.some((baseIndex) =>\n unmatchedHead.some(\n (headIndex) =>\n tokenSimilarityPercent(\n file.baseFunctionTokens?.[baseIndex],\n file.headFunctionTokens?.[headIndex],\n splitEvidenceSimilarityPercent\n ) >= splitEvidenceSimilarityPercent\n )\n );\n}\n\nfunction toFunctionReport(file: string, head: FunctionMetrics, base?: FunctionMetrics): CheckedFunctionReport {\n return {\n file,\n name: head.name ?? '<anonymous>',\n startLine: head.startLine,\n endLine: head.endLine,\n base: base ? toFunctionValues(base) : undefined,\n head: toFunctionValues(head),\n };\n}\n\nfunction toFunctionValues(fn: FunctionMetrics): GateFunctionValues {\n return {\n cognitiveComplexity: fn.cognitiveComplexity,\n ncss: fn.ncss,\n nestingDepth: fn.nestingDepth,\n depDegree: fn.depDegree,\n halsteadVolume: fn.halstead.volume,\n };\n}\n\n/** One side of a match candidate: a function of one changed file plus its token sequence. */\ninterface IndexedFunction {\n fileIndex: number;\n functionIndex: number;\n fn: FunctionMetrics;\n tokens: Int32Array | undefined;\n}\n\ninterface MatchedPair {\n base: FunctionMetrics;\n head: FunctionMetrics;\n headFileIndex: number;\n}\n\ninterface FunctionMatching {\n pairs: MatchedPair[];\n /** Per file, per function index: whether it found a counterpart (anywhere in the change set). */\n baseMatched: boolean[][];\n headMatched: boolean[][];\n}\n\ninterface SimilarityCandidate {\n similarity: number;\n basePosition: number;\n headPosition: number;\n}\n\n/**\n * Matches head functions to base functions: within each file first by name + arity, then by name\n * alone (signature changes) — resolving ambiguous same-name groups by token similarity instead of\n * list position, so an inserted overload cannot shift the pairing — and finally by\n * normalized-token LCS similarity across ALL changed files (renames and moves between files,\n * reusing the near-miss clone machinery), so refactorings don't appear as delete+add and hit the\n * new-code thresholds.\n */\nfunction matchAllFunctions(files: GateFileInput[], matchSimilarityPercent: number): FunctionMatching {\n const baseMatched = files.map((file) => (file.baseMetrics?.functions ?? []).map(() => false));\n const headMatched = files.map((file) => (file.headMetrics?.functions ?? []).map(() => false));\n const pairs: MatchedPair[] = [];\n\n for (const fileIndex of files.keys()) {\n const pairByKey = (key: (fn: FunctionMetrics) => string | undefined): void => {\n const baseByKey = groupByKey(collectUnmatched(files, baseMatched, 'base', fileIndex), key);\n const headByKey = groupByKey(collectUnmatched(files, headMatched, 'head', fileIndex), key);\n for (const [groupKey, baseGroup] of baseByKey) {\n pairGroup(baseGroup, headByKey.get(groupKey) ?? [], baseMatched, headMatched, pairs);\n }\n };\n pairByKey((fn) => (fn.name === undefined ? undefined : `${fn.name}\\u0000${fn.parameterCount}`));\n pairByKey((fn) => fn.name);\n }\n\n pairAcrossChangeSet(files, baseMatched, headMatched, pairs, matchSimilarityPercent);\n return { pairs, baseMatched, headMatched };\n}\n\n/** Unmatched functions of one file (or of every file when onlyFileIndex is undefined). */\nfunction collectUnmatched(\n files: GateFileInput[],\n matchedByFile: boolean[][],\n side: 'base' | 'head',\n onlyFileIndex?: number\n): IndexedFunction[] {\n const unmatched: IndexedFunction[] = [];\n for (const [fileIndex, file] of files.entries()) {\n if (onlyFileIndex !== undefined && fileIndex !== onlyFileIndex) {\n continue;\n }\n const matched = matchedByFile[fileIndex] as boolean[];\n const metrics = side === 'base' ? file.baseMetrics : file.headMetrics;\n const tokens = side === 'base' ? file.baseFunctionTokens : file.headFunctionTokens;\n for (const [functionIndex, fn] of (metrics?.functions ?? []).entries()) {\n if (!matched[functionIndex]) {\n unmatched.push({ fileIndex, functionIndex, fn, tokens: tokens?.[functionIndex] });\n }\n }\n }\n return unmatched;\n}\n\nfunction groupByKey(\n functions: IndexedFunction[],\n key: (fn: FunctionMetrics) => string | undefined\n): Map<string, IndexedFunction[]> {\n const groups = new Map<string, IndexedFunction[]>();\n for (const indexed of functions) {\n const groupKey = key(indexed.fn);\n if (groupKey === undefined) {\n continue;\n }\n const group = groups.get(groupKey) ?? [];\n group.push(indexed);\n groups.set(groupKey, group);\n }\n return groups;\n}\n\n/** Bounds the quadratic similarity passes; beyond this, leftovers gate as new/removed functions. */\nconst maxSimilarityComparisons = 10_000;\n\n/**\n * Pairs one key group. An unambiguous 1x1 group matches directly; a larger group (same-name\n * methods of different classes, overload sets) is assigned best-similarity-first so an inserted\n * function cannot shift the pairing of the others. The names already match, so any pairing is\n * acceptable: similarity only ORDERS the assignment (no threshold), and without token sequences\n * (or in an oversized group) the stable tie-break reproduces positional order.\n */\nfunction pairGroup(\n baseGroup: IndexedFunction[],\n headGroup: IndexedFunction[],\n baseMatched: boolean[][],\n headMatched: boolean[][],\n pairs: MatchedPair[]\n): void {\n const ambiguous =\n baseGroup.length + headGroup.length > 2 && baseGroup.length * headGroup.length <= maxSimilarityComparisons;\n const candidates: SimilarityCandidate[] = [];\n for (const [basePosition, base] of baseGroup.entries()) {\n for (const [headPosition, head] of headGroup.entries()) {\n candidates.push({\n similarity: ambiguous ? tokenSimilarityPercent(base.tokens, head.tokens, 0) : 0,\n basePosition,\n headPosition,\n });\n }\n }\n takeMaximumMatches(candidates, baseGroup, headGroup, baseMatched, headMatched, pairs);\n}\n\n/** Cross-file (and remaining within-file) similarity matching over every unmatched function. */\nfunction pairAcrossChangeSet(\n files: GateFileInput[],\n baseMatched: boolean[][],\n headMatched: boolean[][],\n pairs: MatchedPair[],\n matchSimilarityPercent: number\n): void {\n const unmatchedBase = collectUnmatched(files, baseMatched, 'base');\n const unmatchedHead = collectUnmatched(files, headMatched, 'head');\n if (unmatchedBase.length * unmatchedHead.length > maxSimilarityComparisons) {\n return;\n }\n\n const candidates: SimilarityCandidate[] = [];\n for (const [basePosition, base] of unmatchedBase.entries()) {\n for (const [headPosition, head] of unmatchedHead.entries()) {\n const similarity = tokenSimilarityPercent(base.tokens, head.tokens, matchSimilarityPercent);\n if (similarity >= matchSimilarityPercent) {\n candidates.push({ similarity, basePosition, headPosition });\n }\n }\n }\n takeMaximumMatches(candidates, unmatchedBase, unmatchedHead, baseMatched, headMatched, pairs);\n}\n\n/**\n * Assignment over the candidate edges: a greedy best-similarity-first seed, then Kuhn's\n * augmenting paths for the bases the seed left unmatched, so a function whose only counterpart\n * was taken by a slightly better pair is re-matched by rewiring instead of being falsely gated as\n * new code. Augmentation runs only when it increases cardinality, and an exact (100%) seed pair —\n * certain identity — is locked and never rewired even then: trading it for two partial matches\n * would ratchet an untouched function against some other function's rewrite. Non-exact seed pairs\n * may be rewired, but only when that matches strictly more functions (which a maximum-weight\n * assignment would also prefer). Without token sequences every similarity ties at 0 and the seed\n * reproduces positional order.\n */\nfunction takeMaximumMatches(\n candidates: SimilarityCandidate[],\n baseGroup: IndexedFunction[],\n headGroup: IndexedFunction[],\n baseMatched: boolean[][],\n headMatched: boolean[][],\n pairs: MatchedPair[]\n): void {\n candidates.sort(\n (left, right) =>\n right.similarity - left.similarity ||\n left.basePosition - right.basePosition ||\n left.headPosition - right.headPosition\n );\n const adjacency = new Map<number, number[]>();\n const baseOfHead = new Map<number, number>();\n const lockedHeads = new Set<number>();\n const matchedBases = seedGreedyMatches(candidates, adjacency, baseOfHead, lockedHeads);\n for (const basePosition of [...adjacency.keys()].toSorted((left, right) => left - right)) {\n if (!matchedBases.has(basePosition)) {\n tryAugment(basePosition, adjacency, baseOfHead, lockedHeads, new Set());\n }\n }\n\n for (const [headPosition, basePosition] of [...baseOfHead.entries()].toSorted((left, right) => left[0] - right[0])) {\n const base = baseGroup[basePosition] as IndexedFunction;\n const head = headGroup[headPosition] as IndexedFunction;\n (baseMatched[base.fileIndex] as boolean[])[base.functionIndex] = true;\n (headMatched[head.fileIndex] as boolean[])[head.functionIndex] = true;\n pairs.push({ base: base.fn, head: head.fn, headFileIndex: head.fileIndex });\n }\n}\n\n/**\n * Fills the adjacency lists and takes each best edge whose endpoints are both still free; a taken\n * exact (100%) edge locks its head against later rewiring.\n */\nfunction seedGreedyMatches(\n candidates: SimilarityCandidate[],\n adjacency: Map<number, number[]>,\n baseOfHead: Map<number, number>,\n lockedHeads: Set<number>\n): Set<number> {\n const matchedBases = new Set<number>();\n for (const candidate of candidates) {\n const edges = adjacency.get(candidate.basePosition) ?? [];\n edges.push(candidate.headPosition);\n adjacency.set(candidate.basePosition, edges);\n if (!matchedBases.has(candidate.basePosition) && !baseOfHead.has(candidate.headPosition)) {\n baseOfHead.set(candidate.headPosition, candidate.basePosition);\n matchedBases.add(candidate.basePosition);\n if (candidate.similarity === 100) {\n lockedHeads.add(candidate.headPosition);\n }\n }\n }\n return matchedBases;\n}\n\n/** One Kuhn augmentation step: rewires existing (unlocked) matches only when that frees a head for `basePosition`. */\nfunction tryAugment(\n basePosition: number,\n adjacency: Map<number, number[]>,\n baseOfHead: Map<number, number>,\n lockedHeads: Set<number>,\n visitedHeads: Set<number>\n): boolean {\n for (const headPosition of adjacency.get(basePosition) ?? []) {\n if (visitedHeads.has(headPosition) || lockedHeads.has(headPosition)) {\n continue;\n }\n visitedHeads.add(headPosition);\n const currentBase = baseOfHead.get(headPosition);\n if (currentBase === undefined || tryAugment(currentBase, adjacency, baseOfHead, lockedHeads, visitedHeads)) {\n baseOfHead.set(headPosition, basePosition);\n return true;\n }\n }\n return false;\n}\n\n/** Token-LCS similarity of two sequences relative to the longer one, in percent (0 when unusable). */\nfunction tokenSimilarityPercent(\n base: Int32Array | undefined,\n head: Int32Array | undefined,\n minPercent: number\n): number {\n if (!base || !head || base.length === 0 || head.length === 0) {\n return 0;\n }\n // The LCS cannot exceed the shorter sequence, so mismatched lengths are pruned for free.\n const maxLength = Math.max(base.length, head.length);\n if (Math.min(base.length, head.length) * 100 < minPercent * maxLength) {\n return 0;\n }\n return (lcsLength(base, head) * 100) / maxLength;\n}\n\nfunction checkRatchets(\n file: string,\n base: FunctionMetrics,\n head: FunctionMetrics,\n tolerances: GateTolerances\n): GateViolation[] {\n const violations: GateViolation[] = [];\n for (const ratchet of ratchetMetrics) {\n const baseValue = ratchet.value(base);\n const headValue = ratchet.value(head);\n const allowedValue = baseValue + ratchet.allowance(tolerances, baseValue);\n if (headValue > allowedValue) {\n const name = head.name ?? '<anonymous>';\n violations.push({\n gate: 'function-regression',\n metric: ratchet.metric,\n file,\n functionName: name,\n startLine: head.startLine,\n endLine: head.endLine,\n baseValue,\n headValue,\n allowedValue,\n message:\n `${file}:${head.startLine}-${head.endLine} ${name}: ${ratchet.metric} worsened ` +\n `${ratchet.format(baseValue)} -> ${ratchet.format(headValue)} (allowed <= ${ratchet.format(allowedValue)}). ` +\n ratchet.remediation,\n });\n }\n }\n return violations;\n}\n\nfunction checkNewFunction(file: string, fn: FunctionMetrics, thresholds: NewFunctionThresholds): GateViolation[] {\n const violations: GateViolation[] = [];\n for (const check of newFunctionMetrics) {\n const headValue = check.value(fn);\n const allowedValue = check.limit(thresholds);\n if (headValue > allowedValue) {\n const name = fn.name ?? '<anonymous>';\n violations.push({\n gate: 'new-function',\n metric: check.metric,\n file,\n functionName: name,\n startLine: fn.startLine,\n endLine: fn.endLine,\n headValue,\n allowedValue,\n message:\n `${file}:${fn.startLine}-${fn.endLine} new function ${name}: ${check.metric} ${headValue} ` +\n `exceeds the new-code limit ${allowedValue}. ${check.remediation}`,\n });\n }\n }\n return violations;\n}\n\n/**\n * Anti-gaming backstops: splitting a function resets its entity identity and could hide a\n * worsening behind the (laxer) new-code thresholds, so when a removed named function's content\n * reappears in unmatched new code (see hasSplitEvidence) the file-level aggregates ratchet too —\n * the max cognitive complexity per file and the file's total NCSS. Purely additive changes and\n * unrelated remove-plus-add changes stay ungated. The max-cognitive backstop is also skipped when\n * a function-level cognitive violation already reports the file's maximum, since it would only\n * restate it.\n */\nfunction checkFileBackstops(\n file: GateFileInput,\n splitEvidence: boolean,\n reportedViolations: GateViolation[],\n options: GateOptions\n): GateViolation[] {\n const { baseMetrics, headMetrics } = file;\n if (!baseMetrics || !headMetrics || !splitEvidence) {\n return [];\n }\n const violations: GateViolation[] = [];\n const tolerances = options.tolerance;\n\n const maximumAlreadyReported = reportedViolations.some(\n (violation) =>\n violation.file === file.file &&\n violation.metric === 'cognitive complexity' &&\n (violation.gate === 'function-regression' || violation.gate === 'new-function') &&\n violation.headValue === headMetrics.maxCognitiveComplexity\n );\n const allowedMaxCognitive = baseMetrics.maxCognitiveComplexity + tolerances.cognitiveComplexity;\n if (!maximumAlreadyReported && headMetrics.maxCognitiveComplexity > allowedMaxCognitive) {\n const worst = findMostComplexFunction(headMetrics.functions);\n const startLine = worst?.startLine ?? 1;\n const endLine = worst?.endLine ?? headMetrics.lines.total;\n violations.push({\n gate: 'file-regression',\n metric: 'file max cognitive complexity',\n file: file.file,\n functionName: worst?.name ?? undefined,\n startLine,\n endLine,\n baseValue: baseMetrics.maxCognitiveComplexity,\n headValue: headMetrics.maxCognitiveComplexity,\n allowedValue: allowedMaxCognitive,\n message:\n `${file.file}:${startLine}-${endLine}: the file's max cognitive complexity worsened ` +\n `${baseMetrics.maxCognitiveComplexity} -> ${headMetrics.maxCognitiveComplexity} ` +\n `(allowed <= ${allowedMaxCognitive}). Simplify or split the most complex ` +\n `function${worst ? ` (${worst.name ?? '<anonymous>'})` : ''}.`,\n });\n }\n\n const allowedFileNcss = baseMetrics.ncssCount + tolerances.fileNcss;\n if (headMetrics.ncssCount > allowedFileNcss) {\n violations.push({\n gate: 'file-regression',\n metric: 'file NCSS',\n file: file.file,\n startLine: 1,\n endLine: headMetrics.lines.total,\n baseValue: baseMetrics.ncssCount,\n headValue: headMetrics.ncssCount,\n allowedValue: allowedFileNcss,\n message:\n `${file.file}:1-${headMetrics.lines.total}: functions were removed or split while the file grew from NCSS ` +\n `${baseMetrics.ncssCount} to ${headMetrics.ncssCount} (allowed <= ${allowedFileNcss}). ` +\n `Remove the added statements or move genuinely new code into its own module.`,\n });\n }\n\n return violations;\n}\n\nfunction findMostComplexFunction(functions: FunctionMetrics[]): FunctionMetrics | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (!worst || fn.cognitiveComplexity > worst.cognitiveComplexity) {\n worst = fn;\n }\n }\n return worst;\n}\n\n/**\n * No new duplication: the distinct duplicated lines of a changed file (within-file plus\n * cross-file against the whole project, so copy-paste from existing code into new files is\n * caught) must not exceed the base revision's count.\n */\nfunction checkDuplication(file: GateFileInput, tolerances: GateTolerances): GateViolation[] {\n const allowedValue = file.baseDuplicatedLineCount + tolerances.duplicateLines;\n if (file.headDuplicatedLineCount <= allowedValue) {\n return [];\n }\n const partners = file.duplicationPartners.slice(0, 3).join(', ');\n const endLine = file.headMetrics?.lines.total ?? 1;\n return [\n {\n gate: 'duplication',\n metric: 'duplicated lines',\n file: file.file,\n startLine: 1,\n endLine,\n baseValue: file.baseDuplicatedLineCount,\n headValue: file.headDuplicatedLineCount,\n allowedValue,\n message:\n `${file.file}:1-${endLine}: duplicated lines increased ${file.baseDuplicatedLineCount} -> ` +\n `${file.headDuplicatedLineCount} (allowed <= ${allowedValue}). Deduplicate` +\n `${partners ? ` against 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AGZ,OAAO,CACT,CAOA,SAAS,EAAiB,EAAqB,EAA6C,CAC1F,IAAM,EAAe,EAAK,wBAA0B,EAAW,eAC/D,GAAI,EAAK,yBAA2B,EAClC,MAAO,CAAC,EAEV,IAAM,EAAW,EAAK,oBAAoB,MAAM,EAAG,CAAC,CAAC,CAAC,KAAK,IAAI,EACzD,EAAU,EAAK,aAAa,MAAM,OAAS,EACjD,MAAO,CACL,CACE,KAAM,cACN,OAAQ,mBACR,KAAM,EAAK,KACX,UAAW,EACX,UACA,UAAW,EAAK,wBAChB,UAAW,EAAK,wBAChB,eACA,QACE,GAAG,EAAK,KAAK,KAAK,EAAQ,+BAA+B,EAAK,wBAAwB,MACnF,EAAK,wBAAwB,eAAe,EAAa,gBACzD,EAAW,YAAY,IAAa,qBAAqB,gCAChE,CACF,CACF"}
@@ -0,0 +1,106 @@
1
+ import type { CodeMetrics } from './types.js';
2
+ /**
3
+ * Absolute limits applied only to functions with no base counterpart (SonarQube-style "Clean as
4
+ * You Code"): new code is the one place absolute thresholds are required, since there is nothing
5
+ * to ratchet against.
6
+ */
7
+ export interface NewFunctionThresholds {
8
+ maxCognitiveComplexity: number;
9
+ maxNcss: number;
10
+ maxNestingDepth: number;
11
+ }
12
+ /**
13
+ * Allowances added on top of each base value before a ratchet fires, so legitimate refactorings
14
+ * that transiently worsen one number (e.g. an extraction adding a few NCSS lines) don't trap the
15
+ * agent in a loop.
16
+ */
17
+ export interface GateTolerances {
18
+ cognitiveComplexity: number;
19
+ ncss: number;
20
+ nestingDepth: number;
21
+ depDegree: number;
22
+ halsteadVolume: number;
23
+ /** File-total NCSS growth allowed when base functions disappeared (the anti-gaming backstop). */
24
+ fileNcss: number;
25
+ /** Duplicated-line growth allowed per changed file. */
26
+ duplicateLines: number;
27
+ }
28
+ export interface GateOptions {
29
+ newFunction: NewFunctionThresholds;
30
+ tolerance: GateTolerances;
31
+ /**
32
+ * Minimum token-LCS similarity percent for re-matching a renamed/moved function to its base
33
+ * counterpart, so renames don't appear as delete+add and hit the new-code thresholds.
34
+ */
35
+ matchSimilarityPercent: number;
36
+ }
37
+ export declare const defaultGateOptions: GateOptions;
38
+ /** One changed file with both revisions measured; the caller resolves git and duplication data. */
39
+ export interface GateFileInput {
40
+ /** Display path (repository-relative head path; base path for deleted files). */
41
+ file: string;
42
+ /** Absent for added files. */
43
+ baseMetrics?: CodeMetrics;
44
+ /** Absent for deleted files. */
45
+ headMetrics?: CodeMetrics;
46
+ /** Token sequences index-parallel to baseMetrics.functions, for similarity re-matching. */
47
+ baseFunctionTokens?: Int32Array[];
48
+ headFunctionTokens?: Int32Array[];
49
+ /** Distinct duplicated lines of this file at the base revision (within-file and cross-file). */
50
+ baseDuplicatedLineCount: number;
51
+ headDuplicatedLineCount: number;
52
+ /** Other files sharing cross-file duplicates with this file at head, as remediation evidence. */
53
+ duplicationPartners: string[];
54
+ /**
55
+ * false: the file only feeds function matching and the duplication universes (it lies outside
56
+ * the gated target directory); no violations are evaluated or reported for it. Default true.
57
+ */
58
+ gated?: boolean;
59
+ }
60
+ export interface GateViolation {
61
+ gate: 'function-regression' | 'new-function' | 'file-regression' | 'duplication';
62
+ metric: string;
63
+ file: string;
64
+ functionName?: string;
65
+ startLine: number;
66
+ endLine: number;
67
+ /** Absent for new-function violations, which have no base value. */
68
+ baseValue?: number;
69
+ headValue: number;
70
+ /** The largest value that would have passed. */
71
+ allowedValue: number;
72
+ /** One-line human/agent-readable statement with the remediation direction. */
73
+ message: string;
74
+ }
75
+ /** The gated per-function values of one checked (matched or new) function, for `--full` output. */
76
+ export interface CheckedFunctionReport {
77
+ /** The head file (a cross-file move is reported where the function now lives). */
78
+ file: string;
79
+ name: string;
80
+ startLine: number;
81
+ endLine: number;
82
+ /** Absent for new functions. */
83
+ base?: GateFunctionValues;
84
+ head: GateFunctionValues;
85
+ }
86
+ export interface GateFunctionValues {
87
+ cognitiveComplexity: number;
88
+ ncss: number;
89
+ nestingDepth: number;
90
+ depDegree: number;
91
+ halsteadVolume: number;
92
+ }
93
+ export interface GateResult {
94
+ violations: GateViolation[];
95
+ checkedFileCount: number;
96
+ checkedFunctionCount: number;
97
+ newFunctionCount: number;
98
+ /** Every checked function with its gated values, ordered by file and line. */
99
+ checkedFunctions: CheckedFunctionReport[];
100
+ }
101
+ /**
102
+ * Evaluates the regression gate over changed files measured at both revisions. Violations are the
103
+ * whole output contract: everything that passes stays silent, so a clean change costs the
104
+ * consuming agent almost no tokens.
105
+ */
106
+ export declare function evaluateRegressionGate(files: GateFileInput[], options: GateOptions): GateResult;
@@ -0,0 +1,2 @@
1
+ import{lcsLength as e}from"./duplication.js";const t={newFunction:{maxCognitiveComplexity:15,maxNcss:60,maxNestingDepth:4},tolerance:{cognitiveComplexity:2,ncss:5,nestingDepth:1,depDegree:10,halsteadVolume:150,fileNcss:20,duplicateLines:0},matchSimilarityPercent:70},n=String,r=[{metric:`cognitive complexity`,value:e=>e.cognitiveComplexity,allowance:e=>e.cognitiveComplexity,remediation:`Simplify the added branching or split the function.`,format:n},{metric:`NCSS`,value:e=>e.ncss,allowance:e=>e.ncss,remediation:`Extract the added statements into helper functions or remove them.`,format:n},{metric:`max nesting depth`,value:e=>e.nestingDepth,allowance:e=>e.nestingDepth,remediation:`Flatten the added nesting with early returns or extracted helpers.`,format:n},{metric:`DepDegree`,value:e=>e.depDegree,allowance:e=>e.depDegree,remediation:`Reduce how many earlier definitions the code reads, e.g. by splitting the data flow.`,format:n},{metric:`Halstead volume`,value:e=>e.halstead.volume,allowance:(e,t)=>Math.max(e.halsteadVolume,t*.25),remediation:`Shrink the function: fewer distinct names and operations.`,format:e=>e.toFixed(1)}],i=[{metric:`cognitive complexity`,value:e=>e.cognitiveComplexity,limit:e=>e.maxCognitiveComplexity,remediation:`Split the new function or simplify its branching.`},{metric:`NCSS`,value:e=>e.ncss,limit:e=>e.maxNcss,remediation:`Split the new function into smaller ones.`},{metric:`max nesting depth`,value:e=>e.nestingDepth,limit:e=>e.maxNestingDepth,remediation:`Flatten the new function with early returns or extracted helpers.`}];function a(e,t){let n=l(e,t.matchSimilarityPercent),r=[],i=[],a=0,c=0;for(let o of n.pairs){let n=e[o.headFileIndex];n.gated!==!1&&(a+=1,r.push(...y(n.file,o.base,o.head,t.tolerance)),i.push(s(n.file,o.head,o.base)))}let u=0;for(let[a,l]of e.entries()){if(l.gated===!1)continue;u+=1;let e=l.headMetrics?.functions??[],d=n.headMatched[a];for(let[n,a]of e.entries())d[n]||(c+=1,r.push(...b(l.file,a,t.newFunction)),i.push(s(l.file,a)));r.push(...x(l,o(l,a,n),r,t)),r.push(...C(l,t.tolerance))}return r.sort((e,t)=>e.file.localeCompare(t.file)||e.startLine-t.startLine),i.sort((e,t)=>e.file.localeCompare(t.file)||e.startLine-t.startLine),{violations:r,checkedFileCount:u,checkedFunctionCount:a+c,newFunctionCount:c,checkedFunctions:i}}function o(e,t,n){let r=e.baseMetrics?.functions??[],i=n.baseMatched[t],a=n.headMatched[t],o=r.flatMap((e,t)=>!i[t]&&e.name!==void 0?[t]:[]);if(o.length===0)return!1;let s=(e.headMetrics?.functions??[]).flatMap((e,t)=>a[t]?[]:[t]);return o.length*s.length>f?!1:o.some(t=>s.some(n=>v(e.baseFunctionTokens?.[t],e.headFunctionTokens?.[n],30)>=30))}function s(e,t,n){return{file:e,name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,base:n?c(n):void 0,head:c(t)}}function c(e){return{cognitiveComplexity:e.cognitiveComplexity,ncss:e.ncss,nestingDepth:e.nestingDepth,depDegree:e.depDegree,halsteadVolume:e.halstead.volume}}function l(e,t){let n=e.map(e=>(e.baseMetrics?.functions??[]).map(()=>!1)),r=e.map(e=>(e.headMetrics?.functions??[]).map(()=>!1)),i=[];for(let t of e.keys()){let a=a=>{let o=d(u(e,n,`base`,t),a),s=d(u(e,r,`head`,t),a);for(let[e,t]of o)p(t,s.get(e)??[],n,r,i)};a(e=>e.name===void 0?void 0:`${e.name}\u0000${e.parameterCount}`),a(e=>e.name)}return m(e,n,r,i,t),{pairs:i,baseMatched:n,headMatched:r}}function u(e,t,n,r){let i=[];for(let[a,o]of e.entries()){if(r!==void 0&&a!==r)continue;let e=t[a],s=n===`base`?o.baseMetrics:o.headMetrics,c=n===`base`?o.baseFunctionTokens:o.headFunctionTokens;for(let[t,n]of(s?.functions??[]).entries())e[t]||i.push({fileIndex:a,functionIndex:t,fn:n,tokens:c?.[t]})}return i}function d(e,t){let n=new Map;for(let r of e){let e=t(r.fn);if(e===void 0)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return n}const f=1e4;function p(e,t,n,r,i){let a=e.length+t.length>2&&e.length*t.length<=f,o=[];for(let[n,r]of e.entries())for(let[e,i]of t.entries())o.push({similarity:a?v(r.tokens,i.tokens,0):0,basePosition:n,headPosition:e});h(o,e,t,n,r,i)}function m(e,t,n,r,i){let a=u(e,t,`base`),o=u(e,n,`head`);if(a.length*o.length>f)return;let s=[];for(let[e,t]of a.entries())for(let[n,r]of o.entries()){let a=v(t.tokens,r.tokens,i);a>=i&&s.push({similarity:a,basePosition:e,headPosition:n})}h(s,a,o,t,n,r)}function h(e,t,n,r,i,a){e.sort((e,t)=>t.similarity-e.similarity||e.basePosition-t.basePosition||e.headPosition-t.headPosition);let o=new Map,s=new Map,c=new Set,l=g(e,o,s,c);for(let e of[...o.keys()].toSorted((e,t)=>e-t))l.has(e)||_(e,o,s,c,new Set);for(let[e,o]of[...s.entries()].toSorted((e,t)=>e[0]-t[0])){let s=t[o],c=n[e];r[s.fileIndex][s.functionIndex]=!0,i[c.fileIndex][c.functionIndex]=!0,a.push({base:s.fn,head:c.fn,headFileIndex:c.fileIndex})}}function g(e,t,n,r){let i=new Set;for(let a of e){let e=t.get(a.basePosition)??[];e.push(a.headPosition),t.set(a.basePosition,e),!i.has(a.basePosition)&&!n.has(a.headPosition)&&(n.set(a.headPosition,a.basePosition),i.add(a.basePosition),a.similarity===100&&r.add(a.headPosition))}return i}function _(e,t,n,r,i){for(let a of t.get(e)??[]){if(i.has(a)||r.has(a))continue;i.add(a);let o=n.get(a);if(o===void 0||_(o,t,n,r,i))return n.set(a,e),!0}return!1}function v(t,n,r){if(!t||!n||t.length===0||n.length===0)return 0;let i=Math.max(t.length,n.length);return Math.min(t.length,n.length)*100<r*i?0:e(t,n)*100/i}function y(e,t,n,i){let a=[];for(let o of r){let r=o.value(t),s=o.value(n),c=r+o.allowance(i,r);if(s>c){let t=n.name??`<anonymous>`;a.push({gate:`function-regression`,metric:o.metric,file:e,functionName:t,startLine:n.startLine,endLine:n.endLine,baseValue:r,headValue:s,allowedValue:c,message:`${e}:${n.startLine}-${n.endLine} ${t}: ${o.metric} worsened ${o.format(r)} -> ${o.format(s)} (allowed <= ${o.format(c)}). `+o.remediation})}}return a}function b(e,t,n){let r=[];for(let a of i){let i=a.value(t),o=a.limit(n);if(i>o){let n=t.name??`<anonymous>`;r.push({gate:`new-function`,metric:a.metric,file:e,functionName:n,startLine:t.startLine,endLine:t.endLine,headValue:i,allowedValue:o,message:`${e}:${t.startLine}-${t.endLine} new function ${n}: ${a.metric} ${i} exceeds the new-code limit ${o}. ${a.remediation}`})}}return r}function x(e,t,n,r){let{baseMetrics:i,headMetrics:a}=e;if(!i||!a||!t)return[];let o=[],s=r.tolerance,c=n.some(t=>t.file===e.file&&t.metric===`cognitive complexity`&&(t.gate===`function-regression`||t.gate===`new-function`)&&t.headValue===a.maxCognitiveComplexity),l=i.maxCognitiveComplexity+s.cognitiveComplexity;if(!c&&a.maxCognitiveComplexity>l){let t=S(a.functions),n=t?.startLine??1,r=t?.endLine??a.lines.total;o.push({gate:`file-regression`,metric:`file max cognitive complexity`,file:e.file,functionName:t?.name??void 0,startLine:n,endLine:r,baseValue:i.maxCognitiveComplexity,headValue:a.maxCognitiveComplexity,allowedValue:l,message:`${e.file}:${n}-${r}: the file's max cognitive complexity worsened ${i.maxCognitiveComplexity} -> ${a.maxCognitiveComplexity} (allowed <= ${l}). Simplify or split the most complex function${t?` (${t.name??`<anonymous>`})`:``}.`})}let u=i.ncssCount+s.fileNcss;return a.ncssCount>u&&o.push({gate:`file-regression`,metric:`file NCSS`,file:e.file,startLine:1,endLine:a.lines.total,baseValue:i.ncssCount,headValue:a.ncssCount,allowedValue:u,message:`${e.file}:1-${a.lines.total}: functions were removed or split while the file grew from NCSS ${i.ncssCount} to ${a.ncssCount} (allowed <= ${u}). Remove the added statements or move genuinely new code into its own module.`}),o}function S(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity)&&(t=n);return t}function C(e,t){let n=e.baseDuplicatedLineCount+t.duplicateLines;if(e.headDuplicatedLineCount<=n)return[];let r=e.duplicationPartners.slice(0,3).join(`, `),i=e.headMetrics?.lines.total??1;return[{gate:`duplication`,metric:`duplicated lines`,file:e.file,startLine:1,endLine:i,baseValue:e.baseDuplicatedLineCount,headValue:e.headDuplicatedLineCount,allowedValue:n,message:`${e.file}:1-${i}: duplicated lines increased ${e.baseDuplicatedLineCount} -> ${e.headDuplicatedLineCount} (allowed <= ${n}). Deduplicate${r?` against ${r}`:` the repeated code`} by extracting a shared helper.`}]}export{t as defaultGateOptions,a as evaluateRegressionGate};
2
+ //# sourceMappingURL=regressionGate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regressionGate.js","names":[],"sources":["../src/regressionGate.ts"],"sourcesContent":["import { lcsLength } from './duplication.js';\nimport type { CodeMetrics, FunctionMetrics } from './types.js';\n\n/**\n * Absolute limits applied only to functions with no base counterpart (SonarQube-style \"Clean as\n * You Code\"): new code is the one place absolute thresholds are required, since there is nothing\n * to ratchet against.\n */\nexport interface NewFunctionThresholds {\n maxCognitiveComplexity: number;\n maxNcss: number;\n maxNestingDepth: number;\n}\n\n/**\n * Allowances added on top of each base value before a ratchet fires, so legitimate refactorings\n * that transiently worsen one number (e.g. an extraction adding a few NCSS lines) don't trap the\n * agent in a loop.\n */\nexport interface GateTolerances {\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n depDegree: number;\n halsteadVolume: number;\n /** File-total NCSS growth allowed when base functions disappeared (the anti-gaming backstop). */\n fileNcss: number;\n /** Duplicated-line growth allowed per changed file. */\n duplicateLines: number;\n}\n\nexport interface GateOptions {\n newFunction: NewFunctionThresholds;\n tolerance: GateTolerances;\n /**\n * Minimum token-LCS similarity percent for re-matching a renamed/moved function to its base\n * counterpart, so renames don't appear as delete+add and hit the new-code thresholds.\n */\n matchSimilarityPercent: number;\n}\n\nexport const defaultGateOptions: GateOptions = {\n // 15 is SonarSource's conventional default; 4 is where the measured cognitive-load response to\n // nesting saturates (Peitek et al. 2021); 60 matches PMD's NcssCount method default.\n newFunction: { maxCognitiveComplexity: 15, maxNcss: 60, maxNestingDepth: 4 },\n // The per-metric allowances are calibrated to admit roughly the same edit: ~5 added statements\n // or one added branch (cognitive 2 ~ nesting 1 ~ ncss 5 ~ depDegree 10 ~ Halstead volume 150;\n // the volume allowance additionally scales with the base value, see ratchetMetrics), so one\n // ratchet cannot block an addition the others deliberately allow.\n tolerance: {\n cognitiveComplexity: 2,\n ncss: 5,\n nestingDepth: 1,\n depDegree: 10,\n halsteadVolume: 150,\n fileNcss: 20,\n duplicateLines: 0,\n },\n matchSimilarityPercent: 70,\n};\n\n/** One changed file with both revisions measured; the caller resolves git and duplication data. */\nexport interface GateFileInput {\n /** Display path (repository-relative head path; base path for deleted files). */\n file: string;\n /** Absent for added files. */\n baseMetrics?: CodeMetrics;\n /** Absent for deleted files. */\n headMetrics?: CodeMetrics;\n /** Token sequences index-parallel to baseMetrics.functions, for similarity re-matching. */\n baseFunctionTokens?: Int32Array[];\n headFunctionTokens?: Int32Array[];\n /** Distinct duplicated lines of this file at the base revision (within-file and cross-file). */\n baseDuplicatedLineCount: number;\n headDuplicatedLineCount: number;\n /** Other files sharing cross-file duplicates with this file at head, as remediation evidence. */\n duplicationPartners: string[];\n /**\n * false: the file only feeds function matching and the duplication universes (it lies outside\n * the gated target directory); no violations are evaluated or reported for it. Default true.\n */\n gated?: boolean;\n}\n\nexport interface GateViolation {\n gate: 'function-regression' | 'new-function' | 'file-regression' | 'duplication';\n metric: string;\n file: string;\n functionName?: string;\n startLine: number;\n endLine: number;\n /** Absent for new-function violations, which have no base value. */\n baseValue?: number;\n headValue: number;\n /** The largest value that would have passed. */\n allowedValue: number;\n /** One-line human/agent-readable statement with the remediation direction. */\n message: string;\n}\n\n/** The gated per-function values of one checked (matched or new) function, for `--full` output. */\nexport interface CheckedFunctionReport {\n /** The head file (a cross-file move is reported where the function now lives). */\n file: string;\n name: string;\n startLine: number;\n endLine: number;\n /** Absent for new functions. */\n base?: GateFunctionValues;\n head: GateFunctionValues;\n}\n\nexport interface GateFunctionValues {\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n depDegree: number;\n halsteadVolume: number;\n}\n\nexport interface GateResult {\n violations: GateViolation[];\n checkedFileCount: number;\n checkedFunctionCount: number;\n newFunctionCount: number;\n /** Every checked function with its gated values, ordered by file and line. */\n checkedFunctions: CheckedFunctionReport[];\n}\n\ninterface RatchetMetric {\n metric: string;\n value: (fn: FunctionMetrics) => number;\n /** The growth allowed on top of the base value before the ratchet fires. */\n allowance: (tolerances: GateTolerances, baseValue: number) => number;\n remediation: string;\n format: (value: number) => string;\n}\n\nconst formatInteger = String;\nconst formatFloat = (value: number): string => value.toFixed(1);\n\n/**\n * Gate-eligible per-function metrics (monotone, stable, actionable): a matched function must not\n * worsen any of them beyond its tolerance. \"Your change made this function worse\" is defensible\n * regardless of metric calibration, so no absolute threshold is involved.\n */\nconst ratchetMetrics: RatchetMetric[] = [\n {\n metric: 'cognitive complexity',\n value: (fn) => fn.cognitiveComplexity,\n allowance: (tolerances) => tolerances.cognitiveComplexity,\n remediation: 'Simplify the added branching or split the function.',\n format: formatInteger,\n },\n {\n metric: 'NCSS',\n value: (fn) => fn.ncss,\n allowance: (tolerances) => tolerances.ncss,\n remediation: 'Extract the added statements into helper functions or remove them.',\n format: formatInteger,\n },\n {\n metric: 'max nesting depth',\n value: (fn) => fn.nestingDepth,\n allowance: (tolerances) => tolerances.nestingDepth,\n remediation: 'Flatten the added nesting with early returns or extracted helpers.',\n format: formatInteger,\n },\n {\n metric: 'DepDegree',\n value: (fn) => fn.depDegree,\n allowance: (tolerances) => tolerances.depDegree,\n remediation: 'Reduce how many earlier definitions the code reads, e.g. by splitting the data flow.',\n format: formatInteger,\n },\n {\n metric: 'Halstead volume',\n value: (fn) => fn.halstead.volume,\n // Volume grows as length * log2(vocabulary), so a flat allowance that admits ~5 statements in\n // a small function admits barely one in a large-vocabulary function; the relative term keeps\n // the ~5-statement calibration at every function size.\n allowance: (tolerances, baseValue) => Math.max(tolerances.halsteadVolume, baseValue * 0.25),\n remediation: 'Shrink the function: fewer distinct names and operations.',\n format: formatFloat,\n },\n];\n\ninterface NewFunctionMetric {\n metric: string;\n value: (fn: FunctionMetrics) => number;\n limit: (thresholds: NewFunctionThresholds) => number;\n remediation: string;\n}\n\nconst newFunctionMetrics: NewFunctionMetric[] = [\n {\n metric: 'cognitive complexity',\n value: (fn) => fn.cognitiveComplexity,\n limit: (thresholds) => thresholds.maxCognitiveComplexity,\n remediation: 'Split the new function or simplify its branching.',\n },\n {\n metric: 'NCSS',\n value: (fn) => fn.ncss,\n limit: (thresholds) => thresholds.maxNcss,\n remediation: 'Split the new function into smaller ones.',\n },\n {\n metric: 'max nesting depth',\n value: (fn) => fn.nestingDepth,\n limit: (thresholds) => thresholds.maxNestingDepth,\n remediation: 'Flatten the new function with early returns or extracted helpers.',\n },\n];\n\n/**\n * Evaluates the regression gate over changed files measured at both revisions. Violations are the\n * whole output contract: everything that passes stays silent, so a clean change costs the\n * consuming agent almost no tokens.\n */\nexport function evaluateRegressionGate(files: GateFileInput[], options: GateOptions): GateResult {\n const matching = matchAllFunctions(files, options.matchSimilarityPercent);\n const violations: GateViolation[] = [];\n const checkedFunctions: CheckedFunctionReport[] = [];\n let checkedPairCount = 0;\n let newFunctionCount = 0;\n\n for (const pair of matching.pairs) {\n const file = files[pair.headFileIndex] as GateFileInput;\n if (file.gated === false) {\n continue;\n }\n checkedPairCount += 1;\n violations.push(...checkRatchets(file.file, pair.base, pair.head, options.tolerance));\n checkedFunctions.push(toFunctionReport(file.file, pair.head, pair.base));\n }\n\n let gatedFileCount = 0;\n for (const [fileIndex, file] of files.entries()) {\n if (file.gated === false) {\n continue;\n }\n gatedFileCount += 1;\n const headFunctions = file.headMetrics?.functions ?? [];\n const headMatched = matching.headMatched[fileIndex] as boolean[];\n for (const [functionIndex, fn] of headFunctions.entries()) {\n if (headMatched[functionIndex]) {\n continue;\n }\n newFunctionCount += 1;\n violations.push(...checkNewFunction(file.file, fn, options.newFunction));\n checkedFunctions.push(toFunctionReport(file.file, fn));\n }\n violations.push(...checkFileBackstops(file, hasSplitEvidence(file, fileIndex, matching), violations, options));\n violations.push(...checkDuplication(file, options.tolerance));\n }\n\n violations.sort((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n checkedFunctions.sort((left, right) => left.file.localeCompare(right.file) || left.startLine - right.startLine);\n return {\n violations,\n checkedFileCount: gatedFileCount,\n checkedFunctionCount: checkedPairCount + newFunctionCount,\n newFunctionCount,\n checkedFunctions,\n };\n}\n\n/**\n * Similarity below the match threshold but above this marks a removed function's content as\n * reappearing inside unmatched new code — the signature of a split or evasive rewrite.\n */\nconst splitEvidenceSimilarityPercent = 30;\n\n/**\n * Whether a removed NAMED base function's content partially reappears in an unmatched head\n * function of the same file. This is what arms the file-level backstops: splitting a function to\n * hide a worsening behind the (laxer) new-code thresholds leaves its fragments partially similar\n * to the removed original, while an ordinary \"delete a helper, add an unrelated function\" change\n * shares nothing and must not have its brand-new code re-judged against the file's old aggregates.\n */\nfunction hasSplitEvidence(file: GateFileInput, fileIndex: number, matching: FunctionMatching): boolean {\n const baseFunctions = file.baseMetrics?.functions ?? [];\n const baseMatchedFlags = matching.baseMatched[fileIndex] as boolean[];\n const headMatchedFlags = matching.headMatched[fileIndex] as boolean[];\n const removedNamed = baseFunctions.flatMap((fn, index) =>\n !baseMatchedFlags[index] && fn.name !== undefined ? [index] : []\n );\n if (removedNamed.length === 0) {\n return false;\n }\n const unmatchedHead = (file.headMetrics?.functions ?? []).flatMap((_, index) =>\n headMatchedFlags[index] ? [] : [index]\n );\n if (removedNamed.length * unmatchedHead.length > maxSimilarityComparisons) {\n return false;\n }\n return removedNamed.some((baseIndex) =>\n unmatchedHead.some(\n (headIndex) =>\n tokenSimilarityPercent(\n file.baseFunctionTokens?.[baseIndex],\n file.headFunctionTokens?.[headIndex],\n splitEvidenceSimilarityPercent\n ) >= splitEvidenceSimilarityPercent\n )\n );\n}\n\nfunction toFunctionReport(file: string, head: FunctionMetrics, base?: FunctionMetrics): CheckedFunctionReport {\n return {\n file,\n name: head.name ?? '<anonymous>',\n startLine: head.startLine,\n endLine: head.endLine,\n base: base ? toFunctionValues(base) : undefined,\n head: toFunctionValues(head),\n };\n}\n\nfunction toFunctionValues(fn: FunctionMetrics): GateFunctionValues {\n return {\n cognitiveComplexity: fn.cognitiveComplexity,\n ncss: fn.ncss,\n nestingDepth: fn.nestingDepth,\n depDegree: fn.depDegree,\n halsteadVolume: fn.halstead.volume,\n };\n}\n\n/** One side of a match candidate: a function of one changed file plus its token sequence. */\ninterface IndexedFunction {\n fileIndex: number;\n functionIndex: number;\n fn: FunctionMetrics;\n tokens: Int32Array | undefined;\n}\n\ninterface MatchedPair {\n base: FunctionMetrics;\n head: FunctionMetrics;\n headFileIndex: number;\n}\n\ninterface FunctionMatching {\n pairs: MatchedPair[];\n /** Per file, per function index: whether it found a counterpart (anywhere in the change set). */\n baseMatched: boolean[][];\n headMatched: boolean[][];\n}\n\ninterface SimilarityCandidate {\n similarity: number;\n basePosition: number;\n headPosition: number;\n}\n\n/**\n * Matches head functions to base functions: within each file first by name + arity, then by name\n * alone (signature changes) — resolving ambiguous same-name groups by token similarity instead of\n * list position, so an inserted overload cannot shift the pairing — and finally by\n * normalized-token LCS similarity across ALL changed files (renames and moves between files,\n * reusing the near-miss clone machinery), so refactorings don't appear as delete+add and hit the\n * new-code thresholds.\n */\nfunction matchAllFunctions(files: GateFileInput[], matchSimilarityPercent: number): FunctionMatching {\n const baseMatched = files.map((file) => (file.baseMetrics?.functions ?? []).map(() => false));\n const headMatched = files.map((file) => (file.headMetrics?.functions ?? []).map(() => false));\n const pairs: MatchedPair[] = [];\n\n for (const fileIndex of files.keys()) {\n const pairByKey = (key: (fn: FunctionMetrics) => string | undefined): void => {\n const baseByKey = groupByKey(collectUnmatched(files, baseMatched, 'base', fileIndex), key);\n const headByKey = groupByKey(collectUnmatched(files, headMatched, 'head', fileIndex), key);\n for (const [groupKey, baseGroup] of baseByKey) {\n pairGroup(baseGroup, headByKey.get(groupKey) ?? [], baseMatched, headMatched, pairs);\n }\n };\n pairByKey((fn) => (fn.name === undefined ? undefined : `${fn.name}\\u0000${fn.parameterCount}`));\n pairByKey((fn) => fn.name);\n }\n\n pairAcrossChangeSet(files, baseMatched, headMatched, pairs, matchSimilarityPercent);\n return { pairs, baseMatched, headMatched };\n}\n\n/** Unmatched functions of one file (or of every file when onlyFileIndex is undefined). */\nfunction collectUnmatched(\n files: GateFileInput[],\n matchedByFile: boolean[][],\n side: 'base' | 'head',\n onlyFileIndex?: number\n): IndexedFunction[] {\n const unmatched: IndexedFunction[] = [];\n for (const [fileIndex, file] of files.entries()) {\n if (onlyFileIndex !== undefined && fileIndex !== onlyFileIndex) {\n continue;\n }\n const matched = matchedByFile[fileIndex] as boolean[];\n const metrics = side === 'base' ? file.baseMetrics : file.headMetrics;\n const tokens = side === 'base' ? file.baseFunctionTokens : file.headFunctionTokens;\n for (const [functionIndex, fn] of (metrics?.functions ?? []).entries()) {\n if (!matched[functionIndex]) {\n unmatched.push({ fileIndex, functionIndex, fn, tokens: tokens?.[functionIndex] });\n }\n }\n }\n return unmatched;\n}\n\nfunction groupByKey(\n functions: IndexedFunction[],\n key: (fn: FunctionMetrics) => string | undefined\n): Map<string, IndexedFunction[]> {\n const groups = new Map<string, IndexedFunction[]>();\n for (const indexed of functions) {\n const groupKey = key(indexed.fn);\n if (groupKey === undefined) {\n continue;\n }\n const group = groups.get(groupKey) ?? [];\n group.push(indexed);\n groups.set(groupKey, group);\n }\n return groups;\n}\n\n/** Bounds the quadratic similarity passes; beyond this, leftovers gate as new/removed functions. */\nconst maxSimilarityComparisons = 10_000;\n\n/**\n * Pairs one key group. An unambiguous 1x1 group matches directly; a larger group (same-name\n * methods of different classes, overload sets) is assigned best-similarity-first so an inserted\n * function cannot shift the pairing of the others. The names already match, so any pairing is\n * acceptable: similarity only ORDERS the assignment (no threshold), and without token sequences\n * (or in an oversized group) the stable tie-break reproduces positional order.\n */\nfunction pairGroup(\n baseGroup: IndexedFunction[],\n headGroup: IndexedFunction[],\n baseMatched: boolean[][],\n headMatched: boolean[][],\n pairs: MatchedPair[]\n): void {\n const ambiguous =\n baseGroup.length + headGroup.length > 2 && baseGroup.length * headGroup.length <= maxSimilarityComparisons;\n const candidates: SimilarityCandidate[] = [];\n for (const [basePosition, base] of baseGroup.entries()) {\n for (const [headPosition, head] of headGroup.entries()) {\n candidates.push({\n similarity: ambiguous ? tokenSimilarityPercent(base.tokens, head.tokens, 0) : 0,\n basePosition,\n headPosition,\n });\n }\n }\n takeMaximumMatches(candidates, baseGroup, headGroup, baseMatched, headMatched, pairs);\n}\n\n/** Cross-file (and remaining within-file) similarity matching over every unmatched function. */\nfunction pairAcrossChangeSet(\n files: GateFileInput[],\n baseMatched: boolean[][],\n headMatched: boolean[][],\n pairs: MatchedPair[],\n matchSimilarityPercent: number\n): void {\n const unmatchedBase = collectUnmatched(files, baseMatched, 'base');\n const unmatchedHead = collectUnmatched(files, headMatched, 'head');\n if (unmatchedBase.length * unmatchedHead.length > maxSimilarityComparisons) {\n return;\n }\n\n const candidates: SimilarityCandidate[] = [];\n for (const [basePosition, base] of unmatchedBase.entries()) {\n for (const [headPosition, head] of unmatchedHead.entries()) {\n const similarity = tokenSimilarityPercent(base.tokens, head.tokens, matchSimilarityPercent);\n if (similarity >= matchSimilarityPercent) {\n candidates.push({ similarity, basePosition, headPosition });\n }\n }\n }\n takeMaximumMatches(candidates, unmatchedBase, unmatchedHead, baseMatched, headMatched, pairs);\n}\n\n/**\n * Assignment over the candidate edges: a greedy best-similarity-first seed, then Kuhn's\n * augmenting paths for the bases the seed left unmatched, so a function whose only counterpart\n * was taken by a slightly better pair is re-matched by rewiring instead of being falsely gated as\n * new code. Augmentation runs only when it increases cardinality, and an exact (100%) seed pair —\n * certain identity — is locked and never rewired even then: trading it for two partial matches\n * would ratchet an untouched function against some other function's rewrite. Non-exact seed pairs\n * may be rewired, but only when that matches strictly more functions (which a maximum-weight\n * assignment would also prefer). Without token sequences every similarity ties at 0 and the seed\n * reproduces positional order.\n */\nfunction takeMaximumMatches(\n candidates: SimilarityCandidate[],\n baseGroup: IndexedFunction[],\n headGroup: IndexedFunction[],\n baseMatched: boolean[][],\n headMatched: boolean[][],\n pairs: MatchedPair[]\n): void {\n candidates.sort(\n (left, right) =>\n right.similarity - left.similarity ||\n left.basePosition - right.basePosition ||\n left.headPosition - right.headPosition\n );\n const adjacency = new Map<number, number[]>();\n const baseOfHead = new Map<number, number>();\n const lockedHeads = new Set<number>();\n const matchedBases = seedGreedyMatches(candidates, adjacency, baseOfHead, lockedHeads);\n for (const basePosition of [...adjacency.keys()].toSorted((left, right) => left - right)) {\n if (!matchedBases.has(basePosition)) {\n tryAugment(basePosition, adjacency, baseOfHead, lockedHeads, new Set());\n }\n }\n\n for (const [headPosition, basePosition] of [...baseOfHead.entries()].toSorted((left, right) => left[0] - right[0])) {\n const base = baseGroup[basePosition] as IndexedFunction;\n const head = headGroup[headPosition] as IndexedFunction;\n (baseMatched[base.fileIndex] as boolean[])[base.functionIndex] = true;\n (headMatched[head.fileIndex] as boolean[])[head.functionIndex] = true;\n pairs.push({ base: base.fn, head: head.fn, headFileIndex: head.fileIndex });\n }\n}\n\n/**\n * Fills the adjacency lists and takes each best edge whose endpoints are both still free; a taken\n * exact (100%) edge locks its head against later rewiring.\n */\nfunction seedGreedyMatches(\n candidates: SimilarityCandidate[],\n adjacency: Map<number, number[]>,\n baseOfHead: Map<number, number>,\n lockedHeads: Set<number>\n): Set<number> {\n const matchedBases = new Set<number>();\n for (const candidate of candidates) {\n const edges = adjacency.get(candidate.basePosition) ?? [];\n edges.push(candidate.headPosition);\n adjacency.set(candidate.basePosition, edges);\n if (!matchedBases.has(candidate.basePosition) && !baseOfHead.has(candidate.headPosition)) {\n baseOfHead.set(candidate.headPosition, candidate.basePosition);\n matchedBases.add(candidate.basePosition);\n if (candidate.similarity === 100) {\n lockedHeads.add(candidate.headPosition);\n }\n }\n }\n return matchedBases;\n}\n\n/** One Kuhn augmentation step: rewires existing (unlocked) matches only when that frees a head for `basePosition`. */\nfunction tryAugment(\n basePosition: number,\n adjacency: Map<number, number[]>,\n baseOfHead: Map<number, number>,\n lockedHeads: Set<number>,\n visitedHeads: Set<number>\n): boolean {\n for (const headPosition of adjacency.get(basePosition) ?? []) {\n if (visitedHeads.has(headPosition) || lockedHeads.has(headPosition)) {\n continue;\n }\n visitedHeads.add(headPosition);\n const currentBase = baseOfHead.get(headPosition);\n if (currentBase === undefined || tryAugment(currentBase, adjacency, baseOfHead, lockedHeads, visitedHeads)) {\n baseOfHead.set(headPosition, basePosition);\n return true;\n }\n }\n return false;\n}\n\n/** Token-LCS similarity of two sequences relative to the longer one, in percent (0 when unusable). */\nfunction tokenSimilarityPercent(\n base: Int32Array | undefined,\n head: Int32Array | undefined,\n minPercent: number\n): number {\n if (!base || !head || base.length === 0 || head.length === 0) {\n return 0;\n }\n // The LCS cannot exceed the shorter sequence, so mismatched lengths are pruned for free.\n const maxLength = Math.max(base.length, head.length);\n if (Math.min(base.length, head.length) * 100 < minPercent * maxLength) {\n return 0;\n }\n return (lcsLength(base, head) * 100) / maxLength;\n}\n\nfunction checkRatchets(\n file: string,\n base: FunctionMetrics,\n head: FunctionMetrics,\n tolerances: GateTolerances\n): GateViolation[] {\n const violations: GateViolation[] = [];\n for (const ratchet of ratchetMetrics) {\n const baseValue = ratchet.value(base);\n const headValue = ratchet.value(head);\n const allowedValue = baseValue + ratchet.allowance(tolerances, baseValue);\n if (headValue > allowedValue) {\n const name = head.name ?? '<anonymous>';\n violations.push({\n gate: 'function-regression',\n metric: ratchet.metric,\n file,\n functionName: name,\n startLine: head.startLine,\n endLine: head.endLine,\n baseValue,\n headValue,\n allowedValue,\n message:\n `${file}:${head.startLine}-${head.endLine} ${name}: ${ratchet.metric} worsened ` +\n `${ratchet.format(baseValue)} -> ${ratchet.format(headValue)} (allowed <= ${ratchet.format(allowedValue)}). ` +\n ratchet.remediation,\n });\n }\n }\n return violations;\n}\n\nfunction checkNewFunction(file: string, fn: FunctionMetrics, thresholds: NewFunctionThresholds): GateViolation[] {\n const violations: GateViolation[] = [];\n for (const check of newFunctionMetrics) {\n const headValue = check.value(fn);\n const allowedValue = check.limit(thresholds);\n if (headValue > allowedValue) {\n const name = fn.name ?? '<anonymous>';\n violations.push({\n gate: 'new-function',\n metric: check.metric,\n file,\n functionName: name,\n startLine: fn.startLine,\n endLine: fn.endLine,\n headValue,\n allowedValue,\n message:\n `${file}:${fn.startLine}-${fn.endLine} new function ${name}: ${check.metric} ${headValue} ` +\n `exceeds the new-code limit ${allowedValue}. ${check.remediation}`,\n });\n }\n }\n return violations;\n}\n\n/**\n * Anti-gaming backstops: splitting a function resets its entity identity and could hide a\n * worsening behind the (laxer) new-code thresholds, so when a removed named function's content\n * reappears in unmatched new code (see hasSplitEvidence) the file-level aggregates ratchet too —\n * the max cognitive complexity per file and the file's total NCSS. Purely additive changes and\n * unrelated remove-plus-add changes stay ungated. The max-cognitive backstop is also skipped when\n * a function-level cognitive violation already reports the file's maximum, since it would only\n * restate it.\n */\nfunction checkFileBackstops(\n file: GateFileInput,\n splitEvidence: boolean,\n reportedViolations: GateViolation[],\n options: GateOptions\n): GateViolation[] {\n const { baseMetrics, headMetrics } = file;\n if (!baseMetrics || !headMetrics || !splitEvidence) {\n return [];\n }\n const violations: GateViolation[] = [];\n const tolerances = options.tolerance;\n\n const maximumAlreadyReported = reportedViolations.some(\n (violation) =>\n violation.file === file.file &&\n violation.metric === 'cognitive complexity' &&\n (violation.gate === 'function-regression' || violation.gate === 'new-function') &&\n violation.headValue === headMetrics.maxCognitiveComplexity\n );\n const allowedMaxCognitive = baseMetrics.maxCognitiveComplexity + tolerances.cognitiveComplexity;\n if (!maximumAlreadyReported && headMetrics.maxCognitiveComplexity > allowedMaxCognitive) {\n const worst = findMostComplexFunction(headMetrics.functions);\n const startLine = worst?.startLine ?? 1;\n const endLine = worst?.endLine ?? headMetrics.lines.total;\n violations.push({\n gate: 'file-regression',\n metric: 'file max cognitive complexity',\n file: file.file,\n functionName: worst?.name ?? undefined,\n startLine,\n endLine,\n baseValue: baseMetrics.maxCognitiveComplexity,\n headValue: headMetrics.maxCognitiveComplexity,\n allowedValue: allowedMaxCognitive,\n message:\n `${file.file}:${startLine}-${endLine}: the file's max cognitive complexity worsened ` +\n `${baseMetrics.maxCognitiveComplexity} -> ${headMetrics.maxCognitiveComplexity} ` +\n `(allowed <= ${allowedMaxCognitive}). Simplify or split the most complex ` +\n `function${worst ? ` (${worst.name ?? '<anonymous>'})` : ''}.`,\n });\n }\n\n const allowedFileNcss = baseMetrics.ncssCount + tolerances.fileNcss;\n if (headMetrics.ncssCount > allowedFileNcss) {\n violations.push({\n gate: 'file-regression',\n metric: 'file NCSS',\n file: file.file,\n startLine: 1,\n endLine: headMetrics.lines.total,\n baseValue: baseMetrics.ncssCount,\n headValue: headMetrics.ncssCount,\n allowedValue: allowedFileNcss,\n message:\n `${file.file}:1-${headMetrics.lines.total}: functions were removed or split while the file grew from NCSS ` +\n `${baseMetrics.ncssCount} to ${headMetrics.ncssCount} (allowed <= ${allowedFileNcss}). ` +\n `Remove the added statements or move genuinely new code into its own module.`,\n });\n }\n\n return violations;\n}\n\nfunction findMostComplexFunction(functions: FunctionMetrics[]): FunctionMetrics | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (!worst || fn.cognitiveComplexity > worst.cognitiveComplexity) {\n worst = fn;\n }\n }\n return worst;\n}\n\n/**\n * No new duplication: the distinct duplicated lines of a changed file (within-file plus\n * cross-file against the whole project, so copy-paste from existing code into new files is\n * caught) must not exceed the base revision's count.\n */\nfunction checkDuplication(file: GateFileInput, tolerances: GateTolerances): GateViolation[] {\n const allowedValue = file.baseDuplicatedLineCount + tolerances.duplicateLines;\n if (file.headDuplicatedLineCount <= allowedValue) {\n return [];\n }\n const partners = file.duplicationPartners.slice(0, 3).join(', ');\n const endLine = file.headMetrics?.lines.total ?? 1;\n return [\n {\n gate: 'duplication',\n metric: 'duplicated lines',\n file: file.file,\n startLine: 1,\n endLine,\n baseValue: file.baseDuplicatedLineCount,\n headValue: file.headDuplicatedLineCount,\n allowedValue,\n message:\n `${file.file}:1-${endLine}: duplicated lines increased ${file.baseDuplicatedLineCount} -> ` +\n `${file.headDuplicatedLineCount} (allowed <= ${allowedValue}). Deduplicate` +\n `${partners ? ` against ${partners}` : ' the repeated code'} by extracting a shared helper.`,\n },\n ];\n}\n"],"mappings":"6CAyCA,MAAa,EAAkC,CAG7C,YAAa,CAAE,uBAAwB,GAAI,QAAS,GAAI,gBAAiB,CAAE,EAK3E,UAAW,CACT,oBAAqB,EACrB,KAAM,EACN,aAAc,EACd,UAAW,GACX,eAAgB,IAChB,SAAU,GACV,eAAgB,CAClB,EACA,uBAAwB,EAC1B,EA+EM,EAAgB,OAQhB,EAAkC,CACtC,CACE,OAAQ,uBACR,MAAQ,GAAO,EAAG,oBAClB,UAAY,GAAe,EAAW,oBACtC,YAAa,sDACb,OAAQ,CACV,EACA,CACE,OAAQ,OACR,MAAQ,GAAO,EAAG,KAClB,UAAY,GAAe,EAAW,KACtC,YAAa,qEACb,OAAQ,CACV,EACA,CACE,OAAQ,oBACR,MAAQ,GAAO,EAAG,aAClB,UAAY,GAAe,EAAW,aACtC,YAAa,qEACb,OAAQ,CACV,EACA,CACE,OAAQ,YACR,MAAQ,GA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n=require("./metrics.cjs");let r=require("node:fs/promises"),i=require("node:path");i=e.__toESM(i,1);let a=require("node:os");a=e.__toESM(a,1);const o=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),s=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`target`,`test-fixtures`,`vendor`,`venv`]),c=new Set([`__tests__`,`test`,`tests`,`spec`]),l=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,u=/Test\.java$/u;function d(e){return e===`~`?a.default.homedir():e.startsWith(`~/`)?i.default.join(a.default.homedir(),e.slice(2)):i.default.resolve(e)}async function f(e){try{return(await(0,r.stat)(e)).isDirectory()?e:i.default.dirname(e)}catch{return i.default.dirname(e)}}async function p(e,t){let n=[],a=[],o=[],s=e;try{s=await(0,r.realpath)(e)}catch{}let c=i.default.dirname(s),l;try{l=await(0,r.stat)(s)}catch(e){let t=`${O(s,c)}: ${j(e)}`;return{displayRoot:c,files:n,errors:[t],warnings:o,fatalError:t}}if(l.isFile()){let e=i.default.dirname(s),r=D(s,t,!0);if(!r){let t=`${O(s,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:o,fatalError:t}}let c=h(t,n,a,o,e);return await x(s,r,`single-file`,c,s),{displayRoot:e,files:n,errors:a,warnings:o}}return await v(s,h(t,n,a,o,s)),{displayRoot:s,files:n,errors:a,warnings:o}}async function m(e,t,n){let a=[],o=[],s=[],c=h(n,a,o,s,e);for(let a of t){let t=E(a,n)?D(a,n):void 0;if(!t)continue;let o=i.default.join(e,a);(await(0,r.lstat)(o).catch(()=>{}))?.isSymbolicLink()||await x(o,t,`directory`,c)}return{displayRoot:e,files:a,errors:o,warnings:s}}function h(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function g(e,t,n){try{return await e()}catch(e){n.errors.push(`${O(t,n.rootDirectory)}: ${j(e)}`);return}}async function _(e,t){let n=await g(()=>(0,r.realpath)(e),e,t);return n!==void 0&&T(n,t.rootDirectory)?n:void 0}async function v(e,t){let n=await _(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let a=await g(()=>(0,r.readdir)(e,{withFileTypes:!0}),e,t);if(a!==void 0)for(let n of a){let r=i.default.join(e,n.name);if(n.isSymbolicLink()){await y(n.name,r,t);continue}if(n.isDirectory()){if(w(n.name,t.options))continue;await v(r,t);continue}n.isFile()&&await b(r,t)}}async function y(e,t,n){let a=await _(t,n);if(a===void 0)return;let o=await g(()=>(0,r.stat)(t),t,n);if(o!==void 0){if(o.isDirectory()){if(w(e,n.options)||w(i.default.basename(a),n.options))return;await v(t,n);return}o.isFile()&&await b(t,n,a,a)}}async function b(e,t,n=e,r){let i=D(n,t.options);i&&await x(e,i,`directory`,t,r)}async function x(e,t,i,a,o){try{let s=o??await(0,r.realpath)(e);if(a.visitedFiles.has(s))return;a.visitedFiles.add(s);let c=await(0,r.readFile)(e,`utf8`),l={language:t,duplication:a.options.duplication},u={file:e,metrics:n.measureCode(c,l)};if(i===`directory`)try{u.duplicationCandidates=n.collectCrossFileDuplicationFileData(c,l)}catch(t){a.warnings.push(`${O(e,a.rootDirectory)}: cross-file duplication candidates unavailable: ${j(t)}`)}a.files.push(u)}catch(t){a.errors.push(`${O(e,a.rootDirectory)}: ${j(t)}`)}}function S(e,n){if(e.fatalError||e.files.length<2)return;let r=e.files.flatMap(({file:t,duplicationCandidates:n})=>n?[{file:O(t,e.displayRoot),...n}]:[]);r.length<2||(e.crossFileDuplication=t.measureCrossFileDuplication(r,n.duplication))}function C(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function w(e,t){return s.has(e)?!0:!t.includeTests&&c.has(e)}function T(e,t){let n=i.default.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${i.default.sep}`)&&!i.default.isAbsolute(n)}function E(e,t){let n=e.split(`/`);for(let e of n.slice(0,-1))if(s.has(e)||!t.includeTests&&c.has(e))return!1;return D(e,t)!==void 0}function D(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(l.test(i.default.basename(e))||u.test(i.default.basename(e)))))return i.default.extname(e)===`.C`?`cpp`:o.get(i.default.extname(r))}function O(e,t){return i.default.relative(t,e)||i.default.basename(e)}function k(e){process.stdout.write(e)}function A(e){process.stderr.write(e)}function j(e){return e instanceof Error?e.message:String(e)}exports.addCrossFileDuplication=S,exports.collectDuplicatedLineNumbers=C,exports.configSearchDirectory=f,exports.formatError=j,exports.formatPath=O,exports.getLanguage=D,exports.isScannedPath=E,exports.resolveTarget=d,exports.scanListedFiles=m,exports.scanTarget=p,exports.writeStderr=A,exports.writeStdout=k;
2
+ //# sourceMappingURL=scan.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan.cjs","names":["os","path","stat","realpath","lstat","readdir","readFile","measureCode","collectCrossFileDuplicationFileData","measureCrossFileDuplication"],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport { collectCrossFileDuplicationFileData, measureCode } from './metrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit tests use a case-sensitive `Test.java` suffix; case-insensitive matching would catch\n// production files like `contest.java`.\nconst javaTestFilePattern = /Test\\.java$/u;\n\nexport function resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return { displayRoot, files, errors, warnings };\n }\n\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions\n): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const context = makeScanContext(options, files, errors, warnings, rootDirectory);\n for (const relativePath of relativePaths) {\n const language = isScannedPath(relativePath, options) ? getLanguage(relativePath, options) : undefined;\n if (!language) {\n continue;\n }\n const absolutePath = path.join(rootDirectory, relativePath);\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (stats?.isSymbolicLink()) {\n continue;\n }\n await measureFile(absolutePath, language, 'directory', context);\n }\n return { displayRoot: rootDirectory, files, errors, warnings };\n}\n\nfunction makeScanContext(\n options: ScanOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n context.errors.push(`${formatPath(target, context.rootDirectory)}: ${formatError(error)}`);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection failing (it always parses with the JavaScript binding, which can give\n // up where the native backend measured fine) must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectCrossFileDuplicationFileData(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions): boolean {\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"wPA+BA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,QAAQ,EAChB,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,CAChB,CAAC,EAEK,EAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eACA,SACA,gBACA,SACA,MACF,CAAC,EAEK,EAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAsB,eAE5B,SAAgB,EAAc,EAAwB,CASpD,OARI,IAAW,IACNA,EAAAA,QAAG,QAAQ,EAGhB,EAAO,WAAW,IAAI,EACjBC,EAAA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AC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAwB,CAClD,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
package/dist/scan.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { type CrossFileDuplicationMetrics } from './crossFileDuplication.js';
2
+ import type { CrossFileDuplicationFileData } from './duplication.js';
3
+ import type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';
4
+ /** The scan settings shared by every command (a structural subset of each command's options). */
5
+ export interface ScanOptions {
6
+ duplication: Required<DuplicationOptions>;
7
+ includeTests: boolean;
8
+ }
9
+ export interface FileMetrics {
10
+ file: string;
11
+ metrics: CodeMetrics;
12
+ /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */
13
+ duplicationCandidates?: CrossFileDuplicationFileData;
14
+ }
15
+ export interface ScanResult {
16
+ crossFileDuplication?: CrossFileDuplicationMetrics;
17
+ displayRoot: string;
18
+ errors: string[];
19
+ /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */
20
+ warnings: string[];
21
+ fatalError?: string;
22
+ files: FileMetrics[];
23
+ }
24
+ export declare function resolveTarget(target: string): string;
25
+ /** Returns the directory from which the config file search should start (the target itself if it is a directory). */
26
+ export declare function configSearchDirectory(target: string): Promise<string>;
27
+ export declare function scanTarget(target: string, options: ScanOptions): Promise<ScanResult>;
28
+ /**
29
+ * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)
30
+ * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths
31
+ * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped
32
+ * with the same rules as the walk.
33
+ */
34
+ export declare function scanListedFiles(rootDirectory: string, relativePaths: Iterable<string>, options: ScanOptions): Promise<ScanResult>;
35
+ /** Runs after the scan so every measured file's candidates participate. */
36
+ export declare function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void;
37
+ /**
38
+ * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both
39
+ * sources expose the exact lines carrying matched tokens (never block bounding ranges, which
40
+ * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is
41
+ * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.
42
+ */
43
+ export declare function collectDuplicatedLineNumbers(metrics: CodeMetrics | undefined, crossFileDuplication: CrossFileDuplicationMetrics | undefined, formattedFile: string): Set<number>;
44
+ /**
45
+ * Whether a repository-relative path would be scanned: no ignored or excluded-test directory
46
+ * segment and a supported, non-test file name. The diff gate uses this for base-revision
47
+ * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against
48
+ * a blob the scanner would never have measured.
49
+ */
50
+ export declare function isScannedPath(relativePath: string, options: ScanOptions): boolean;
51
+ export declare function getLanguage(file: string, options: ScanOptions, explicitTarget?: boolean): LanguageName | undefined;
52
+ export declare function formatPath(file: string, base: string): string;
53
+ export declare function writeStdout(message: string): void;
54
+ export declare function writeStderr(message: string): void;
55
+ export declare function formatError(error: unknown): string;
package/dist/scan.js ADDED
@@ -0,0 +1,2 @@
1
+ import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{collectCrossFileDuplicationFileData as t,measureCode as n}from"./metrics.js";import{lstat as r,readFile as i,readdir as a,realpath as o,stat as s}from"node:fs/promises";import c from"node:path";import l from"node:os";const u=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),d=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`target`,`test-fixtures`,`vendor`,`venv`]),f=new Set([`__tests__`,`test`,`tests`,`spec`]),p=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,m=/Test\.java$/u;function h(e){return e===`~`?l.homedir():e.startsWith(`~/`)?c.join(l.homedir(),e.slice(2)):c.resolve(e)}async function g(e){try{return(await s(e)).isDirectory()?e:c.dirname(e)}catch{return c.dirname(e)}}async function _(e,t){let n=[],r=[],i=[],a=e;try{a=await o(e)}catch{}let l=c.dirname(a),u;try{u=await s(a)}catch(e){let t=`${M(a,l)}: ${F(e)}`;return{displayRoot:l,files:n,errors:[t],warnings:i,fatalError:t}}if(u.isFile()){let e=c.dirname(a),o=j(a,t,!0);if(!o){let t=`${M(a,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:i,fatalError:t}}let s=y(t,n,r,i,e);return await T(a,o,`single-file`,s,a),{displayRoot:e,files:n,errors:r,warnings:i}}return await S(a,y(t,n,r,i,a)),{displayRoot:a,files:n,errors:r,warnings:i}}async function v(e,t,n){let i=[],a=[],o=[],s=y(n,i,a,o,e);for(let i of t){let t=A(i,n)?j(i,n):void 0;if(!t)continue;let a=c.join(e,i);(await r(a).catch(()=>{}))?.isSymbolicLink()||await T(a,t,`directory`,s)}return{displayRoot:e,files:i,errors:a,warnings:o}}function y(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function b(e,t,n){try{return await e()}catch(e){n.errors.push(`${M(t,n.rootDirectory)}: ${F(e)}`);return}}async function x(e,t){let n=await b(()=>o(e),e,t);return n!==void 0&&k(n,t.rootDirectory)?n:void 0}async function S(e,t){let n=await x(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await b(()=>a(e,{withFileTypes:!0}),e,t);if(r!==void 0)for(let n of r){let r=c.join(e,n.name);if(n.isSymbolicLink()){await C(n.name,r,t);continue}if(n.isDirectory()){if(O(n.name,t.options))continue;await S(r,t);continue}n.isFile()&&await w(r,t)}}async function C(e,t,n){let r=await x(t,n);if(r===void 0)return;let i=await b(()=>s(t),t,n);if(i!==void 0){if(i.isDirectory()){if(O(e,n.options)||O(c.basename(r),n.options))return;await S(t,n);return}i.isFile()&&await w(t,n,r,r)}}async function w(e,t,n=e,r){let i=j(n,t.options);i&&await T(e,i,`directory`,t,r)}async function T(e,r,a,s,c){try{let l=c??await o(e);if(s.visitedFiles.has(l))return;s.visitedFiles.add(l);let u=await i(e,`utf8`),d={language:r,duplication:s.options.duplication},f={file:e,metrics:n(u,d)};if(a===`directory`)try{f.duplicationCandidates=t(u,d)}catch(t){s.warnings.push(`${M(e,s.rootDirectory)}: cross-file duplication candidates unavailable: ${F(t)}`)}s.files.push(f)}catch(t){s.errors.push(`${M(e,s.rootDirectory)}: ${F(t)}`)}}function E(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:M(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function D(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function O(e,t){return d.has(e)?!0:!t.includeTests&&f.has(e)}function k(e,t){let n=c.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${c.sep}`)&&!c.isAbsolute(n)}function A(e,t){let n=e.split(`/`);for(let e of n.slice(0,-1))if(d.has(e)||!t.includeTests&&f.has(e))return!1;return j(e,t)!==void 0}function j(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(p.test(c.basename(e))||m.test(c.basename(e)))))return c.extname(e)===`.C`?`cpp`:u.get(c.extname(r))}function M(e,t){return c.relative(t,e)||c.basename(e)}function N(e){process.stdout.write(e)}function P(e){process.stderr.write(e)}function F(e){return e instanceof Error?e.message:String(e)}export{E as addCrossFileDuplication,D as collectDuplicatedLineNumbers,g as configSearchDirectory,F as formatError,M as formatPath,j as getLanguage,A as isScannedPath,h as resolveTarget,v as scanListedFiles,_ as scanTarget,P as writeStderr,N as writeStdout};
2
+ //# sourceMappingURL=scan.js.map