@codeledger/core-engine 0.2.1 → 0.5.1
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 +16 -16
- 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 De=require("node:fs");var _e=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"]),je=new Set(["test","tests","testing","build","lint","debug","deploy","review","audit","evaluate","assess","analyze","examine","application","app","project","codebase","code","repo"]),Pe=["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`)),We=["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`)),U=50,ye=[".sql",".proto",".prisma",".graphql",".gql"],we=["openapi","swagger","schema","migrations"],Be=new Set(["config","configuration","script","dependency","dependencies","setup","package","tsconfig","eslint","prettier","webpack","vite","rollup"]),ze=new Set(["test","tests","testing","ci","pipeline","failing","pass","coverage","jest","vitest","mocha","cypress","playwright"]),Ue=new Set(["schema","api","endpoint","migration","contract","proto","graphql","openapi","swagger","prisma","database"]),Ke=["package.json","tsconfig","pnpm-workspace",".env.example","eslint","prettier","webpack.config","vite.config","rollup.config"],$e=["vitest.config","jest.config",".github/workflows","ci.yml","ci.yaml","test-setup","test-helper","test-utils"],Ge=/\b(?:and then|and also|and|then|also|plus)\b|[;,]/i;function z(e){let t=e.toLowerCase(),o=Pe.some(r=>r.test(t))?new Set([..._e,...je]):_e,n=t.split(/[^\p{L}\p{N}]+/u).filter(r=>r.length>1&&!o.has(r));return[...new Set(n)]}function xe(e){let t=e.split(Ge).map(o=>o.trim()).filter(o=>o.length>0);if(t.length<=1)return[z(e)];let s=[];for(let o of t){let n=z(o);n.length>0&&s.push(n)}return s.length>0?s:[z(e)]}function be(e,t,s){let o=new Map;for(let n of e){let r=0;for(let a of t.files)(a.path.toLowerCase().includes(n)||a.content_keywords?.some(h=>h===n||h===n+"s"||n===h+"s"))&&r++;if(r===0){o.set(n,0);continue}let i=1/Math.sqrt(Math.max(1,r));n.length<=2&&(i=Math.min(i,.35)),r>s&&(i=Math.min(i,.35)),i=Math.max(.35,Math.min(1,i)),o.set(n,i)}return o}function qe(e){let t=e.toLowerCase();return We.some(s=>s.test(t))}function He(e,t){let s=[];for(let o of t.files){let i=(o.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/);for(let a of e)if(i.some(f=>f===a||f===a+"s"||a===f+"s")){s.push(o.path);break}}return s}function J(e,t,s,o){let n=new Set,r=new Set,i=new Set,a=o??s.default_scope,h=xe(e),f=[...new Set(h.flat())],l=be(f,t,s.hot_zone_count),p=a?t.files.filter(w=>a.some(_=>w.path.startsWith(_))):t.files;for(let w of h)for(let _ of p){if(n.has(_.path))continue;let S=_.path.toLowerCase();for(let d of w){if(S.includes(d)){n.add(_.path);break}if(_.content_keywords?.some(v=>v===d||v===d+"s"||d===v+"s")){n.add(_.path);break}}}let u=(s.default_budget.max_files??1/0)<=15,g=new Set(p.map(w=>w.path)),m=t.churn.slice(0,s.hot_zone_count);for(let w of m)g.has(w.path)&&(u&&!n.has(w.path)||n.add(w.path));let c=a?g:void 0,x=[...n];for(let w of x)Ye(w,t,n,s.dependency_depth,s.dependency_cap_per_seed,c);if(qe(e)){let w=He(f,t);for(let _ of w){if(n.size>=U)break;let S=t.dep_graph.dependents[_]??[];for(let d of S){if(n.size>=U)break;c&&!c.has(d)||(n.add(d),r.add(d))}if(n.size<U)for(let d of S){if(n.size>=U)break;if(c&&!c.has(d))continue;let v=t.dep_graph.dependents[d]??[];for(let O of v){if(n.size>=U)break;c&&!c.has(O)||(n.add(O),r.add(O))}}}}let b=[...n];for(let w of t.test_map)b.includes(w.source_file)&&(!c||c.has(w.test_file))&&n.add(w.test_file),b.includes(w.test_file)&&(!c||c.has(w.source_file))&&n.add(w.source_file);let C=Xe(t.files,s.contract_patterns);if(C.length>0&&n.size>0){let w=new Set([...n].map(_=>_.split("/").slice(0,-1).join("/")));for(let _ of C){let S=_.split("/").slice(0,-1).join("/");(w.has(S)||[...w].some(v=>v.startsWith(S+"/")||S.startsWith(v+"/")))&&n.add(_)}}let T=new Set(f),N=[...Be].some(w=>T.has(w)),M=[...ze].some(w=>T.has(w)),D=[...Ue].some(w=>T.has(w));if(N||M||D){let w=D?new Set([...n].map(_=>_.split("/").slice(0,-1).join("/"))):void 0;for(let _ of p){if(n.has(_.path))continue;let S=_.path.toLowerCase();if(N&&Ke.some(d=>S.includes(d))){n.add(_.path),i.add(_.path);continue}if(M&&$e.some(d=>S.includes(d))){n.add(_.path),i.add(_.path);continue}if(D&&w){let d=_.extension.toLowerCase(),v=S.split("/").pop()??"";if(ye.includes(d)||we.some(I=>v.startsWith(I))){let I=_.path.split("/").slice(0,-1).join("/");(w.has(I)||[...w].some(R=>R.startsWith(I+"/")||I.startsWith(R+"/")))&&(n.add(_.path),i.add(_.path))}}}}return{candidates:n,tokenWeights:l,fanoutFiles:r,surfaceFiles:i}}function Xe(e,t){let s=[];for(let o of e){let n=o.extension.toLowerCase(),r=o.path.toLowerCase();if(ye.includes(n)){s.push(o.path);continue}if(t?.some(a=>r.includes(a.toLowerCase()))){s.push(o.path);continue}let i=r.split("/").pop()??"";we.some(a=>i.startsWith(a))&&s.push(o.path)}return s}function Ye(e,t,s,o,n,r){let i=[e],a=0;for(let h=0;h<o&&a<n;h++){let f=[];for(let l of i){let p=t.dep_graph.imports[l]??[];for(let g of p)r&&!r.has(g)||!s.has(g)&&a<n&&(s.add(g),f.push(g),a++);let u=t.dep_graph.dependents[l]??[];for(let g of u)r&&!r.has(g)||!s.has(g)&&a<n&&(s.add(g),f.push(g),a++)}i=f}}var Je=["error","exception","validation","validator","schema"];function Ve(e){return(e.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/).some(r=>Je.some(i=>r===i||r===i+"s"))?1:0}function ke(e,t,s,o,n,r){let i=e.path.toLowerCase(),a=e.content_keywords??[],f=(i.split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/),l=0,p=0,u=!1;for(let E of t){let R=n?.get(E)??1;if(R!==0)if(p+=R,i.includes(E)){let F=f.some(W=>W===E||W===E+"s"||E===W+"s");l+=R*(F?3:1)}else a.some(F=>F===E||F===E+"s"||E===F+"s")&&(l+=R*.5,u=!0)}let g=p>0?Math.min(1,l/(p*1.5)):0,m=s.dep_graph.imports[e.path]?.length??0,c=s.dep_graph.dependents[e.path]?.length??0,x=m+c,b=Math.max(1,...s.files.map(E=>{let R=s.dep_graph.imports[E.path]?.length??0,F=s.dep_graph.dependents[E.path]?.length??0;return R+F})),C=x/b,T=s.churn.find(E=>E.path===e.path),N=T?.time_decayed_score??0,M=T?.days_since_last_touch??999,D=M<=7?1:M<=14?.8:M<=30?.5:M<=60?.2:0,w=s.test_map.filter(E=>E.source_file===e.path||E.test_file===e.path),_=0;w.length>0&&(_=.5,_+=Math.min(.5,w.length*.25));let S=Math.max(0,Math.min(1,e.lines/1e3)),d=o?.success_files.has(e.path)?1:0,v=o?.fail_files.has(e.path)?1:0,O=Ve(e),I=r?.has(e.path)?1:0;return{keyword:g,centrality:C,churn:N,recent_touch:D,test_relevance:_,size_penalty:S,success_prior:d,fail_prior:v,error_infrastructure:O,branch_changed:I,_hasContentMatch:u}}function Se(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 Te(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)}function Ee(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"),t}function V(e,t,s,o,n,r,i,a,h){let f=new Map(s.files.map(p=>[p.path,p])),l=[];for(let p of e){let u=f.get(p);if(!u)continue;let g=ke(u,t,s,n,r,a),c={...Se(g),_hasContentMatch:g._hasContentMatch,branch_changed:g.branch_changed},x=Te(c,o),b=Ee(c);i?.has(p)&&(x+=.25,b.includes("dependent_neighbor")||b.push("dependent_neighbor")),h?.has(p)&&c.keyword===0&&(x=0,b.length=0,b.push("surface_auto_include")),l.push({path:p,score:x,features:c,reasons:b})}return l.sort((p,u)=>u.score-p.score),l}function Ze(e){return e.some(t=>t.reasons.includes("keyword_match")||t.reasons.includes("test_relevant"))}function Z(e,t,s,o){return!!(t.max_files&&e.files.length>=t.max_files||t.tokens&&e.totalTokens>=t.tokens||o>0&&e.cumulativeScore/o>=s&&Ze(e.files))}var $=require("node:fs"),Ce=require("node:path"),Qe=10*1024*1024;function G(e,t,s,o,n){let r=(0,Ce.join)(e,t),i;try{let c=(0,$.statSync)(r).size;if(c>Qe)return{content:`// File too large (${Math.round(c/1024)}KB), skipped`,spans:null,lineCount:1};i=(0,$.readFileSync)(r,"utf-8")}catch{return{content:"",spans:null,lineCount:0}}let a=i.split(`
|
|
8
|
-
`);if(a.length<=
|
|
9
|
-
// ... (lines ${
|
|
10
|
-
`),
|
|
11
|
-
`),
|
|
12
|
-
`).length,
|
|
13
|
-
`),
|
|
14
|
-
${
|
|
15
|
-
`)}`}function
|
|
16
|
-
`}return
|
|
17
|
-
`);for(let r=0;r<n.length;r++){let i=n[r],a=i.trim();if(!(a.startsWith("//")||a.startsWith("*")||a.startsWith("/*")))for(let
|
|
18
|
-
`).length,M=(0,
|
|
19
|
-
`),
|
|
20
|
-
`),!0):e.includes("--license")?(process.stdout.write([`CodeLedger Core Engine v${
|
|
21
|
-
`)),!0):e.includes("--explain-architecture")?(process.stdout.write([`CodeLedger Core Engine v${
|
|
22
|
-
`)),!0):!1}async function
|
|
7
|
+
"use strict";var $e=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"]),Ue=new Set(["test","tests","testing","build","lint","debug","deploy","review","audit","evaluate","assess","analyze","examine","application","app","project","codebase","code","repo"]),He=["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`)),qe=["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`)),U=50,ve=[".sql",".proto",".prisma",".graphql",".gql"],Te=["openapi","swagger","schema","migrations"],Ge=new Set(["config","configuration","script","dependency","dependencies","setup","package","tsconfig","eslint","prettier","webpack","vite","rollup"]),Xe=new Set(["test","tests","testing","ci","pipeline","failing","pass","coverage","jest","vitest","mocha","cypress","playwright"]),Ye=new Set(["schema","api","endpoint","migration","contract","proto","graphql","openapi","swagger","prisma","database"]),Ze=["package.json","tsconfig","pnpm-workspace",".env.example","eslint","prettier","webpack.config","vite.config","rollup.config"],Je=["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__/"],Ve=/\b(?:and then|and also|and|then|also|plus)\b|[;,]/i;function K(e){let t=e.toLowerCase(),s=He.some(r=>r.test(t))?new Set([...Q,...Ue]):Q,n=t.split(/[^\p{L}\p{N}]+/u).filter(r=>r.length>1&&!s.has(r));return[...new Set(n)]}function Ee(e){let t=e.split(Ve).map(s=>s.trim()).filter(s=>s.length>0);if(t.length<=1)return[K(e)];let o=[];for(let s of t){let n=K(s);n.length>0&&o.push(n)}return o.length>0?o:[K(e)]}function Ce(e,t,o){let s=new Map;for(let n of e){let r=0;for(let a of t.files)(a.path.toLowerCase().includes(n)||a.content_keywords?.some(f=>f===n||f===n+"s"||n===f+"s"))&&r++;if(r===0){s.set(n,0);continue}let i=1/Math.sqrt(Math.max(1,r));n.length<=2&&(i=Math.min(i,.35)),r>o&&(i=Math.min(i,.35)),i=Math.max(.35,Math.min(1,i)),s.set(n,i)}return s}function Qe(e){let t=e.toLowerCase();return qe.some(o=>o.test(t))}function et(e,t){let o=[];for(let s of t.files){let i=(s.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/);for(let a of e)if(i.some(l=>l===a||l===a+"s"||a===l+"s")){o.push(s.path);break}}return o}function ee(e,t,o,s){let n=new Set,r=new Set,i=new Set,a=s??o.default_scope??Me(e,t),f=Ee(e),l=[...new Set(f.flat())],p=Ce(l,t,o.hot_zone_count),u=a?t.files.filter(y=>a.some(w=>y.path.startsWith(w))):t.files;for(let y of f)for(let w of u){if(n.has(w.path))continue;let S=w.path.toLowerCase();for(let h of y){if(S.includes(h)){n.add(w.path);break}if(w.content_keywords?.some(C=>C===h||C===h+"s"||h===C+"s")){n.add(w.path);break}}}let m=(o.default_budget.max_files??1/0)<=15,g=new Set(u.map(y=>y.path)),d=t.churn.slice(0,o.hot_zone_count);for(let y of d)g.has(y.path)&&(m&&!n.has(y.path)||n.add(y.path));let c=a?g:void 0,x=[...n];for(let y of x)nt(y,t,n,o.dependency_depth,o.dependency_cap_per_seed,c);if(Qe(e)){let y=et(l,t);for(let w of y){if(n.size>=U)break;let S=t.dep_graph.dependents[w]??[];for(let h of S){if(n.size>=U)break;c&&!c.has(h)||(n.add(h),r.add(h))}if(n.size<U)for(let h of S){if(n.size>=U)break;if(c&&!c.has(h))continue;let C=t.dep_graph.dependents[h]??[];for(let N of C){if(n.size>=U)break;c&&!c.has(N)||(n.add(N),r.add(N))}}}}let b=[...n];for(let y of t.test_map)b.includes(y.source_file)&&(!c||c.has(y.test_file))&&n.add(y.test_file),b.includes(y.test_file)&&(!c||c.has(y.source_file))&&n.add(y.source_file);let T=tt(t.files,o.contract_patterns);if(T.length>0&&n.size>0){let y=new Set([...n].map(w=>w.split("/").slice(0,-1).join("/")));for(let w of T){let S=w.split("/").slice(0,-1).join("/");(y.has(S)||[...y].some(C=>C.startsWith(S+"/")||S.startsWith(C+"/")))&&n.add(w)}}let k=new Set(l),A=[...Ge].some(y=>k.has(y)),M=[...Xe].some(y=>k.has(y)),D=[...Ye].some(y=>k.has(y));if(A||M||D){let y=D?new Set([...n].map(w=>w.split("/").slice(0,-1).join("/"))):void 0;for(let w of u){if(n.has(w.path))continue;let S=w.path.toLowerCase();if(A&&Ze.some(h=>S.includes(h))){n.add(w.path),i.add(w.path);continue}if(M&&Je.some(h=>S.includes(h))){n.add(w.path),i.add(w.path);continue}if(D&&y){let h=w.extension.toLowerCase(),C=S.split("/").pop()??"";if(ve.includes(h)||Te.some(F=>C.startsWith(F))){let F=w.path.split("/").slice(0,-1).join("/");(y.has(F)||[...y].some(z=>z.startsWith(F+"/")||F.startsWith(z+"/")))&&(n.add(w.path),i.add(w.path))}}}}return{candidates:n,tokenWeights:p,fanoutFiles:r,surfaceFiles:i}}function tt(e,t){let o=[];for(let s of e){let n=s.extension.toLowerCase(),r=s.path.toLowerCase();if(ve.includes(n)){o.push(s.path);continue}if(t?.some(a=>r.includes(a.toLowerCase()))){o.push(s.path);continue}let i=r.split("/").pop()??"";Te.some(a=>i.startsWith(a))&&o.push(s.path)}return o}function nt(e,t,o,s,n,r){let i=[e],a=0;for(let f=0;f<s&&a<n;f++){let l=[];for(let p of i){let u=t.dep_graph.imports[p]??[];for(let g of u)r&&!r.has(g)||!o.has(g)&&a<n&&(o.add(g),l.push(g),a++);let m=t.dep_graph.dependents[p]??[];for(let g of m)r&&!r.has(g)||!o.has(g)&&a<n&&(o.add(g),l.push(g),a++)}i=l}}function Me(e,t){let o=e.toLowerCase(),s=/[a-z][a-z0-9]*(?:[-_][a-z][a-z0-9]*)+/g,n=(o.match(s)??[]).filter(f=>!Q.has(f));if(n.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 u=l[p];if(!u)continue;let m=u.toLowerCase(),g=l.slice(0,p+1).join("/")+"/";r.has(m)||r.set(m,new Set),r.get(m).add(g)}}let i=new Set;for(let f of n){let l=r.get(f);if(!(!l||l.size===0))for(let p of l)i.add(p)}if(i.size===0)return;let a=[...i].filter(f=>![...i].some(l=>l!==f&&l.startsWith(f)));return a.length>0?a:void 0}var st=["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"],ot=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 o=e.path.toLowerCase().split("/"),s=[];for(let r of o){let i=r.replace(/\.\w+$/,"");for(let a of i.split(/[-_]/))a.length>0&&s.push(a)}return s.some(r=>st.some(i=>r===i||r===i+"s"||r.startsWith(i)))?1:0}function ne(e){return e.some(t=>ot.has(t))}var rt=["error","exception","validation","validator","schema"],it=3,at=.5,ct=.25;function lt(e){return(e.path.toLowerCase().split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/).some(r=>rt.some(i=>r===i||r===i+"s"))?1:0}function Re(e,t,o,s,n,r){let i=e.path.toLowerCase(),a=e.content_keywords??[],l=(i.split("/").pop()?.replace(/\.\w+$/,"")??"").split(/[-_]/),p=0,u=0,m=!1;for(let E of t){let P=n?.get(E)??1;if(P!==0)if(u+=P,i.includes(E)){let j=l.some($=>$===E||$===E+"s"||E===$+"s");p+=P*(j?it:1)}else a.some(j=>j===E||j===E+"s"||E===j+"s")&&(p+=P*at,m=!0)}let g=u>0?Math.min(1,p/(u*1.5)):0,d=o.dep_graph.imports[e.path]?.length??0,c=o.dep_graph.dependents[e.path]?.length??0,x=d+c,b=Math.max(1,...o.files.map(E=>{let P=o.dep_graph.imports[E.path]?.length??0,j=o.dep_graph.dependents[E.path]?.length??0;return P+j})),T=x/b,k=o.churn.find(E=>E.path===e.path),A=k?.time_decayed_score??0,M=k?.days_since_last_touch??999,D=M<=7?1:M<=14?.8:M<=30?.5:M<=60?.2:0,y=o.test_map.filter(E=>E.source_file===e.path||E.test_file===e.path),w=/[./](?:test|spec)\.[^/]+$/.test(i)||i.includes("__tests__/"),S=0;y.length>0?(S=.5,S+=Math.min(.5,y.length*.25)):w&&(S=.4);let h=Math.max(0,Math.min(1,e.lines/1e3)),C=s?.success_files.has(e.path)?1:0,N=s?.fail_files.has(e.path)?1:0,F=lt(e),I=r?.has(e.path)?1:0,z=te(e);return{keyword:g,centrality:T,churn:A,recent_touch:D,test_relevance:S,size_penalty:h,success_prior:C,fail_prior:N,error_infrastructure:F,branch_changed:I,security_surface:z,_hasContentMatch:m}}function Le(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 Ae(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 De(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 se(e,t,o,s,n,r,i,a,f){let l=new Map(o.files.map(u=>[u.path,u])),p=[];for(let u of e){let m=l.get(u);if(!m)continue;let g=Re(m,t,o,n,r,a),c={...Le(g),_hasContentMatch:g._hasContentMatch,branch_changed:g.branch_changed,security_surface:g.security_surface},x=Ae(c,s),b=De(c);i?.has(u)&&(x+=ct,b.includes("dependent_neighbor")||b.push("dependent_neighbor")),f?.has(u)&&c.keyword===0&&(x=0,b.length=0,b.push("surface_auto_include")),p.push({path:u,score:x,features:c,reasons:b})}return p.sort((u,m)=>m.score-u.score),p}function pt(e){return e.some(t=>t.reasons.includes("keyword_match")||t.reasons.includes("test_relevant"))}function oe(e,t,o,s){return!!(t.max_files&&e.files.length>=t.max_files||t.tokens&&e.totalTokens>=t.tokens||s>0&&e.cumulativeScore/s>=o&&pt(e.files))}var G=require("node:fs"),Ne=require("node:path"),dt=10*1024*1024;function X(e,t,o,s,n){let r=(0,Ne.join)(e,t),i;try{let c=(0,G.statSync)(r).size;if(c>dt)return{content:`// File too large (${Math.round(c/1024)}KB), skipped`,spans:null,lineCount:1};i=(0,G.readFileSync)(r,"utf-8")}catch{return{content:"",spans:null,lineCount:0}}let a=i.split(`
|
|
8
|
+
`);if(a.length<=s)return{content:i,spans:null,lineCount:a.length};let f=[],l=new Set;for(let c=0;c<a.length;c++){let x=a[c];if(ft(x)){let b=Math.max(0,c-1),T=Math.min(a.length-1,c+1);ut(x)&&(T=ht(a,c,20)),f.push({start_line:b+1,end_line:T+1,reason:"type_surface"});for(let k=b;k<=T;k++)l.add(k)}}for(let c=0;c<a.length;c++){let x=a[c];if(mt(x)&&!l.has(c)){let b=Math.max(0,c-1),T=Math.min(a.length-1,c+2);f.push({start_line:b+1,end_line:T+1,reason:"export_signature"});for(let k=b;k<=T;k++)l.add(k)}}for(let c=0;c<a.length;c++){let x=a[c].toLowerCase();for(let b of o)if(x.includes(b)){let T=Math.max(0,c-n),k=Math.min(a.length-1,c+n);f.push({start_line:T+1,end_line:k+1,reason:`keyword_match:${b}`});for(let A=T;A<=k;A++)l.add(A);break}}let p=[...l].sort((c,x)=>c-x),u=[],m=-2;for(let c of p)c>m+1&&u.push(`
|
|
9
|
+
// ... (lines ${m+2}\u2013${c} omitted) ...
|
|
10
|
+
`),u.push(a[c]),m=c;let g=u.join(`
|
|
11
|
+
`),d=gt(f);return{content:g,spans:d,lineCount:p.length}}function ft(e){let o=e.trim().replace(/^export\s+(default\s+)?/,"").replace(/^declare\s+/,"");return o.startsWith("interface ")||o.startsWith("type ")||o.startsWith("enum ")||o.startsWith("function ")&&!o.includes("=>")||o.startsWith("abstract class ")||o.startsWith("class ")}function ut(e){let t=e.trim();return t.includes("{")&&!t.includes("}")}function ht(e,t,o){let s=0,n=Math.min(e.length-1,t+o);for(let r=t;r<=n;r++){let i=e[r];for(let a of i)a==="{"&&s++,a==="}"&&s--;if(s<=0&&r>t)return r}return n}function mt(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 gt(e){if(e.length===0)return[];let t=[...e].sort((s,n)=>s.start_line-n.start_line),o=[t[0]];for(let s=1;s<t.length;s++){let n=t[s],r=o[o.length-1];n.start_line<=r.end_line+1?(r.end_line=Math.max(r.end_line,n.end_line),r.reason=`${r.reason}+${n.reason}`):o.push({...n})}return o}var Ie=require("node:crypto");function re(e,t,o,s,n){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),f=a.filter(d=>d.reasons.includes("keyword_match")),l=f.length/a.length;if(l>=.6?(i+=.35,r.push(`Strong keyword signal: ${f.length}/${a.length} top files match task keywords`)):l>0?(i+=.15,r.push(`Weak keyword signal: only ${f.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 d=e[0].score,c=e[1].score;d>0&&c>0&&((d-c)/d>=.3?(i+=.2,r.push("Clear top-ranked file with significant score gap")):i+=.1)}let p=e.reduce((d,c)=>d+c.reasons.length,0)/e.length;p>=2?(i+=.2,r.push("Files selected for multiple independent reasons")):p>=1.5&&(i+=.1),o>=3?i+=.15:o>=2?i+=.1:r.push("Task description has few discriminating keywords \u2014 consider being more specific"),e.filter(d=>!d.reasons.every(c=>c==="test_relevant")).length>=e.length*.5&&(i+=.1);let m;if(i>=.65?m="high":i>=.35?m="medium":m="low",m!=="high"){let d=wt(e,l,o);for(let c of d)r.push(c)}let g=_t(e,s,n);return{level:m,score:Math.round(i*100)/100,reasons:r,envelope:g}}function _t(e,t,o){let s=e.filter(l=>!l.is_stub&&!l.is_exemplar),n=0;if(t&&s.length>0){let l=new Set(s.map(u=>u.path)),p=0;for(let u of s){let m=t.dep_graph.imports[u.path]??[],g=t.dep_graph.dependents[u.path]??[];(m.some(c=>l.has(c))||g.some(c=>l.has(c)))&&p++}n=p/s.length}else s.length>0&&(n=e.some(p=>p.reasons.includes("dependency_neighbor")||p.reasons.includes("dependent_neighbor"))?.5:.2);let r=0;s.length>0&&(r=s.filter(p=>p.reasons.includes("test_relevant")).length/s.length);let i=0;s.length>0&&(i=s.filter(p=>p.reasons.includes("recent_touch")||p.reasons.includes("high_churn")).length/s.length);let a=0;if(o&&o.length>0&&s.length>0){let l=new Set;for(let p of o)for(let u of s)if(u.path.toLowerCase().includes(p)){l.add(p);break}a=l.size/o.length}else if(s.length>0){let l=s.filter(p=>p.reasons.includes("keyword_match")).length;a=Math.min(1,l/Math.max(1,s.length*.5))}let f=0;if(t&&s.length>0){let l=new Set(s.map(u=>u.path)),p=0;for(let u of s){let m=0,g=[u.path],d=new Set;for(let c=0;c<3;c++){let x=[];for(let b of g){if(d.has(b))continue;d.add(b);let T=t.dep_graph.imports[b]??[];for(let k of T)l.has(k)&&!d.has(k)&&(x.push(k),m=c+1)}if(x.length===0)break;g=x}p+=m}f=Math.min(1,p/s.length/3)}return{structural_coverage:H(n),test_presence:H(r),churn_recency:H(i),keyword_saturation:H(a),dependency_depth:H(f)}}function H(e){return Math.round(e*100)/100}function wt(e,t,o){let s=[];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&&s.push(`Suggestion: try including file-specific keywords like "${r.join('", "')}" in your task`)}return o<=1&&s.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&&s.push("Suggestion: bundle contains only test files \u2014 add source file keywords to your task"),s}var Oe=require("node:fs"),Y=require("node:path");var yt={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},xt=4;function Fe(e,t){let o=yt[t.toLowerCase()]??xt;return Math.ceil(e*o)}function O(e,t){let o=St(t);return Fe(e,o)}var bt={".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 St(e){return bt[e.toLowerCase()]??"unknown"}function ie(e,t,o,s,n){let r=new Map;for(let l of t){let p=o.imports[l]??[];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((l,p)=>p[1]-l[1]).slice(0,s),a=[],f=0;for(let[l]of i){let p=(0,Y.join)(e,l),u;try{u=(0,Oe.readFileSync)(p,"utf-8")}catch{continue}let m=kt(u,l);if(!m)continue;let g=m.split(`
|
|
12
|
+
`).length,d=(0,Y.extname)(l),c=O(g,d);if(f+c>n)continue;let x=["interface_stub"];a.push({path:l,score:0,reasons:x,excerpt_spans:null,content:m,token_estimate:c,is_stub:!0}),f+=c}return a}function kt(e,t){let o=e.split(`
|
|
13
|
+
`),s=[],n=0;for(;n<o.length;){let r=o[n],i=r.trim();if(vt(i)){if(i.includes("{")&&!i.includes("}")){let a=Et(o,n);s.push(...a),n+=a.length;continue}s.push(r),n++;continue}if(Tt(i)){let a=Ct(o,n);s.push(a),n=Mt(o,n);continue}n++}return s.length===0?null:`// Interface stub (auto-generated by CodeLedger)
|
|
14
|
+
${s.join(`
|
|
15
|
+
`)}`}function vt(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 Tt(e){return e.startsWith("export ")?e.slice(7).replace(/^default\s+/,"").replace(/^async\s+/,"").startsWith("function "):!1}function Et(e,t){let o=[],s=0;for(let n=t;n<e.length&&n<t+50;n++){let r=e[n];o.push(r);for(let i of r)i==="{"&&s++,i==="}"&&s--;if(s<=0&&n>t)break}return o}function Ct(e,t){let o="";for(let s=t;s<e.length&&s<t+5;s++){let n=e[s],r=n.indexOf("{");if(r>=0){o+=n.slice(0,r).trimEnd()+";";break}o+=n+`
|
|
16
|
+
`}return o||e[t]}function Mt(e,t){let o=0;for(let s=t;s<e.length;s++){let n=e[s];for(let r of n)r==="{"&&o++,r==="}"&&o--;if(o<=0&&s>t)return s+1}return e.length}var Rt=[{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 o=[...Rt,...t??[]],s=[],n=e.split(`
|
|
17
|
+
`);for(let r=0;r<n.length;r++){let i=n[r],a=i.trim();if(!(a.startsWith("//")||a.startsWith("*")||a.startsWith("/*")))for(let f of o){let l;try{l=new RegExp(f.pattern)}catch{continue}let p=l.exec(i);p&&s.push({line:r+1,matched:p[0],message:f.message})}}return s}var Pe=require("node:fs"),R=require("node:path");var Lt=["add","create","implement","build","new","introduce","scaffold","write","make","generate","setup","set up"];function ce(e,t,o,s,n,r){if(!s.some(m=>Lt.includes(m)))return[];let a=new Set(t.map(m=>m.path)),f=new Map;for(let m of t){if(m.is_stub||m.is_exemplar)continue;let g=(0,R.dirname)(m.path),d=f.get(g)??[];d.push(m.path),f.set(g,d)}let l=[],p=0,u=new Set;for(let[m,g]of f){if(u.has(m))continue;if(l.length>=n)break;let d=o.files.filter(w=>a.has(w.path)||w.is_test?!1:(0,R.dirname)(w.path)===m);if(d.length===0)continue;let c=(0,R.extname)(g[0]),x=d.map(w=>{let S=0;(0,R.extname)(w.path)===c&&(S+=2);let h=(0,R.basename)(w.path,(0,R.extname)(w.path));for(let C of g){let N=(0,R.basename)(C,(0,R.extname)(C)),F=h.split(/[-_.]/),I=N.split(/[-_.]/),z=F.filter(E=>I.includes(E));S+=z.length*.5}return w.lines<=150?S+=1:w.lines<=300&&(S+=.5),{file:w,score:S}});x.sort((w,S)=>S.score-w.score);let b=x[0];if(!b||b.score<1)continue;let T=(0,R.join)(e,b.file.path),k;try{k=(0,Pe.readFileSync)(T,"utf-8")}catch{continue}let A=k.split(`
|
|
18
|
+
`).length,M=(0,R.extname)(b.file.path),D=O(A,M);if(p+D>r)continue;let y=["pattern_exemplar"];l.push({path:b.file.path,score:0,reasons:y,excerpt_spans:null,content:k,token_estimate:D,is_exemplar:!0}),p+=D,u.add(m)}return l}var je=["test","tests","testing","spec","specs","jest","vitest","mocha"],At=["config","configuration","settings","setup","env","environment"],Dt=["database","migration","schema","sql","query","model","table"];function le(e,t,o,s){let n=[],r=s.toLowerCase();!e.some(d=>!d.is_stub&&!d.is_exemplar&&d.reasons.includes("keyword_match"))&&e.length>0&&n.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(d=>je.includes(d))||je.some(d=>r.includes(d)),f=e.some(d=>d.path.includes(".test.")||d.path.includes(".spec.")||d.path.includes("__tests__"));a&&!f&&n.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 l=t.some(d=>At.includes(d)),p=e.some(d=>{let c=d.path.toLowerCase();return c.includes("config")||c.includes(".env")||c.includes("tsconfig")||c.includes("package.json")});l&&!p&&n.push({level:"info",code:"missing_config_files",message:"Task mentions configuration but no config files are in the bundle."});let u=t.some(d=>Dt.includes(d)),m=e.some(d=>{let c=d.path.toLowerCase();return c.includes("model")||c.includes("migration")||c.includes("schema")||c.includes(".sql")||c.includes("db/")||c.includes("database")});u&&!m&&n.push({level:"info",code:"missing_db_files",message:"Task mentions database/schema but no database files are in the bundle."});let g=e.filter(d=>!d.is_stub&&!d.is_exemplar);if(g.length>=5){let d=g[0]?.score??0,c=g[g.length-1]?.score??0;d>0&&c>0&&c/d>.85&&n.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(g.length===0&&n.push({level:"warning",code:"empty_bundle",message:"Bundle contains no source files. The task may not match any files in the repository."}),o.length>0&&g.length>0){let d=g[g.length-1].score,c=o.filter(x=>x.score>d&&!e.some(b=>b.path===x.path));c.length>3&&n.push({level:"info",code:"budget_squeeze",message:`${c.length} files with strong scores were excluded by budget constraints. Consider increasing --budget or --max-files.`})}return n}var Nt=5;function pe(e,t,o,s,n,r){let i=new Set(t.map(p=>p.path)),a=n??Nt,f=[],l=0;for(let p of e){if(l++,i.has(p.path)||p.score<=0)continue;if(f.length>=a)break;let m=r?.get(p.path)??Math.max(1,Math.round(p.features.size_penalty*1e3)),g=p.path.includes(".")?"."+p.path.split(".").pop():"",d=O(m,g),c=s?s-o:1/0,x=Math.max(0,d-c),b=Ft(p,x),T=[...p.reasons];f.push({path:p.path,score:Math.round(p.score*1e3)/1e3,rank:l,reasons:T,budget_gap_tokens:x,suggestion:b})}return f}function Ft(e,t){let o=[],s=e.path.split("/"),r=(s[s.length-1]??"").replace(/\.\w+$/,"").split(/[-_.]/).join(" ");return t>0&&o.push(`increase budget by ~${t} tokens`),e.features.keyword===0&&r&&o.push(`add "${r}" to your task description`),o.length===0&&o.push("increase --max-files or --budget"),o.join("; or ")}function de(e,t,o){let s=[],n=new Set(e.map(i=>i.path)),r=new Map;for(let i of o){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=>!n.has(u)),f=Ot(i.path,t,n),l=new Set,p=r.get(i.path)??[];for(let u of p)l.add(u);for(let u of a){let m=r.get(u)??[];for(let g of m)l.add(g)}for(let u of f){let m=r.get(u)??[];for(let g of m)l.add(g)}a.length===0&&f.length===0&&l.size===0||s.push({path:i.path,direct_dependents:a,transitive_dependents:f,impacted_tests:[...l]})}return s.sort((i,a)=>{let f=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-f}),s}function Ot(e,t,o){let s=new Set([e]),n=[],r=[e];for(let i=0;i<3;i++){let a=[];for(let f of r){let l=t.dependents[f]??[];for(let p of l)if(!s.has(p)){if(s.add(p),!o.has(p)&&(n.push(p),n.length>=20))return n;a.push(p)}}if(r=a,r.length===0)break}return n}var Pt=["fix","bug","broken","crash","error","issue","wrong","fail","incorrect","invalid","null","undefined","exception","regression","patch","hotfix"],jt=["add","create","implement","build","new","introduce","scaffold","feature","endpoint","component","page","route","service"],It=["refactor","restructure","reorganize","clean","simplify","extract","rename","move","split","merge","consolidate","optimize","improve","modernize","upgrade","migrate","replace"],zt=["test","tests","testing","spec","specs","coverage","assertion","mock","stub","fixture","jest","vitest","mocha","e2e","run","execute","validate","verify"],Wt=["config","configuration","settings","setup","env","environment","ci","pipeline","deploy","docker","workflow","lint","eslint","prettier","tsconfig","webpack","vite"];function fe(e){let o=e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(i=>i.length>0),s={bug_fix:0,feature_add:0,refactor:0,test_update:0,config:0,general:0};for(let i of o)Pt.includes(i)&&(s.bug_fix+=1),jt.includes(i)&&(s.feature_add+=1),It.includes(i)&&(s.refactor+=1),zt.includes(i)&&(s.test_update+=1),Wt.includes(i)&&(s.config+=1);let n="general",r=0;for(let[i,a]of Object.entries(s))a>r&&(r=a,n=i);return r>0?n:"general"}var $t={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},general:{}};function ue(e,t){let o=$t[t];if(Object.keys(o).length===0)return e;let s={...e};for(let[n,r]of Object.entries(o)){let i=s[n];typeof i=="number"&&(s[n]=i*r)}return s}var Bt=[{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}],Kt=5;function he(e,t){let o=t??Bt,s=e.toLowerCase();for(let n of o)if(s.includes(n.pattern))return n.layer;return Kt}function me(e,t){return[...e].sort((o,s)=>{let n=he(o.path,t),r=he(s.path,t);return n-r})}var Ut=[/\bTODO\b/i,/\bFIXME\b/i,/\bHACK\b/i,/\bXXX\b/i,/\bBUG\b(?:\s*#?\d+)/i,/\bWORKAROUND\b/i];function ge(e){let t=e.split(`
|
|
19
|
+
`),o=[],s=0;for(let r of t)for(let i of Ut){let a=i.exec(r);if(a){s++;let f=a[0].toUpperCase();o.includes(f)||o.push(f);break}}let n=t.length>0?Math.min(1,s/t.length*100):0;return{count:s,density:n,markers:o}}function _e(e){let{taskText:t,repoIndex:o,selectorConfig:s,budget:n=s.default_budget,sufficiencyThreshold:r=s.sufficiency_threshold,ledgerStats:i,explain:a=!1,scope:f,branchChangedFiles:l,includeNearMisses:p=!1,includeBlastRadius:u=!1,layerOrder:m=!1}=e,g=fe(t),d=ue(s.weights,g),c=K(t),x=l&&l.size>0?{...d,branch_changed:d.branch_changed??.15}:d;ne(c)&&(x={...x,security_surface:Math.max(x.security_surface??0,.2)});let{candidates:b,tokenWeights:T,fanoutFiles:k,surfaceFiles:A}=ee(t,o,s,f),M=se(b,c,o,x,i,T,k,l,A),D=M.reduce((_,v)=>_+Math.max(0,v.score),0),w=(n.max_files??1/0)<=15?2:0,S={...n,max_files:n.max_files?Math.max(1,n.max_files-w):void 0},h={files:[],totalTokens:0,cumulativeScore:0},C={};for(let _ of M){if(oe(h,S,r,D))break;let v=X(o.root,_.path,c,s.excerpt_full_file_max_lines,s.excerpt_window_lines),W=_.path.includes(".")?"."+_.path.split(".").pop():"",L=O(v.lineCount,W);if(n.tokens&&h.totalTokens+L>n.tokens*1.1&&h.files.length>0)break;let B=ae(v.content,s.deprecation_rules),q=ge(v.content),Be=_.reasons.includes("security_surface"),Ke={path:_.path,score:Math.round(_.score*1e3)/1e3,reasons:_.reasons,excerpt_spans:v.spans,content:v.content,token_estimate:L,deprecation_warnings:B.length>0?B:void 0,todo_count:q.count>0?q.count:void 0,security_relevant:Be||void 0};h.files.push(Ke),h.totalTokens+=L,h.cumulativeScore+=Math.max(0,_.score),a&&(C[_.path]=_.features)}let N=new Set(h.files.map(_=>_.path)),F=new Map(h.files.map(_=>[_.path,_.score])),I=[];for(let _ of o.test_map)N.has(_.source_file)&&!N.has(_.test_file)&&I.push({testPath:_.test_file,sourceScore:F.get(_.source_file)??0});I.sort((_,v)=>v.sourceScore-_.sourceScore);for(let{testPath:_}of I){if(n.max_files&&h.files.length>=n.max_files)break;let v=X(o.root,_,c,s.excerpt_full_file_max_lines,s.excerpt_window_lines),W=_.includes(".")?"."+_.split(".").pop():"",L=O(v.lineCount,W);if(n.tokens&&h.totalTokens+L>n.tokens*1.1)continue;let B=M.find(q=>q.path===_);h.files.push({path:_,score:B?Math.round(B.score*1e3)/1e3:0,reasons:B?.reasons??["test_relevant"],excerpt_spans:v.spans,content:v.content,token_estimate:L}),h.totalTokens+=L}let z=new Set(h.files.map(_=>_.path)),E=(n.tokens??1/0)-h.totalTokens,P=Math.max(0,(n.max_files??25)-h.files.length);if(P>0&&E>0){let _=ie(o.root,z,o.dep_graph,Math.min(P,5),Math.min(E,1e3));for(let v of _)h.files.push(v),h.totalTokens+=v.token_estimate}let j=re(h.files,h.cumulativeScore,c.length,o,c),$=new Set(h.files.map(_=>_.path)),Z=[];for(let _ of $){let v=o.dep_graph.imports[_]??[];for(let W of v)$.has(W)&&Z.push({from:_,to:W})}let be=(n.tokens??1/0)-h.totalTokens,Se=Math.max(0,(n.max_files??25)-h.files.length);if(Se>0&&be>0){let _=ce(o.root,h.files,o,c,Math.min(Se,2),Math.min(be,2e3));for(let v of _)h.files.push(v),h.totalTokens+=v.token_estimate}if(m){let _=h.files.filter(L=>!L.is_stub&&!L.is_exemplar),v=h.files.filter(L=>L.is_stub||L.is_exemplar),W=me(_);h.files=[...W,...v]}let ke=le(h.files,c,M,t),J=p?(()=>{let _=new Map(o.files.map(v=>[v.path,v.lines]));return pe(M,h.files,h.totalTokens,n.tokens,void 0,_)})():void 0,V=u?de(h.files,o.dep_graph,o.test_map):void 0;return{bundle_id:`bnd_${(0,Ie.randomUUID)().slice(0,12)}`,task:t,budget:n,sufficiency_threshold:r,cumulative_score:Math.round(h.cumulativeScore*1e3)/1e3,files:h.files,total_tokens:h.totalTokens,generated_at:new Date().toISOString(),confidence:j,explain:a?C:void 0,file_relationships:Z.length>0?Z:void 0,warnings:ke.length>0?ke:void 0,near_misses:J&&J.length>0?J:void 0,blast_radius:V&&V.length>0?V:void 0}}var Ht=require("node:crypto");var ze=require("node:fs"),Qt=require("node:path"),ps=10*1024*1024;var We=require("node:crypto");var xe="0.1.0";function cn(e){return e.includes("--version")?(process.stdout.write(`codeledger-core ${xe}
|
|
20
|
+
`),!0):e.includes("--license")?(process.stdout.write([`CodeLedger Core Engine v${xe}`,"","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
|
+
`)),!0):e.includes("--explain-architecture")?(process.stdout.write([`CodeLedger Core Engine v${xe} \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 ln(){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 pn(){if(cn(process.argv.slice(2)))return;let e=await ln(),t=JSON.parse(e),o;if(t.indexPath)o=JSON.parse((0,$e.readFileSync)(t.indexPath,"utf-8"));else if(t.repoIndex)o=t.repoIndex;else throw new Error("Either indexPath or repoIndex must be provided");let s=t.ledgerStats?{success_files:new Set(t.ledgerStats.success_files),fail_files:new Set(t.ledgerStats.fail_files)}:void 0,n=t.branchChangedFiles?new Set(t.branchChangedFiles):void 0,r=_e({taskText:t.task,repoIndex:o,selectorConfig:t.selectorConfig,budget:t.budget,explain:t.explain,ledgerStats:s,scope:t.scope,branchChangedFiles:n,includeNearMisses:t.includeNearMisses,includeBlastRadius:t.includeBlastRadius,layerOrder:t.layerOrder});process.stdout.write(JSON.stringify(r))}pn().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.
|
|
3
|
+
"version": "0.5.1",
|
|
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.
|
|
28
|
+
"@codeledger/types": "0.5.1"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"typescript": "^5.4.0",
|
|
32
|
-
"@codeledger/selector": "0.
|
|
32
|
+
"@codeledger/selector": "0.5.1"
|
|
33
33
|
},
|
|
34
34
|
"scripts": {
|
|
35
35
|
"build": "tsc",
|