@codeledger/core-engine 0.6.2 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/codeledger-core.cjs +13 -13
- package/package.json +3 -3
package/bin/codeledger-core.cjs
CHANGED
|
@@ -4,20 +4,20 @@
|
|
|
4
4
|
/* Free for individual use. Commercial use requires a license. */
|
|
5
5
|
/* No network calls. No telemetry. Runs entirely local. */
|
|
6
6
|
/* Run with --license or --explain-architecture for details. */
|
|
7
|
-
"use strict";var He=require("node:fs");var Q=new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","is","it","that","this","be","as","are","was","were","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","not","no","if","then","else","when","up","out","so","than","too","very","just","about","into","over","after","before","between","under","above","all","each","every","both","few","more","most","some","any","add","fix","update","change","make","use","get","set","find","check","look","see","know","think","want","try","run","show","help","work","take","give","tell","call","go","come","keep","let","begin","start","end","stop","ready","live","done","good","new","old","big","small"]),Ze=new Set(["test","tests","testing","build","lint","debug","deploy","review","audit","evaluate","assess","analyze","examine","application","app","project","codebase","code","repo"]),Ye=["ready for","go live","production ready","readiness","find out","evaluate","assess","audit","review the","status of","state of","quality of","health of","overall","end to end","full","comprehensive"].map(e=>new RegExp(`\\b${e}\\b`)),Xe=["replace","everywhere","all files","every file","migrate","files that import","files that use","across all","update all","rename all"].map(e=>new RegExp(`\\b${e}\\b`)),H=50,Me=[".sql",".proto",".prisma",".graphql",".gql"],Re=["openapi","swagger","schema","migrations"],Je=new Set(["config","configuration","script","dependency","dependencies","setup","package","tsconfig","eslint","prettier","webpack","vite","rollup"]),Ve=new Set(["test","tests","testing","ci","pipeline","failing","pass","coverage","jest","vitest","mocha","cypress","playwright"]),Qe=new Set(["schema","api","endpoint","migration","contract","proto","graphql","openapi","swagger","prisma","database"]),et=["package.json","tsconfig","pnpm-workspace",".env.example","eslint","prettier","webpack.config","vite.config","rollup.config"],tt=["vitest.config","jest.config",".github/workflows","ci.yml","ci.yaml","test-setup","test-helper","test-utils",".test.ts",".test.tsx",".test.js",".spec.ts",".spec.tsx",".spec.js","__tests__/"],st=/\b(?:and then|and also|and|then|also|plus)\b|[;,]/i;function K(e){let t=e.toLowerCase(),o=Ye.some(r=>r.test(t))?new Set([...Q,...Ze]):Q,s=t.split(/[^\p{L}\p{N}]+/u).filter(r=>r.length>1&&!o.has(r));return[...new Set(s)]}function Ae(e){let t=e.split(st).map(o=>o.trim()).filter(o=>o.length>0);if(t.length<=1)return[K(e)];let n=[];for(let o of t){let s=K(o);s.length>0&&n.push(s)}return n.length>0?n:[K(e)]}function Le(e,t,n){let o=new Map;for(let s of e){let r=0;for(let c of t.files)(c.path.toLowerCase().includes(s)||c.content_keywords?.some(f=>f===s||f===s+"s"||s===f+"s"))&&r++;if(r===0){o.set(s,0);continue}let i=1/Math.sqrt(Math.max(1,r));s.length<=2&&(i=Math.min(i,.35)),r>n&&(i=Math.min(i,.35)),i=Math.max(.35,Math.min(1,i)),o.set(s,i)}return o}function nt(e){let t=e.toLowerCase();return Xe.some(n=>n.test(t))}function ot(e,t){let n=[];for(let o of t.files){let i=(o.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/);for(let c of e)if(i.some(l=>l===c||l===c+"s"||c===l+"s")){n.push(o.path);break}}return n}function ee(e,t,n,o){let s=new Set,r=new Set,i=new Set,c=o??n.default_scope??Ne(e,t),f=Ae(e),l=[...new Set(f.flat())],p=Le(l,t,n.hot_zone_count),h=c?t.files.filter(x=>c.some(y=>x.path.startsWith(y))):t.files;for(let x of f)for(let y of h){if(s.has(y.path))continue;let v=y.path.toLowerCase();for(let m of x){if(v.includes(m)){s.add(y.path);break}if(y.content_keywords?.some(C=>C===m||C===m+"s"||m===C+"s")){s.add(y.path);break}}}let d=(n.default_budget.max_files??1/0)<=15,g=new Set(h.map(x=>x.path)),u=t.churn.slice(0,n.hot_zone_count);for(let x of u)g.has(x.path)&&(d&&!s.has(x.path)||s.add(x.path));let a=c?g:void 0,w=[...s];for(let x of w)it(x,t,s,n.dependency_depth,n.dependency_cap_per_seed,a);if(nt(e)){let x=ot(l,t);for(let y of x){if(s.size>=H)break;let v=t.dep_graph.dependents[y]??[];for(let m of v){if(s.size>=H)break;a&&!a.has(m)||(s.add(m),r.add(m))}if(s.size<H)for(let m of v){if(s.size>=H)break;if(a&&!a.has(m))continue;let C=t.dep_graph.dependents[m]??[];for(let O of C){if(s.size>=H)break;a&&!a.has(O)||(s.add(O),r.add(O))}}}}let b=[...s];for(let x of t.test_map)b.includes(x.source_file)&&(!a||a.has(x.test_file))&&s.add(x.test_file),b.includes(x.test_file)&&(!a||a.has(x.source_file))&&s.add(x.source_file);let E=rt(t.files,n.contract_patterns);if(E.length>0&&s.size>0){let x=new Set([...s].map(y=>y.split("/").slice(0,-1).join("/")));for(let y of E){let v=y.split("/").slice(0,-1).join("/");(x.has(v)||[...x].some(C=>C.startsWith(v+"/")||v.startsWith(C+"/")))&&s.add(y)}}let k=new Set(l),R=[...Je].some(x=>k.has(x)),M=[...Ve].some(x=>k.has(x)),L=[...Qe].some(x=>k.has(x));if(R||M||L){let x=L?new Set([...s].map(y=>y.split("/").slice(0,-1).join("/"))):void 0;for(let y of h){if(s.has(y.path))continue;let v=y.path.toLowerCase();if(R&&et.some(m=>v.includes(m))){s.add(y.path),i.add(y.path);continue}if(M&&tt.some(m=>v.includes(m))){s.add(y.path),i.add(y.path);continue}if(L&&x){let m=y.extension.toLowerCase(),C=v.split("/").pop()??"";if(Me.includes(m)||Re.some(F=>C.startsWith(F))){let F=y.path.split("/").slice(0,-1).join("/");(x.has(F)||[...x].some(j=>j.startsWith(F+"/")||F.startsWith(j+"/")))&&(s.add(y.path),i.add(y.path))}}}}return{candidates:s,tokenWeights:p,fanoutFiles:r,surfaceFiles:i}}function rt(e,t){let n=[];for(let o of e){let s=o.extension.toLowerCase(),r=o.path.toLowerCase();if(Me.includes(s)){n.push(o.path);continue}if(t?.some(c=>r.includes(c.toLowerCase()))){n.push(o.path);continue}let i=r.split("/").pop()??"";Re.some(c=>i.startsWith(c))&&n.push(o.path)}return n}function it(e,t,n,o,s,r){let i=[e],c=0;for(let f=0;f<o&&c<s;f++){let l=[];for(let p of i){let h=t.dep_graph.imports[p]??[];for(let g of h)r&&!r.has(g)||!n.has(g)&&c<s&&(n.add(g),l.push(g),c++);let d=t.dep_graph.dependents[p]??[];for(let g of d)r&&!r.has(g)||!n.has(g)&&c<s&&(n.add(g),l.push(g),c++)}i=l}}function Ne(e,t){let n=e.toLowerCase(),o=/[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)+/g,s=(n.match(o)??[]).filter(f=>!Q.has(f));if(s.length===0)return;let r=new Map;for(let f of t.files){let l=f.path.split("/");for(let p=0;p<l.length-1;p++){let h=l[p];if(!h)continue;let d=h.toLowerCase(),g=l.slice(0,p+1).join("/")+"/";r.has(d)||r.set(d,new Set),r.get(d).add(g)}}let i=new Set;for(let f of s){let l=r.get(f);if(!(!l||l.size===0))for(let p of l)i.add(p)}if(i.size===0)return;let c=[...i].filter(f=>![...i].some(l=>l!==f&&l.startsWith(f)));return c.length>0?c:void 0}var at=["auth","login","logout","session","oauth","jwt","token","crypt","hash","secret","password","credential","validat","sanitiz","escap","query","sql","database","migration","route","controller","endpoint","middleware","permission","rbac","acl","role","csrf","cors","helmet","rate-limit"],ct=new Set(["security","secure","audit","vulnerability","vulnerabilities","injection","xss","csrf","auth","authentication","authorization","encrypt","decrypt","hash","password","credential","token","sanitize","escape","validate","permission","privilege"]);function te(e){let n=e.path.toLowerCase().split("/"),o=[];for(let r of n){let i=r.replace(/\.\w+$/,"");for(let c of i.split(/[-_]/))c.length>0&&o.push(c)}return o.some(r=>at.some(i=>r===i||r===i+"s"||r.startsWith(i)))?1:0}function se(e){return e.some(t=>ct.has(t))}var lt=["error","exception","validation","validator","schema"],pt=3,dt=.5,ut=.25;function ft(e){return(e.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/).some(r=>lt.some(i=>r===i||r===i+"s"))?1:0}function De(e,t,n,o,s,r){let i=e.path.toLowerCase(),c=e.content_keywords??[],l=(i.split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/),p=0,h=0,d=!1;for(let T of t){let W=s?.get(T)??1;if(W!==0)if(h+=W,i.includes(T)){let P=l.some(U=>U===T||U===T+"s"||T===U+"s");p+=W*(P?pt:1)}else c.some(P=>P===T||P===T+"s"||T===P+"s")&&(p+=W*dt,d=!0)}let g=h>0?Math.min(1,p/(h*1.5)):0,u=n.dep_graph.imports[e.path]?.length??0,a=n.dep_graph.dependents[e.path]?.length??0,w=u+a,b=Math.max(1,...n.files.map(T=>{let W=n.dep_graph.imports[T.path]?.length??0,P=n.dep_graph.dependents[T.path]?.length??0;return W+P})),E=w/b,k=n.churn.find(T=>T.path===e.path),R=k?.time_decayed_score??0,M=k?.days_since_last_touch??999,L=M<=7?1:M<=14?.8:M<=30?.5:M<=60?.2:0,x=n.test_map.filter(T=>T.source_file===e.path||T.test_file===e.path),y=/[./](?:test|spec)\.[^/]+$/.test(i)||i.includes("__tests__/"),v=0;x.length>0?(v=.5,v+=Math.min(.5,x.length*.25)):y&&(v=.4);let m=Math.max(0,Math.min(1,e.lines/1e3)),C=o?.success_files.has(e.path)?1:0,O=o?.fail_files.has(e.path)?1:0,F=ft(e),$=r?.has(e.path)?1:0,j=te(e);return{keyword:g,centrality:E,churn:R,recent_touch:L,test_relevance:v,size_penalty:m,success_prior:C,fail_prior:O,error_infrastructure:F,branch_changed:$,security_surface:j,_hasContentMatch:d}}function Oe(e){let t;return e.keyword>=.3?t=1:e.keyword>0?t=.5:e.test_relevance>0||e.centrality>.1?t=.4:t=0,t===1?e:{...e,churn:e.churn*t,recent_touch:e.recent_touch*t}}function Fe(e,t){return e.keyword*t.keyword+e.centrality*t.centrality+e.churn*t.churn+e.recent_touch*t.recent_touch+e.test_relevance*t.test_relevance-e.size_penalty*t.size_penalty+e.success_prior*t.success_prior-e.fail_prior*t.fail_prior+e.error_infrastructure*(t.error_infrastructure??.08)+e.branch_changed*(t.branch_changed??0)+(e.security_surface??0)*(t.security_surface??0)}function Ie(e){let t=[];return e.keyword>0&&(t.push("keyword_match"),e._hasContentMatch&&t.push("content_match")),e.centrality>.3&&t.push("dependency_neighbor"),e.churn>.3&&t.push("high_churn"),e.recent_touch>.5&&t.push("recent_touch"),e.test_relevance>0&&t.push("test_relevant"),e.size_penalty>.5&&t.push("size_penalty"),e.success_prior>0&&t.push("success_prior"),e.error_infrastructure>0&&t.push("error_infrastructure"),e.branch_changed>0&&t.push("branch_changed"),(e.security_surface??0)>0&&t.push("security_surface"),t}function ne(e,t,n,o,s,r,i,c,f){let l=new Map(n.files.map(h=>[h.path,h])),p=[];for(let h of e){let d=l.get(h);if(!d)continue;let g=De(d,t,n,s,r,c),a={...Oe(g),_hasContentMatch:g._hasContentMatch,branch_changed:g.branch_changed,security_surface:g.security_surface},w=Fe(a,o),b=Ie(a);i?.has(h)&&(w+=ut,b.includes("dependent_neighbor")||b.push("dependent_neighbor")),f?.has(h)&&a.keyword===0&&(w=0,b.length=0,b.push("surface_auto_include")),p.push({path:h,score:w,features:a,reasons:b})}return p.sort((h,d)=>d.score-h.score),p}function ht(e){return e.some(t=>t.reasons.includes("keyword_match")||t.reasons.includes("test_relevant")||t.reasons.includes("temporal_affinity"))}function oe(e,t,n,o){return!!(t.max_files&&e.files.length>=t.max_files||t.tokens&&e.totalTokens>=t.tokens||o>0&&e.cumulativeScore/o>=n&&ht(e.files))}var Z=require("node:fs"),Pe=require("node:path"),mt=10*1024*1024;function G(e,t,n,o,s){let r=(0,Pe.join)(e,t),i;try{let a=(0,Z.statSync)(r).size;if(a>mt)return{content:`// File too large (${Math.round(a/1024)}KB), skipped`,spans:null,lineCount:1};i=(0,Z.readFileSync)(r,"utf-8")}catch{return{content:"",spans:null,lineCount:0}}let c=i.split(`
|
|
8
|
-
`);if(
|
|
9
|
-
// ... (lines ${
|
|
10
|
-
`),
|
|
11
|
-
`),
|
|
12
|
-
`).length,
|
|
13
|
-
`),o=[],s=0;for(;s<n.length;){let r=n[s],i=r.trim();if(Mt(i)){if(i.includes("{")&&!i.includes("}")){let
|
|
7
|
+
"use strict";var qe=require("node:fs");var Q=new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","is","it","that","this","be","as","are","was","were","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","not","no","if","then","else","when","up","out","so","than","too","very","just","about","into","over","after","before","between","under","above","all","each","every","both","few","more","most","some","any","add","fix","update","change","make","use","get","set","find","check","look","see","know","think","want","try","run","show","help","work","take","give","tell","call","go","come","keep","let","begin","start","end","stop","ready","live","done","good","new","old","big","small"]),Ye=new Set(["test","tests","testing","build","lint","debug","deploy","review","audit","evaluate","assess","analyze","examine","application","app","project","codebase","code","repo"]),Je=["ready for","go live","production ready","readiness","find out","evaluate","assess","audit","review the","status of","state of","quality of","health of","overall","end to end","full","comprehensive"].map(e=>new RegExp(`\\b${e}\\b`)),Ve=["replace","everywhere","all files","every file","migrate","files that import","files that use","across all","update all","rename all"].map(e=>new RegExp(`\\b${e}\\b`)),H=50,Re=[".sql",".proto",".prisma",".graphql",".gql"],Ae=["openapi","swagger","schema","migrations"],Qe=new Set(["config","configuration","script","dependency","dependencies","setup","package","tsconfig","eslint","prettier","webpack","vite","rollup"]),et=new Set(["test","tests","testing","ci","pipeline","failing","pass","coverage","jest","vitest","mocha","cypress","playwright"]),tt=new Set(["schema","api","endpoint","migration","contract","proto","graphql","openapi","swagger","prisma","database"]),st=["package.json","tsconfig","pnpm-workspace",".env.example","eslint","prettier","webpack.config","vite.config","rollup.config"],nt=["vitest.config","jest.config",".github/workflows","ci.yml","ci.yaml","test-setup","test-helper","test-utils",".test.ts",".test.tsx",".test.js",".spec.ts",".spec.tsx",".spec.js","__tests__/"],ot=/\b(?:and then|and also|and|then|also|plus)\b|[;,]/i;function K(e){let t=e.toLowerCase(),o=Je.some(r=>r.test(t))?new Set([...Q,...Ye]):Q,s=t.split(/[^\p{L}\p{N}]+/u).filter(r=>r.length>1&&!o.has(r));return[...new Set(s)]}function Me(e){let t=e.split(ot).map(o=>o.trim()).filter(o=>o.length>0);if(t.length<=1)return[K(e)];let n=[];for(let o of t){let s=K(o);s.length>0&&n.push(s)}return n.length>0?n:[K(e)]}function Le(e,t,n){let o=new Map;for(let s of e){let r=0;for(let a of t.files)(a.path.toLowerCase().includes(s)||a.content_keywords?.some(d=>d===s||d===s+"s"||s===d+"s"))&&r++;if(r===0){o.set(s,0);continue}let i=1/Math.sqrt(Math.max(1,r));s.length<=2&&(i=Math.min(i,.35)),r>n&&(i=Math.min(i,.35)),i=Math.max(.35,Math.min(1,i)),o.set(s,i)}return o}function rt(e){let t=e.toLowerCase();return Ve.some(n=>n.test(t))}function it(e,t){let n=[];for(let o of t.files){let i=(o.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/);for(let a of e)if(i.some(c=>c===a||c===a+"s"||a===c+"s")){n.push(o.path);break}}return n}function ee(e,t,n,o){let s=new Set,r=new Set,i=new Set,a=o??n.default_scope??Ne(e,t),d=Me(e),c=[...new Set(d.flat())],p=Le(c,t,n.hot_zone_count),u=a?t.files.filter(x=>a.some(y=>x.path.startsWith(y))):t.files;for(let x of d)for(let y of u){if(s.has(y.path))continue;let v=y.path.toLowerCase();for(let m of x){if(v.includes(m)){s.add(y.path);break}if(y.content_keywords?.some(C=>C===m||C===m+"s"||m===C+"s")){s.add(y.path);break}}}let f=(n.default_budget.max_files??1/0)<=15,_=new Set(u.map(x=>x.path)),h=t.churn.slice(0,n.hot_zone_count);for(let x of h)_.has(x.path)&&(f&&!s.has(x.path)||s.add(x.path));let l=a?_:void 0,w=[...s];for(let x of w)ct(x,t,s,n.dependency_depth,n.dependency_cap_per_seed,l);if(rt(e)){let x=it(c,t);for(let y of x){if(s.size>=H)break;let v=t.dep_graph.dependents[y]??[];for(let m of v){if(s.size>=H)break;l&&!l.has(m)||(s.add(m),r.add(m))}if(s.size<H)for(let m of v){if(s.size>=H)break;if(l&&!l.has(m))continue;let C=t.dep_graph.dependents[m]??[];for(let O of C){if(s.size>=H)break;l&&!l.has(O)||(s.add(O),r.add(O))}}}}let b=[...s];for(let x of t.test_map)b.includes(x.source_file)&&(!l||l.has(x.test_file))&&s.add(x.test_file),b.includes(x.test_file)&&(!l||l.has(x.source_file))&&s.add(x.source_file);let E=at(t.files,n.contract_patterns);if(E.length>0&&s.size>0){let x=new Set([...s].map(y=>y.split("/").slice(0,-1).join("/")));for(let y of E){let v=y.split("/").slice(0,-1).join("/");(x.has(v)||[...x].some(C=>C.startsWith(v+"/")||v.startsWith(C+"/")))&&s.add(y)}}let k=new Set(c),A=[...Qe].some(x=>k.has(x)),R=[...et].some(x=>k.has(x)),L=[...tt].some(x=>k.has(x));if(A||R||L){let x=L?new Set([...s].map(y=>y.split("/").slice(0,-1).join("/"))):void 0;for(let y of u){if(s.has(y.path))continue;let v=y.path.toLowerCase();if(A&&st.some(m=>v.includes(m))){s.add(y.path),i.add(y.path);continue}if(R&&nt.some(m=>v.includes(m))){s.add(y.path),i.add(y.path);continue}if(L&&x){let m=y.extension.toLowerCase(),C=v.split("/").pop()??"";if(Re.includes(m)||Ae.some(F=>C.startsWith(F))){let F=y.path.split("/").slice(0,-1).join("/");(x.has(F)||[...x].some(z=>z.startsWith(F+"/")||F.startsWith(z+"/")))&&(s.add(y.path),i.add(y.path))}}}}return{candidates:s,tokenWeights:p,fanoutFiles:r,surfaceFiles:i}}function at(e,t){let n=[];for(let o of e){let s=o.extension.toLowerCase(),r=o.path.toLowerCase();if(Re.includes(s)){n.push(o.path);continue}if(t?.some(a=>r.includes(a.toLowerCase()))){n.push(o.path);continue}let i=r.split("/").pop()??"";Ae.some(a=>i.startsWith(a))&&n.push(o.path)}return n}function ct(e,t,n,o,s,r){let i=[e],a=0;for(let d=0;d<o&&a<s;d++){let c=[];for(let p of i){let u=t.dep_graph.imports[p]??[];for(let _ of u)r&&!r.has(_)||!n.has(_)&&a<s&&(n.add(_),c.push(_),a++);let f=t.dep_graph.dependents[p]??[];for(let _ of f)r&&!r.has(_)||!n.has(_)&&a<s&&(n.add(_),c.push(_),a++)}i=c}}function Ne(e,t){let n=e.toLowerCase(),o=/[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)+/g,s=(n.match(o)??[]).filter(d=>!Q.has(d));if(s.length===0)return;let r=new Map;for(let d of t.files){let c=d.path.split("/");for(let p=0;p<c.length-1;p++){let u=c[p];if(!u)continue;let f=u.toLowerCase(),_=c.slice(0,p+1).join("/")+"/";r.has(f)||r.set(f,new Set),r.get(f).add(_)}}let i=new Set;for(let d of s){let c=r.get(d);if(!(!c||c.size===0))for(let p of c)i.add(p)}if(i.size===0)return;let a=[...i].filter(d=>![...i].some(c=>c!==d&&c.startsWith(d)));return a.length>0?a:void 0}var lt=["auth","login","logout","session","oauth","jwt","token","crypt","hash","secret","password","credential","validat","sanitiz","escap","query","sql","database","migration","route","controller","endpoint","middleware","permission","rbac","acl","role","csrf","cors","helmet","rate-limit"],pt=new Set(["security","secure","audit","vulnerability","vulnerabilities","injection","xss","csrf","auth","authentication","authorization","encrypt","decrypt","hash","password","credential","token","sanitize","escape","validate","permission","privilege"]);function te(e){let n=e.path.toLowerCase().split("/"),o=[];for(let r of n){let i=r.replace(/\.\w+$/,"");for(let a of i.split(/[-_]/))a.length>0&&o.push(a)}return o.some(r=>lt.some(i=>r===i||r===i+"s"||r.startsWith(i)))?1:0}function se(e){return e.some(t=>pt.has(t))}var dt=["error","exception","validation","validator","schema"],ft=3,ut=.5,ht=.25;function mt(e){return(e.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/).some(r=>dt.some(i=>r===i||r===i+"s"))?1:0}function De(e,t,n,o,s,r){let i=e.path.toLowerCase(),a=e.content_keywords??[],c=(i.split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/),p=0,u=0,f=!1;for(let T of t){let W=s?.get(T)??1;if(W!==0)if(u+=W,i.includes(T)){let P=c.some(U=>U===T||U===T+"s"||T===U+"s");p+=W*(P?ft:1)}else a.some(P=>P===T||P===T+"s"||T===P+"s")&&(p+=W*ut,f=!0)}let _=u>0?Math.min(1,p/(u*1.5)):0,h=n.dep_graph.imports[e.path]?.length??0,l=n.dep_graph.dependents[e.path]?.length??0,w=h+l,b=Math.max(1,...n.files.map(T=>{let W=n.dep_graph.imports[T.path]?.length??0,P=n.dep_graph.dependents[T.path]?.length??0;return W+P})),E=w/b,k=n.churn.find(T=>T.path===e.path),A=k?.time_decayed_score??0,R=k?.days_since_last_touch??999,L=R<=7?1:R<=14?.8:R<=30?.5:R<=60?.2:0,x=n.test_map.filter(T=>T.source_file===e.path||T.test_file===e.path),y=/[./](?:test|spec)\.[^/]+$/.test(i)||i.includes("__tests__/"),v=0;x.length>0?(v=.5,v+=Math.min(.5,x.length*.25)):y&&(v=.4);let m=Math.max(0,Math.min(1,e.lines/1e3)),C=o?.success_files.has(e.path)?1:0,O=o?.fail_files.has(e.path)?1:0,F=mt(e),$=r?.has(e.path)?1:0,z=te(e);return{keyword:_,centrality:E,churn:A,recent_touch:L,test_relevance:v,size_penalty:m,success_prior:C,fail_prior:O,error_infrastructure:F,branch_changed:$,security_surface:z,_hasContentMatch:f}}function Oe(e){let t;return e.keyword>=.3?t=1:e.keyword>0?t=.5:e.test_relevance>0||e.centrality>.1?t=.4:t=0,t===1?e:{...e,churn:e.churn*t,recent_touch:e.recent_touch*t}}function Fe(e,t){return e.keyword*t.keyword+e.centrality*t.centrality+e.churn*t.churn+e.recent_touch*t.recent_touch+e.test_relevance*t.test_relevance-e.size_penalty*t.size_penalty+e.success_prior*t.success_prior-e.fail_prior*t.fail_prior+e.error_infrastructure*(t.error_infrastructure??.08)+e.branch_changed*(t.branch_changed??0)+(e.security_surface??0)*(t.security_surface??0)}function Ie(e){let t=[];return e.keyword>0&&(t.push("keyword_match"),e._hasContentMatch&&t.push("content_match")),e.centrality>.3&&t.push("dependency_neighbor"),e.churn>.3&&t.push("high_churn"),e.recent_touch>.5&&t.push("recent_touch"),e.test_relevance>0&&t.push("test_relevant"),e.size_penalty>.5&&t.push("size_penalty"),e.success_prior>0&&t.push("success_prior"),e.error_infrastructure>0&&t.push("error_infrastructure"),e.branch_changed>0&&t.push("branch_changed"),(e.security_surface??0)>0&&t.push("security_surface"),t}function ne(e,t,n,o,s,r,i,a,d){let c=new Map(n.files.map(u=>[u.path,u])),p=[];for(let u of e){let f=c.get(u);if(!f)continue;let _=De(f,t,n,s,r,a),l={...Oe(_),_hasContentMatch:_._hasContentMatch,branch_changed:_.branch_changed,security_surface:_.security_surface},w=Fe(l,o),b=Ie(l);i?.has(u)&&(w+=ht,b.includes("dependent_neighbor")||b.push("dependent_neighbor")),d?.has(u)&&l.keyword===0&&(w=0,b.length=0,b.push("surface_auto_include")),p.push({path:u,score:w,features:l,reasons:b})}return p.sort((u,f)=>f.score-u.score),p}function _t(e){return e.some(t=>t.reasons.includes("keyword_match")||t.reasons.includes("test_relevant")||t.reasons.includes("temporal_affinity"))}function oe(e,t,n,o){return!!(t.max_files&&e.files.length>=t.max_files||t.tokens&&e.totalTokens>=t.tokens||o>0&&e.cumulativeScore/o>=n&&_t(e.files))}var Z=require("node:fs"),Pe=require("node:path"),gt=10*1024*1024;function G(e,t,n,o,s){let r=(0,Pe.join)(e,t),i;try{let l=(0,Z.statSync)(r).size;if(l>gt)return{content:`// File too large (${Math.round(l/1024)}KB), skipped`,spans:null,lineCount:1};i=(0,Z.readFileSync)(r,"utf-8")}catch{return{content:"",spans:null,lineCount:0}}let a=i.split(`
|
|
8
|
+
`);if(a.length<=o)return{content:i,spans:null,lineCount:a.length};let d=[],c=new Set;for(let l=0;l<a.length;l++){let w=a[l];if(yt(w)){let b=Math.max(0,l-1),E=Math.min(a.length-1,l+1);wt(w)&&(E=xt(a,l,20)),d.push({start_line:b+1,end_line:E+1,reason:"type_surface"});for(let k=b;k<=E;k++)c.add(k)}}for(let l=0;l<a.length;l++){let w=a[l];if(bt(w)&&!c.has(l)){let b=Math.max(0,l-1),E=Math.min(a.length-1,l+2);d.push({start_line:b+1,end_line:E+1,reason:"export_signature"});for(let k=b;k<=E;k++)c.add(k)}}for(let l=0;l<a.length;l++){let w=a[l].toLowerCase();for(let b of n)if(w.includes(b)){let E=Math.max(0,l-s),k=Math.min(a.length-1,l+s);d.push({start_line:E+1,end_line:k+1,reason:`keyword_match:${b}`});for(let A=E;A<=k;A++)c.add(A);break}}let p=[...c].sort((l,w)=>l-w),u=[],f=-2;for(let l of p)l>f+1&&u.push(`
|
|
9
|
+
// ... (lines ${f+2}\u2013${l} omitted) ...
|
|
10
|
+
`),u.push(a[l]),f=l;let _=u.join(`
|
|
11
|
+
`),h=St(d);return{content:_,spans:h,lineCount:p.length}}function yt(e){let n=e.trim().replace(/^export\s+(default\s+)?/,"").replace(/^declare\s+/,"");return n.startsWith("interface ")||n.startsWith("type ")||n.startsWith("enum ")||n.startsWith("function ")&&!n.includes("=>")||n.startsWith("abstract class ")||n.startsWith("class ")}function wt(e){let t=e.trim();return t.includes("{")&&!t.includes("}")}function xt(e,t,n){let o=0,s=Math.min(e.length-1,t+n);for(let r=t;r<=s;r++){let i=e[r];for(let a of i)a==="{"&&o++,a==="}"&&o--;if(o<=0&&r>t)return r}return s}function bt(e){let t=e.trim();return t.startsWith("export ")&&(t.includes("function ")||t.includes("class ")||t.includes("interface ")||t.includes("type ")||t.includes("const ")||t.includes("enum "))}function St(e){if(e.length===0)return[];let t=[...e].sort((o,s)=>o.start_line-s.start_line),n=[t[0]];for(let o=1;o<t.length;o++){let s=t[o],r=n[n.length-1];s.start_line<=r.end_line+1?(r.end_line=Math.max(r.end_line,s.end_line),r.reason=`${r.reason}+${s.reason}`):n.push({...s})}return n}var Be=require("node:crypto"),Ke=require("node:fs"),Ue=require("node:path");function re(e,t,n,o,s){let r=[],i=0;if(e.length===0)return{level:"low",score:0,reasons:["Empty bundle \u2014 no files matched"],envelope:{structural_coverage:0,test_presence:0,churn_recency:0,keyword_saturation:0,dependency_depth:0}};let a=e.slice(0,5),d=a.filter(h=>h.reasons.includes("keyword_match")),c=d.length/a.length;if(c>=.6?(i+=.35,r.push(`Strong keyword signal: ${d.length}/${a.length} top files match task keywords`)):c>0?(i+=.15,r.push(`Weak keyword signal: only ${d.length}/${a.length} top files match task keywords`)):r.push("No keyword matches in top 5 files \u2014 selection driven by churn/centrality"),e.length>=2){let h=e[0].score,l=e[1].score;h>0&&l>0&&((h-l)/h>=.3?(i+=.2,r.push("Clear top-ranked file with significant score gap")):i+=.1)}let p=e.reduce((h,l)=>h+l.reasons.length,0)/e.length;p>=2?(i+=.2,r.push("Files selected for multiple independent reasons")):p>=1.5&&(i+=.1),n>=3?i+=.15:n>=2?i+=.1:r.push("Task description has few discriminating keywords \u2014 consider being more specific"),e.filter(h=>!h.reasons.every(l=>l==="test_relevant")).length>=e.length*.5&&(i+=.1);let f;if(i>=.65?f="high":i>=.35?f="medium":f="low",f!=="high"){let h=vt(e,c,n);for(let l of h)r.push(l)}let _=kt(e,o,s);return{level:f,score:Math.round(i*100)/100,reasons:r,envelope:_}}function kt(e,t,n){let o=e.filter(c=>!c.is_stub&&!c.is_exemplar),s=0;if(t&&o.length>0){let c=new Set(o.map(u=>u.path)),p=0;for(let u of o){let f=t.dep_graph.imports[u.path]??[],_=t.dep_graph.dependents[u.path]??[];(f.some(l=>c.has(l))||_.some(l=>c.has(l)))&&p++}s=p/o.length}else o.length>0&&(s=e.some(p=>p.reasons.includes("dependency_neighbor")||p.reasons.includes("dependent_neighbor"))?.5:.2);let r=0;o.length>0&&(r=o.filter(p=>p.reasons.includes("test_relevant")).length/o.length);let i=0;o.length>0&&(i=o.filter(p=>p.reasons.includes("recent_touch")||p.reasons.includes("high_churn")).length/o.length);let a=0;if(n&&n.length>0&&o.length>0){let c=new Set;for(let p of n)for(let u of o)if(u.path.toLowerCase().includes(p)){c.add(p);break}a=c.size/n.length}else if(o.length>0){let c=o.filter(p=>p.reasons.includes("keyword_match")).length;a=Math.min(1,c/Math.max(1,o.length*.5))}let d=0;if(t&&o.length>0){let c=new Set(o.map(u=>u.path)),p=0;for(let u of o){let f=0,_=[u.path],h=new Set;for(let l=0;l<3;l++){let w=[];for(let b of _){if(h.has(b))continue;h.add(b);let E=t.dep_graph.imports[b]??[];for(let k of E)c.has(k)&&!h.has(k)&&(w.push(k),f=l+1)}if(w.length===0)break;_=w}p+=f}d=Math.min(1,p/o.length/3)}return{structural_coverage:q(s),test_presence:q(r),churn_recency:q(i),keyword_saturation:q(a),dependency_depth:q(d)}}function q(e){return Math.round(e*100)/100}function vt(e,t,n){let o=[];if(t===0){let r=e.slice(0,3).map(i=>{let a=i.path.split("/");return a[a.length-1]?.replace(/\.\w+$/,"")??i.path});r.length>0&&o.push(`Suggestion: try including file-specific keywords like "${r.join('", "')}" in your task`)}return n<=1&&o.push('Suggestion: use a more descriptive task \u2014 e.g., "fix JWT refresh in auth middleware" instead of "fix auth"'),e.every(r=>r.path.includes(".test.")||r.path.includes(".spec.")||r.path.includes("tests/"))&&e.length>0&&o.push("Suggestion: bundle contains only test files \u2014 add source file keywords to your task"),o}var ze=require("node:fs"),X=require("node:path");var Et={typescript:3.5,javascript:3.5,tsx:3.5,jsx:3.5,go:3.8,rust:4.2,c:3.8,cpp:4,java:4.5,kotlin:3.8,csharp:4.2,python:3.2,ruby:3,php:3.8,json:2.5,yaml:2.5,toml:2.5,xml:4,markdown:5,bash:3.5,shell:3.5,css:3,scss:3.2,sql:4,graphql:3,protobuf:3.5,prisma:3},Tt=4;function je(e,t){let n=Et[t.toLowerCase()]??Tt;return Math.ceil(e*n)}function I(e,t){let n=Rt(t);return je(e,n)}var Ct={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"jsx",".mjs":"javascript",".cjs":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".cs":"csharp",".rb":"ruby",".php":"php",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".xml":"xml",".md":"markdown",".mdx":"markdown",".sh":"bash",".bash":"bash",".css":"css",".scss":"scss",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".prisma":"prisma"};function Rt(e){return Ct[e.toLowerCase()]??"unknown"}function ie(e,t,n,o,s){let r=new Map;for(let c of t){let p=n.imports[c]??[];for(let u of p)t.has(u)||r.set(u,(r.get(u)??0)+1)}if(r.size===0)return[];let i=[...r.entries()].sort((c,p)=>p[1]-c[1]).slice(0,o),a=[],d=0;for(let[c]of i){let p=(0,X.join)(e,c),u;try{u=(0,ze.readFileSync)(p,"utf-8")}catch{continue}let f=At(u,c);if(!f)continue;let _=f.split(`
|
|
12
|
+
`).length,h=(0,X.extname)(c),l=I(_,h);if(d+l>s)continue;let w=["interface_stub"];a.push({path:c,score:0,reasons:w,excerpt_spans:null,content:f,token_estimate:l,is_stub:!0}),d+=l}return a}function At(e,t){let n=e.split(`
|
|
13
|
+
`),o=[],s=0;for(;s<n.length;){let r=n[s],i=r.trim();if(Mt(i)){if(i.includes("{")&&!i.includes("}")){let a=Nt(n,s);o.push(...a),s+=a.length;continue}o.push(r),s++;continue}if(Lt(i)){let a=Dt(n,s);o.push(a),s=Ot(n,s);continue}s++}return o.length===0?null:`// Interface stub (auto-generated by CodeLedger)
|
|
14
14
|
${o.join(`
|
|
15
|
-
`)}`}function Mt(e){let t=e.startsWith("export ")?e.slice(7).replace(/^default\s+/,""):null;return t?t.startsWith("interface ")||t.startsWith("type ")||t.startsWith("enum "):!1}function
|
|
16
|
-
`}return n||e[t]}function
|
|
17
|
-
`);for(let r=0;r<s.length;r++){let i=s[r],
|
|
18
|
-
`).length,
|
|
19
|
-
`),n=[],o=0;for(let r of t)for(let i of
|
|
15
|
+
`)}`}function Mt(e){let t=e.startsWith("export ")?e.slice(7).replace(/^default\s+/,""):null;return t?t.startsWith("interface ")||t.startsWith("type ")||t.startsWith("enum "):!1}function Lt(e){return e.startsWith("export ")?e.slice(7).replace(/^default\s+/,"").replace(/^async\s+/,"").startsWith("function "):!1}function Nt(e,t){let n=[],o=0;for(let s=t;s<e.length&&s<t+50;s++){let r=e[s];n.push(r);for(let i of r)i==="{"&&o++,i==="}"&&o--;if(o<=0&&s>t)break}return n}function Dt(e,t){let n="";for(let o=t;o<e.length&&o<t+5;o++){let s=e[o],r=s.indexOf("{");if(r>=0){n+=s.slice(0,r).trimEnd()+";";break}n+=s+`
|
|
16
|
+
`}return n||e[t]}function Ot(e,t){let n=0;for(let o=t;o<e.length;o++){let s=e[o];for(let r of s)r==="{"&&n++,r==="}"&&n--;if(n<=0&&o>t)return o+1}return e.length}var Ft=[{pattern:"\\bfs\\.exists\\b",message:"fs.exists is deprecated \u2014 use fs.access() or fs.stat()"},{pattern:"\\bfs\\.existsSync\\b",message:"fs.existsSync is deprecated in async contexts \u2014 prefer fs.accessSync()"},{pattern:"\\bnew Buffer\\(",message:"Buffer() constructor is deprecated \u2014 use Buffer.from() or Buffer.alloc()"},{pattern:"\\brequire\\('url'\\)\\.parse",message:"url.parse() is deprecated \u2014 use new URL() constructor"},{pattern:"\\burl\\.parse\\(",message:"url.parse() is deprecated \u2014 use new URL() constructor"},{pattern:"\\butil\\.isArray\\b",message:"util.isArray is deprecated \u2014 use Array.isArray()"},{pattern:"\\butil\\.isDate\\b",message:"util.isDate is deprecated \u2014 use instanceof Date"},{pattern:"\\butil\\.isRegExp\\b",message:"util.isRegExp is deprecated \u2014 use instanceof RegExp"},{pattern:"\\bcomponentWillMount\\b",message:"componentWillMount is deprecated \u2014 use componentDidMount or useEffect"},{pattern:"\\bcomponentWillReceiveProps\\b",message:"componentWillReceiveProps is deprecated \u2014 use getDerivedStateFromProps or useEffect"},{pattern:"\\bcomponentWillUpdate\\b",message:"componentWillUpdate is deprecated \u2014 use getSnapshotBeforeUpdate"},{pattern:"\\bReact\\.createClass\\b",message:"React.createClass is removed \u2014 use class components or function components"},{pattern:"\\bReactDOM\\.render\\(",message:"ReactDOM.render is deprecated in React 18+ \u2014 use createRoot().render()"},{pattern:"@ts-ignore",message:"Prefer @ts-expect-error over @ts-ignore for better error tracking"}];function ae(e,t){let n=[...Ft,...t??[]],o=[],s=e.split(`
|
|
17
|
+
`);for(let r=0;r<s.length;r++){let i=s[r],a=i.trim();if(!(a.startsWith("//")||a.startsWith("*")||a.startsWith("/*")))for(let d of n){let c;try{c=new RegExp(d.pattern)}catch{continue}let p=c.exec(i);p&&o.push({line:r+1,matched:p[0],message:d.message})}}return o}var We=require("node:fs"),N=require("node:path");var It=["add","create","implement","build","new","introduce","scaffold","write","make","generate","setup","set up"];function ce(e,t,n,o,s,r){if(!o.some(f=>It.includes(f)))return[];let a=new Set(t.map(f=>f.path)),d=new Map;for(let f of t){if(f.is_stub||f.is_exemplar)continue;let _=(0,N.dirname)(f.path),h=d.get(_)??[];h.push(f.path),d.set(_,h)}let c=[],p=0,u=new Set;for(let[f,_]of d){if(u.has(f))continue;if(c.length>=s)break;let h=n.files.filter(y=>a.has(y.path)||y.is_test?!1:(0,N.dirname)(y.path)===f);if(h.length===0)continue;let l=(0,N.extname)(_[0]),w=h.map(y=>{let v=0;(0,N.extname)(y.path)===l&&(v+=2);let m=(0,N.basename)(y.path,(0,N.extname)(y.path));for(let C of _){let O=(0,N.basename)(C,(0,N.extname)(C)),F=m.split(/[-_.]/),$=O.split(/[-_.]/),z=F.filter(T=>$.includes(T));v+=z.length*.5}return y.lines<=150?v+=1:y.lines<=300&&(v+=.5),{file:y,score:v}});w.sort((y,v)=>v.score-y.score);let b=w[0];if(!b||b.score<1)continue;let E=(0,N.join)(e,b.file.path),k;try{k=(0,We.readFileSync)(E,"utf-8")}catch{continue}let A=k.split(`
|
|
18
|
+
`).length,R=(0,N.extname)(b.file.path),L=I(A,R);if(p+L>r)continue;let x=["pattern_exemplar"];c.push({path:b.file.path,score:0,reasons:x,excerpt_spans:null,content:k,token_estimate:L,is_exemplar:!0}),p+=L,u.add(f)}return c}var $e=["test","tests","testing","spec","specs","jest","vitest","mocha"],Pt=["config","configuration","settings","setup","env","environment"],jt=["database","migration","schema","sql","query","model","table"];function le(e,t,n,o){let s=[],r=o.toLowerCase();!e.some(h=>!h.is_stub&&!h.is_exemplar&&h.reasons.includes("keyword_match"))&&e.length>0&&s.push({level:"warning",code:"no_keyword_match",message:"No files matched task keywords. Bundle is based on churn/centrality signals only \u2014 consider rephrasing the task."});let a=t.some(h=>$e.includes(h))||$e.some(h=>r.includes(h)),d=e.some(h=>h.path.includes(".test.")||h.path.includes(".spec.")||h.path.includes("__tests__"));a&&!d&&s.push({level:"warning",code:"missing_test_files",message:"Task mentions testing but no test files are in the bundle. Test files may have been filtered or out of budget."});let c=t.some(h=>Pt.includes(h)),p=e.some(h=>{let l=h.path.toLowerCase();return l.includes("config")||l.includes(".env")||l.includes("tsconfig")||l.includes("package.json")});c&&!p&&s.push({level:"info",code:"missing_config_files",message:"Task mentions configuration but no config files are in the bundle."});let u=t.some(h=>jt.includes(h)),f=e.some(h=>{let l=h.path.toLowerCase();return l.includes("model")||l.includes("migration")||l.includes("schema")||l.includes(".sql")||l.includes("db/")||l.includes("database")});u&&!f&&s.push({level:"info",code:"missing_db_files",message:"Task mentions database/schema but no database files are in the bundle."});let _=e.filter(h=>!h.is_stub&&!h.is_exemplar);if(_.length>=5){let h=_[0]?.score??0,l=_[_.length-1]?.score??0;h>0&&l>0&&l/h>.85&&s.push({level:"info",code:"score_plateau",message:"File scores are very close together \u2014 no strong signal file. The task may be too broad or generic."})}if(_.length===0&&s.push({level:"warning",code:"empty_bundle",message:"Bundle contains no source files. The task may not match any files in the repository."}),n.length>0&&_.length>0){let h=_[_.length-1].score,l=n.filter(w=>w.score>h&&!e.some(b=>b.path===w.path));l.length>3&&s.push({level:"info",code:"budget_squeeze",message:`${l.length} files with strong scores were excluded by budget constraints. Consider increasing --budget or --max-files.`})}return s}var zt=5;function pe(e,t,n,o,s,r){let i=new Set(t.map(p=>p.path)),a=s??zt,d=[],c=0;for(let p of e){if(c++,i.has(p.path)||p.score<=0)continue;if(d.length>=a)break;let f=r?.get(p.path)??Math.max(1,Math.round(p.features.size_penalty*1e3)),_=p.path.includes(".")?"."+p.path.split(".").pop():"",h=I(f,_),l=o?o-n:1/0,w=Math.max(0,h-l),b=Wt(p,w),E=[...p.reasons];d.push({path:p.path,score:Math.round(p.score*1e3)/1e3,rank:c,reasons:E,budget_gap_tokens:w,suggestion:b})}return d}function Wt(e,t){let n=[],o=e.path.split("/"),r=(o[o.length-1]??"").replace(/\.\w+$/,"").split(/[-_.]/).join(" ");return t>0&&n.push(`increase budget by ~${t} tokens`),e.features.keyword===0&&r&&n.push(`add "${r}" to your task description`),n.length===0&&n.push("increase --max-files or --budget"),n.join("; or ")}function de(e,t,n){let o=[],s=new Set(e.map(i=>i.path)),r=new Map;for(let i of n){let a=r.get(i.source_file)??[];a.push(i.test_file),r.set(i.source_file,a)}for(let i of e){if(i.is_stub||i.is_exemplar)continue;let a=(t.dependents[i.path]??[]).filter(u=>!s.has(u)),d=$t(i.path,t,s),c=new Set,p=r.get(i.path)??[];for(let u of p)c.add(u);for(let u of a){let f=r.get(u)??[];for(let _ of f)c.add(_)}for(let u of d){let f=r.get(u)??[];for(let _ of f)c.add(_)}a.length===0&&d.length===0&&c.size===0||o.push({path:i.path,direct_dependents:a,transitive_dependents:d,impacted_tests:[...c]})}return o.sort((i,a)=>{let d=i.direct_dependents.length+i.transitive_dependents.length+i.impacted_tests.length;return a.direct_dependents.length+a.transitive_dependents.length+a.impacted_tests.length-d}),o}function $t(e,t,n){let o=new Set([e]),s=[],r=[e];for(let i=0;i<3;i++){let a=[];for(let d of r){let c=t.dependents[d]??[];for(let p of c)if(!o.has(p)){if(o.add(p),!n.has(p)&&(s.push(p),s.length>=20))return s;a.push(p)}}if(r=a,r.length===0)break}return s}var Bt=["fix","bug","broken","crash","error","issue","wrong","fail","incorrect","invalid","null","undefined","exception","regression","patch","hotfix"],Kt=["add","create","implement","build","new","introduce","scaffold","feature","endpoint","component","page","route","service"],Ut=["refactor","restructure","reorganize","clean","simplify","extract","rename","move","split","merge","consolidate","optimize","improve","modernize","upgrade","migrate","replace"],Ht=["test","tests","testing","spec","specs","coverage","assertion","mock","stub","fixture","jest","vitest","mocha","e2e","execute"],Gt=["config","configuration","settings","setup","env","environment","ci","pipeline","deploy","docker","workflow","tsconfig","webpack","vite"],qt=["validate","lint","format","prettier","eslint","compliance","todo","todos","fixme","codemod","sweep"],Zt=["repo.?wide","across repo","everywhere","update all","rename everywhere","bulk"].map(e=>new RegExp(`\\b${e}\\b`,"i"));function fe(e){let t=e.toLowerCase(),n=t.split(/[^\p{L}\p{N}]+/u).filter(i=>i.length>0),o={bug_fix:0,feature_add:0,refactor:0,test_update:0,config:0,repo_scan:0,general:0};for(let i of n)Bt.includes(i)&&(o.bug_fix+=1),Kt.includes(i)&&(o.feature_add+=1),Ut.includes(i)&&(o.refactor+=1),Ht.includes(i)&&(o.test_update+=1),Gt.includes(i)&&(o.config+=1),qt.includes(i)&&(o.repo_scan+=1);for(let i of Zt)i.test(t)&&(o.repo_scan+=1);if(o.repo_scan>0)return"repo_scan";let s="general",r=0;for(let[i,a]of Object.entries(o))a>r&&(r=a,s=i);return r>0?s:"general"}var Xt={bug_fix:{error_infrastructure:1.5,recent_touch:1.3,churn:1.2,keyword:1.1},feature_add:{centrality:1.3,keyword:1.2,test_relevance:.8},refactor:{churn:1.4,centrality:1.3,size_penalty:.7},test_update:{test_relevance:2.5,keyword:1.2,centrality:.5,churn:.5},config:{keyword:1.3,churn:.7,centrality:.8},repo_scan:{keyword:1.4,recent_touch:1.3,centrality:.4,size_penalty:1.3,churn:.6,test_relevance:.5},general:{}};function ue(e,t){let n=Xt[t];if(Object.keys(n).length===0)return e;let o={...e};for(let[s,r]of Object.entries(n)){let i=o[s];typeof i=="number"&&(o[s]=i*r)}return o}var Yt=[{pattern:"/types/",layer:0},{pattern:"/types.",layer:0},{pattern:"/interfaces/",layer:0},{pattern:"/models/",layer:1},{pattern:"/entities/",layer:1},{pattern:"/schemas/",layer:1},{pattern:"/repo/",layer:2},{pattern:"/repositories/",layer:2},{pattern:"/db/",layer:2},{pattern:"/database/",layer:2},{pattern:"/migrations/",layer:2},{pattern:"/services/",layer:3},{pattern:"/service.",layer:3},{pattern:"/use-cases/",layer:3},{pattern:"/domain/",layer:3},{pattern:"/api/",layer:4},{pattern:"/routes/",layer:4},{pattern:"/controllers/",layer:4},{pattern:"/handlers/",layer:4},{pattern:"/pages/",layer:4},{pattern:"/components/",layer:4},{pattern:"/middleware/",layer:5},{pattern:"/config/",layer:6},{pattern:"/utils/",layer:6},{pattern:"/helpers/",layer:6},{pattern:"/lib/",layer:6},{pattern:"/jobs/",layer:7},{pattern:"/workers/",layer:7},{pattern:"/tasks/",layer:7},{pattern:"/tests/",layer:8},{pattern:"/test/",layer:8},{pattern:"/__tests__/",layer:8},{pattern:".test.",layer:8},{pattern:".spec.",layer:8}],Jt=5;function he(e,t){let n=t??Yt,o=e.toLowerCase();for(let s of n)if(o.includes(s.pattern))return s.layer;return Jt}function me(e,t){return[...e].sort((n,o)=>{let s=he(n.path,t),r=he(o.path,t);return s-r})}var Vt=[/\bTODO\b/i,/\bFIXME\b/i,/\bHACK\b/i,/\bXXX\b/i,/\bBUG\b(?:\s*#?\d+)/i,/\bWORKAROUND\b/i];function _e(e){let t=e.split(`
|
|
19
|
+
`),n=[],o=0;for(let r of t)for(let i of Vt){let a=i.exec(r);if(a){o++;let d=a[0].toUpperCase();n.includes(d)||n.push(d);break}}let s=t.length>0?Math.min(1,o/t.length*100):0;return{count:o,density:s,markers:n}}var ye={enabled:!1,weight:.2,min_affinity:.25,min_co_commit_count:3,tau_days:60,commit_size_penalty:!0,max_shadow_adds:8};function ge(e){return Math.round(e*1e3)/1e3}function we(e,t,n){if(!t.temporal_co_commit)return[];let{meta:o,adjacency:s}=t.temporal_co_commit,r=new Set(e.map(c=>c.path)),i=new Map(t.churn.map(c=>[c.path,c.commit_count])),a=new Map;for(let c of e){let p=s[c.path];if(!p)continue;let u=i.get(c.path)??0;for(let f of p){if(r.has(f.other_path)||f.co_commit_count<n.min_co_commit_count)continue;let _=i.get(f.other_path)??0,h=Math.max(u||f.co_commit_count,_||f.co_commit_count),l=f.co_commit_count/h;if(l<n.min_affinity)continue;let w=(o.built_at_unix-f.last_co_commit_unix)/86400,b=Math.exp(-w/n.tau_days),E=n.commit_size_penalty?1/Math.log2(2+f.avg_commit_files):1,k=l*b*E,A=n.weight*Math.min(1,k),R={linked_to:c.path,co_commit_count:f.co_commit_count,churn_shadow:_,churn_linked:u,affinity:ge(l),recency_days:Math.round(w),shadow_score:ge(k),boost:ge(A)},L=a.get(f.other_path);(!L||A>L.boost)&&a.set(f.other_path,{path:f.other_path,boost:A,reason:R})}}let d=Array.from(a.values());return d.sort((c,p)=>p.boost-c.boost),d.slice(0,n.max_shadow_adds)}function xe(e){let{taskText:t,repoIndex:n,selectorConfig:o,budget:s=o.default_budget,sufficiencyThreshold:r=o.sufficiency_threshold,ledgerStats:i,explain:a=!1,scope:d,branchChangedFiles:c,includeNearMisses:p=!1,includeBlastRadius:u=!1,layerOrder:f=!1}=e,_=fe(t),h=ue(o.weights,_),l=K(t),w=c&&c.size>0?{...h,branch_changed:h.branch_changed??.15}:h;se(l)&&(w={...w,security_surface:Math.max(w.security_surface??0,.2)});let{candidates:b,tokenWeights:E,fanoutFiles:k,surfaceFiles:A}=ee(t,n,o,d);_==="repo_scan"&&rs(b,n,t);let R=ne(b,l,n,w,i,E,k,c,A),L=R.reduce((g,S)=>g+Math.max(0,S.score),0),y=(s.max_files??1/0)<=15?2:0,v={...s,max_files:s.max_files?Math.max(1,s.max_files-y):void 0},m={files:[],totalTokens:0,cumulativeScore:0},C={};for(let g of R){if(oe(m,v,r,L))break;let S=G(n.root,g.path,l,o.excerpt_full_file_max_lines,o.excerpt_window_lines),D=g.path.includes(".")?"."+g.path.split(".").pop():"",M=I(S.lineCount,D);if(s.tokens&&m.totalTokens+M>s.tokens*1.1&&m.files.length>0)break;let j=ae(S.content,o.deprecation_rules),B=_e(S.content),Ze=g.reasons.includes("security_surface"),Xe={path:g.path,score:Math.round(g.score*1e3)/1e3,reasons:g.reasons,excerpt_spans:S.spans,content:S.content,token_estimate:M,deprecation_warnings:j.length>0?j:void 0,todo_count:B.count>0?B.count:void 0,security_relevant:Ze||void 0};m.files.push(Xe),m.totalTokens+=M,m.cumulativeScore+=Math.max(0,g.score),a&&(C[g.path]=g.features)}let O=new Set(m.files.map(g=>g.path)),F=new Map(m.files.map(g=>[g.path,g.score])),$=[];for(let g of n.test_map)O.has(g.source_file)&&!O.has(g.test_file)&&$.push({testPath:g.test_file,sourceScore:F.get(g.source_file)??0});$.sort((g,S)=>S.sourceScore-g.sourceScore);for(let{testPath:g}of $){if(s.max_files&&m.files.length>=s.max_files)break;let S=G(n.root,g,l,o.excerpt_full_file_max_lines,o.excerpt_window_lines),D=g.includes(".")?"."+g.split(".").pop():"",M=I(S.lineCount,D);if(s.tokens&&m.totalTokens+M>s.tokens*1.1)continue;let j=R.find(B=>B.path===g);m.files.push({path:g,score:j?Math.round(j.score*1e3)/1e3:0,reasons:j?.reasons??["test_relevant"],excerpt_spans:S.spans,content:S.content,token_estimate:M}),m.totalTokens+=M}let z={...ye,...o.shadow_files};if(z.enabled&&n.temporal_co_commit){let g=we(m.files,n,z);for(let S of g){if(s.max_files&&m.files.length>=s.max_files)break;let D=G(n.root,S.path,l,o.excerpt_full_file_max_lines,o.excerpt_window_lines),M=S.path.includes(".")?"."+S.path.split(".").pop():"",j=I(D.lineCount,M);if(s.tokens&&m.totalTokens+j>s.tokens*1.1)continue;let B={path:S.path,score:Math.round(S.boost*1e3)/1e3,reasons:["temporal_affinity"],excerpt_spans:D.spans,content:D.content,token_estimate:j,shadow_reason:S.reason};m.files.push(B),m.totalTokens+=j}}let T=new Set(m.files.map(g=>g.path)),W=(s.tokens??1/0)-m.totalTokens,P=Math.max(0,(s.max_files??25)-m.files.length);if(P>0&&W>0){let g=ie(n.root,T,n.dep_graph,Math.min(P,5),Math.min(W,1e3));for(let S of g)m.files.push(S),m.totalTokens+=S.token_estimate}let U=re(m.files,m.cumulativeScore,l.length,n,l),ve=new Set(m.files.map(g=>g.path)),Y=[];for(let g of ve){let S=n.dep_graph.imports[g]??[];for(let D of S)ve.has(D)&&Y.push({from:g,to:D})}let Ee=(s.tokens??1/0)-m.totalTokens,Te=Math.max(0,(s.max_files??25)-m.files.length);if(Te>0&&Ee>0){let g=ce(n.root,m.files,n,l,Math.min(Te,2),Math.min(Ee,2e3));for(let S of g)m.files.push(S),m.totalTokens+=S.token_estimate}if(f){let g=m.files.filter(M=>!M.is_stub&&!M.is_exemplar),S=m.files.filter(M=>M.is_stub||M.is_exemplar),D=me(g);m.files=[...D,...S]}let Ce=le(m.files,l,R,t),J=p?(()=>{let g=new Map(n.files.map(S=>[S.path,S.lines]));return pe(R,m.files,m.totalTokens,s.tokens,void 0,g)})():void 0,V=u?de(m.files,n.dep_graph,n.test_map):void 0;return{bundle_id:`bnd_${(0,Be.randomUUID)().slice(0,12)}`,task:t,task_type:_,budget:s,sufficiency_threshold:r,cumulative_score:Math.round(m.cumulativeScore*1e3)/1e3,files:m.files,total_tokens:m.totalTokens,generated_at:new Date().toISOString(),confidence:U,explain:a?C:void 0,file_relationships:Y.length>0?Y:void 0,warnings:Ce.length>0?Ce:void 0,near_misses:J&&J.length>0?J:void 0,blast_radius:V&&V.length>0?V:void 0}}var Qt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".md",".json",".yml",".yaml",".txt",".sql",".py",".go",".rs",".java",".rb",".sh"]),es=["scripts/","tools/",".github/"],ts=["validate","lint","format","eslint","prettier"],ss=256*1024,ns=2e3,os=400;function rs(e,t,n){let o=n.toLowerCase();for(let d of t.files){let c=d.path.toLowerCase();if(es.some(u=>c.startsWith(u))){e.add(d.path);continue}let p=c.split("/").pop()??"";if(ts.some(u=>p.includes(u))){e.add(d.path);continue}}let s=t.files.find(d=>d.path==="package.json");if(s&&e.add(s.path),!/\btodo|todos|fixme\b/i.test(o))return;let i=t.files.filter(d=>{if(e.has(d.path)||d.is_test)return!1;let c=d.extension.toLowerCase();return!(!Qt.has(c)||d.size>ss)}).sort((d,c)=>d.path.localeCompare(c.path)).slice(0,ns),a=0;for(let d of i){if(a>=os)break;if((d.content_keywords??[]).some(p=>p==="todo"||p==="fixme")){e.add(d.path),a++;continue}try{let p=(0,Ke.readFileSync)((0,Ue.join)(t.root,d.path),"utf-8");/\bTODO\b|\bFIXME\b/i.test(p)&&(e.add(d.path),a++)}catch{}}}var is=require("node:crypto");var He=require("node:fs"),hs=require("node:path"),Rn=10*1024*1024;var Ge=require("node:crypto");var ke="0.1.0";function Ss(e){return e.includes("--version")?(process.stdout.write(`codeledger-core ${ke}
|
|
20
20
|
`),!0):e.includes("--license")?(process.stdout.write([`CodeLedger Core Engine v${ke}`,"","Copyright (c) 2025 Intelligent Context AI, Inc.","","This binary is licensed under the CodeLedger Core License:"," - FREE for individual developer use"," - FREE for open-source projects"," - Commercial and CI/CD usage requires a CodeLedger Pro license","","Contact: team@codeledger.dev","Details: https://codeledger.dev/license","","Privacy: This engine runs entirely locally. No network calls,","no telemetry, no data collection. Your code never leaves your machine.",""].join(`
|
|
21
21
|
`)),!0):e.includes("--explain-architecture")?(process.stdout.write([`CodeLedger Core Engine v${ke} \u2014 Architecture`,"","The engine selects the most relevant files for a coding task using","a deterministic, multi-signal scoring algorithm:",""," 1. CANDIDATE GENERATION (five-stage pipeline)"," - Keyword matching with IDF weighting"," - Hot-zone inclusion from git churn history"," - Dependency graph expansion (imports + dependents)"," - Fan-out detection for cross-cutting changes"," - Test neighborhood pairing",""," 2. SCORING (weighted multi-signal)"," Each candidate is scored across 9 signals:"," keyword, centrality, churn, recency, test_relevance,"," size_penalty, success_prior, fail_prior, error_infrastructure",""," 3. BOUNDED SELECTION"," Files are selected in score order until the token budget"," or file count ceiling is reached. A sufficiency threshold"," stops early when cumulative score plateaus.",""," 4. POST-PROCESSING"," - Deterministic test pairing (source \u2192 test)"," - Interface stub generation for adjacent dependencies"," - Confidence assessment (high / medium / low)"," - Smart excerpt extraction with keyword windowing","","Input: Task description + repo index + config","Output: Deterministic ContextBundle (same input = same rankings and content; metadata fields like bundle_id vary)","","Privacy: Runs entirely local. No network calls. No telemetry.",""].join(`
|
|
22
|
-
`)),!0):!1}async function
|
|
22
|
+
`)),!0):!1}async function ks(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(e).toString("utf-8")}async function vs(){if(Ss(process.argv.slice(2)))return;let e=await ks(),t=JSON.parse(e),n;if(t.indexPath)n=JSON.parse((0,qe.readFileSync)(t.indexPath,"utf-8"));else if(t.repoIndex)n=t.repoIndex;else throw new Error("Either indexPath or repoIndex must be provided");let o=t.ledgerStats?{success_files:new Set(t.ledgerStats.success_files),fail_files:new Set(t.ledgerStats.fail_files)}:void 0,s=t.branchChangedFiles?new Set(t.branchChangedFiles):void 0,r=xe({taskText:t.task,repoIndex:n,selectorConfig:t.selectorConfig,budget:t.budget,explain:t.explain,ledgerStats:o,scope:t.scope,branchChangedFiles:s,includeNearMisses:t.includeNearMisses,includeBlastRadius:t.includeBlastRadius,layerOrder:t.layerOrder});process.stdout.write(JSON.stringify(r))}vs().catch(e=>{process.stderr.write(JSON.stringify({error:String(e)})+`
|
|
23
23
|
`),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeledger/core-engine",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Protected scoring engine for CodeLedger — compiled binary bridge",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE-CORE",
|
|
@@ -25,11 +25,11 @@
|
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@codeledger/types": "0.6.
|
|
28
|
+
"@codeledger/types": "0.6.3"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"typescript": "^5.4.0",
|
|
32
|
-
"@codeledger/selector": "0.6.
|
|
32
|
+
"@codeledger/selector": "0.6.3"
|
|
33
33
|
},
|
|
34
34
|
"scripts": {
|
|
35
35
|
"build": "tsc",
|