@wbern/obscene
Advanced tools
+43
-34
| #!/usr/bin/env node | ||
| import{execSync as Tt,spawnSync as Pe}from"child_process";import{existsSync as z,realpathSync as Be,writeFileSync as It}from"fs";import{relative as Ft}from"path";import{Command as Nt}from"commander";import{execSync as $,spawnSync as Y}from"child_process";import{existsSync as Ve,mkdtempSync as qe,readFileSync as ge,rmSync as de}from"fs";import{tmpdir as Je}from"os";import{join as Q}from"path";var Ke=[".obsignore",".obsceneignore"];function he(){for(let e of Ke)try{return ge(e,"utf-8").split(` | ||
| `).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 Z=[{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"}]}],Ye=.5,Xe=.8,J=5,K=3,N={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}},T={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 A(e,t,n,o,i){let s;return t<n.weak?s="inconclusive":t<n.plausible?s="weak":t<n.acceptable?s="plausible":s="acceptable",{level:s,reason:i(s),inputs:{metric:e,value:t,thresholds:n},source:o}}function ye(e,t){return t.some(n=>n.test(e))}function we(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\u27E8GLOBSTAR\u27E9").replace(/\*/g,"[^/]*").replace(/⟨GLOBSTAR⟩/g,".*").replace(/\?/g,".");return new RegExp(t)}function D(e){let t=e.replaceAll("\\","/");return t.startsWith("./")?t.slice(2):t}function H(e=[],t){let n=e.map(we),o;try{o=$("scc --by-file --format json --no-cocomo --no-gen",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch(r){throw r&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"?new Error("scc not found. Install it: https://github.com/boyter/scc#install"):r}let i=JSON.parse(o.toString()),s=[];for(let r of i)for(let l of r.Files){let u=D(l.Location);ye(u,n)||s.push({file:u,code:l.Code,lines:l.Lines,complexity:l.Complexity,comments:l.Comment,complexityDensity:l.Code>0?Math.round(l.Complexity/l.Code*100)/100:0})}return s.sort((r,l)=>l.complexity-r.complexity)}function be(e,t,n){let o;try{o=$(e,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:n})}catch{throw new Error(t)}let i=new Map;for(let s of o.toString().split(` | ||
| `)){let r=D(s.trim());r&&i.set(r,(i.get(r)??0)+1)}return i}function P(e,t){return be(`git log --since="${e} months ago" --format="" --name-only`,"Not a git repository or git is not installed.",t)}function Qe(e,t){let n;try{n=$(`git log --since="${e} months ago" --numstat --format=`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch{throw new Error("Not a git repository or git is not installed.")}let o=new Map;for(let i of n.toString().split(` | ||
| `)){if(!i)continue;let s=i.split(" ");if(s.length<3)continue;let r=s[0],l=s[1];if(r==="-"||l==="-")continue;let u=D(s[2].trim());if(!u)continue;let c=parseInt(r,10)+parseInt(l,10);Number.isFinite(c)&&o.set(u,(o.get(u)??0)+c)}return o}var X=3;function Ze(e,t){let n;try{n=$("git log --format=%ct --name-only --no-merges",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch{throw new Error("Not a git repository or git is not installed.")}let o=e*ce,i=Math.floor(Date.now()/1e3)-o*86400,s=o*X,r=new Map,l=new Map,u=null;for(let p of n.toString().split(` | ||
| `)){if(!p)continue;if(/^\d+$/.test(p)){u=parseInt(p,10);continue}if(u===null)continue;let a=D(p.trim());if(a)if(u>=i){let f=l.get(a);(f===void 0||u<f)&&l.set(a,u)}else{let f=r.get(a);(f===void 0||u>f)&&r.set(a,u)}}let c=new Map;for(let[p,a]of l){let f=r.get(p);if(f===void 0)continue;let g=Math.floor((a-f)/86400);g<s||c.set(p,{dormancyDays:g,dormancyMultiple:Math.round(g/o*10)/10,lastTouchedBeforeWindow:f,firstTouchedInWindow:a})}return c}function et(e,t){return be(`git log --since="${e} months ago" --grep="^fix" --format="" --name-only`,"Not a git repository or git is not installed.",t)}function tt(e){let t=new Set,n=[];for(let o of e.split(" ")){let i=o.trim();if(!i)continue;let s=i.match(/^(.+?)\s*<[^>]+>\s*$/),r=(s?s[1]:i).trim();!r||r.endsWith("[bot]")||t.has(r)||(t.add(r),n.push(r))}return n}function nt(e,t){let n;try{n=$(`git log --since="${e} months ago" --format="COMMIT_SEP%n%aN%x09%(trailers:key=Co-authored-by,valueonly,separator=%x09)" --name-only`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch{throw new Error("Not a git repository or git is not installed.")}let o=new Map,i=n.toString().split(`COMMIT_SEP | ||
| import{execSync as At,spawnSync as ze}from"child_process";import{existsSync as z,realpathSync as Ve,writeFileSync as Lt}from"fs";import{relative as _t}from"path";import{Command as Pt}from"commander";import{execSync as E,spawnSync as Y}from"child_process";import{existsSync as Xe,mkdtempSync as Qe,readFileSync as he,rmSync as me}from"fs";import{tmpdir as Ze}from"os";import{join as Q}from"path";var et=[".obsignore",".obsceneignore"];function ye(){for(let e of et)try{return he(e,"utf-8").split(` | ||
| `).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 Z=[{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"}]}],tt=.5,nt=.8,J=5,K=3,H={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}},T={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 A(e,t,n,o,i){let s;return t<n.weak?s="inconclusive":t<n.plausible?s="weak":t<n.acceptable?s="plausible":s="acceptable",{level:s,reason:i(s),inputs:{metric:e,value:t,thresholds:n},source:o}}function we(e,t){return t.some(n=>n.test(e))}function Ce(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\u27E8GLOBSTAR\u27E9").replace(/\*/g,"[^/]*").replace(/⟨GLOBSTAR⟩/g,".*").replace(/\?/g,".");return new RegExp(t)}function D(e){let t=e.replaceAll("\\","/");return t.startsWith("./")?t.slice(2):t}function N(e=[],t){let n=e.map(Ce),o;try{o=E("scc --by-file --format json --no-cocomo --no-gen",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch(r){throw r&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"?new Error("scc not found. Install it: https://github.com/boyter/scc#install"):r}let i=JSON.parse(o.toString()),s=[];for(let r of i)for(let l of r.Files){let u=D(l.Location);we(u,n)||s.push({file:u,code:l.Code,lines:l.Lines,complexity:l.Complexity,comments:l.Comment,complexityDensity:l.Code>0?Math.round(l.Complexity/l.Code*100)/100:0})}return s.sort((r,l)=>l.complexity-r.complexity)}function be(e,t,n){let o;try{o=E(e,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:n})}catch{throw new Error(t)}let i=new Map;for(let s of o.toString().split(` | ||
| `)){let r=D(s.trim());r&&i.set(r,(i.get(r)??0)+1)}return i}function W(e,t){return be(`git log --since="${e} months ago" --format="" --name-only`,"Not a git repository or git is not installed.",t)}function ot(e,t){let n;try{n=E(`git log --since="${e} months ago" --numstat --format=`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch{throw new Error("Not a git repository or git is not installed.")}let o=new Map;for(let i of n.toString().split(` | ||
| `)){if(!i)continue;let s=i.split(" ");if(s.length<3)continue;let r=s[0],l=s[1];if(r==="-"||l==="-")continue;let u=D(s[2].trim());if(!u)continue;let c=parseInt(r,10)+parseInt(l,10);Number.isFinite(c)&&o.set(u,(o.get(u)??0)+c)}return o}var X=3;function it(e,t){let n;try{n=E("git log --format=%ct --name-only --no-merges",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch{throw new Error("Not a git repository or git is not installed.")}let o=e*ce,i=Math.floor(Date.now()/1e3)-o*86400,s=o*X,r=new Map,l=new Map,u=null;for(let p of n.toString().split(` | ||
| `)){if(!p)continue;if(/^\d+$/.test(p)){u=parseInt(p,10);continue}if(u===null)continue;let a=D(p.trim());if(a)if(u>=i){let f=l.get(a);(f===void 0||u<f)&&l.set(a,u)}else{let f=r.get(a);(f===void 0||u>f)&&r.set(a,u)}}let c=new Map;for(let[p,a]of l){let f=r.get(p);if(f===void 0)continue;let g=Math.floor((a-f)/86400);g<s||c.set(p,{dormancyDays:g,dormancyMultiple:Math.round(g/o*10)/10,lastTouchedBeforeWindow:f,firstTouchedInWindow:a})}return c}function rt(e,t){return be(`git log --since="${e} months ago" --grep="^fix" --format="" --name-only`,"Not a git repository or git is not installed.",t)}function st(e){let t=new Set,n=[];for(let o of e.split(" ")){let i=o.trim();if(!i)continue;let s=i.match(/^(.+?)\s*<[^>]+>\s*$/),r=(s?s[1]:i).trim();!r||r.endsWith("[bot]")||t.has(r)||(t.add(r),n.push(r))}return n}function at(e,t){let n;try{n=E(`git log --since="${e} months ago" --format="COMMIT_SEP%n%aN%x09%(trailers:key=Co-authored-by,valueonly,separator=%x09)" --name-only`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:t})}catch{throw new Error("Not a git repository or git is not installed.")}let o=new Map,i=n.toString().split(`COMMIT_SEP | ||
| `);for(let s of i){if(!s.trim())continue;let r=s.split(` | ||
| `),l=tt(r[0]);if(l.length!==0)for(let u=1;u<r.length;u++){let c=D(r[u].trim());if(!c)continue;let p=o.get(c);p||(p=new Map,o.set(c,p));for(let a of l)p.set(a,(p.get(a)??0)+1)}}return o}var ot=20;function ee(e,t=[],n){let o=t.map(we),i;try{i=$(`git log --since="${e} months ago" --format="COMMIT_SEP%n" --name-only`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:n})}catch{throw new Error("Not a git repository or git is not installed.")}let s=new Map,r=i.toString().split(`COMMIT_SEP | ||
| `),l=st(r[0]);if(l.length!==0)for(let u=1;u<r.length;u++){let c=D(r[u].trim());if(!c)continue;let p=o.get(c);p||(p=new Map,o.set(c,p));for(let a of l)p.set(a,(p.get(a)??0)+1)}}return o}var ct=20;function ee(e,t=[],n){let o=t.map(Ce),i;try{i=E(`git log --since="${e} months ago" --format="COMMIT_SEP%n" --name-only`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:n})}catch{throw new Error("Not a git repository or git is not installed.")}let s=new Map,r=i.toString().split(`COMMIT_SEP | ||
| `);for(let l of r){if(!l.trim())continue;let u=new Set;for(let p of l.split(` | ||
| `)){let a=D(p.trim());a&&(ye(a,o)||u.add(a))}let c=[...u];if(!(c.length<2||c.length>ot))for(let p=0;p<c.length;p++)for(let a=p+1;a<c.length;a++){let[f,g]=c[p]<c[a]?[c[p],c[a]]:[c[a],c[p]],y=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"",k=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";if(y===k)continue;let m=`${f}\0${g}`;s.set(m,(s.get(m)??0)+1)}}return s}var te=5,ne=70,it=5;function Ce(e,t,n,o={}){let i=o.minCochanges??te,s=o.minDegree??ne,r=o.maxResults??it,l=new Map;for(let[u,c]of e){if(c<i)continue;let[p,a]=u.split("\0"),f=n.has(p),g=n.has(a);if(f===g)continue;let y=t.get(p)??0,k=t.get(a)??0,m=Math.min(y,k);if(m===0)continue;let d=Math.max(y,k);if(c/d>=.9)continue;let x=Math.round(c/m*1e3)/10;if(x<s)continue;let h=f?p:a,C=f?a:p,S=l.get(h);(!S||x>S.degree)&&l.set(h,{file:h,partner:C,cochanges:c,degree:x})}return[...l.values()].sort((u,c)=>c.degree-u.degree||c.cochanges-u.cochanges||u.file.localeCompare(c.file)).slice(0,r)}function B(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<=Ye?o.tier="hot":i<=Xe?o.tier="warm":o.tier="cool"}}var oe=[{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 rt(e,t,n,o){let i=e.map(r=>{let l=t.get(r.file)??0,u=n(r);return{file:r.file,score:u*l,percentOfTotal:0,tier:"cool",churn:l,metricValue:u,metricDensity:o?o(r):void 0}}).filter(r=>r.score>0).sort((r,l)=>l.score-r.score),s=i.reduce((r,l)=>r+l.score,0);return s===0?[]:(B(i,s),i)}var st=.05,at=2;function ct(e){if(!e||e.size===0)return null;let t=0;for(let i of e.values())t+=i;if(t<at)return null;let n=t*st,o=0;for(let i of e.values())i<n&&o++;return o}function lt(e,t,n,o,i,s,r){let l={complexity:{extract:d=>d.complexity,density:d=>d.complexityDensity},nesting:{extract:d=>d.complexity===0?0:o.get(d.file)??0},defects:{extract:d=>n.get(d.file)??0,density:d=>{let x=n.get(d.file)??0;return d.code>0?Math.round(x/d.code*1e4)/1e4:0}},authors:{extract:d=>i.get(d.file)??0}},u={},c={},p=0;for(let d of e)d.complexity>0&&p++;c.complexity=A("filesWithComplexity",p,N.complexity,T.complexity,d=>d==="inconclusive"?`${p} files with measurable complexity \u2014 not enough to rank.`:`${p} files with measurable complexity (${d.toUpperCase()} sample size).`);let a=0;for(let d of e)d.complexity>0&&(o.get(d.file)??0)>=3&&a++;c.nesting=A("filesWithNesting>=3",a,N.nesting,T.nesting,d=>d==="inconclusive"?`${a} files with nesting depth \u2265 3 \u2014 not enough to rank.`:`${a} files with nesting depth \u2265 3 (${d.toUpperCase()} sample size).`);let f=[...n.values()].reduce((d,x)=>d+x,0),g=n.size,y=f<J||g<K;c.defects=A("fixCommits",f,N.defects,T.defects,d=>d==="inconclusive"||y?`${f} fix: commits across ${g} files \u2014 need \u2265 ${J} commits across \u2265 ${K} files (matches code-maat's --min-revs default).`:`${f} fix: commits across ${g} files (${d.toUpperCase()} sample size).`),y&&(c.defects={...c.defects,level:"inconclusive"},u.defects={reason:`insufficient data (${f} fix: commits across ${g} files, need ${J}+ commits across ${K}+ files)`,suggestion:"Adopt conventional commits with fix: prefix. See conventionalcommits.org",confidence:c.defects});let k=0;for(let d of i.values())d>k&&(k=d);c.authors=A("maxAuthors",k,N.authors,T.authors,d=>d==="inconclusive"?`${k} distinct authors on the most-touched file \u2014 not enough to rank ownership.`:`${k} distinct authors on the most-touched file (${d.toUpperCase()} sample size).`),k<=1&&(c.authors={...c.authors,level:"inconclusive"},u.authors={reason:"all files have the same author count \u2014 no variance to rank",confidence:c.authors});let m={};for(let d of oe){if(u[d.key])continue;if(c[d.key].level==="inconclusive"){u[d.key]={reason:c[d.key].reason,confidence:c[d.key]};continue}let x=l[d.key],h=rt(e,t,x.extract,x.density);if(h.length===0)continue;if(d.key==="authors"&&r)for(let R of h)R.minorAuthors=ct(r.get(R.file));let C=s>0?h.slice(0,s):h,S={hot:0,warm:0,cool:0};for(let R of h)S[R.tier]++;m[d.key]={label:d.label,scoreFormula:d.scoreFormula,totalScore:h.reduce((R,F)=>R+F.score,0),tierCounts:S,tiers:S,totalEntries:h.length,showing:C.length,entries:C,confidence:c[d.key]}}return{rankings:m,skipped:u}}function ie(e){let t;try{t=$(`git diff --name-only ${e}...HEAD`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch{throw new Error(`Failed to compute diff against base ref '${e}'. Verify the ref exists (e.g. 'git rev-parse --verify <ref>').`)}let n=new Set;for(let o of t.toString().split(` | ||
| `)){let i=D(o.trim());i&&n.add(i)}return n}var ut=["main","master"];function xe(){for(let e of ut)try{return $(`git rev-parse --verify ${e}`,{stdio:["pipe","pipe","pipe"]}),e}catch{}}function ke(){try{return $("git rev-parse --show-toplevel",{stdio:["pipe","pipe","pipe"]}).toString().trim()||void 0}catch{return}}function pt(e,t){let n=new Map;if(t.length===0)return n;let o=t.filter(r=>Ve(Q(e,r)));if(o.length===0)return n;let i=Y("scc",["--by-file","--format","json","--no-cocomo","--no-gen",...o],{cwd:e,maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]});if(i.error&&"code"in i.error&&i.error.code==="ENOENT")throw new Error("scc not found. Install it: https://github.com/boyter/scc#install");if(i.error)throw new Error(`scc spawn failed: ${i.error.message}`);if(i.status!==0)throw new Error(`scc failed on base worktree: ${i.stderr?.toString().trim()||"unknown error"}`);let s=JSON.parse(i.stdout.toString());for(let r of s)for(let l of r.Files){let u=D(l.Location);n.set(u,{file:u,code:l.Code,lines:l.Lines,complexity:l.Complexity,comments:l.Comment,complexityDensity:l.Code>0?Math.round(l.Complexity/l.Code*100)/100:0})}return n}function j(e,t){let n=qe(Q(Je(),"obscene-base-")),o={...process.env};for(let s of Object.keys(o))s.startsWith("GIT_")&&delete o[s];let i=Y("git",["worktree","add","--detach",n,e],{stdio:["pipe","pipe","pipe"],env:o});if(i.status!==0){de(n,{recursive:!0,force:!0});let s=i.stderr?.toString().trim();throw new Error(`Could not create worktree at '${e}'${s?`: ${s}`:""}. Verify the ref exists (e.g. 'git rev-parse --verify <ref>').`)}try{return t(n)}finally{Y("git",["worktree","remove","--force",n],{stdio:["pipe","pipe","pipe"],env:o}).status!==0&&de(n,{recursive:!0,force:!0})}}function Se(e,t,n){let o=new Map;if(t.length===0)return o;let i=j(e,s=>pt(s,t));for(let s of t){let r=n.get(s);if(r===void 0)continue;let l=i.get(s);l===void 0?o.set(s,{oldComplexity:null,newComplexity:r,change:null}):o.set(s,{oldComplexity:l.complexity,newComplexity:r,change:r-l.complexity})}return o}function re(e){let t;try{t=$("git ls-files",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:e})}catch{throw new Error("Not a git repository or git is not installed.")}let n=new Set;for(let o of t.toString().split(` | ||
| `)){let i=D(o.trim());i&&n.add(i)}return n}function Re(e,t,n,o,i){let s=[];for(let[u,c]of e){if(c<o)continue;let[p,a]=u.split("\0"),f=t.get(p)??0,g=t.get(a)??0,y=Math.min(f,g),k=y>0?Math.round(c/y*1e3)/10:0,m=(n.get(p)??0)+(n.get(a)??0),d={file1:p,file2:a,cochanges:c,degree:k,totalComplexity:m,couplingScore:c,percentOfTotal:0,tier:"cool"},x=Math.max(f,g);c>0&&x>0&&c/x>=.9&&(d.lockstep=!0),i&&(i.has(p)||(d.file1Deleted=!0),i.has(a)||(d.file2Deleted=!0)),s.push(d)}s.sort((u,c)=>c.couplingScore-u.couplingScore);let r=s.reduce((u,c)=>u+c.couplingScore,0);if(r===0)return[];let l=s.map(u=>({...u,score:u.couplingScore}));B(l,r);for(let u=0;u<s.length;u++)s[u].percentOfTotal=l[u].percentOfTotal,s[u].tier=l[u].tier;return s}function ve(e,t,n,o){let i=new Map,s=new Map;for(let[c,p]of e){if(p<t)continue;let[a,f]=c.split("\0");if(n){let g=Math.max(n.get(a)??0,n.get(f)??0);if(g>0&&p/g>=.9)continue}i.has(a)||i.set(a,new Set),i.has(f)||i.set(f,new Set),i.get(a)?.add(f),i.get(f)?.add(a),s.set(a,(s.get(a)??0)+p),s.set(f,(s.get(f)??0)+p)}let r=[];for(let[c,p]of i){let a={file:c,partners:p.size,strength:s.get(c),percentOfTotal:0,tier:"cool"};o&&!o.has(c)&&(a.fileDeleted=!0),r.push(a)}r.sort((c,p)=>p.strength!==c.strength?p.strength-c.strength:p.partners!==c.partners?p.partners-c.partners:c.file.localeCompare(p.file));let l=r.reduce((c,p)=>c+p.strength,0),u=r.map(c=>({...c,score:c.strength}));B(u,l);for(let c=0;c<r.length;c++)r[c].percentOfTotal=u[c].percentOfTotal,r[c].tier=u[c].tier;return r}function ft(e,t){let n=new Map;for(let o of e){let i;try{i=ge(t?Q(t,o):o,"utf-8")}catch{n.set(o,0);continue}let s=[],r=new Map,l=0;for(let a of i.split(` | ||
| `)){if(!a.trim())continue;let f=a.match(/^(\s+)/);if(!f){l=0;continue}let g=f[1];if(s.push(g),g.includes(" "))continue;let y=g.length,k=y-l;k>0&&r.set(k,(r.get(k)??0)+1),l=y}let u=4,c=0;for(let[a,f]of r)(f>c||f===c&&a<u)&&(c=f,u=a);let p=0;for(let a of s){let f=0;for(let g of a)g===" "?f+=1:g===" "&&(f+=1/u);f=Math.floor(f),f>p&&(p=f)}n.set(o,p)}return n}var dt=[{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"}],mt=[{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 Ee(){let e=re(),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 dt)n.has(o.dir)&&t.push({pattern:o.pattern,comment:o.comment});for(let o of mt)for(let i of e)if(o.test.test(i)){t.push({pattern:o.pattern,comment:o.comment});break}return t}function $e(e,t=Z){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(` | ||
| `)}var gt=10,me={inconclusive:0,weak:1,plausible:2,acceptable:3};function ht(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:T.composite};let o="acceptable";for(let i of t)me[i.level]<me[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:T.composite}}function yt(e,t,n){let o=Object.keys(e).length,i=ht(e),s=new Map;for(let p of Object.values(e))for(let a=0;a<p.entries.length;a++){let f=p.entries[a].file,g=1/(gt+a+1),y=s.get(f);y?(y.score+=g,y.dims+=1):s.set(f,{score:g,dims:1})}let r=[];for(let[p,a]of s)r.push({file:p,score:Math.round(a.score*1e4)/1e4,percentOfTotal:0,tier:"cool",churn:t.get(p)??0,dimensionCount:a.dims});r.sort((p,a)=>a.score-p.score);let l=r.reduce((p,a)=>p+a.score,0);if(l===0)return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:0,tierCounts:{hot:0,warm:0,cool:0},tiers:{hot:0,warm:0,cool:0},totalDimensions:o,totalEntries:0,showing:0,entries:[],confidence:i};B(r,l);let u=n>0?r.slice(0,n):r,c={hot:0,warm:0,cool:0};for(let p of r)c[p.tier]++;return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:Math.round(l*1e4)/1e4,tierCounts:c,tiers:c,totalDimensions:o,totalEntries:r.length,showing:u.length,entries:u,confidence:i}}function L(e,t,n,o,i="commits"){let s=i==="lines"?Qe(t,o):P(t,o),r=et(t,o),l=nt(t,o),u=Ze(t,o),c=new Map;for(let[h,C]of l)c.set(h,C.size);let p=ft(e.map(h=>h.file),o),{rankings:a,skipped:f}=lt(e,s,r,p,c,n,l),g=yt(a,s,n),y=0;for(let h of e)y+=h.complexity;let k=t*ce,m=new Map(e.map(h=>[h.file,h])),d=[];for(let[h,C]of u){let S=m.get(h);S&&d.push({file:h,dormancyDays:C.dormancyDays,dormancyMultiple:C.dormancyMultiple,lastTouchedBeforeWindow:C.lastTouchedBeforeWindow,firstTouchedInWindow:C.firstTouchedInWindow,complexity:S.complexity,churn:s.get(h)??0})}d.sort((h,C)=>C.dormancyMultiple-h.dormancyMultiple||h.file.localeCompare(C.file));let x={windowDays:k,minDormancyMultiple:X,minDormancyDays:k*X,entries:d};return{rankings:a,skipped:f,composite:g,corpus:{fileCount:e.length,totalComplexity:y},churn:s,reawakened:x}}function Me(e,t){if(t<=0)return e;let n={};for(let[i,s]of Object.entries(e.rankings)){let r=s.entries.slice(0,t);n[i]={...s,entries:r,showing:r.length}}let o=e.composite.entries.slice(0,t);return{rankings:n,skipped:e.skipped,composite:{...e.composite,entries:o,showing:o.length},corpus:e.corpus,churn:e.churn,reawakened:e.reawakened}}function se(e){let t=H(e.excludes,e.cwd),n=L(t,e.months,0,e.cwd,e.churnMode);return{files:t,rankings:n.rankings,skipped:n.skipped,composite:n.composite,reawakened:n.reawakened,corpus:n.corpus}}function ae(e,t,n,o){let i=new Map;for(let m of n.composite.entries)i.set(m.file,{score:m.score,tier:m.tier});let s=new Map;for(let m of o.composite.entries)s.set(m.file,{score:m.score,tier:m.tier});let r=new Set(n.files.map(m=>m.file)),l=new Set(o.files.map(m=>m.file)),u=[],c=[];for(let m of l)r.has(m)||u.push(m);for(let m of r)l.has(m)||c.push(m);u.sort(),c.sort();let p=new Set([...i.keys(),...s.keys()]),a=[],f=[],g=[],y=[],k=[];for(let m of p){let d=i.get(m),x=s.get(m),h=d?.score??null,C=x?.score??null,S=d?.tier??null,R=x?.tier??null,F=h!==null&&C!==null?C-h:null,ze=F!==null&&h!==null&&h!==0?Math.round(F/h*1e3)/10:null,E;S===null?E="new":R===null?E="deleted":S!=="hot"&&R==="hot"?E="entered-hot":S==="cool"&&R==="warm"?E="entered-warm":S==="hot"&&R!=="hot"?E="exited-hot":S==="warm"&&R==="cool"?E="exited-warm":E="stable",E==="entered-hot"?f.push(m):E==="entered-warm"?g.push(m):E==="exited-hot"?y.push(m):E==="exited-warm"&&k.push(m),a.push({file:m,oldScore:h,newScore:C,change:F!==null?Math.round(F*1e4)/1e4:null,percentChange:ze,oldTier:S,newTier:R,transition:E})}return a.sort((m,d)=>{let x=Math.abs(m.change??0),h=Math.abs(d.change??0);return x!==h?h-x:m.file.localeCompare(d.file)}),f.sort(),g.sort(),y.sort(),k.sort(),{base:e,head:t,newFiles:u,deletedFiles:c,tierTransitions:{enteredHot:f,enteredWarm:g,exitedHot:y,exitedWarm:k},scoreChanges:a,perDimensionDeltas:{complexity:{oldTotal:n.corpus.totalComplexity,newTotal:o.corpus.totalComplexity,change:o.corpus.totalComplexity-n.corpus.totalComplexity},fileCount:{oldTotal:n.corpus.fileCount,newTotal:o.corpus.fileCount,change:o.corpus.fileCount-n.corpus.fileCount}}}}function De(e){return A("commitsInWindow",e,N.coupling,T.coupling,t=>t==="inconclusive"?`${e} commits in window \u2014 need \u2265 ${N.coupling.weak} (matches code-maat's --min-revs default).`:`${e} commits in window (${t.toUpperCase()} sample size).`)}function Oe(e,t){try{let n=$(`git rev-list --count --since="${e} months ago" HEAD`,{stdio:["pipe","pipe","pipe"],cwd:t});return parseInt(n.toString().trim(),10)||0}catch{throw new Error("Not a git repository or git is not installed.")}}var ce=30;function Te(e,t){let n=e*ce,o;try{let l=$("git log --format=%ct --reverse HEAD",{maxBuffer:52428800,stdio:["pipe","pipe","pipe"],cwd:t}).toString().split(` | ||
| `,1)[0].trim();if(o=parseInt(l,10),!Number.isFinite(o)||o<=0)return{windowDays:n,spanDays:0,underCovered:!0}}catch{throw new Error("Not a git repository or git is not installed.")}let i=Math.floor(Date.now()/1e3),s=Math.max(0,Math.floor((i-o)/86400));return{windowDays:n,spanDays:s,underCovered:s<n}}import w from"picocolors";import O from"picocolors";var wt=/\x1b\[[0-9;]*m/g;function bt(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 Ie(e){let t=e.replace(wt,""),n=0;for(let o of t){let i=o.codePointAt(0);i===65038||i===65039||(n+=bt(i)?2:1)}return n}function v(e,t){let n=Ie(e);return n>=t?e:e+" ".repeat(t-n)}function b(e,t){let n=Ie(e);return n>=t?e:" ".repeat(t-n)+e}function M(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 _(e){return e==="hot"?O.red("\u{1F525} HOT "):e==="warm"?O.yellow("\u2600\uFE0F WARM"):O.blue("\u{1F9CA} COOL")}function W(e,t){return e==="hot"?O.red(t):e==="warm"?O.yellow(t):O.blue(t)}function U(e,t,n){let o=[];return o.push(`Tiers: ${O.red(`${e.hot} HOT`)}, ${O.yellow(`${e.warm} WARM`)}, ${O.blue(`${e.cool} COOL`)}`),o.push(`Showing: ${t} of ${n}`),o}var Ct={inconclusive:w.gray,weak:w.yellow,plausible:w.cyan,acceptable:w.green};function G(e){let t=Ct[e.level];return[t(`Confidence: ${e.level.toUpperCase()} \u2014 ${e.reason}`)]}var xt=Object.fromEntries(oe.map(e=>[e.key,e.label]));function Fe(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(v("File",60)+b("Code",8)+b("Complexity",12)+b("Density",9)+b("Comments",10)),t.push("\u2500".repeat(99));for(let i of o)t.push(v(M(i.file,58),60)+b(String(i.code),8)+b(String(i.complexity),12)+b(i.complexityDensity.toFixed(2),9)+b(String(i.comments),10));return t.push(""),t.push(w.dim("Complexity=cyclomatic branch/loop count | Density=complexity/code | Comments=comment lines")),t.push(w.dim("High complexity is expected for parsers, state machines, and business logic. Compare density across files, not raw values.")),t.push(w.dim("Docs: https://github.com/wbern/obscene#metrics")),t.join(` | ||
| `)}function Ne(e){return e?e.oldComplexity===null||e.change===null?"new":e.change===0?"0":e.change>0?`+${e.change}`:String(e.change):"\xB7"}function kt(e,t){let n=[{header:"File",width:50,align:"left",value:r=>M(r.file,48)},{header:"Score",width:8,align:"right",value:r=>r.score.toLocaleString()},{header:"%",width:7,align:"right",value:r=>r.percentOfTotal.toFixed(1)},{header:"Churn",width:7,align:"right",value:r=>String(r.churn)}],o={complexity:[{header:"Cmplx",width:7,align:"right",value:r=>String(r.metricValue)},{header:"Dens",width:7,align:"right",value:r=>(r.metricDensity??0).toFixed(2)}],nesting:[{header:"Nest",width:6,align:"right",value:r=>String(r.metricValue)}],defects:[{header:"Fixes",width:6,align:"right",value:r=>String(r.metricValue)},{header:"FxDns",width:7,align:"right",value:r=>(r.metricDensity??0).toFixed(4)}],authors:[{header:"Auth",width:6,align:"right",value:r=>String(r.metricValue)},{header:"MinAuth",width:9,align:"right",value:r=>r.minorAuthors===null||r.minorAuthors===void 0?"\u2014":String(r.minorAuthors)}]},i={header:"Tier",width:12,align:"right",value:r=>_(r.tier)},s={header:"\u0394",width:7,align:"right",value:r=>Ne(r.complexityDelta)};return[...n,...o[e]??[],...t?[s]:[],i]}var St={complexity:"\u{1F9EC}",nesting:"\u{1F4CF}",defects:"\u{1F527}",authors:"\u{1F465}"};function Rt(e,t,n,o){let i=[],s=kt(e,o),r=St[e],l=r?`${r} `:"",u=t.label.toUpperCase().replace("CHURN","\u{1F504} CHURN");if(i.push(`${l}${u} \u2014 Total score: ${t.totalScore.toLocaleString()}`),i.push(...G(t.confidence)),n)for(let a of n.split(` | ||
| `))i.push(w.dim(a));i.push(...U(t.tierCounts,t.showing,t.totalEntries)),i.push("");let c=s.map(a=>a.align==="left"?v(a.header,a.width):b(a.header,a.width)).join("");i.push(c);let p=s.reduce((a,f)=>a+f.width,0);i.push("\u2500".repeat(p));for(let a of t.entries){let g=s.map(y=>{let k=y.value(a);return y.align==="left"?v(k,y.width):b(k,y.width)}).join("");i.push(W(a.tier,g))}return i}function vt(e){let t=[];t.push(""),t.push(w.cyan(`Full Delta \u2014 ${e.base} \u2192 ${e.head}`)),t.push(w.dim("Tier transitions are relative percentile bands \u2014 a file can shift tiers because its absolute score moved OR because the rest of the corpus moved around it. scoreChanges carries the absolute delta."));let{enteredHot:n,enteredWarm:o,exitedHot:i,exitedWarm:s}=e.tierTransitions;if(n.length===0&&o.length===0&&i.length===0&&s.length===0&&e.newFiles.length===0&&e.deletedFiles.length===0)t.push(w.dim("No tier transitions, no new/deleted files."));else{let p=(a,f)=>{if(f.length!==0){t.push(a);for(let g of f.slice(0,10))t.push(` ${M(g,80)}`);f.length>10&&t.push(w.dim(` \u2026 and ${f.length-10} more`))}};p(w.red(` \u2191 entered HOT (${n.length}):`),n),p(w.yellow(` \u2191 entered WARM (${o.length}):`),o),p(w.green(` \u2193 cooled out of HOT (${i.length}):`),i),p(w.green(` \u2193 cooled out of WARM (${s.length}):`),s),p(w.cyan(` + new files (${e.newFiles.length}):`),e.newFiles),p(w.cyan(` \u2212 deleted files (${e.deletedFiles.length}):`),e.deletedFiles)}let r=e.perDimensionDeltas.complexity,l=e.perDimensionDeltas.fileCount,u=r.change>0?"+":"",c=l.change>0?"+":"";return t.push(""),t.push(w.dim(`Corpus: complexity ${r.oldTotal} \u2192 ${r.newTotal} (${u}${r.change}) \xB7 files ${l.oldTotal} \u2192 ${l.newTotal} (${c}${l.change})`)),t}function Et(e){let t=[],{windowDays:n,minDormancyMultiple:o,minDormancyDays:i,entries:s}=e;t.push(w.magenta(`Reawakened \u2014 dormant \u2265 ${o}\xD7 window (${i}d) then touched again`)),t.push(w.dim(` Window: ${n}d \xB7 Rule: gap between last pre-window commit and first in-window commit \u2265 ${i}d`)),t.push("");let r=` ${v("File",40)} ${b("Dormancy",12)} ${b("\xD7Window",10)} ${b("Cx",6)} ${b("Churn",6)}`;t.push(w.dim(r));for(let l of s)t.push(` ${v(M(l.file,40),40)} ${b(`${l.dormancyDays}d`,12)} ${b(`${l.dormancyMultiple}\xD7`,10)} ${b(String(l.complexity),6)} ${b(String(l.churn),6)}`);return t}function le(e){let t=[],{churnWindow:n,churnMode:o,rankings:i,corpus:s,delta:r,fullDelta:l}=e;if(r&&(t.push(w.cyan(`Delta \u2014 ${r.changedFiles.length} file${r.changedFiles.length===1?"":"s"} changed since ${r.base}`)),r.fallback&&t.push(w.yellow(` \u26A0 full-delta unavailable \u2014 showing filtered view. Reason: ${r.fallback.reason}`)),r.changedFiles.length===0))return t.push(""),t.push(w.dim("No changes \u2014 nothing to rank.")),t.join(` | ||
| `);l&&t.push(...vt(l));let u=o==="lines"?" (line-based)":"";t.push(`Hotspots \u2014 ${n} churn window${u}`),s&&s.fileCount>0&&s.totalComplexity===0&&(t.push(""),t.push(w.yellow("Note: no measurable code complexity detected across this corpus (cyclomatic = 0).")),t.push(w.yellow("Rankings reflect size and churn only \u2014 HOT/WARM/COOL are relative groupings, not risk labels."))),t.push("");let c=r!==void 0&&Object.values(i).some(f=>f.entries.some(g=>g.complexityDelta!==void 0)),p=Object.keys(i);for(let f=0;f<p.length;f++){let g=p[f];t.push(...Rt(g,i[g],e.guide[g],c)),f<p.length-1&&(t.push(""),t.push("\xB7 \xB7 \xB7"),t.push(""))}if(e.skipped)for(let[f,g]of Object.entries(e.skipped)){t.push("");let y=xt[f]??`${f.charAt(0).toUpperCase()+f.slice(1)} \xD7 Churn`;t.push(`${y} \u2014 skipped (${g.reason})`),g.suggestion&&t.push(` ${g.suggestion}`)}e.reawakened&&(t.push(""),t.push("\xB7 \xB7 \xB7"),t.push(""),t.push(...Et(e.reawakened))),t.push(""),t.push(w.dim("Score=metric\xD7churn | Tiers are relative to THIS codebase, not absolute quality grades."));let a=s!==void 0&&s.fileCount>0&&s.totalComplexity===0;return t.push(w.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(w.dim("Docs: https://github.com/wbern/obscene#metrics")),s?.filtered===!1&&(t.push(""),t.push(w.yellow("\u26A0 Corpus unfiltered \u2014 no .obsignore found. Lockfiles, generated code, and vendored dependencies may dominate these rankings.")),t.push(w.dim(" Run `obscene init` to generate a starter .obsignore."))),t.join(` | ||
| `)}function He(e){let t=[],{tierCounts:n,totalScore:o,churnWindow:i,couplings:s}=e;t.push(`Coupling \u2014 ${i} churn window | Min shared: ${e.minCochanges} | Total score: ${o.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...U(n,e.showing,e.totalCouplings)),t.push(v("File 1",35)+v("File 2",35)+b("Shared",7)+b("Degree",8)+b("Cmplx",7)+b("Tier",12)),t.push("\u2500".repeat(104));let r=!1,l=!1;for(let u of s){(u.file1Deleted||u.file2Deleted)&&(r=!0),u.lockstep&&(l=!0);let c=u.file1Deleted?`\u2020 ${M(u.file1,31)}`:M(u.file1,33),p=u.file2Deleted?`\u2020 ${M(u.file2,31)}`:M(u.file2,33),a=u.lockstep?`${u.degree.toFixed(1)}\u21C4`:`${u.degree.toFixed(1)}%`,f=v(c,35)+v(p,35)+b(String(u.cochanges),7)+b(a,8)+b(String(u.totalComplexity),7)+b(_(u.tier),12);t.push(W(u.tier,f))}return t.push(""),t.push(w.dim("Shared=co-changed commits | Degree=shared/min(churn)\xD7100 | Cmplx=sum of both files")),r&&t.push(w.dim("\u2020 = file no longer present at HEAD (deleted or renamed)")),l&&t.push(w.dim("\u21C4 = lockstep pair (both files only ever changed together \u2014 signal is real but uninformative)")),t.push(w.dim("Tiers are relative to THIS codebase, not absolute quality grades. High coupling may be intentional and fine.")),t.push(w.dim("Same-directory pairs excluded. Commits touching >20 files skipped. Only cross-directory dependencies shown.")),t.push(w.dim("Docs: https://github.com/wbern/obscene#metrics")),e.sumOfCoupling&&e.sumOfCoupling.length>0&&(t.push(""),t.push(...$t(e.sumOfCoupling,e.confidence))),t.join(` | ||
| `)}function $t(e,t){let n=[];n.push("\u2500".repeat(68)),n.push(`${w.bold("Sum of Coupling")} ${w.dim("(experimental \u2014 not independently validated)")} \u2014 files whose couplings concentrate the most cross-dir change traffic`),n.push(...G(t)),n.push(""),n.push(v("File",40)+b("Partners",10)+b("Strength",10)+b("Tier",8)),n.push("\u2500".repeat(68));let o=!1;for(let i of e){let s=i.fileDeleted?`\u2020 ${i.file}`:i.file;i.fileDeleted&&(o=!0);let r=v(M(s,38),40)+b(String(i.partners),10)+b(String(i.strength),10)+b(_(i.tier),8);n.push(W(i.tier,r))}return n.push(""),o&&n.push(w.dim("\u2020 = file no longer present at HEAD (deleted or renamed away); coupling signal is historical.")),n.push(w.dim("Partners=distinct cross-dir co-change partners | Strength=\u03A3 pair cochange counts (= code-maat's SoC analysis, filtered to cross-dir pairs and \u226420-file commits).")),n.push(w.dim(`Navigation aid: high strength means "worth a look at this file's couplings", not "this file is defect-prone".`)),n.push(w.dim("EXPERIMENTAL: NOT independently validated against defect data; may change, be reframed, or be removed.")),n}function Ae(e){let t=[],n=e.entries.some(s=>s.complexityDelta!==void 0),o=n?91:84;t.push("\u2550".repeat(o)),t.push(`\u2605 ${e.label.toUpperCase()} \u2014 Total score: ${e.totalScore.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...U(e.tierCounts,e.showing,e.totalEntries)),t.push("");let i=v("File",50)+b("Score",9)+b("Churn",7)+b("Dims",6);n&&(i+=b("\u0394",7)),i+=b("Tier",12),t.push(i),t.push("\u2500".repeat(o));for(let s of e.entries){let r=v(M(s.file,48),50)+b(s.score.toFixed(4),9)+b(String(s.churn),7)+b(`${s.dimensionCount}/${e.totalDimensions}`,6);n&&(r+=b(Ne(s.complexityDelta),7)),r+=b(_(s.tier),12),t.push(W(s.tier,r))}return t.join(` | ||
| `)}var Mt=25,Dt=new Set(["UserPromptSubmit","PostToolUse","PostToolBatch"]);function Le(e){return`${e>0?"+":""}${e.toFixed(0)}%`}function _e(e,t={}){let n=t.significantPercentChange??Mt,o=new Set([...e.tierTransitions.enteredHot,...e.tierTransitions.enteredWarm,...e.tierTransitions.exitedHot,...e.tierTransitions.exitedWarm]),i=new Map(e.scoreChanges.map(m=>[m.file,m])),s=[];for(let m of[...o].sort()){let d=i.get(m);if(!d)continue;let x=d.oldTier??"\u2014",h=d.newTier??"\u2014",C=d.percentChange!==null?Le(d.percentChange):"\u2014";s.push(`- ${m}: ${x} \u2192 ${h} (score ${C})`)}let r=e.scoreChanges.filter(m=>!o.has(m.file)).filter(m=>m.percentChange!==null&&Math.abs(m.percentChange)>=n).sort((m,d)=>Math.abs(d.percentChange)-Math.abs(m.percentChange));for(let m of r){let d=m.newTier??m.oldTier??"\u2014";s.push(`- ${m.file}: score ${Le(m.percentChange)} (stayed ${d})`)}let l=Ot(t.reminders);if(s.length===0&&l.length===0)return null;let u=e.tierTransitions.enteredHot.length,c=e.tierTransitions.exitedHot.length,p=e.tierTransitions.enteredWarm.length,a=e.tierTransitions.exitedWarm.length,f=u+c+p+a>0,g=`obscene drift (vs ${e.base}):`,y=f?`tiers: HOT +${u}/-${c} \xB7 WARM +${p}/-${a}`:null,k=[];return y&&k.push(y),k.push(...s),l.length>0&&(k.length>0&&k.push(""),k.push(...l)),`${g} | ||
| `)){let a=D(p.trim());a&&(we(a,o)||u.add(a))}let c=[...u];if(!(c.length<2||c.length>ct))for(let p=0;p<c.length;p++)for(let a=p+1;a<c.length;a++){let[f,g]=c[p]<c[a]?[c[p],c[a]]:[c[a],c[p]],w=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"",k=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";if(w===k)continue;let m=`${f}\0${g}`;s.set(m,(s.get(m)??0)+1)}}return s}var te=5,ne=70,lt=5;function xe(e,t,n,o={}){let i=o.minCochanges??te,s=o.minDegree??ne,r=o.maxResults??lt,l=new Map;for(let[u,c]of e){if(c<i)continue;let[p,a]=u.split("\0"),f=n.has(p),g=n.has(a);if(f===g)continue;let w=t.get(p)??0,k=t.get(a)??0,m=Math.min(w,k);if(m===0)continue;let d=Math.max(w,k);if(c/d>=.9)continue;let x=Math.round(c/m*1e3)/10;if(x<s)continue;let h=f?p:a,b=f?a:p,S=l.get(h);(!S||x>S.degree)&&l.set(h,{file:h,partner:b,cochanges:c,degree:x})}return[...l.values()].sort((u,c)=>c.degree-u.degree||c.cochanges-u.cochanges||u.file.localeCompare(c.file)).slice(0,r)}function j(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<=tt?o.tier="hot":i<=nt?o.tier="warm":o.tier="cool"}}var oe=[{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 ut(e,t,n,o){let i=e.map(r=>{let l=t.get(r.file)??0,u=n(r);return{file:r.file,score:u*l,percentOfTotal:0,tier:"cool",churn:l,metricValue:u,metricDensity:o?o(r):void 0}}).filter(r=>r.score>0).sort((r,l)=>l.score-r.score),s=i.reduce((r,l)=>r+l.score,0);return s===0?[]:(j(i,s),i)}var pt=.05,ft=2;function dt(e){if(!e||e.size===0)return null;let t=0;for(let i of e.values())t+=i;if(t<ft)return null;let n=t*pt,o=0;for(let i of e.values())i<n&&o++;return o}function mt(e,t,n,o,i,s,r){let l={complexity:{extract:d=>d.complexity,density:d=>d.complexityDensity},nesting:{extract:d=>d.complexity===0?0:o.get(d.file)??0},defects:{extract:d=>n.get(d.file)??0,density:d=>{let x=n.get(d.file)??0;return d.code>0?Math.round(x/d.code*1e4)/1e4:0}},authors:{extract:d=>i.get(d.file)??0}},u={},c={},p=0;for(let d of e)d.complexity>0&&p++;c.complexity=A("filesWithComplexity",p,H.complexity,T.complexity,d=>d==="inconclusive"?`${p} files with measurable complexity \u2014 not enough to rank.`:`${p} files with measurable complexity (${d.toUpperCase()} sample size).`);let a=0;for(let d of e)d.complexity>0&&(o.get(d.file)??0)>=3&&a++;c.nesting=A("filesWithNesting>=3",a,H.nesting,T.nesting,d=>d==="inconclusive"?`${a} files with nesting depth \u2265 3 \u2014 not enough to rank.`:`${a} files with nesting depth \u2265 3 (${d.toUpperCase()} sample size).`);let f=[...n.values()].reduce((d,x)=>d+x,0),g=n.size,w=f<J||g<K;c.defects=A("fixCommits",f,H.defects,T.defects,d=>d==="inconclusive"||w?`${f} fix: commits across ${g} files \u2014 need \u2265 ${J} commits across \u2265 ${K} files (matches code-maat's --min-revs default).`:`${f} fix: commits across ${g} files (${d.toUpperCase()} sample size).`),w&&(c.defects={...c.defects,level:"inconclusive"},u.defects={reason:`insufficient data (${f} fix: commits across ${g} files, need ${J}+ commits across ${K}+ files)`,suggestion:"Adopt conventional commits with fix: prefix. See conventionalcommits.org",confidence:c.defects});let k=0;for(let d of i.values())d>k&&(k=d);c.authors=A("maxAuthors",k,H.authors,T.authors,d=>d==="inconclusive"?`${k} distinct authors on the most-touched file \u2014 not enough to rank ownership.`:`${k} distinct authors on the most-touched file (${d.toUpperCase()} sample size).`),k<=1&&(c.authors={...c.authors,level:"inconclusive"},u.authors={reason:"all files have the same author count \u2014 no variance to rank",confidence:c.authors});let m={};for(let d of oe){if(u[d.key])continue;if(c[d.key].level==="inconclusive"){u[d.key]={reason:c[d.key].reason,confidence:c[d.key]};continue}let x=l[d.key],h=ut(e,t,x.extract,x.density);if(h.length===0)continue;if(d.key==="authors"&&r)for(let v of h)v.minorAuthors=dt(r.get(v.file));let b=s>0?h.slice(0,s):h,S={hot:0,warm:0,cool:0};for(let v of h)S[v.tier]++;m[d.key]={label:d.label,scoreFormula:d.scoreFormula,totalScore:h.reduce((v,F)=>v+F.score,0),tierCounts:S,tiers:S,totalEntries:h.length,showing:b.length,entries:b,confidence:c[d.key]}}return{rankings:m,skipped:u}}function ie(e){let t;try{t=E(`git diff --name-only ${e}...HEAD`,{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]})}catch{throw new Error(`Failed to compute diff against base ref '${e}'. Verify the ref exists (e.g. 'git rev-parse --verify <ref>').`)}let n=new Set;for(let o of t.toString().split(` | ||
| `)){let i=D(o.trim());i&&n.add(i)}return n}var gt=["main","master"];function ke(){for(let e of gt)try{return E(`git rev-parse --verify ${e}`,{stdio:["pipe","pipe","pipe"]}),e}catch{}}function Se(){try{return E("git rev-parse --show-toplevel",{stdio:["pipe","pipe","pipe"]}).toString().trim()||void 0}catch{return}}function ht(e,t){let n=new Map;if(t.length===0)return n;let o=t.filter(r=>Xe(Q(e,r)));if(o.length===0)return n;let i=Y("scc",["--by-file","--format","json","--no-cocomo","--no-gen",...o],{cwd:e,maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"]});if(i.error&&"code"in i.error&&i.error.code==="ENOENT")throw new Error("scc not found. Install it: https://github.com/boyter/scc#install");if(i.error)throw new Error(`scc spawn failed: ${i.error.message}`);if(i.status!==0)throw new Error(`scc failed on base worktree: ${i.stderr?.toString().trim()||"unknown error"}`);let s=JSON.parse(i.stdout.toString());for(let r of s)for(let l of r.Files){let u=D(l.Location);n.set(u,{file:u,code:l.Code,lines:l.Lines,complexity:l.Complexity,comments:l.Comment,complexityDensity:l.Code>0?Math.round(l.Complexity/l.Code*100)/100:0})}return n}function B(e,t){let n=Qe(Q(Ze(),"obscene-base-")),o={...process.env};for(let s of Object.keys(o))s.startsWith("GIT_")&&delete o[s];let i=Y("git",["worktree","add","--detach",n,e],{stdio:["pipe","pipe","pipe"],env:o});if(i.status!==0){me(n,{recursive:!0,force:!0});let s=i.stderr?.toString().trim();throw new Error(`Could not create worktree at '${e}'${s?`: ${s}`:""}. Verify the ref exists (e.g. 'git rev-parse --verify <ref>').`)}try{return t(n)}finally{Y("git",["worktree","remove","--force",n],{stdio:["pipe","pipe","pipe"],env:o}).status!==0&&me(n,{recursive:!0,force:!0})}}function $e(e,t,n){let o=new Map;if(t.length===0)return o;let i=B(e,s=>ht(s,t));for(let s of t){let r=n.get(s);if(r===void 0)continue;let l=i.get(s);l===void 0?o.set(s,{oldComplexity:null,newComplexity:r,change:null}):o.set(s,{oldComplexity:l.complexity,newComplexity:r,change:r-l.complexity})}return o}function re(e){let t;try{t=E("git ls-files",{maxBuffer:50*1024*1024,stdio:["pipe","pipe","pipe"],cwd:e})}catch{throw new Error("Not a git repository or git is not installed.")}let n=new Set;for(let o of t.toString().split(` | ||
| `)){let i=D(o.trim());i&&n.add(i)}return n}function ve(e,t,n,o,i){let s=[];for(let[u,c]of e){if(c<o)continue;let[p,a]=u.split("\0"),f=t.get(p)??0,g=t.get(a)??0,w=Math.min(f,g),k=w>0?Math.round(c/w*1e3)/10:0,m=(n.get(p)??0)+(n.get(a)??0),d={file1:p,file2:a,cochanges:c,degree:k,totalComplexity:m,couplingScore:c,percentOfTotal:0,tier:"cool"},x=Math.max(f,g);c>0&&x>0&&c/x>=.9&&(d.lockstep=!0),i&&(i.has(p)||(d.file1Deleted=!0),i.has(a)||(d.file2Deleted=!0)),s.push(d)}s.sort((u,c)=>c.couplingScore-u.couplingScore);let r=s.reduce((u,c)=>u+c.couplingScore,0);if(r===0)return[];let l=s.map(u=>({...u,score:u.couplingScore}));j(l,r);for(let u=0;u<s.length;u++)s[u].percentOfTotal=l[u].percentOfTotal,s[u].tier=l[u].tier;return s}function Re(e,t,n,o){let i=new Map,s=new Map;for(let[c,p]of e){if(p<t)continue;let[a,f]=c.split("\0");if(n){let g=Math.max(n.get(a)??0,n.get(f)??0);if(g>0&&p/g>=.9)continue}i.has(a)||i.set(a,new Set),i.has(f)||i.set(f,new Set),i.get(a)?.add(f),i.get(f)?.add(a),s.set(a,(s.get(a)??0)+p),s.set(f,(s.get(f)??0)+p)}let r=[];for(let[c,p]of i){let a={file:c,partners:p.size,strength:s.get(c),percentOfTotal:0,tier:"cool"};o&&!o.has(c)&&(a.fileDeleted=!0),r.push(a)}r.sort((c,p)=>p.strength!==c.strength?p.strength-c.strength:p.partners!==c.partners?p.partners-c.partners:c.file.localeCompare(p.file));let l=r.reduce((c,p)=>c+p.strength,0),u=r.map(c=>({...c,score:c.strength}));j(u,l);for(let c=0;c<r.length;c++)r[c].percentOfTotal=u[c].percentOfTotal,r[c].tier=u[c].tier;return r}function yt(e,t){let n=new Map;for(let o of e){let i;try{i=he(t?Q(t,o):o,"utf-8")}catch{n.set(o,0);continue}let s=[],r=new Map,l=0;for(let a of i.split(` | ||
| `)){if(!a.trim())continue;let f=a.match(/^(\s+)/);if(!f){l=0;continue}let g=f[1];if(s.push(g),g.includes(" "))continue;let w=g.length,k=w-l;k>0&&r.set(k,(r.get(k)??0)+1),l=w}let u=4,c=0;for(let[a,f]of r)(f>c||f===c&&a<u)&&(c=f,u=a);let p=0;for(let a of s){let f=0;for(let g of a)g===" "?f+=1:g===" "&&(f+=1/u);f=Math.floor(f),f>p&&(p=f)}n.set(o,p)}return n}var wt=[{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"}],Ct=[{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 Ee(){let e=re(),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 wt)n.has(o.dir)&&t.push({pattern:o.pattern,comment:o.comment});for(let o of Ct)for(let i of e)if(o.test.test(i)){t.push({pattern:o.pattern,comment:o.comment});break}return t}function Oe(e,t=Z){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(` | ||
| `)}var bt=10,ge={inconclusive:0,weak:1,plausible:2,acceptable:3};function xt(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:T.composite};let o="acceptable";for(let i of t)ge[i.level]<ge[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:T.composite}}function kt(e,t,n){let o=Object.keys(e).length,i=xt(e),s=new Map;for(let p of Object.values(e))for(let a=0;a<p.entries.length;a++){let f=p.entries[a].file,g=1/(bt+a+1),w=s.get(f);w?(w.score+=g,w.dims+=1):s.set(f,{score:g,dims:1})}let r=[];for(let[p,a]of s)r.push({file:p,score:Math.round(a.score*1e4)/1e4,percentOfTotal:0,tier:"cool",churn:t.get(p)??0,dimensionCount:a.dims});r.sort((p,a)=>a.score-p.score);let l=r.reduce((p,a)=>p+a.score,0);if(l===0)return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:0,tierCounts:{hot:0,warm:0,cool:0},tiers:{hot:0,warm:0,cool:0},totalDimensions:o,totalEntries:0,showing:0,entries:[],confidence:i};j(r,l);let u=n>0?r.slice(0,n):r,c={hot:0,warm:0,cool:0};for(let p of r)c[p.tier]++;return{label:"Combined",scoreFormula:"reciprocal rank fusion across all dimensions",totalScore:Math.round(l*1e4)/1e4,tierCounts:c,tiers:c,totalDimensions:o,totalEntries:r.length,showing:u.length,entries:u,confidence:i}}function L(e,t,n,o,i="commits"){let s=i==="lines"?ot(t,o):W(t,o),r=rt(t,o),l=at(t,o),u=it(t,o),c=new Map;for(let[h,b]of l)c.set(h,b.size);let p=yt(e.map(h=>h.file),o),{rankings:a,skipped:f}=mt(e,s,r,p,c,n,l),g=kt(a,s,n),w=0;for(let h of e)w+=h.complexity;let k=t*ce,m=new Map(e.map(h=>[h.file,h])),d=[];for(let[h,b]of u){let S=m.get(h);S&&d.push({file:h,dormancyDays:b.dormancyDays,dormancyMultiple:b.dormancyMultiple,lastTouchedBeforeWindow:b.lastTouchedBeforeWindow,firstTouchedInWindow:b.firstTouchedInWindow,complexity:S.complexity,churn:s.get(h)??0})}d.sort((h,b)=>b.dormancyMultiple-h.dormancyMultiple||h.file.localeCompare(b.file));let x={windowDays:k,minDormancyMultiple:X,minDormancyDays:k*X,entries:d};return{rankings:a,skipped:f,composite:g,corpus:{fileCount:e.length,totalComplexity:w},churn:s,reawakened:x}}function De(e,t){if(t<=0)return e;let n={};for(let[i,s]of Object.entries(e.rankings)){let r=s.entries.slice(0,t);n[i]={...s,entries:r,showing:r.length}}let o=e.composite.entries.slice(0,t);return{rankings:n,skipped:e.skipped,composite:{...e.composite,entries:o,showing:o.length},corpus:e.corpus,churn:e.churn,reawakened:e.reawakened}}function se(e){let t=N(e.excludes,e.cwd),n=L(t,e.months,0,e.cwd,e.churnMode);return{files:t,rankings:n.rankings,skipped:n.skipped,composite:n.composite,reawakened:n.reawakened,corpus:n.corpus}}function ae(e,t,n,o){let i=new Map;for(let m of n.composite.entries)i.set(m.file,{score:m.score,tier:m.tier});let s=new Map;for(let m of o.composite.entries)s.set(m.file,{score:m.score,tier:m.tier});let r=new Set(n.files.map(m=>m.file)),l=new Set(o.files.map(m=>m.file)),u=[],c=[];for(let m of l)r.has(m)||u.push(m);for(let m of r)l.has(m)||c.push(m);u.sort(),c.sort();let p=new Set([...i.keys(),...s.keys()]),a=[],f=[],g=[],w=[],k=[];for(let m of p){let d=i.get(m),x=s.get(m),h=d?.score??null,b=x?.score??null,S=d?.tier??null,v=x?.tier??null,F=h!==null&&b!==null?b-h:null,Ye=F!==null&&h!==null&&h!==0?Math.round(F/h*1e3)/10:null,R;S===null?R="new":v===null?R="deleted":S!=="hot"&&v==="hot"?R="entered-hot":S==="cool"&&v==="warm"?R="entered-warm":S==="hot"&&v!=="hot"?R="exited-hot":S==="warm"&&v==="cool"?R="exited-warm":R="stable",R==="entered-hot"?f.push(m):R==="entered-warm"?g.push(m):R==="exited-hot"?w.push(m):R==="exited-warm"&&k.push(m),a.push({file:m,oldScore:h,newScore:b,change:F!==null?Math.round(F*1e4)/1e4:null,percentChange:Ye,oldTier:S,newTier:v,transition:R})}return a.sort((m,d)=>{let x=Math.abs(m.change??0),h=Math.abs(d.change??0);return x!==h?h-x:m.file.localeCompare(d.file)}),f.sort(),g.sort(),w.sort(),k.sort(),{base:e,head:t,newFiles:u,deletedFiles:c,tierTransitions:{enteredHot:f,enteredWarm:g,exitedHot:w,exitedWarm:k},scoreChanges:a,perDimensionDeltas:{complexity:{oldTotal:n.corpus.totalComplexity,newTotal:o.corpus.totalComplexity,change:o.corpus.totalComplexity-n.corpus.totalComplexity},fileCount:{oldTotal:n.corpus.fileCount,newTotal:o.corpus.fileCount,change:o.corpus.fileCount-n.corpus.fileCount}}}}function Me(e){return A("commitsInWindow",e,H.coupling,T.coupling,t=>t==="inconclusive"?`${e} commits in window \u2014 need \u2265 ${H.coupling.weak} (matches code-maat's --min-revs default).`:`${e} commits in window (${t.toUpperCase()} sample size).`)}function Te(e,t){try{let n=E(`git rev-list --count --since="${e} months ago" HEAD`,{stdio:["pipe","pipe","pipe"],cwd:t});return parseInt(n.toString().trim(),10)||0}catch{throw new Error("Not a git repository or git is not installed.")}}var ce=30;function Ie(e,t){let n=e*ce,o;try{let l=E("git log --format=%ct --reverse HEAD",{maxBuffer:52428800,stdio:["pipe","pipe","pipe"],cwd:t}).toString().split(` | ||
| `,1)[0].trim();if(o=parseInt(l,10),!Number.isFinite(o)||o<=0)return{windowDays:n,spanDays:0,underCovered:!0}}catch{throw new Error("Not a git repository or git is not installed.")}let i=Math.floor(Date.now()/1e3),s=Math.max(0,Math.floor((i-o)/86400));return{windowDays:n,spanDays:s,underCovered:s<n}}import C from"picocolors";import M from"picocolors";var St=/\x1b\[[0-9;]*m/g;function $t(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(St,""),n=0;for(let o of t){let i=o.codePointAt(0);i===65038||i===65039||(n+=$t(i)?2:1)}return n}function $(e,t){let n=Fe(e);return n>=t?e:e+" ".repeat(t-n)}function y(e,t){let n=Fe(e);return n>=t?e:" ".repeat(t-n)+e}function O(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 _(e){return e==="hot"?M.red("\u{1F525} HOT "):e==="warm"?M.yellow("\u2600\uFE0F WARM"):M.blue("\u{1F9CA} COOL")}function P(e,t){return e==="hot"?M.red(t):e==="warm"?M.yellow(t):M.blue(t)}function U(e,t,n){let o=[];return o.push(`Tiers: ${M.red(`${e.hot} HOT`)}, ${M.yellow(`${e.warm} WARM`)}, ${M.blue(`${e.cool} COOL`)}`),o.push(`Showing: ${t} of ${n}`),o}var vt={inconclusive:C.gray,weak:C.yellow,plausible:C.cyan,acceptable:C.green};function G(e){let t=vt[e.level];return[t(`Confidence: ${e.level.toUpperCase()} \u2014 ${e.reason}`)]}var Rt=Object.fromEntries(oe.map(e=>[e.key,e.label]));function He(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($("File",60)+y("Code",8)+y("Complexity",12)+y("Density",9)+y("Comments",10)),t.push("\u2500".repeat(99));for(let i of o)t.push($(O(i.file,58),60)+y(String(i.code),8)+y(String(i.complexity),12)+y(i.complexityDensity.toFixed(2),9)+y(String(i.comments),10));return t.push(""),t.push(C.dim("Complexity=cyclomatic branch/loop count | Density=complexity/code | Comments=comment lines")),t.push(C.dim("High complexity is expected for parsers, state machines, and business logic. Compare density across files, not raw values.")),t.push(C.dim("Docs: https://github.com/wbern/obscene#metrics")),t.join(` | ||
| `)}function Ne(e){return e?e.oldComplexity===null||e.change===null?"new":e.change===0?"0":e.change>0?`+${e.change}`:String(e.change):"\xB7"}function Et(e,t){let n=[{header:"File",width:50,align:"left",value:r=>O(r.file,48)},{header:"Score",width:8,align:"right",value:r=>r.score.toLocaleString()},{header:"%",width:7,align:"right",value:r=>r.percentOfTotal.toFixed(1)},{header:"Churn",width:7,align:"right",value:r=>String(r.churn)}],o={complexity:[{header:"Cmplx",width:7,align:"right",value:r=>String(r.metricValue)},{header:"Dens",width:7,align:"right",value:r=>(r.metricDensity??0).toFixed(2)}],nesting:[{header:"Nest",width:6,align:"right",value:r=>String(r.metricValue)}],defects:[{header:"Fixes",width:6,align:"right",value:r=>String(r.metricValue)},{header:"FxDns",width:7,align:"right",value:r=>(r.metricDensity??0).toFixed(4)}],authors:[{header:"Auth",width:6,align:"right",value:r=>String(r.metricValue)},{header:"MinAuth",width:9,align:"right",value:r=>r.minorAuthors===null||r.minorAuthors===void 0?"\u2014":String(r.minorAuthors)}]},i={header:"Tier",width:12,align:"right",value:r=>_(r.tier)},s={header:"\u0394",width:7,align:"right",value:r=>Ne(r.complexityDelta)};return[...n,...o[e]??[],...t?[s]:[],i]}var Ot={complexity:"\u{1F9EC}",nesting:"\u{1F4CF}",defects:"\u{1F527}",authors:"\u{1F465}"};function Dt(e,t,n,o){let i=[],s=Et(e,o),r=Ot[e],l=r?`${r} `:"",u=t.label.toUpperCase().replace("CHURN","\u{1F504} CHURN");if(i.push(`${l}${u} \u2014 Total score: ${t.totalScore.toLocaleString()}`),i.push(...G(t.confidence)),n)for(let a of n.split(` | ||
| `))i.push(C.dim(a));i.push(...U(t.tierCounts,t.showing,t.totalEntries)),i.push("");let c=s.map(a=>a.align==="left"?$(a.header,a.width):y(a.header,a.width)).join("");i.push(c);let p=s.reduce((a,f)=>a+f.width,0);i.push("\u2500".repeat(p));for(let a of t.entries){let g=s.map(w=>{let k=w.value(a);return w.align==="left"?$(k,w.width):y(k,w.width)}).join("");i.push(P(a.tier,g))}return i}function Mt(e){let t=[];t.push(""),t.push(C.cyan(`Full Delta \u2014 ${e.base} \u2192 ${e.head}`)),t.push(C.dim("Tier transitions are relative percentile bands \u2014 a file can shift tiers because its absolute score moved OR because the rest of the corpus moved around it. scoreChanges carries the absolute delta."));let{enteredHot:n,enteredWarm:o,exitedHot:i,exitedWarm:s}=e.tierTransitions;if(n.length===0&&o.length===0&&i.length===0&&s.length===0&&e.newFiles.length===0&&e.deletedFiles.length===0)t.push(C.dim("No tier transitions, no new/deleted files."));else{let p=(a,f)=>{if(f.length!==0){t.push(a);for(let g of f.slice(0,10))t.push(` ${O(g,80)}`);f.length>10&&t.push(C.dim(` \u2026 and ${f.length-10} more`))}};p(C.red(` \u2191 entered HOT (${n.length}):`),n),p(C.yellow(` \u2191 entered WARM (${o.length}):`),o),p(C.green(` \u2193 cooled out of HOT (${i.length}):`),i),p(C.green(` \u2193 cooled out of WARM (${s.length}):`),s),p(C.cyan(` + new files (${e.newFiles.length}):`),e.newFiles),p(C.cyan(` \u2212 deleted files (${e.deletedFiles.length}):`),e.deletedFiles)}let r=e.perDimensionDeltas.complexity,l=e.perDimensionDeltas.fileCount,u=r.change>0?"+":"",c=l.change>0?"+":"";return t.push(""),t.push(C.dim(`Corpus: complexity ${r.oldTotal} \u2192 ${r.newTotal} (${u}${r.change}) \xB7 files ${l.oldTotal} \u2192 ${l.newTotal} (${c}${l.change})`)),t}function Tt(e){let t=[],{windowDays:n,minDormancyMultiple:o,minDormancyDays:i,entries:s}=e;t.push(C.magenta(`Reawakened \u2014 dormant \u2265 ${o}\xD7 window (${i}d) then touched again`)),t.push(C.dim(` Window: ${n}d \xB7 Rule: gap between last pre-window commit and first in-window commit \u2265 ${i}d`)),t.push("");let r=` ${$("File",40)} ${y("Dormancy",12)} ${y("\xD7Window",10)} ${y("Cx",6)} ${y("Churn",6)}`;t.push(C.dim(r));for(let l of s)t.push(` ${$(O(l.file,40),40)} ${y(`${l.dormancyDays}d`,12)} ${y(`${l.dormancyMultiple}\xD7`,10)} ${y(String(l.complexity),6)} ${y(String(l.churn),6)}`);return t}function le(e){let t=[],{churnWindow:n,churnMode:o,rankings:i,corpus:s,delta:r,fullDelta:l}=e;if(r&&(t.push(C.cyan(`Delta \u2014 ${r.changedFiles.length} file${r.changedFiles.length===1?"":"s"} changed since ${r.base}`)),r.fallback&&t.push(C.yellow(` \u26A0 full-delta unavailable \u2014 showing filtered view. Reason: ${r.fallback.reason}`)),r.changedFiles.length===0))return t.push(""),t.push(C.dim("No changes \u2014 nothing to rank.")),t.join(` | ||
| `);l&&t.push(...Mt(l));let u=o==="lines"?" (line-based)":"";t.push(`Hotspots \u2014 ${n} churn window${u}`),s&&s.fileCount>0&&s.totalComplexity===0&&(t.push(""),t.push(C.yellow("Note: no measurable code complexity detected across this corpus (cyclomatic = 0).")),t.push(C.yellow("Rankings reflect size and churn only \u2014 HOT/WARM/COOL are relative groupings, not risk labels."))),t.push("");let c=r!==void 0&&Object.values(i).some(f=>f.entries.some(g=>g.complexityDelta!==void 0)),p=Object.keys(i);for(let f=0;f<p.length;f++){let g=p[f];t.push(...Dt(g,i[g],e.guide[g],c)),f<p.length-1&&(t.push(""),t.push("\xB7 \xB7 \xB7"),t.push(""))}if(e.skipped)for(let[f,g]of Object.entries(e.skipped)){t.push("");let w=Rt[f]??`${f.charAt(0).toUpperCase()+f.slice(1)} \xD7 Churn`;t.push(`${w} \u2014 skipped (${g.reason})`),g.suggestion&&t.push(` ${g.suggestion}`)}e.reawakened&&(t.push(""),t.push("\xB7 \xB7 \xB7"),t.push(""),t.push(...Tt(e.reawakened))),t.push(""),t.push(C.dim("Score=metric\xD7churn | Tiers are relative to THIS codebase, not absolute quality grades."));let a=s!==void 0&&s.fileCount>0&&s.totalComplexity===0;return t.push(C.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(C.dim("Docs: https://github.com/wbern/obscene#metrics")),s?.filtered===!1&&(t.push(""),t.push(C.yellow("\u26A0 Corpus unfiltered \u2014 no .obsignore found. Lockfiles, generated code, and vendored dependencies may dominate these rankings.")),t.push(C.dim(" Run `obscene init` to generate a starter .obsignore."))),t.join(` | ||
| `)}function Ae(e){let t=[],{tierCounts:n,totalScore:o,churnWindow:i,couplings:s}=e;t.push(`Coupling \u2014 ${i} churn window | Min shared: ${e.minCochanges} | Total score: ${o.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...U(n,e.showing,e.totalCouplings)),t.push($("File 1",35)+$("File 2",35)+y("Shared",7)+y("Degree",8)+y("Cmplx",7)+y("Tier",12)),t.push("\u2500".repeat(104));let r=!1,l=!1;for(let u of s){(u.file1Deleted||u.file2Deleted)&&(r=!0),u.lockstep&&(l=!0);let c=u.file1Deleted?`\u2020 ${O(u.file1,31)}`:O(u.file1,33),p=u.file2Deleted?`\u2020 ${O(u.file2,31)}`:O(u.file2,33),a=u.lockstep?`${u.degree.toFixed(1)}\u21C4`:`${u.degree.toFixed(1)}%`,f=$(c,35)+$(p,35)+y(String(u.cochanges),7)+y(a,8)+y(String(u.totalComplexity),7)+y(_(u.tier),12);t.push(P(u.tier,f))}return t.push(""),t.push(C.dim("Shared=co-changed commits | Degree=shared/min(churn)\xD7100 | Cmplx=sum of both files")),r&&t.push(C.dim("\u2020 = file no longer present at HEAD (deleted or renamed)")),l&&t.push(C.dim("\u21C4 = lockstep pair (both files only ever changed together \u2014 signal is real but uninformative)")),t.push(C.dim("Tiers are relative to THIS codebase, not absolute quality grades. High coupling may be intentional and fine.")),t.push(C.dim("Same-directory pairs excluded. Commits touching >20 files skipped. Only cross-directory dependencies shown.")),t.push(C.dim("Docs: https://github.com/wbern/obscene#metrics")),e.sumOfCoupling&&e.sumOfCoupling.length>0&&(t.push(""),t.push(...It(e.sumOfCoupling,e.confidence))),t.join(` | ||
| `)}function It(e,t){let n=[];n.push("\u2500".repeat(68)),n.push(`${C.bold("Sum of Coupling")} ${C.dim("(experimental \u2014 not independently validated)")} \u2014 files whose couplings concentrate the most cross-dir change traffic`),n.push(...G(t)),n.push(""),n.push($("File",40)+y("Partners",10)+y("Strength",10)+y("Tier",8)),n.push("\u2500".repeat(68));let o=!1;for(let i of e){let s=i.fileDeleted?`\u2020 ${i.file}`:i.file;i.fileDeleted&&(o=!0);let r=$(O(s,38),40)+y(String(i.partners),10)+y(String(i.strength),10)+y(_(i.tier),8);n.push(P(i.tier,r))}return n.push(""),o&&n.push(C.dim("\u2020 = file no longer present at HEAD (deleted or renamed away); coupling signal is historical.")),n.push(C.dim("Partners=distinct cross-dir co-change partners | Strength=\u03A3 pair cochange counts (= code-maat's SoC analysis, filtered to cross-dir pairs and \u226420-file commits).")),n.push(C.dim(`Navigation aid: high strength means "worth a look at this file's couplings", not "this file is defect-prone".`)),n.push(C.dim("EXPERIMENTAL: NOT independently validated against defect data; may change, be reframed, or be removed.")),n}function Le(e){return e==="hot"?"HOT ":e==="warm"?"WARM":"COOL"}function _e(e){let t=e.historyCoverage;return t?.underCovered?` [history covers ~${t.spanDays}d, window ${t.windowDays}d]`:""}function ue(e){let t=[],n=e.composite,o=e.corpus,i=o?`${o.fileCount} files, ${o.totalComplexity} total complexity`:"",s=`Hotspot landscape (composite RRF, ${e.churnWindow} window`+(i?`, ${i}`:"")+_e(e)+"):";if(t.push(s),!n||n.entries.length===0)return t.push("(no composite ranking \u2014 insufficient signal)"),t.join(` | ||
| `);t.push(`Confidence: ${n.confidence.level.toUpperCase()} \u2014 ${n.confidence.reason}`);for(let r of n.entries)t.push(`${Le(r.tier)} ${$(r.file,50)} ${y(`${r.percentOfTotal.toFixed(1)}%`,6)} ${y(`${r.churn} commits`,12)} ${r.dimensionCount}/${n.totalDimensions} dims`);return t.join(` | ||
| `)}function Pe(e){let t=[],{summary:n,files:o}=e;t.push(`Complexity report \u2014 ${n.fileCount} files, ${n.totalComplexity} total complexity, ${n.avgComplexityPerFile} avg/file (showing ${n.showing}):`);for(let i of o)t.push(`${$(i.file,50)} complexity=${y(String(i.complexity),5)} density=${i.complexityDensity.toFixed(2)} code=${i.code}`);return t.join(` | ||
| `)}function We(e){let t=[],n=`Coupling \u2014 ${e.churnWindow} window, min shared: ${e.minCochanges}`+_e(e)+":";if(t.push(n),e.couplings.length===0)return t.push("(no pairs above thresholds)"),t.join(` | ||
| `);t.push(`Confidence: ${e.confidence.level.toUpperCase()} \u2014 ${e.confidence.reason}`);for(let o of e.couplings){let i=`${o.file1} \u2194 ${o.file2}`,s=o.lockstep?"\u21C4":"%";t.push(`${Le(o.tier)} ${$(i,70)} ${y(`${o.cochanges} shared`,10)} ${y(`${o.degree.toFixed(1)}${s}`,8)}`)}return t.join(` | ||
| `)}function je(e){let t=[],n=e.entries.some(s=>s.complexityDelta!==void 0),o=n?91:84;t.push("\u2550".repeat(o)),t.push(`\u2605 ${e.label.toUpperCase()} \u2014 Total score: ${e.totalScore.toLocaleString()}`),t.push(...G(e.confidence)),t.push(...U(e.tierCounts,e.showing,e.totalEntries)),t.push("");let i=$("File",50)+y("Score",9)+y("Churn",7)+y("Dims",6);n&&(i+=y("\u0394",7)),i+=y("Tier",12),t.push(i),t.push("\u2500".repeat(o));for(let s of e.entries){let r=$(O(s.file,48),50)+y(s.score.toFixed(4),9)+y(String(s.churn),7)+y(`${s.dimensionCount}/${e.totalDimensions}`,6);n&&(r+=y(Ne(s.complexityDelta),7)),r+=y(_(s.tier),12),t.push(P(s.tier,r))}return t.join(` | ||
| `)}var Ft=25,Ht=new Set(["SessionStart","Setup","SubagentStart","UserPromptSubmit","UserPromptExpansion","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch"]);function Be(e){return`${e>0?"+":""}${e.toFixed(0)}%`}function Ue(e,t={}){let n=t.significantPercentChange??Ft,o=new Set([...e.tierTransitions.enteredHot,...e.tierTransitions.enteredWarm,...e.tierTransitions.exitedHot,...e.tierTransitions.exitedWarm]),i=new Map(e.scoreChanges.map(m=>[m.file,m])),s=[];for(let m of[...o].sort()){let d=i.get(m);if(!d)continue;let x=d.oldTier??"\u2014",h=d.newTier??"\u2014",b=d.percentChange!==null?Be(d.percentChange):"\u2014";s.push(`- ${m}: ${x} \u2192 ${h} (score ${b})`)}let r=e.scoreChanges.filter(m=>!o.has(m.file)).filter(m=>m.percentChange!==null&&Math.abs(m.percentChange)>=n).sort((m,d)=>Math.abs(d.percentChange)-Math.abs(m.percentChange));for(let m of r){let d=m.newTier??m.oldTier??"\u2014";s.push(`- ${m.file}: score ${Be(m.percentChange)} (stayed ${d})`)}let l=Nt(t.reminders);if(s.length===0&&l.length===0)return null;let u=e.tierTransitions.enteredHot.length,c=e.tierTransitions.exitedHot.length,p=e.tierTransitions.enteredWarm.length,a=e.tierTransitions.exitedWarm.length,f=u+c+p+a>0,g=`obscene drift (vs ${e.base}):`,w=f?`tiers: HOT +${u}/-${c} \xB7 WARM +${p}/-${a}`:null,k=[];return w&&k.push(w),k.push(...s),l.length>0&&(k.length>0&&k.push(""),k.push(...l)),`${g} | ||
| ${k.join(` | ||
| `)}`}function Ot(e){if(!e||e.length===0)return[];let t=[`co-change reminders (\u2265${te} commits, \u2265${ne}% degree):`];for(let n of e)t.push(`- ${n.file} \u2194 ${n.partner}: ${n.cochanges} shared commits (degree ${n.degree.toFixed(0)}%)`);return t.push("ignore if unrelated to this change."),t}function We(e,t){return Dt.has(t)?{hookSpecificOutput:{hookEventName:t,additionalContext:e}}:{systemMessage:e}}var I=new Nt;I.name("obscene").description("Identify hotspot files \u2014 complex code that changes frequently").version("2.10.0");var Ht={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. | ||
| `)}`}function Nt(e){if(!e||e.length===0)return[];let t=[`co-change reminders (\u2265${te} commits, \u2265${ne}% degree):`];for(let n of e)t.push(`- ${n.file} \u2194 ${n.partner}: ${n.cochanges} shared commits (degree ${n.degree.toFixed(0)}%)`);return t.push("ignore if unrelated to this change."),t}function Ge(e,t){return Ht.has(t)?{hookSpecificOutput:{hookEventName:t,additionalContext:e}}:{systemMessage:e}}var I=new Pt;I.name("obscene").description("Identify hotspot files \u2014 complex code that changes frequently").version("2.11.0");var Wt={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."},qe={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. | ||
| 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. | ||
@@ -28,20 +33,24 @@ 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. | ||
| Metric concept: code ownership research (Bird et al. 2011, Microsoft); Co-authored-by trailers folded into author set to close the squash-merge gap \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. | ||
| 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.",reawakened:"Files that were dormant for \u2265 3\xD7 the churn window and just got touched again inside it. The objective rule: gap between the latest pre-window commit and the earliest in-window commit must be \u2265 minDormancyDays. Reawakened code often carries forgotten context \u2014 the original author may be gone, mental models stale.\nMetric concept: forensic 'reawakened files' signal from Tornhill, *Your Code as a Crime Scene* (2nd ed., Ch. 2) \xB7 Strength: highlights risk that pure churn \xD7 complexity misses \xB7 Limit: pre-window history must exist (omits truly new files), and `git log --follow` isn't used so file renames break the dormancy chain."},At={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.",sumOfCoupling:'Per-file Sum of Coupling. `strength` = \u03A3 pair cochange counts a file participates in \u2014 equivalent to the SoC analysis in code-maat (\u03A3(changeset_size \u2212 1); see github.com/adamtornhill/code-maat), restricted here to cross-directory pairs and commits touching \u226420 files; near-lockstep pairs (count/max(churn) \u2265 0.9) are suppressed so mirror/generator artifacts don\'t dominate. `partners` = distinct co-change partners (graph degree). Treat as a navigation aid \u2014 high `strength` says "this file\'s couplings deserve a closer look", not "this file is buggy". EXPERIMENTAL: this surface has NOT been independently validated against defect data; it may change, be reframed, or be removed.'};function ue(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)")}ue(I.command("report").description("per-file complexity data")).action(e=>{try{Lt(e)}catch(t){q(t)}});ue(I.command("hotspots",{isDefault:!0}).description("churn \xD7 complexity hotspot analysis (default)")).option("--months <n>","churn window in months","3").option("--base [ref]","delta mode: filter rankings to files changed since this ref (bare flag auto-detects main/master)").option("--full-delta","with --base, run the full hotspots pipeline against the base ref too and emit a structured before/after diff (slower; tier transitions, score deltas, new/deleted files)").option("--paths <files...>","filter displayed entries to these paths (tiers stay corpus-anchored \u2014 answers 'are MY changes in hot territory?')").option("--since <ref>","shorthand for --paths $(git diff --name-only <ref>...HEAD) \u2014 filter to files changed since ref").option("--churn-mode <mode>","how to count churn: 'commits' counts commits touching each file; 'lines' sums added+deleted lines via git log --numstat","commits").action(e=>{try{Ut(e)}catch(t){q(t)}});ue(I.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{Gt(e)}catch(t){q(t)}});I.command("hook").description("emit Claude Code hook JSON summarizing hotspot drift since a base ref (use in PostToolUse/Stop hooks)").option("--base <ref>","base ref to compare against (default: HEAD \u2014 i.e. working tree vs last commit)","HEAD").option("--event <name>","hook event name to emit in hookSpecificOutput","Stop").option("--months <n>","churn window in months","3").option("--significant-percent <n>","minimum |percent change| for a stable-tier score change to be surfaced (tier transitions are always surfaced)").action(e=>{Vt(e)});I.command("init").description("generate a starter .obsignore based on project structure").action(()=>{try{qt()}catch(e){q(e)}});function V(e){return[...he(),...e??[]]}function Ue(){return z(".obsignore")||z(".obsceneignore")}function pe(){Ue()||process.stderr.write("hint: no .obsignore found \u2014 run `obscene init` to generate one with recommended exclusions\n")}function fe(){let e=ke();if(!e)return;let t;try{t=Be(process.cwd())}catch{return}let n=(()=>{try{return Be(e)}catch{return e}})();if(t===n)return;let o=Ft(n,t)||".";process.stderr.write(`warning: scanning subtree '${o}' only \u2014 cd to repo root for whole-repo results (GH#13) | ||
| `)}function Ge(e){let t=Te(e);return t.underCovered&&process.stderr.write(`warning: git history covers ~${t.spanDays}d, but --months window is ${t.windowDays}d \u2014 count-based confidence won't reflect time-based trust on a young repo | ||
| `),t}function Lt(e){pe(),fe();let t=parseInt(e.top,10),n=V(e.exclude),o=H(n),i=o.reduce((l,u)=>({totalComplexity:l.totalComplexity+u.complexity,totalCode:l.totalCode+u.code,totalLines:l.totalLines+u.lines}),{totalComplexity:0,totalCode:0,totalLines:0}),s=t>0?o.slice(0,t):o,r={generated:new Date().toISOString(),guide:Ht,summary:{...i,fileCount:o.length,avgComplexityPerFile:o.length>0?Math.round(i.totalComplexity/o.length*10)/10:0,showing:s.length},files:s};e.format==="table"?process.stdout.write(`${Fe(r)} | ||
| 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.",reawakened:"Files that were dormant for \u2265 3\xD7 the churn window and just got touched again inside it. The objective rule: gap between the latest pre-window commit and the earliest in-window commit must be \u2265 minDormancyDays. Reawakened code often carries forgotten context \u2014 the original author may be gone, mental models stale.\nMetric concept: forensic 'reawakened files' signal from Tornhill, *Your Code as a Crime Scene* (2nd ed., Ch. 2) \xB7 Strength: highlights risk that pure churn \xD7 complexity misses \xB7 Limit: pre-window history must exist (omits truly new files), and `git log --follow` isn't used so file renames break the dormancy chain."},jt={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.",sumOfCoupling:'Per-file Sum of Coupling. `strength` = \u03A3 pair cochange counts a file participates in \u2014 equivalent to the SoC analysis in code-maat (\u03A3(changeset_size \u2212 1); see github.com/adamtornhill/code-maat), restricted here to cross-directory pairs and commits touching \u226420 files; near-lockstep pairs (count/max(churn) \u2265 0.9) are suppressed so mirror/generator artifacts don\'t dominate. `partners` = distinct co-change partners (graph degree). Treat as a navigation aid \u2014 high `strength` says "this file\'s couplings deserve a closer look", not "this file is buggy". EXPERIMENTAL: this surface has NOT been independently validated against defect data; it may change, be reframed, or be removed.'};function pe(e){return e.option("--top <n>","limit to top N entries (0 = all)","20").option("--format <type>","output format: json | table | compact (compact = terse plain-text lines for hooks and quick reads)","json").option("--exclude <patterns...>","additional file patterns to exclude (also reads .obsignore / .obsceneignore)")}pe(I.command("report").description("per-file complexity data")).action(e=>{try{Bt(e)}catch(t){q(t)}});pe(I.command("hotspots",{isDefault:!0}).description("churn \xD7 complexity hotspot analysis (default)")).option("--months <n>","churn window in months","3").option("--base [ref]","delta mode: filter rankings to files changed since this ref (bare flag auto-detects main/master)").option("--full-delta","with --base, run the full hotspots pipeline against the base ref too and emit a structured before/after diff (slower; tier transitions, score deltas, new/deleted files)").option("--paths <files...>","filter displayed entries to these paths (tiers stay corpus-anchored \u2014 answers 'are MY changes in hot territory?')").option("--since <ref>","shorthand for --paths $(git diff --name-only <ref>...HEAD) \u2014 filter to files changed since ref").option("--churn-mode <mode>","how to count churn: 'commits' counts commits touching each file; 'lines' sums added+deleted lines via git log --numstat","commits").action(e=>{try{Jt(e)}catch(t){q(t)}});pe(I.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{Kt(e)}catch(t){q(t)}});I.command("hook").description("emit Claude Code hook JSON summarizing hotspot drift since a base ref (use in PostToolUse/Stop hooks)").option("--base <ref>","base ref to compare against (default: HEAD \u2014 i.e. working tree vs last commit)","HEAD").option("--event <name>","hook event name (selects the right output envelope: hookSpecificOutput.additionalContext for SessionStart / UserPromptSubmit / Pre|PostToolUse / etc., or top-level systemMessage for Stop / SubagentStop / ConfigChange / PreCompact)","Stop").option("--months <n>","churn window in months","3").option("--significant-percent <n>","minimum |percent change| for a stable-tier score change to be surfaced (tier transitions are always surfaced)").action(e=>{Xt(e)});I.command("init").description("generate a starter .obsignore based on project structure").action(()=>{try{Qt()}catch(e){q(e)}});function V(e){return[...ye(),...e??[]]}function Je(){return z(".obsignore")||z(".obsceneignore")}function fe(){Je()||process.stderr.write("hint: no .obsignore found \u2014 run `obscene init` to generate one with recommended exclusions\n")}function de(){let e=Se();if(!e)return;let t;try{t=Ve(process.cwd())}catch{return}let n=(()=>{try{return Ve(e)}catch{return e}})();if(t===n)return;let o=_t(n,t)||".";process.stderr.write(`warning: scanning subtree '${o}' only \u2014 cd to repo root for whole-repo results (GH#13) | ||
| `)}function Ke(e){let t=Ie(e);return t.underCovered&&process.stderr.write(`warning: git history covers ~${t.spanDays}d, but --months window is ${t.windowDays}d \u2014 count-based confidence won't reflect time-based trust on a young repo | ||
| `),t}function Bt(e){fe(),de();let t=parseInt(e.top,10),n=V(e.exclude),o=N(n),i=o.reduce((l,u)=>({totalComplexity:l.totalComplexity+u.complexity,totalCode:l.totalCode+u.code,totalLines:l.totalLines+u.lines}),{totalComplexity:0,totalCode:0,totalLines:0}),s=t>0?o.slice(0,t):o,r={generated:new Date().toISOString(),guide:Wt,summary:{...i,fileCount:o.length,avgComplexityPerFile:o.length>0?Math.round(i.totalComplexity/o.length*10)/10:0,showing:s.length},files:s};e.format==="table"?process.stdout.write(`${He(r)} | ||
| `):e.format==="compact"?process.stdout.write(`${Pe(r)} | ||
| `):process.stdout.write(`${JSON.stringify(r,null,2)} | ||
| `)}function _t(e,t,n){for(let o of Object.values(e))for(let i of o.entries){let s=n.get(i.file);s&&(i.complexityDelta=s)}if(t)for(let o of t.entries){let i=n.get(o.file);i&&(o.complexityDelta=i)}}function Wt(e){if(typeof e=="string")return e;let t=xe();if(!t)throw new Error("--base used without a ref but no default branch found (looked for main, master). Specify the base ref explicitly, e.g. --base <branch-or-sha>.");return t}function Pt(e){if(e.paths&&e.paths.length>0&&e.since)throw new Error("--paths and --since are mutually exclusive \u2014 pick one path-source.");return e.paths&&e.paths.length>0?{paths:new Set(e.paths),source:`--paths (${e.paths.length} file${e.paths.length===1?"":"s"})`}:e.since?{paths:ie(e.since),source:`--since ${e.since}`}:null}function Bt(e,t){let n=e.composite?.tierCounts.hot??0,o=e.composite?.totalEntries??0,i=new Set;for(let a of Object.values(e.rankings))for(let f of a.entries)i.add(f.file);for(let a of e.composite?.entries??[])i.add(a.file);for(let a of Object.values(e.rankings))a.entries=a.entries.filter(f=>t.paths.has(f.file)),a.showing=a.entries.length;e.composite&&(e.composite.entries=e.composite.entries.filter(a=>t.paths.has(a.file)),e.composite.showing=e.composite.entries.length),e.reawakened&&(e.reawakened.entries=e.reawakened.entries.filter(a=>t.paths.has(a.file)),e.reawakened.entries.length===0&&(e.reawakened=void 0));let s=0,r=0,l=0;for(let a of e.composite?.entries??[])a.tier==="hot"?s++:a.tier==="warm"?r++:l++;let u=[...t.paths].filter(a=>!i.has(a)).sort(),c=o>0?`${Math.round(n/o*100)}%`:"n/a",p=s+r+l;process.stderr.write(`path filter ${t.source}: ${s} HOT, ${r} WARM, ${l} COOL of ${p} ranked file${p===1?"":"s"}; ${u.length} not in any ranking. Corpus base rate: ${c} HOT. | ||
| `),e.pathFilter={source:t.source,paths:[...t.paths].sort(),rankedCount:p,hotCount:s,warmCount:r,coolCount:l,notRanked:u,corpusHotRate:o>0?n/o:null}}function jt(e){if(e==="commits"||e==="lines")return e;throw new Error(`Unknown --churn-mode '${e}'. Expected 'commits' or 'lines'.`)}function Ut(e){pe(),fe();let t=Ue(),n=parseInt(e.top,10),o=parseInt(e.months,10),i=jt(e.churnMode),s=Ge(o),r=V(e.exclude),l=H(r);if(e.fullDelta&&e.base===void 0)throw new Error("--full-delta requires --base. Specify a base ref, e.g. --base main --full-delta.");let u=Pt(e);if(u&&e.base!==void 0)throw new Error('--paths/--since and --base are mutually exclusive \u2014 they answer different questions. --paths gives corpus-anchored tiers ("are MY changes hot in the codebase?"); --base re-ranks within the changed set ("of my changes, which is hottest?").');let c,p,a;if(e.base!==void 0){let x=Wt(e.base),h=ie(x);if(h.size===0){process.stderr.write(`No files changed since ${x}. | ||
| `);let C={generated:new Date().toISOString(),guide:je,churnWindow:`${o} months`,churnMode:i,historyCoverage:s,delta:{base:x,head:"HEAD",changedFiles:[]},rankings:{},corpus:{fileCount:0,totalComplexity:0,filtered:t}};e.format==="table"?process.stdout.write(`${le(C)} | ||
| `):process.stdout.write(`${JSON.stringify(C,null,2)} | ||
| `);return}if(c={base:x,head:"HEAD",changedFiles:[...h].sort()},e.fullDelta)try{let C=j(x,R=>se({months:o,excludes:r,cwd:R,churnMode:i}));a=L(l,o,0,void 0,i);let S={files:l,rankings:a.rankings,skipped:a.skipped,composite:a.composite,reawakened:a.reawakened,corpus:a.corpus};p=ae(x,"HEAD",C,S)}catch(C){let S=C instanceof Error?C.message:String(C);process.stderr.write(`warning: full-delta unavailable (${S}). Falling back to filtered rankings. | ||
| `),l=l.filter(R=>h.has(R.file)),a=void 0,c.fallback={from:"full-delta",reason:S}}else l=l.filter(C=>h.has(C.file))}let{rankings:f,skipped:g,composite:y,corpus:k,reawakened:m}=a?Me(a,n):L(l,o,n,void 0,i);if(c&&p===void 0){let x=new Map,h=[];for(let C of l)x.set(C.file,C.complexity),h.push(C.file);try{let C=Se(c.base,h,x);_t(f,y,C)}catch(C){let S=C instanceof Error?C.message:String(C);process.stderr.write(`warning: complexity delta unavailable (${S}). Falling back to filtered rankings without per-file deltas. | ||
| `)}}let d={generated:new Date().toISOString(),guide:je,churnWindow:`${o} months`,churnMode:i,historyCoverage:s,delta:c,fullDelta:p,rankings:f,skipped:Object.keys(g).length>0?g:void 0,composite:y,reawakened:m.entries.length>0?m:void 0,corpus:{...k,filtered:t}};u&&Bt(d,u),e.format==="table"?(process.stdout.write(`${le(d)} | ||
| `),y.entries.length>0&&process.stdout.write(` | ||
| ${Ae(y)} | ||
| `)}function Ut(e,t,n){for(let o of Object.values(e))for(let i of o.entries){let s=n.get(i.file);s&&(i.complexityDelta=s)}if(t)for(let o of t.entries){let i=n.get(o.file);i&&(o.complexityDelta=i)}}function Gt(e){if(typeof e=="string")return e;let t=ke();if(!t)throw new Error("--base used without a ref but no default branch found (looked for main, master). Specify the base ref explicitly, e.g. --base <branch-or-sha>.");return t}function zt(e){if(e.paths&&e.paths.length>0&&e.since)throw new Error("--paths and --since are mutually exclusive \u2014 pick one path-source.");return e.paths&&e.paths.length>0?{paths:new Set(e.paths),source:`--paths (${e.paths.length} file${e.paths.length===1?"":"s"})`}:e.since?{paths:ie(e.since),source:`--since ${e.since}`}:null}function Vt(e,t){let n=e.composite?.tierCounts.hot??0,o=e.composite?.totalEntries??0,i=new Set;for(let a of Object.values(e.rankings))for(let f of a.entries)i.add(f.file);for(let a of e.composite?.entries??[])i.add(a.file);for(let a of Object.values(e.rankings))a.entries=a.entries.filter(f=>t.paths.has(f.file)),a.showing=a.entries.length;e.composite&&(e.composite.entries=e.composite.entries.filter(a=>t.paths.has(a.file)),e.composite.showing=e.composite.entries.length),e.reawakened&&(e.reawakened.entries=e.reawakened.entries.filter(a=>t.paths.has(a.file)),e.reawakened.entries.length===0&&(e.reawakened=void 0));let s=0,r=0,l=0;for(let a of e.composite?.entries??[])a.tier==="hot"?s++:a.tier==="warm"?r++:l++;let u=[...t.paths].filter(a=>!i.has(a)).sort(),c=o>0?`${Math.round(n/o*100)}%`:"n/a",p=s+r+l;process.stderr.write(`path filter ${t.source}: ${s} HOT, ${r} WARM, ${l} COOL of ${p} ranked file${p===1?"":"s"}; ${u.length} not in any ranking. Corpus base rate: ${c} HOT. | ||
| `),e.pathFilter={source:t.source,paths:[...t.paths].sort(),rankedCount:p,hotCount:s,warmCount:r,coolCount:l,notRanked:u,corpusHotRate:o>0?n/o:null}}function qt(e){if(e==="commits"||e==="lines")return e;throw new Error(`Unknown --churn-mode '${e}'. Expected 'commits' or 'lines'.`)}function Jt(e){fe(),de();let t=Je(),n=parseInt(e.top,10),o=parseInt(e.months,10),i=qt(e.churnMode),s=Ke(o),r=V(e.exclude),l=N(r);if(e.fullDelta&&e.base===void 0)throw new Error("--full-delta requires --base. Specify a base ref, e.g. --base main --full-delta.");let u=zt(e);if(u&&e.base!==void 0)throw new Error('--paths/--since and --base are mutually exclusive \u2014 they answer different questions. --paths gives corpus-anchored tiers ("are MY changes hot in the codebase?"); --base re-ranks within the changed set ("of my changes, which is hottest?").');let c,p,a;if(e.base!==void 0){let x=Gt(e.base),h=ie(x);if(h.size===0){process.stderr.write(`No files changed since ${x}. | ||
| `);let b={generated:new Date().toISOString(),guide:qe,churnWindow:`${o} months`,churnMode:i,historyCoverage:s,delta:{base:x,head:"HEAD",changedFiles:[]},rankings:{},corpus:{fileCount:0,totalComplexity:0,filtered:t}};e.format==="table"?process.stdout.write(`${le(b)} | ||
| `):e.format==="compact"?process.stdout.write(`${ue(b)} | ||
| `):process.stdout.write(`${JSON.stringify(b,null,2)} | ||
| `);return}if(c={base:x,head:"HEAD",changedFiles:[...h].sort()},e.fullDelta)try{let b=B(x,v=>se({months:o,excludes:r,cwd:v,churnMode:i}));a=L(l,o,0,void 0,i);let S={files:l,rankings:a.rankings,skipped:a.skipped,composite:a.composite,reawakened:a.reawakened,corpus:a.corpus};p=ae(x,"HEAD",b,S)}catch(b){let S=b instanceof Error?b.message:String(b);process.stderr.write(`warning: full-delta unavailable (${S}). Falling back to filtered rankings. | ||
| `),l=l.filter(v=>h.has(v.file)),a=void 0,c.fallback={from:"full-delta",reason:S}}else l=l.filter(b=>h.has(b.file))}let{rankings:f,skipped:g,composite:w,corpus:k,reawakened:m}=a?De(a,n):L(l,o,n,void 0,i);if(c&&p===void 0){let x=new Map,h=[];for(let b of l)x.set(b.file,b.complexity),h.push(b.file);try{let b=$e(c.base,h,x);Ut(f,w,b)}catch(b){let S=b instanceof Error?b.message:String(b);process.stderr.write(`warning: complexity delta unavailable (${S}). Falling back to filtered rankings without per-file deltas. | ||
| `)}}let d={generated:new Date().toISOString(),guide:qe,churnWindow:`${o} months`,churnMode:i,historyCoverage:s,delta:c,fullDelta:p,rankings:f,skipped:Object.keys(g).length>0?g:void 0,composite:w,reawakened:m.entries.length>0?m:void 0,corpus:{...k,filtered:t}};u&&Vt(d,u),e.format==="compact"?process.stdout.write(`${ue(d)} | ||
| `):e.format==="table"?(process.stdout.write(`${le(d)} | ||
| `),w.entries.length>0&&process.stdout.write(` | ||
| ${je(w)} | ||
| `)):process.stdout.write(`${JSON.stringify(d,null,2)} | ||
| `)}function Gt(e){pe(),fe();let t=parseInt(e.top,10),n=parseInt(e.months,10),o=parseInt(e.minCochanges,10),i=Ge(n),s=V(e.exclude),r=H(s),l=P(n),u=ee(n,s),c=new Map;for(let x of r)c.set(x.file,x.complexity);let p=re(),a=Re(u,l,c,o,p),f=t>0?a.slice(0,t):a,g={hot:0,warm:0,cool:0};for(let x of a)g[x.tier]++;let y=a.reduce((x,h)=>x+h.couplingScore,0),k=ve(u,o,l,p),m=t>0?k.slice(0,t):k,d={generated:new Date().toISOString(),guide:At,churnWindow:`${n} months`,historyCoverage:i,minCochanges:o,totalScore:y,tierCounts:g,tiers:g,totalCouplings:a.length,showing:f.length,couplings:f,sumOfCoupling:m.length>0?m:void 0,confidence:De(Oe(n))};e.format==="table"?process.stdout.write(`${He(d)} | ||
| `)}function Kt(e){fe(),de();let t=parseInt(e.top,10),n=parseInt(e.months,10),o=parseInt(e.minCochanges,10),i=Ke(n),s=V(e.exclude),r=N(s),l=W(n),u=ee(n,s),c=new Map;for(let x of r)c.set(x.file,x.complexity);let p=re(),a=ve(u,l,c,o,p),f=t>0?a.slice(0,t):a,g={hot:0,warm:0,cool:0};for(let x of a)g[x.tier]++;let w=a.reduce((x,h)=>x+h.couplingScore,0),k=Re(u,o,l,p),m=t>0?k.slice(0,t):k,d={generated:new Date().toISOString(),guide:jt,churnWindow:`${n} months`,historyCoverage:i,minCochanges:o,totalScore:w,tierCounts:g,tiers:g,totalCouplings:a.length,showing:f.length,couplings:f,sumOfCoupling:m.length>0?m:void 0,confidence:Me(Te(n))};e.format==="table"?process.stdout.write(`${Ae(d)} | ||
| `):e.format==="compact"?process.stdout.write(`${We(d)} | ||
| `):process.stdout.write(`${JSON.stringify(d,null,2)} | ||
| `)}function zt(){try{if(Pe("git",["diff","--quiet","HEAD"],{stdio:["ignore","ignore","ignore"]}).status!==0)return!1;let t=Pe("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8"});return t.status!==0?!1:t.stdout.trim().length===0}catch{return!1}}function Vt(e){try{if(e.base==="HEAD"&&zt())return;let t=parseInt(e.months,10),n=V(),o=H(n),i=j(e.base,f=>se({months:t,excludes:n,cwd:f})),s=L(o,t,0),r={files:o,rankings:s.rankings,skipped:s.skipped,composite:s.composite,reawakened:s.reawakened,corpus:s.corpus},l=ae(e.base,"HEAD",i,r),u=e.significantPercent!==void 0?parseFloat(e.significantPercent):void 0,c=new Set;try{let f=Tt(`git diff --name-only ${e.base}`,{maxBuffer:52428800,stdio:["pipe","pipe","pipe"]}).toString().split(` | ||
| `);for(let g of f){let y=g.trim();y&&c.add(y)}}catch{}let p=[];if(c.size>0){let f=P(t),g=ee(t,n);p=Ce(g,f,c)}let a=_e(l,{significantPercentChange:u!==void 0&&!Number.isNaN(u)?u:void 0,reminders:p});if(a===null)return;process.stdout.write(JSON.stringify(We(a,e.event)))}catch{}}function qt(){if(z(".obsignore"))throw new Error(".obsignore already exists. Remove it first to regenerate.");if(z(".obsceneignore"))throw new Error(".obsceneignore already exists. Remove it first to regenerate.");let e=Ee(),t=$e(e);It(".obsignore",t);let n=Z.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: | ||
| `)}function Yt(){try{if(ze("git",["diff","--quiet","HEAD"],{stdio:["ignore","ignore","ignore"]}).status!==0)return!1;let t=ze("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8"});return t.status!==0?!1:t.stdout.trim().length===0}catch{return!1}}function Xt(e){try{if(e.base==="HEAD"&&Yt())return;let t=parseInt(e.months,10),n=V(),o=N(n),i=B(e.base,f=>se({months:t,excludes:n,cwd:f})),s=L(o,t,0),r={files:o,rankings:s.rankings,skipped:s.skipped,composite:s.composite,reawakened:s.reawakened,corpus:s.corpus},l=ae(e.base,"HEAD",i,r),u=e.significantPercent!==void 0?parseFloat(e.significantPercent):void 0,c=new Set;try{let f=At(`git diff --name-only ${e.base}`,{maxBuffer:52428800,stdio:["pipe","pipe","pipe"]}).toString().split(` | ||
| `);for(let g of f){let w=g.trim();w&&c.add(w)}}catch{}let p=[];if(c.size>0){let f=W(t),g=ee(t,n);p=xe(g,f,c)}let a=Ue(l,{significantPercentChange:u!==void 0&&!Number.isNaN(u)?u:void 0,reminders:p});if(a===null)return;process.stdout.write(JSON.stringify(Ge(a,e.event)))}catch{}}function Qt(){if(z(".obsignore"))throw new Error(".obsignore already exists. Remove it first to regenerate.");if(z(".obsceneignore"))throw new Error(".obsceneignore already exists. Remove it first to regenerate.");let e=Ee(),t=Oe(e);Lt(".obsignore",t);let n=Z.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: | ||
| `);for(let o of e)process.stderr.write(` ${o.pattern.padEnd(20)} ${o.comment} | ||
@@ -48,0 +57,0 @@ `)}else process.stderr.write(` (no project-specific patterns detected) |
+1
-1
| { | ||
| "name": "@wbern/obscene", | ||
| "version": "2.10.0", | ||
| "version": "2.11.0", | ||
| "description": "Identify hotspot files — complex code that changes frequently. Churn × complexity analysis for any git repo.", | ||
@@ -5,0 +5,0 @@ "type": "module", |
Sorry, the diff of this file is too big to display
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
128947
1.86%242
6.61%