@wbern/obscene 2.2.0 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cli.js +17 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -222,7 +222,7 @@ The thresholds are engineering judgment, not paper-prescribed. The defect/coupli
|
|
|
222
222
|
| Defects | total `fix:` commits in window | 5 / 15 / 50 | Floor matches code-maat `--min-revs 5` |
|
|
223
223
|
| Authors | distinct authors on the most-touched file | 2 / 4 / 8 | Bird et al. (FSE 2011) shows minor contributors correlate with defects, but the floor is engineering judgment |
|
|
224
224
|
| Coupling | commits in window | 5 / 30 / 100 | Floor matches code-maat `--min-revs 5` |
|
|
225
|
-
| Composite (RRF) | number of input rankings | min-of-inputs over per-dimension confidences | Reciprocal Rank Fusion (Cormack et al., SIGIR 2009); `min`
|
|
225
|
+
| Composite (RRF) | number of input rankings | min-of-inputs over per-dimension confidences | Reciprocal Rank Fusion (Cormack et al., SIGIR 2009); `min` ensures the composite can never claim more confidence than its weakest input |
|
|
226
226
|
|
|
227
227
|
I want to be transparent: an earlier release of this section over-attributed thresholds to specific papers. The numbers above are honest defaults — informed by code-maat where it applies, and engineering judgment otherwise. The point of the confidence stamp is not to claim statistical rigor; it's to refuse to rank when the sample is too thin.
|
|
228
228
|
|
package/dist/cli.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{existsSync as
|
|
3
|
-
`).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#"))}catch(t){if(t&&typeof t=="object"&&"code"in t&&t.code==="ENOENT")continue;throw t}return[]}var H=[{title:"Test files and test infrastructure",patterns:[{pattern:"*.test.*",comment:"Unit test files"},{pattern:"*.spec.*",comment:"Spec test files"},{pattern:"*.integration.test.*",comment:"Integration tests"},{pattern:"test-setup.*",comment:"Test setup files"},{pattern:"test-utils.*",comment:"Test utility files"},{pattern:"test-helpers.*",comment:"Test helper files"},{pattern:"__tests__/**",comment:"Test directories"},{pattern:"__mocks__/**",comment:"Mock directories"},{pattern:"*.stories.*",comment:"Storybook stories"},{pattern:"*.d.ts",comment:"TypeScript declaration files"}]},{title:"Lock files and package manifests",patterns:[{pattern:"package.json",comment:"npm package manifest"},{pattern:"package-lock.json",comment:"npm lock file"},{pattern:"pnpm-lock.yaml",comment:"pnpm lock file"},{pattern:"yarn.lock",comment:"Yarn lock file"},{pattern:"bun.lock",comment:"Bun lock file"}]}],xe=.5,we=.8,_=5,j=3,R={complexity:{weak:3,plausible:10,acceptable:30},nesting:{weak:3,plausible:10,acceptable:30},defects:{weak:5,plausible:15,acceptable:50},authors:{weak:2,plausible:4,acceptable:8},coupling:{weak:5,plausible:30,acceptable:100}},v={complexity:"Engineering judgment: any rank ordering needs \u2265 3 items to be meaningful; higher tiers scale from there. No paper prescribes these exact cutoffs.",nesting:"Engineering judgment, informed by Campbell (SonarSource 2018) Cognitive Complexity which assigns a compounding penalty per nesting level. The 3/10/30 sample-count tiers are not from the paper.",defects:"code-maat's --min-revs default of 5 (Adam Tornhill); higher tiers are engineering judgment. Gall et al. (IWPSE 2003) and Hassan (ICSE 2009) study co-change and change-entropy but do not prescribe a specific commit-count floor.",authors:"Engineering judgment. Bird et al. (FSE 2011) Don't Touch My Code! shows minor contributors (< 5% of commits) correlate with elevated defects, motivating attention to contributor count \u2014 but the 2/4/8 tiers here are not from the paper.",coupling:"code-maat defaults (--min-revs 5, --max-changeset-size 30, Adam Tornhill). CodeScene's documented temporal-coupling default filters files with fewer than 10 commits. The 30/100 upper tiers are engineering judgment.",composite:"Reciprocal Rank Fusion (Cormack et al., SIGIR 2009) fuses multiple independent rankings; min-of-inputs is a strict monotone aggregator
|
|
2
|
+
import{existsSync as L,writeFileSync as Ne}from"fs";import{Command as Ae}from"commander";import{execSync as E}from"child_process";import{readFileSync as Y}from"fs";var Ce=[".obsignore",".obsceneignore"];function Q(){for(let e of Ce)try{return Y(e,"utf-8").split(`
|
|
3
|
+
`).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#"))}catch(t){if(t&&typeof t=="object"&&"code"in t&&t.code==="ENOENT")continue;throw t}return[]}var H=[{title:"Test files and test infrastructure",patterns:[{pattern:"*.test.*",comment:"Unit test files"},{pattern:"*.spec.*",comment:"Spec test files"},{pattern:"*.integration.test.*",comment:"Integration tests"},{pattern:"test-setup.*",comment:"Test setup files"},{pattern:"test-utils.*",comment:"Test utility files"},{pattern:"test-helpers.*",comment:"Test helper files"},{pattern:"__tests__/**",comment:"Test directories"},{pattern:"__mocks__/**",comment:"Mock directories"},{pattern:"*.stories.*",comment:"Storybook stories"},{pattern:"*.d.ts",comment:"TypeScript declaration files"}]},{title:"Lock files and package manifests",patterns:[{pattern:"package.json",comment:"npm package manifest"},{pattern:"package-lock.json",comment:"npm lock file"},{pattern:"pnpm-lock.yaml",comment:"pnpm lock file"},{pattern:"yarn.lock",comment:"Yarn lock file"},{pattern:"bun.lock",comment:"Bun lock file"}]}],xe=.5,we=.8,_=5,j=3,R={complexity:{weak:3,plausible:10,acceptable:30},nesting:{weak:3,plausible:10,acceptable:30},defects:{weak:5,plausible:15,acceptable:50},authors:{weak:2,plausible:4,acceptable:8},coupling:{weak:5,plausible:30,acceptable:100}},v={complexity:"Engineering judgment: any rank ordering needs \u2265 3 items to be meaningful; higher tiers scale from there. No paper prescribes these exact cutoffs.",nesting:"Engineering judgment, informed by Campbell (SonarSource 2018) Cognitive Complexity which assigns a compounding penalty per nesting level. The 3/10/30 sample-count tiers are not from the paper.",defects:"code-maat's --min-revs default of 5 (Adam Tornhill); higher tiers are engineering judgment. Gall et al. (IWPSE 2003) and Hassan (ICSE 2009) study co-change and change-entropy but do not prescribe a specific commit-count floor.",authors:"Engineering judgment. Bird et al. (FSE 2011) Don't Touch My Code! shows minor contributors (< 5% of commits) correlate with elevated defects, motivating attention to contributor count \u2014 but the 2/4/8 tiers here are not from the paper.",coupling:"code-maat defaults (--min-revs 5, --max-changeset-size 30, Adam Tornhill). CodeScene's documented temporal-coupling default filters files with fewer than 10 commits. The 30/100 upper tiers are engineering judgment.",composite:"Reciprocal Rank Fusion (Cormack et al., SIGIR 2009) fuses multiple independent rankings; min-of-inputs is a strict monotone aggregator \u2014 when every input ranking is at confidence level L, the composite cannot exceed L."};function I(e,t,n,o,i){let c;return t<n.weak?c="inconclusive":t<n.plausible?c="weak":t<n.acceptable?c="plausible":c="acceptable",{level:c,reason:i(c),inputs:{metric:e,value:t,thresholds:n},source:o}}function Z(e,t){return t.some(n=>n.test(e))}function ee(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\u27E8GLOBSTAR\u27E9").replace(/\*/g,"[^/]*").replace(/⟨GLOBSTAR⟩/g,".*").replace(/\?/g,".");return new RegExp(t)}function T(e){let t=e.replaceAll("\\","/");return t.startsWith("./")?t.slice(2):t}function $(e=[]){let t=e.map(ee),n;try{n=E("scc --by-file --format json --no-cocomo --no-gen",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch(c){throw c&&typeof c=="object"&&"code"in c&&c.code==="ENOENT"?new Error("scc not found. Install it: https://github.com/boyter/scc#install"):c}let o=JSON.parse(n.toString()),i=[];for(let c of o)for(let a of c.Files){let l=T(a.Location);Z(l,t)||i.push({file:l,code:a.Code,lines:a.Lines,complexity:a.Complexity,comments:a.Comment,complexityDensity:a.Code>0?Math.round(a.Complexity/a.Code*100)/100:0})}return i.sort((c,a)=>a.complexity-c.complexity)}function te(e,t){let n;try{n=E(e,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch{throw new Error(t)}let o=new Map;for(let i of n.toString().split(`
|
|
4
4
|
`)){let c=T(i.trim());c&&o.set(c,(o.get(c)??0)+1)}return o}function P(e){return te(`git log --since="${e} months ago" --format="" --name-only`,"Not a git repository or git is not installed.")}function ne(e){return te(`git log --since="${e} months ago" --grep="^fix" --format="" --name-only`,"Not a git repository or git is not installed.")}function oe(e){let t;try{t=E(`git log --since="${e} months ago" --format="COMMIT_SEP%n%aN" --name-only`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch{throw new Error("Not a git repository or git is not installed.")}let n=new Map,o=t.toString().split(`COMMIT_SEP
|
|
5
5
|
`);for(let c of o){if(!c.trim())continue;let a=c.split(`
|
|
6
|
-
`),l=a[0].trim();if(!(!l||l.endsWith("[bot]")))for(let r=1;r<a.length;r++){let m=T(a[r].trim());if(!m)continue;let s=n.get(m);s||(s=new Set,n.set(m,s)),s.add(l)}}let i=new Map;for(let[c,a]of n)i.set(c,a.size);return i}var
|
|
6
|
+
`),l=a[0].trim();if(!(!l||l.endsWith("[bot]")))for(let r=1;r<a.length;r++){let m=T(a[r].trim());if(!m)continue;let s=n.get(m);s||(s=new Set,n.set(m,s)),s.add(l)}}let i=new Map;for(let[c,a]of n)i.set(c,a.size);return i}var ke=20;function ie(e,t=[]){let n=t.map(ee),o;try{o=E(`git log --since="${e} months ago" --format="COMMIT_SEP%n" --name-only`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch{throw new Error("Not a git repository or git is not installed.")}let i=new Map,c=o.toString().split(`COMMIT_SEP
|
|
7
7
|
`);for(let a of c){if(!a.trim())continue;let l=new Set;for(let m of a.split(`
|
|
8
|
-
`)){let s=T(m.trim());s&&(Z(s,n)||l.add(s))}let r=[...l];if(!(r.length<2||r.length>
|
|
8
|
+
`)){let s=T(m.trim());s&&(Z(s,n)||l.add(s))}let r=[...l];if(!(r.length<2||r.length>ke))for(let m=0;m<r.length;m++)for(let s=m+1;s<r.length;s++){let[u,f]=r[m]<r[s]?[r[m],r[s]]:[r[s],r[m]],h=u.includes("/")?u.slice(0,u.lastIndexOf("/")):"",g=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";if(h===g)continue;let b=`${u}\0${f}`;i.set(b,(i.get(b)??0)+1)}}return i}function U(e,t){let n=0;for(let o of e){o.percentOfTotal=Math.round(o.score/t*1e3)/10,n+=o.score;let i=n/t;i<=xe?o.tier="hot":i<=we?o.tier="warm":o.tier="cool"}}var W=[{key:"complexity",label:"Complexity \xD7 Churn",scoreFormula:"complexity \xD7 churn"},{key:"nesting",label:"Nesting \xD7 Churn",scoreFormula:"maxNesting \xD7 churn"},{key:"defects",label:"Fix Activity \xD7 Churn",scoreFormula:"fixes \xD7 churn"},{key:"authors",label:"Authors \xD7 Churn",scoreFormula:"authors \xD7 churn"}];function Se(e,t,n,o){let i=e.map(a=>{let l=t.get(a.file)??0,r=n(a);return{file:a.file,score:r*l,percentOfTotal:0,tier:"cool",churn:l,metricValue:r,metricDensity:o?o(a):void 0}}).filter(a=>a.score>0).sort((a,l)=>l.score-a.score),c=i.reduce((a,l)=>a+l.score,0);return c===0?[]:(U(i,c),i)}function re(e,t,n,o,i,c){let a={complexity:{extract:p=>p.complexity,density:p=>p.complexityDensity},nesting:{extract:p=>o.get(p.file)??0},defects:{extract:p=>n.get(p.file)??0,density:p=>{let C=n.get(p.file)??0;return p.code>0?Math.round(C/p.code*1e4)/1e4:0}},authors:{extract:p=>i.get(p.file)??0}},l={},r={},m=0;for(let p of e)p.complexity>0&&m++;r.complexity=I("filesWithComplexity",m,R.complexity,v.complexity,p=>p==="inconclusive"?`${m} files with measurable complexity \u2014 not enough to rank.`:`${m} files with measurable complexity (${p.toUpperCase()} sample size).`);let s=0;for(let p of o.values())p>=3&&s++;r.nesting=I("filesWithNesting>=3",s,R.nesting,v.nesting,p=>p==="inconclusive"?`${s} files with nesting depth \u2265 3 \u2014 not enough to rank.`:`${s} files with nesting depth \u2265 3 (${p.toUpperCase()} sample size).`);let u=[...n.values()].reduce((p,C)=>p+C,0),f=n.size,h=u<_||f<j;r.defects=I("fixCommits",u,R.defects,v.defects,p=>p==="inconclusive"||h?`${u} fix: commits across ${f} files \u2014 need \u2265 ${_} commits across \u2265 ${j} files (matches code-maat's --min-revs default).`:`${u} fix: commits across ${f} files (${p.toUpperCase()} sample size).`),h&&(r.defects={...r.defects,level:"inconclusive"},l.defects={reason:`insufficient data (${u} fix: commits across ${f} files, need ${_}+ commits across ${j}+ files)`,suggestion:"Adopt conventional commits with fix: prefix. See conventionalcommits.org",confidence:r.defects});let g=0;for(let p of i.values())p>g&&(g=p);r.authors=I("maxAuthors",g,R.authors,v.authors,p=>p==="inconclusive"?`${g} distinct authors on the most-touched file \u2014 not enough to rank ownership.`:`${g} distinct authors on the most-touched file (${p.toUpperCase()} sample size).`),g<=1&&(r.authors={...r.authors,level:"inconclusive"},l.authors={reason:"all files have the same author count \u2014 no variance to rank",confidence:r.authors});let b={};for(let p of W){if(l[p.key])continue;if(r[p.key].level==="inconclusive"){l[p.key]={reason:r[p.key].reason,confidence:r[p.key]};continue}let C=a[p.key],w=Se(e,t,C.extract,C.density);if(w.length===0)continue;let K=c>0?w.slice(0,c):w,J={hot:0,warm:0,cool:0};for(let A of w)J[A.tier]++;b[p.key]={label:p.label,scoreFormula:p.scoreFormula,totalScore:w.reduce((A,be)=>A+be.score,0),tierCounts:J,totalEntries:w.length,showing:K.length,entries:K,confidence:r[p.key]}}return{rankings:b,skipped:l}}function B(){let e;try{e=E("git ls-files",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch{throw new Error("Not a git repository or git is not installed.")}let t=new Set;for(let n of e.toString().split(`
|
|
9
9
|
`)){let o=T(n.trim());o&&t.add(o)}return t}function se(e,t,n,o,i){let c=[];for(let[r,m]of e){if(m<o)continue;let[s,u]=r.split("\0"),f=t.get(s)??0,h=t.get(u)??0,g=Math.min(f,h),b=g>0?Math.round(m/g*1e3)/10:0,p=(n.get(s)??0)+(n.get(u)??0),C={file1:s,file2:u,cochanges:m,degree:b,totalComplexity:p,couplingScore:m,percentOfTotal:0,tier:"cool"},w=Math.max(f,h);m>0&&w>0&&m/w>=.9&&(C.lockstep=!0),i&&(i.has(s)||(C.file1Deleted=!0),i.has(u)||(C.file2Deleted=!0)),c.push(C)}c.sort((r,m)=>m.couplingScore-r.couplingScore);let a=c.reduce((r,m)=>r+m.couplingScore,0);if(a===0)return[];let l=c.map(r=>({...r,score:r.couplingScore}));U(l,a);for(let r=0;r<c.length;r++)c[r].percentOfTotal=l[r].percentOfTotal,c[r].tier=l[r].tier;return c}function ce(e){let t=new Map;for(let n of e){let o;try{o=Y(n,"utf-8")}catch{t.set(n,0);continue}let i=[],c=new Map,a=0;for(let s of o.split(`
|
|
10
10
|
`)){if(!s.trim())continue;let u=s.match(/^(\s+)/);if(!u){a=0;continue}let f=u[1];if(i.push(f),f.includes(" "))continue;let h=f.length,g=h-a;g>0&&c.set(g,(c.get(g)??0)+1),a=h}let l=4,r=0;for(let[s,u]of c)(u>r||u===r&&s<l)&&(r=u,l=s);let m=0;for(let s of i){let u=0;for(let f of s)f===" "?u+=1:f===" "&&(u+=1/l);u=Math.floor(u),u>m&&(m=u)}t.set(n,m)}return t}var ve=[{dir:".github",pattern:".github/**",comment:"GitHub Actions and workflows"},{dir:".circleci",pattern:".circleci/**",comment:"CircleCI configuration"},{dir:".husky",pattern:".husky/**",comment:"Git hooks"},{dir:".vscode",pattern:".vscode/**",comment:"VS Code settings"},{dir:".idea",pattern:".idea/**",comment:"JetBrains settings"},{dir:"scripts",pattern:"scripts/**",comment:"Build and utility scripts"},{dir:"docs",pattern:"docs/**",comment:"Documentation"},{dir:"docker",pattern:"docker/**",comment:"Docker configuration"},{dir:"fixtures",pattern:"fixtures/**",comment:"Test fixtures"},{dir:"vendor",pattern:"vendor/**",comment:"Vendored dependencies"}],Re=[{test:/\.generated\./,pattern:"*.generated.*",comment:"Generated code"},{test:/\.gen\.[^.]+$/,pattern:"*.gen.*",comment:"Generated code"},{test:/\.config\.\w/,pattern:"*.config.*",comment:"Configuration files"},{test:/(?:^|\/)\.gitlab-ci/,pattern:".gitlab-ci*",comment:"GitLab CI configuration"},{test:/^\.claude\/commands\//,pattern:".claude/commands/**",comment:"Claude Code slash commands (often generated from sources)"},{test:/^\.opencode\/commands\//,pattern:".opencode/commands/**",comment:"OpenCode slash commands (often generated from sources)"},{test:/^\.cursor\/rules\//,pattern:".cursor/rules/**",comment:"Cursor rules (often generated from sources)"}];function ae(){let e=B(),t=[],n=new Set;for(let o of e){let i=o.indexOf("/");i>0&&n.add(o.slice(0,i))}for(let o of ve)n.has(o.dir)&&t.push({pattern:o.pattern,comment:o.comment});for(let o of Re)for(let i of e)if(o.test.test(i)){t.push({pattern:o.pattern,comment:o.comment});break}return t}function le(e,t=H){let n=["# Generated by obscene init","# Edit this file to customize which files are excluded from analysis.","# Patterns use glob syntax (same as .gitignore).","# See: https://github.com/wbern/obscene#ignore-files",""];for(let o of t){n.push(`# ${o.title}`);for(let i of o.patterns)n.push(i.pattern);n.push("")}if(e.length>0){n.push("# Project-specific patterns");for(let o of e)n.push(`# ${o.comment}`),n.push(o.pattern);n.push("")}return n.join(`
|
|
11
|
-
`)}var Ee=10,X={inconclusive:0,weak:1,plausible:2,acceptable:3};function Oe(e){let t=Object.values(e).map(i=>i.confidence),n=t.length;if(n<2)return{level:"inconclusive",reason:`${n} input ranking \u2014 RRF requires \u2265 2 independent rankings.`,inputs:{metric:"inputRankings",value:n,thresholds:{weak:2,plausible:3,acceptable:4}},source:v.composite};let o="acceptable";for(let i of t)X[i.level]<X[o]&&(o=i.level);return{level:o,reason:`Composite inherits min-of-inputs across ${n} rankings (weakest: ${o.toUpperCase()}).`,inputs:{metric:"inputRankings",value:n,thresholds:{weak:2,plausible:3,acceptable:4}},source:v.composite}}function ue(e,t,n){let o=Object.keys(e).length,i=Oe(e),c=new Map;for(let s of Object.values(e))for(let u=0;u<s.entries.length;u++){let f=s.entries[u].file,h=1/(Ee+u+1),g=c.get(f);g?(g.score+=h,g.dims+=1):c.set(f,{score:h,dims:1})}let a=[];for(let[s,u]of c)a.push({file:s,score:Math.round(u.score*1e4)/1e4,percentOfTotal:0,tier:"cool",churn:t.get(s)??0,dimensionCount:u.dims});a.sort((s,u)=>u.score-s.score);let l=a.reduce((s,u)=>s+u.score,0);if(l===0)return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:0,tierCounts:{hot:0,warm:0,cool:0},totalDimensions:o,totalEntries:0,showing:0,entries:[],confidence:i};U(a,l);let r=n>0?a.slice(0,n):a,m={hot:0,warm:0,cool:0};for(let s of a)m[s.tier]++;return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:Math.round(l*1e4)/1e4,tierCounts:m,totalDimensions:o,totalEntries:a.length,showing:r.length,entries:r,confidence:i}}function pe(e){return I("commitsInWindow",e,R.coupling,v.coupling,t=>t==="inconclusive"?`${e} commits in window \u2014 need \u2265 ${R.coupling.weak} (matches code-maat's --min-revs default).`:`${e} commits in window (${t.toUpperCase()} sample size).`)}function me(e){try{let t=E(`git rev-list --count --since="${e} months ago" HEAD`,{stdio:["pipe","pipe","pipe"]});return parseInt(t.toString().trim(),10)||0}catch{throw new Error("Not a git repository or git is not installed.")}}import y from"picocolors";import
|
|
12
|
-
`)}function
|
|
13
|
-
`))o.push(y.dim(s));o.push(...F(t.tierCounts,t.showing,t.totalEntries)),o.push("");let r=i.map(s=>s.align==="left"?x(s.header,s.width):d(s.header,s.width)).join("");o.push(r);let m=i.reduce((s,u)=>s+u.width,0);o.push("\u2500".repeat(m));for(let s of t.entries){let f=i.map(h=>{let g=h.value(s);return h.align==="left"?x(g,h.width):d(g,h.width)}).join("");o.push(
|
|
14
|
-
`)}function he(e){let t=[],{tierCounts:n,totalScore:o,churnWindow:i,couplings:c}=e;t.push(`Coupling \u2014 ${i} churn window | Min shared: ${e.minCochanges} | Total score: ${o.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...F(n,e.showing,e.totalCouplings)),t.push(x("File 1",35)+x("File 2",35)+d("Shared",7)+d("Degree",8)+d("Cmplx",7)+d("Tier",12)),t.push("\u2500".repeat(104));let a=!1,l=!1;for(let r of c){(r.file1Deleted||r.file2Deleted)&&(a=!0),r.lockstep&&(l=!0);let m=r.file1Deleted?`\u2020 ${
|
|
15
|
-
`)}function ye(e){let t=[];t.push("\u2550".repeat(84)),t.push(`\u2605 ${e.label.toUpperCase()} \u2014 Total score: ${e.totalScore.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...F(e.tierCounts,e.showing,e.totalEntries)),t.push(""),t.push(x("File",50)+d("Score",9)+d("Churn",7)+d("Dims",6)+d("Tier",12)),t.push("\u2500".repeat(84));for(let n of e.entries){let o=x(
|
|
16
|
-
`)}var O=new Ae;O.name("obscene").description("Identify hotspot files \u2014 complex code that changes frequently").version("2.2.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
11
|
+
`)}var Ee=10,X={inconclusive:0,weak:1,plausible:2,acceptable:3};function Oe(e){let t=Object.values(e).map(i=>i.confidence),n=t.length;if(n<2)return{level:"inconclusive",reason:`${n} input ranking \u2014 RRF requires \u2265 2 independent rankings.`,inputs:{metric:"inputRankings",value:n,thresholds:{weak:2,plausible:3,acceptable:4}},source:v.composite};let o="acceptable";for(let i of t)X[i.level]<X[o]&&(o=i.level);return{level:o,reason:`Composite inherits min-of-inputs across ${n} rankings (weakest: ${o.toUpperCase()}).`,inputs:{metric:"inputRankings",value:n,thresholds:{weak:2,plausible:3,acceptable:4}},source:v.composite}}function ue(e,t,n){let o=Object.keys(e).length,i=Oe(e),c=new Map;for(let s of Object.values(e))for(let u=0;u<s.entries.length;u++){let f=s.entries[u].file,h=1/(Ee+u+1),g=c.get(f);g?(g.score+=h,g.dims+=1):c.set(f,{score:h,dims:1})}let a=[];for(let[s,u]of c)a.push({file:s,score:Math.round(u.score*1e4)/1e4,percentOfTotal:0,tier:"cool",churn:t.get(s)??0,dimensionCount:u.dims});a.sort((s,u)=>u.score-s.score);let l=a.reduce((s,u)=>s+u.score,0);if(l===0)return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:0,tierCounts:{hot:0,warm:0,cool:0},totalDimensions:o,totalEntries:0,showing:0,entries:[],confidence:i};U(a,l);let r=n>0?a.slice(0,n):a,m={hot:0,warm:0,cool:0};for(let s of a)m[s.tier]++;return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:Math.round(l*1e4)/1e4,tierCounts:m,totalDimensions:o,totalEntries:a.length,showing:r.length,entries:r,confidence:i}}function pe(e){return I("commitsInWindow",e,R.coupling,v.coupling,t=>t==="inconclusive"?`${e} commits in window \u2014 need \u2265 ${R.coupling.weak} (matches code-maat's --min-revs default).`:`${e} commits in window (${t.toUpperCase()} sample size).`)}function me(e){try{let t=E(`git rev-list --count --since="${e} months ago" HEAD`,{stdio:["pipe","pipe","pipe"]});return parseInt(t.toString().trim(),10)||0}catch{throw new Error("Not a git repository or git is not installed.")}}import y from"picocolors";import k from"picocolors";var Ie=/\x1b\[[0-9;]*m/g;function Te(e){return e>=11904&&e<=12543||e>=12800&&e<=13311||e>=13312&&e<=40959||e>=44032&&e<=55215||e>=63744&&e<=64255||e>=65281&&e<=65376||e>=65504&&e<=65510||e>=9728&&e<=9983||e>=127744&&e<=129791||e>=131072&&e<=195103}function fe(e){let t=e.replace(Ie,""),n=0;for(let o of t){let i=o.codePointAt(0);i===65038||i===65039||(n+=Te(i)?2:1)}return n}function x(e,t){let n=fe(e);return n>=t?e:e+" ".repeat(t-n)}function d(e,t){let n=fe(e);return n>=t?e:" ".repeat(t-n)+e}function S(e,t){if(t<=0)return"";if(e.length<=t)return e;if(t===1)return"\u2026";let n=t-1,o=Math.ceil(n*.6),i=n-o;return`${e.slice(0,i)}\u2026${e.slice(e.length-o)}`}function M(e){return e==="hot"?k.red("\u{1F525} HOT "):e==="warm"?k.yellow("\u2600\uFE0F WARM"):k.blue("\u{1F9CA} COOL")}function D(e,t){return e==="hot"?k.red(t):e==="warm"?k.yellow(t):k.blue(t)}function F(e,t,n){let o=[];return o.push(`Tiers: ${k.red(`${e.hot} HOT`)}, ${k.yellow(`${e.warm} WARM`)}, ${k.blue(`${e.cool} COOL`)}`),o.push(`Showing: ${t} of ${n}`),o}var $e={inconclusive:y.gray,weak:y.yellow,plausible:y.cyan,acceptable:y.green};function G(e){let t=$e[e.level];return[t(`Confidence: ${e.level.toUpperCase()} \u2014 ${e.reason}`)]}var Me=Object.fromEntries(W.map(e=>[e.key,e.label]));function ge(e){let t=[],{summary:n,files:o}=e;t.push(`Complexity Report \u2014 ${n.fileCount} files, ${n.totalComplexity} total complexity`),t.push(`Showing: ${n.showing} | Avg complexity/file: ${n.avgComplexityPerFile}`),t.push(""),t.push(x("File",60)+d("Code",8)+d("Complexity",12)+d("Density",9)+d("Comments",10)),t.push("\u2500".repeat(99));for(let i of o)t.push(x(S(i.file,58),60)+d(String(i.code),8)+d(String(i.complexity),12)+d(i.complexityDensity.toFixed(2),9)+d(String(i.comments),10));return t.push(""),t.push(y.dim("Complexity=cyclomatic branch/loop count | Density=complexity/code | Comments=comment lines")),t.push(y.dim("High complexity is expected for parsers, state machines, and business logic. Compare density across files, not raw values.")),t.push(y.dim("Docs: https://github.com/wbern/obscene#metrics")),t.join(`
|
|
12
|
+
`)}function De(e){let t=[{header:"File",width:50,align:"left",value:i=>S(i.file,48)},{header:"Score",width:8,align:"right",value:i=>i.score.toLocaleString()},{header:"%",width:7,align:"right",value:i=>i.percentOfTotal.toFixed(1)},{header:"Churn",width:7,align:"right",value:i=>String(i.churn)}],n={complexity:[{header:"Cmplx",width:7,align:"right",value:i=>String(i.metricValue)},{header:"Dens",width:7,align:"right",value:i=>(i.metricDensity??0).toFixed(2)}],nesting:[{header:"Nest",width:6,align:"right",value:i=>String(i.metricValue)}],defects:[{header:"Fixes",width:6,align:"right",value:i=>String(i.metricValue)},{header:"FxDns",width:7,align:"right",value:i=>(i.metricDensity??0).toFixed(4)}],authors:[{header:"Auth",width:6,align:"right",value:i=>String(i.metricValue)}]},o={header:"Tier",width:12,align:"right",value:i=>M(i.tier)};return[...t,...n[e]??[],o]}var Fe={complexity:"\u{1F9EC}",nesting:"\u{1F4CF}",defects:"\u{1F527}",authors:"\u{1F465}"};function Le(e,t,n){let o=[],i=De(e),c=Fe[e],a=c?`${c} `:"",l=t.label.toUpperCase().replace("CHURN","\u{1F504} CHURN");if(o.push(`${a}${l} \u2014 Total score: ${t.totalScore.toLocaleString()}`),o.push(...G(t.confidence)),n)for(let s of n.split(`
|
|
13
|
+
`))o.push(y.dim(s));o.push(...F(t.tierCounts,t.showing,t.totalEntries)),o.push("");let r=i.map(s=>s.align==="left"?x(s.header,s.width):d(s.header,s.width)).join("");o.push(r);let m=i.reduce((s,u)=>s+u.width,0);o.push("\u2500".repeat(m));for(let s of t.entries){let f=i.map(h=>{let g=h.value(s);return h.align==="left"?x(g,h.width):d(g,h.width)}).join("");o.push(D(s.tier,f))}return o}function de(e){let t=[],{churnWindow:n,rankings:o,corpus:i}=e;t.push(`Hotspots \u2014 ${n} churn window`),i&&i.fileCount>0&&i.totalComplexity===0&&(t.push(""),t.push(y.yellow("Note: no measurable code complexity detected across this corpus (cyclomatic = 0).")),t.push(y.yellow("Rankings reflect size and churn only \u2014 HOT/WARM/COOL are relative groupings, not risk labels."))),t.push("");let c=Object.keys(o);for(let l=0;l<c.length;l++){let r=c[l];t.push(...Le(r,o[r],e.guide[r])),l<c.length-1&&(t.push(""),t.push("\xB7 \xB7 \xB7"),t.push(""))}if(e.skipped)for(let[l,r]of Object.entries(e.skipped)){t.push("");let m=Me[l]??`${l.charAt(0).toUpperCase()+l.slice(1)} \xD7 Churn`;t.push(`${m} \u2014 skipped (${r.reason})`),r.suggestion&&t.push(` ${r.suggestion}`)}t.push(""),t.push(y.dim("Score=metric\xD7churn | Tiers are relative to THIS codebase, not absolute quality grades."));let a=i!==void 0&&i.fileCount>0&&i.totalComplexity===0;return t.push(y.dim(a?"High scores flag files that change often and are sizable \u2014 neither is bad in itself.":"High scores flag review candidates, not bad code \u2014 stable complex files (parsers, engines) score high naturally.")),t.push(y.dim("Docs: https://github.com/wbern/obscene#metrics")),t.join(`
|
|
14
|
+
`)}function he(e){let t=[],{tierCounts:n,totalScore:o,churnWindow:i,couplings:c}=e;t.push(`Coupling \u2014 ${i} churn window | Min shared: ${e.minCochanges} | Total score: ${o.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...F(n,e.showing,e.totalCouplings)),t.push(x("File 1",35)+x("File 2",35)+d("Shared",7)+d("Degree",8)+d("Cmplx",7)+d("Tier",12)),t.push("\u2500".repeat(104));let a=!1,l=!1;for(let r of c){(r.file1Deleted||r.file2Deleted)&&(a=!0),r.lockstep&&(l=!0);let m=r.file1Deleted?`\u2020 ${S(r.file1,31)}`:S(r.file1,33),s=r.file2Deleted?`\u2020 ${S(r.file2,31)}`:S(r.file2,33),u=r.lockstep?`${r.degree.toFixed(1)}\u21C4`:`${r.degree.toFixed(1)}%`,f=x(m,35)+x(s,35)+d(String(r.cochanges),7)+d(u,8)+d(String(r.totalComplexity),7)+d(M(r.tier),12);t.push(D(r.tier,f))}return t.push(""),t.push(y.dim("Shared=co-changed commits | Degree=shared/min(churn)\xD7100 | Cmplx=sum of both files")),a&&t.push(y.dim("\u2020 = file no longer present at HEAD (deleted or renamed)")),l&&t.push(y.dim("\u21C4 = lockstep pair (both files only ever changed together \u2014 signal is real but uninformative)")),t.push(y.dim("Tiers are relative to THIS codebase, not absolute quality grades. High coupling may be intentional and fine.")),t.push(y.dim("Same-directory pairs excluded. Commits touching >20 files skipped. Only cross-directory dependencies shown.")),t.push(y.dim("Docs: https://github.com/wbern/obscene#metrics")),t.join(`
|
|
15
|
+
`)}function ye(e){let t=[];t.push("\u2550".repeat(84)),t.push(`\u2605 ${e.label.toUpperCase()} \u2014 Total score: ${e.totalScore.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...F(e.tierCounts,e.showing,e.totalEntries)),t.push(""),t.push(x("File",50)+d("Score",9)+d("Churn",7)+d("Dims",6)+d("Tier",12)),t.push("\u2500".repeat(84));for(let n of e.entries){let o=x(S(n.file,48),50)+d(n.score.toFixed(4),9)+d(String(n.churn),7)+d(`${n.dimensionCount}/${e.totalDimensions}`,6)+d(M(n.tier),12);t.push(D(n.tier,o))}return t.join(`
|
|
16
|
+
`)}var O=new Ae;O.name("obscene").description("Identify hotspot files \u2014 complex code that changes frequently").version("2.2.2");var _e={complexity:"Cyclomatic complexity (branch/loop count). NOT a quality judgment \u2014 a 500-line parser will naturally score high. Compare density, not raw values.",complexityDensity:"Complexity per line of code. Normalizes for file size. >0.25 suggests dense logic worth reviewing; <0.10 is typical for straightforward code.",comments:"Comment line count. Low comments in high-density files may indicate under-documented logic. High comments alone is not a problem."},je={rankings:"Four independent ranking tables, each scoring files by a different metric \xD7 churn. A file may rank high in one dimension but not others.",complexity:`complexity \xD7 churn. Complex code that changes often poses maintenance risk.
|
|
17
|
+
Metric concept: McCabe cyclomatic complexity (1976) via scc \xB7 Strength: objective, language-agnostic \xB7 Limit: parsers and state machines score high naturally`,nesting:`maxNesting \xD7 churn. Deeply nested code that changes often is harder to reason about.
|
|
18
|
+
Metric concept: cognitive complexity research (SonarSource, G. Ann Campbell 2018) \xB7 Strength: catches hard-to-follow control flow \xB7 Limit: some patterns (error chains, config) legitimately nest deep`,defects:`fixes \xD7 churn. Count of fix: commits touching the file \xD7 churn. High values can mean latent fragility, but they also flag features that got debugged thoroughly \u2014 read the fix-commit history before concluding which.
|
|
19
|
+
Metric concept: change-history metrics (Moser, Pedrycz & Succi 2008) via conventional commits (fix: prefix) \xB7 Strength: direct fix-history signal \xB7 Limit: counts fix activity, not defects per se; requires consistent fix: convention`,authors:`authors \xD7 churn. Files touched by many authors and changing often may lack clear ownership.
|
|
20
|
+
Metric concept: code ownership research (Bird et al. 2011, Microsoft) \xB7 Strength: flags diffuse ownership risk \xB7 Limit: doesn't measure expertise depth, bot authors filtered automatically`,composite:`Combined ranking using Reciprocal Rank Fusion (RRF) across all dimensions. Files appearing near the top of multiple rankings score highest.
|
|
21
|
+
Metric concept: RRF (Cormack et al. 2009) \xB7 Strength: robust to outliers, no normalization needed \xB7 Limit: equal weight across all dimensions`,tier:"Relative ranking within THIS codebase (top 50% = hot, next 30% = warm, bottom 20% = cool). NOT an absolute quality grade \u2014 a hot file is under heavy load, not necessarily broken.",corpus:"Aggregate stats for the analyzed file set (post-exclude \u2014 files filtered by .obsignore or --exclude are not counted). When totalComplexity is 0, the rankings reflect size and churn only; HOT/WARM/COOL become relative groupings rather than risk labels.",confidence:"Epistemic stamp on each ranking \u2014 INCONCLUSIVE / WEAK / PLAUSIBLE / ACCEPTABLE. These are engineering-judgment sample-size tiers, with the weak floor for defects matching code-maat's --min-revs default of 5. ACCEPTABLE is the ceiling \u2014 the tool never claims certainty about code quality, only that the sample supports the ranking. INCONCLUSIVE rankings are surfaced under skipped rather than ranked."},He={cochanges:"Times both files appeared in the same commit. Higher values suggest a dependency between the files. Same-directory pairs are excluded \u2014 only cross-directory pairs are shown.",degree:"Percentage: shared commits / min(churn of file1, file2) \xD7 100. Shows how tightly coupled the pair is relative to their individual change rates. 100% means every change to the less-active file also touched the other.",totalComplexity:"Sum of both files' cyclomatic complexity. Highlights coupled pairs where the involved code is also complex \u2014 hidden dependency + high complexity compounds maintenance risk.",tier:"Relative ranking within THIS codebase's coupling pairs (top 50% = hot, next 30% = warm, bottom 20% = cool). NOT an absolute quality grade. 'hot' means this pair co-changes more than most \u2014 it may be intentional and fine.",deleted:"file1Deleted / file2Deleted are set when the file is no longer present at HEAD (deleted or renamed away). The coupling signal is historical \u2014 the pair is not actionable in the current tree.",lockstep:"Set when shared commits / max(churn) \u2265 0.9 \u2014 both files almost always change together over the window. Typical of generator/mirror pairs (README \u2194 src/README, *.pb.go \u2194 *.proto). The coupling signal is real but uninformative; treat the pair as a single unit from git's perspective.",confidence:"Epistemic stamp on the coupling table \u2014 INCONCLUSIVE / WEAK / PLAUSIBLE / ACCEPTABLE. Tied to the number of commits in the analysis window. The weak floor of 5 matches code-maat's --min-revs default (Adam Tornhill); higher tiers are engineering judgment. ACCEPTABLE means the sample supports the ranking; it never asserts the couplings themselves are bad."};function z(e){return e.option("--top <n>","limit to top N entries (0 = all)","20").option("--format <type>","output format: json | table","json").option("--exclude <patterns...>","additional file patterns to exclude (also reads .obsignore / .obsceneignore)")}z(O.command("report").description("per-file complexity data")).action(e=>{try{Pe(e)}catch(t){N(t)}});z(O.command("hotspots",{isDefault:!0}).description("churn \xD7 complexity hotspot analysis (default)")).option("--months <n>","churn window in months","3").action(e=>{try{Ue(e)}catch(t){N(t)}});z(O.command("coupling").description("temporal coupling \u2014 files that change together across directories")).option("--months <n>","churn window in months","3").option("--min-cochanges <n>","minimum shared commits to include","2").action(e=>{try{We(e)}catch(t){N(t)}});O.command("init").description("generate a starter .obsignore based on project structure").action(()=>{try{Be()}catch(e){N(e)}});function V(e){return[...Q(),...e??[]]}function q(){!L(".obsignore")&&!L(".obsceneignore")&&process.stderr.write("hint: no .obsignore found \u2014 run `obscene init` to generate one with recommended exclusions\n")}function Pe(e){q();let t=parseInt(e.top,10),n=V(e.exclude),o=$(n),i=o.reduce((l,r)=>({totalComplexity:l.totalComplexity+r.complexity,totalCode:l.totalCode+r.code,totalLines:l.totalLines+r.lines}),{totalComplexity:0,totalCode:0,totalLines:0}),c=t>0?o.slice(0,t):o,a={generated:new Date().toISOString(),guide:_e,summary:{...i,fileCount:o.length,avgComplexityPerFile:o.length>0?Math.round(i.totalComplexity/o.length*10)/10:0,showing:c.length},files:c};e.format==="table"?process.stdout.write(`${ge(a)}
|
|
22
22
|
`):process.stdout.write(`${JSON.stringify(a,null,2)}
|
|
23
23
|
`)}function Ue(e){q();let t=parseInt(e.top,10),n=parseInt(e.months,10),o=V(e.exclude),i=$(o),c=P(n),a=ne(n),l=oe(n),r=ce(i.map(g=>g.file)),{rankings:m,skipped:s}=re(i,c,a,r,l,t),u=ue(m,c,t),f=0;for(let g of i)f+=g.complexity;let h={generated:new Date().toISOString(),guide:je,churnWindow:`${n} months`,rankings:m,skipped:Object.keys(s).length>0?s:void 0,composite:u,corpus:{fileCount:i.length,totalComplexity:f}};e.format==="table"?(process.stdout.write(`${de(h)}
|
|
24
24
|
`),u.entries.length>0&&process.stdout.write(`
|
|
@@ -26,8 +26,8 @@ ${ye(u)}
|
|
|
26
26
|
`)):process.stdout.write(`${JSON.stringify(h,null,2)}
|
|
27
27
|
`)}function We(e){q();let t=parseInt(e.top,10),n=parseInt(e.months,10),o=parseInt(e.minCochanges,10),i=V(e.exclude),c=$(i),a=P(n),l=ie(n,i),r=new Map;for(let b of c)r.set(b.file,b.complexity);let m=B(),s=se(l,a,r,o,m),u=t>0?s.slice(0,t):s,f={hot:0,warm:0,cool:0};for(let b of s)f[b.tier]++;let h=s.reduce((b,p)=>b+p.couplingScore,0),g={generated:new Date().toISOString(),guide:He,churnWindow:`${n} months`,minCochanges:o,totalScore:h,tierCounts:f,totalCouplings:s.length,showing:u.length,couplings:u,confidence:pe(me(n))};e.format==="table"?process.stdout.write(`${he(g)}
|
|
28
28
|
`):process.stdout.write(`${JSON.stringify(g,null,2)}
|
|
29
|
-
`)}function Be(){if(
|
|
29
|
+
`)}function Be(){if(L(".obsignore"))throw new Error(".obsignore already exists. Remove it first to regenerate.");if(L(".obsceneignore"))throw new Error(".obsceneignore already exists. Remove it first to regenerate.");let e=ae(),t=le(e);Ne(".obsignore",t);let n=H.reduce((o,i)=>o+i.patterns.length,0);if(process.stderr.write(`Created .obsignore with ${n} universal exclusions`),e.length>0){process.stderr.write(` + ${e.length} detected patterns:
|
|
30
30
|
`);for(let o of e)process.stderr.write(` ${o.pattern.padEnd(20)} ${o.comment}
|
|
31
31
|
`)}else process.stderr.write(` (no project-specific patterns detected)
|
|
32
|
-
`)}function
|
|
32
|
+
`)}function N(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: ${t}
|
|
33
33
|
`),process.exit(1)}O.parse();
|