@glyphier/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +48 -0
- package/dist/admission-Q3FJHJAY.js +1 -0
- package/dist/agent-adapters-2VCI4NIX.js +1 -0
- package/dist/bin/glyphier.js +33 -0
- package/dist/chunk-B6KCBY3J.js +4 -0
- package/dist/chunk-BJ2IE33Q.js +49 -0
- package/dist/chunk-FOZKI4M3.js +13 -0
- package/dist/chunk-H6T36TY5.js +2 -0
- package/dist/chunk-I6N5RRFT.js +2 -0
- package/dist/chunk-JJMQEAIJ.js +5 -0
- package/dist/chunk-MCPBJALB.js +2 -0
- package/dist/chunk-NIXOREHQ.js +139 -0
- package/dist/chunk-NZULHZGK.js +2 -0
- package/dist/chunk-PCRAPKFZ.js +2 -0
- package/dist/chunk-QYSMWA6Y.js +2 -0
- package/dist/chunk-VOGFZYFC.js +47 -0
- package/dist/chunk-WJT5SDKF.js +1 -0
- package/dist/chunk-Z4N35S7K.js +1 -0
- package/dist/chunk-ZOFLEGRO.js +2 -0
- package/dist/doc-compiler-6H72TGND.js +1 -0
- package/dist/doctor-6OEYEF3A.js +1 -0
- package/dist/document-artifact-RJPU3IRZ.js +1 -0
- package/dist/drift-detector-BY6RWGWP.js +1 -0
- package/dist/explainer-N5B56KNI.js +1 -0
- package/dist/index.d.ts +1421 -0
- package/dist/index.js +1 -0
- package/dist/mcp/glyphier-server.js +2 -0
- package/dist/replanner-NZ3A5THM.js +1 -0
- package/dist/store-T3OGOKTC.js +1 -0
- package/dist/task-planner-JPPFKAG5.js +1 -0
- package/dist/trace-ZLOFETDM.js +1 -0
- package/package.json +76 -0
- package/queries/go/tags.scm +18 -0
- package/queries/python/tags.scm +16 -0
- package/queries/rust/tags.scm +24 -0
- package/queries/typescript/tags.scm +26 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import{a as Oe}from"./chunk-QYSMWA6Y.js";import{b as A,e as K,f as Me}from"./chunk-NIXOREHQ.js";import J from"fs";import M from"path";var W={ignore:["node_modules/**","**/node_modules/**","node_modules","dist/**","**/dist/**","build/**","**/build/**",".next/**","**/.next/**",".turbo/**","**/.turbo/**","out/**","**/out/**",".git/**","**/.git/**","coverage/**","**/coverage/**","**/.cache/**",".glyphier/**","**/.glyphier/**","**/*.min.js","**/*.bundle.js","**/*.map"],maxFileSize:100*1024,defaultLevel:2,callFilter:{exclude:["console.log","console.error","console.warn","console.info","console.debug","print","println","fmt.Println","fmt.Printf","logger.debug"]}};function Ne(e=process.cwd()){let n=M.resolve(e);for(;;){let t=M.join(n,".glyphierrc.json");if(J.existsSync(t))try{let i=J.readFileSync(t,"utf-8"),o=JSON.parse(i);return{...W,...o,ignore:Array.from(new Set([...W.ignore,...o.ignore||[]])),callFilter:{exclude:Array.from(new Set([...W.callFilter?.exclude||[],...o.callFilter?.exclude||[]]))}}}catch(i){return console.warn(`[glyphier] Failed to parse ${t}:`,i),W}let s=M.dirname(n);if(s===n)break;n=s}return W}function Ge(e=process.cwd()){let n=M.resolve(e);J.existsSync(n)&&J.statSync(n).isFile()&&(n=M.dirname(n));let t=null;for(;;){if(J.existsSync(M.join(n,".git"))||J.existsSync(M.join(n,"pnpm-workspace.yaml")))return n;J.existsSync(M.join(n,"package.json"))&&(t=n);let s=M.dirname(n);if(s===n)break;n=s}return t||M.resolve(e)}var Ce=class{entries=new Map;hits=0;misses=0;get(n,t){let s=this.entries.get(n);if(s)return t!==void 0&&s.mtime!==t?(this.entries.delete(n),this.misses++,null):(this.hits++,s.ir);try{let o=A().getIR(n,0);if(o){let a=JSON.parse(o);if(t===void 0||a.metadata?.mtime===t)return this.entries.set(n,{mtime:a.metadata?.mtime||t||0,ir:a}),this.hits++,a}}catch{}return this.misses++,null}set(n,t,s){this.entries.set(n,{mtime:t,ir:s});try{A().setIR(n,0,String(t),JSON.stringify(s))}catch{}}isValid(n,t){let s=this.entries.get(n);return s!==void 0&&s.mtime===t}delete(n){return this.entries.delete(n)}clear(){this.entries.clear(),this.hits=0,this.misses=0}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses}}},ie=new Ce;import wt from"web-tree-sitter";import De from"fs";var je=new Map;async function oe(e,n){let t=n||"typescript",s=await Me(t);if(!s)return null;let i=je.get(t);i||(i=new wt,i.setLanguage(s),je.set(t,i));try{let o=i.parse(e),a=e.split(`
|
|
2
|
+
`).length;return{tree:o,language:t,langInstance:s,lineCount:a}}catch{try{i.delete()}catch{}return je.delete(t),null}}async function We(e){let n=K(e);if(!n||!De.existsSync(e))return null;let t=De.readFileSync(e,"utf-8");return oe(t,n)}import z from"path";import ze from"fs";function I(e){if(!e)return"void";let n=e.trim().replace(/^[:\->\s]+/,"").replace(/^[|\s]+/,"").replace(/\s+/g," ");if(n.includes("|")){let r=n.split("|").map(l=>l.trim()).filter(Boolean);if(r.length>0&&r.every(l=>/^['"].*['"]$/.test(l)))return r.join("|")}let t=n.match(/^Promise<(.+)>$/);if(t)return I(t[1]);let s={string:"str",str:"str",String:"str",number:"int",int:"int",integer:"int",i8:"int",i16:"int",i32:"int",i64:"int",u8:"int",u16:"int",u32:"int",u64:"int",usize:"int",isize:"int",float:"float",f32:"float",f64:"float",double:"float",boolean:"bool",bool:"bool",Boolean:"bool",void:"void",None:"void",unit:"void",any:"any",unknown:"any",object:"any",Object:"any"};if(s[n])return s[n];let i=n.match(/^(?:Array|Vec|list)<(.+)>$/i)||n.match(/^(.+)\[\]$/);if(i)return`arr<${I(i[1])}>`;let o=n.match(/^(?:Map|Record|dict)<([^,]+),\s*(.+)>$/i);if(o)return`map<${I(o[1])},${I(o[2])}>`;let a=n.match(/^(?:Optional|Option)<(.+)>$/i)||n.match(/^(.+)\s*\|\s*(?:null|undefined)$/);return a?`opt<${I(a[1])}>`:n}function qe(e,n,t,s,i={}){let o=i.level??2,a=i.config??W,r=i.rootPath??process.cwd(),l=z.isAbsolute(n)?z.relative(r,n):n,p=l.replace(/\.[^/.]+$/,"").replace(/\\/g,"/"),f=e.rootNode,c=[],d=[],h=[],y=[],v=[],g=new Set(a.callFilter?.exclude||[]);function S(x,C=!1){if(x.hasError&&x.type==="ERROR"&&v.push({kind:"error",message:"Syntax error",lines:{start:x.startPosition.row+1,end:x.endPosition.row+1}}),x.type==="export_statement"){for(let N=0;N<x.childCount;N++){let _=x.child(N);_&&_.type!=="export"&&_.type!=="default"&&$(_,!0)}return}C&&$(x,!1)}function $(x,C){let j=x.type;if(j==="import_statement"||j==="import_from_statement"||j==="use_declaration"||j==="import_declaration"){if(t==="go"){let _=kt(x);for(let T of _)c.push(T);return}let N=vt(x,t);N&&c.push(N);return}if(j==="type_declaration"){for(let N=0;N<x.childCount;N++){let _=x.child(N);if(_&&_.type==="type_spec"){let T=Be(_);T&&(T.isExported=C,d.push(T))}}return}if(j==="interface_declaration"||j==="type_alias_declaration"||j==="enum_declaration"||j==="struct_item"||j==="enum_item"||j==="trait_item"||j==="type_spec"){let N=Be(x);N&&(N.isExported=C,d.push(N));return}if(j==="const_declaration"){Nt(x,d);return}if(j==="class_declaration"||j==="class_definition"||j==="impl_item"){let N=Pt(x,o,g);N&&(N.isExported=C,y.push(N));return}if(j==="function_declaration"||j==="function_definition"||j==="function_item"||j==="method_declaration"){let N=Ue(x,o,g);N&&(N.isExported=C,h.push(N));return}if(j==="lexical_declaration"||j==="variable_declaration"){for(let N=0;N<x.childCount;N++){let _=x.child(N);if(_&&(_.type==="variable_declarator"||_.type==="lexical_declarator")){let T=Ct(_,o,g);if(T)T.isExported=C,h.push(T);else if(C){let E=_.child(0),U=_.child(2)||_.child(1);if(E&&E.text&&E.type==="identifier"){let H=U?U.text.replace(/\s+/g," ").slice(0,50):"";d.push({kind:"type",name:E.text,lines:{start:_.startPosition.row+1,end:_.endPosition.row+1},fields:[],isExported:!0,values:H?[H]:void 0})}}}}return}for(let N=0;N<x.childCount;N++){let _=x.child(N);_&&S(_,!1)}}for(let x=0;x<f.childCount;x++){let C=f.child(x);C&&S(C,!0)}let m=new Map;for(let x of h)if(m.set(x.name,x.lines.start),x.name.includes(".")){let C=x.name.split(".").pop();m.set(C,x.lines.start)}let u=new Set;for(let x of c){let C=x.path.split("/").pop()?.replace(/^[@_]/,"")||x.path;u.add(C);for(let j of x.symbols)u.add(j)}for(let x of h)if(x.calls&&x.calls.length>0){let C=x.name.match(/^\(([^)]+)\)\./),j=C?C[1]:"";x.calls=x.calls.map(N=>{if(typeof N!="string")return N;if(N.startsWith("this.")||N.startsWith("self.")){let _=N.replace(/^this\.|^self\./,""),T=m.get(_);return{name:_,scope:"self",line:T}}if(j&&N.includes(".")){let _=N.split("."),T=_[_.length-1],E=`(${j}).${T}`;if(m.has(E))return{name:T,scope:"self",line:m.get(E)}}if(m.has(N))return{name:N,scope:"local",line:m.get(N)};if(N.includes(".")){let _=N.split("."),T=_[0],E=_.slice(1).join(".");if(u.has(T))return{name:E,scope:"ext",target:T}}return N})}if(o===2&&!n.includes("_test.")&&!n.includes(".test.")&&!n.includes(".spec.")){let x=z.dirname(n),C=z.basename(n),j=z.extname(n),N=C.slice(0,-j.length),_=[];t==="go"?_.push(z.join(x,`${N}_test.go`)):(_.push(z.join(x,`${N}.test${j}`)),_.push(z.join(x,`${N}.spec${j}`)),_.push(z.join(x,"__tests__",`${N}.test${j}`)));for(let T of _)if(ze.existsSync(T)){try{let E=ze.readFileSync(T,"utf-8");Ft(E,h,t)}catch{}break}}let b=h.length+y.reduce((x,C)=>x+C.methods.length,0),w={path:l,language:t,lineCount:s,functionCount:b,mtime:Date.now()};return{module:{kind:"mod",name:p,lines:{start:1,end:Math.max(1,s)},imports:c,types:d,functions:h,classes:y,errors:v.length>0?v:void 0},metadata:w}}function vt(e,n){let t=e.text;if(n==="typescript"||n==="javascript"||n==="tsx"){let s=t.match(/from\s+['"]([^'"]+)['"]/),i=s?s[1]:"",o=[],a=t.match(/\{([^}]+)\}/);a&&a[1].split(",").forEach(p=>{let f=p.trim().split(/\s+as\s+/)[0];f&&o.push(f)});let r=t.match(/import\s+([a-zA-Z0-9_$]+)\s+from/);r&&o.push(r[1]);let l=t.match(/import\s+\*\s+as\s+([a-zA-Z0-9_$]+)\s+from/);if(l&&o.push(`*:${l[1]}`),i||o.length>0)return{kind:"use",path:i||t,symbols:o}}if(n==="python"){let s=t.match(/from\s+([^\s]+)\s+import\s+(.+)/);if(s){let o=s[2].split(",").map(a=>a.trim().split(/\s+as\s+/)[0]);return{kind:"use",path:s[1],symbols:o}}let i=t.match(/import\s+(.+)/);if(i){let o=i[1].split(",").map(a=>a.trim().split(/\s+as\s+/)[0]);return{kind:"use",path:o[0]||"",symbols:o}}}if(n==="rust")return{kind:"use",path:t.replace(/^use\s+/,"").replace(/;$/,"").trim(),symbols:[]};if(n==="go"){let s=t.match(/"([^"]+)"/g);if(s){let i=s.map(o=>o.replace(/"/g,""));return{kind:"use",path:i.join(","),symbols:i}}}return{kind:"use",path:t.trim().slice(0,50),symbols:[]}}function kt(e){let n=[];function t(s){if(s.type==="import_spec"){let i="",o="";for(let a=0;a<s.childCount;a++){let r=s.child(a);r&&(r.type==="package_identifier"||r.type==="identifier"&&a===0?i=r.text:(r.type==="interpreted_string_literal"||r.type==="raw_string_literal"||r.type==="string_literal")&&(o=r.text.replace(/^"|"$/g,"").replace(/^`|`$/g,"").trim()))}if(!o){let a=s.text.match(/"([^"]+)"|`([^`]+)`/);a&&(o=a[1]||a[2])}if(o){let a=i?[i]:[];n.push({kind:"use",path:o,symbols:a})}return}for(let i=0;i<s.childCount;i++){let o=s.child(i);o&&t(o)}}return t(e),n}function Nt(e,n){function t(s){if(s.type==="const_spec"){let i="",o="",a="";for(let r=0;r<s.childCount;r++){let l=s.child(r);l&&(l.type==="identifier"&&!i?i=l.text:l.type==="type_identifier"?o=l.text:l.type==="expression_list"&&(a=l.text.replace(/^["'`]|["'`]$/g,"").trim()))}if(o){let r=n.find(l=>l.name===o);if(r){r.values||(r.values=[]);let l=a?`"${a}"`:i;r.values.includes(l)||r.values.push(l)}}return}for(let i=0;i<s.childCount;i++){let o=s.child(i);o&&t(o)}}t(e)}function Be(e){let n="",t=[],s=[];for(let a=0;a<e.childCount;a++){let r=e.child(a);r&&(r.type==="type_identifier"||r.type==="identifier"||r.type==="name")&&(n||(n=r.text))}if(!n)return null;function i(a){if(a.type==="property_signature"){let r="",l=!1,p="";for(let f=0;f<a.childCount;f++){let c=a.child(f);if(c&&!(c.type==="readonly"||c.type==="accessibility_modifier"||c.type==="static"||c.type==="override")){if(c.type==="property_identifier"||c.type==="identifier"||c.type==="string"){r||(r=c.text.replace(/^['"]|['"]$/g,""));continue}if(c.type==="?"||c.text==="?"){l=!0;continue}c.type==="type_annotation"&&(p=c.text.replace(/^:\s*/,"").trim())}}if(r){let f=I(p||"any");l&&!f.startsWith("opt<")&&(f=`opt<${f}>`),t.push({name:r,type:f})}return}if(a.type==="field_declaration"||a.type==="struct_field"){let r="",l="";for(let p=0;p<a.childCount;p++){let f=a.child(p);f&&(f.type==="field_identifier"||f.type==="identifier"||f.type==="property_identifier"?r||(r=f.text):(f.type==="type_identifier"||f.type==="type"||f.type==="type_annotation"||f.type==="primitive_type")&&(l||(l=f.text.replace(/^:\s*/,"").trim())))}r||(r=a.child(0)?.text||""),l||(l=a.child(1)?.text||"any"),r&&r!=="readonly"&&t.push({name:r,type:I(l)});return}if(a.type==="method_spec"){let r="",l=[],p="void";for(let f=0;f<a.childCount;f++){let c=a.child(f);c&&(c.type==="field_identifier"||c.type==="identifier"?r||(r=c.text):c.type==="parameter_list"?f===1?re(c,l):p=c.text.replace(/\s+/g,""):(c.type==="type_identifier"||c.type==="pointer_type"||c.type==="qualified_type")&&(p=c.text.replace(/\s+/g,"")))}if(r){let f=l.map(c=>`${c.name}:${c.type}`).join(",");t.push({name:r,type:`(${f})->${p}`})}return}for(let r=0;r<a.childCount;r++){let l=a.child(r);l&&i(l)}}function o(a){if(a.type==="union_type"){for(let r=0;r<a.childCount;r++){let l=a.child(r);if(!l||l.type==="|"||l.text==="|")continue;if(l.type==="union_type"){o(l);continue}let p=l.text.replace(/^[|\s]+|[|\s]+$/g,"").replace(/\s+/g," ").trim();p&&!s.includes(p)&&s.push(p)}return}if(a.type==="enum_assignment"||a.type==="enum_member"||a.type==="enum_variant"){let r=a.text.replace(/\s+/g," ").trim();r&&!s.includes(r)&&s.push(r);return}for(let r=0;r<a.childCount;r++){let l=a.child(r);l&&o(l)}}return(e.type==="type_alias_declaration"||e.type==="enum_declaration"||e.type==="enum_item"||e.type==="type_spec")&&o(e),s.length===0&&i(e),{kind:"type",name:n,lines:{start:e.startPosition.row+1,end:e.endPosition.row+1},fields:t,values:s.length>0?s:void 0}}function Ue(e,n,t){let s="",i=[],o="void",a=!1;if(e.type==="method_declaration"){let p="",f=e.child(1);if(f&&f.type==="parameter_list")for(let v=0;v<f.childCount;v++){let g=f.child(v);if(g&&g.type==="parameter_declaration")for(let S=0;S<g.childCount;S++){let $=g.child(S);$&&$.type!=="identifier"&&$.type!==","&&(p=$.text.replace(/\s+/g,""))}}let c=e.child(2),d=c?c.text:"";s=p?`(${p}).${d}`:d;let h=e.child(3);h&&h.type==="parameter_list"&&re(h,i);let y=e.child(e.childCount-1);if(e.childCount>=6&&y&&(y.type==="block"||y.type==="statement_block")){let v=e.child(e.childCount-2);v&&v.type!=="block"&&v.type!=="statement_block"&&(o=I(v.text.replace(/\s+/g,"")))}}else if(e.type==="function_declaration"&&e.child(0)?.type==="func"){let p=e.child(1);p&&(s=p.text);let f=e.child(2);f&&f.type==="parameter_list"&&re(f,i);let c=e.child(e.childCount-1);if(e.childCount>=5&&c&&(c.type==="block"||c.type==="statement_block")){let d=e.child(e.childCount-2);d&&d.type!=="block"&&d.type!=="statement_block"&&(o=I(d.text.replace(/\s+/g,"")))}}else for(let p=0;p<e.childCount;p++){let f=e.child(p);f&&(f.type==="async"&&(a=!0),(f.type==="identifier"||f.type==="property_identifier"||f.type==="field_identifier"||f.type==="name")&&(s||(s=f.text)),(f.type==="formal_parameters"||f.type==="parameters"||f.type==="parameter_list")&&re(f,i),(f.type==="type_annotation"||f.type==="return_type")&&(o=I(f.text)))}if(!s)return null;let r={kind:"fn",name:s,lines:{start:e.startPosition.row+1,end:e.endPosition.row+1},params:i,returnType:o,isAsync:a||void 0},l=_e(e);if(l.length>0&&(r.decorators=l),n===2){let p=He(e);if(p){let f=Ke(p,t);f.validates.length>0&&(r.validates=f.validates),f.calls.length>0&&(r.calls=f.calls),f.throws.length>0&&(r.throws=f.throws),f.states.length>0&&(r.states=f.states),f.returns.length>0&&(r.returns=f.returns)}}return r}function Ct(e,n,t){let s=e.child(0),i=e.child(2)||e.child(1);if(!s||!i)return null;let o=s.text;if(i.type==="arrow_function"||i.type==="function_expression"){let a=[],r="void",l=!1;for(let c=0;c<i.childCount;c++){let d=i.child(c);d&&(d.type==="async"&&(l=!0),(d.type==="formal_parameters"||d.type==="parameters")&&re(d,a),d.type==="type_annotation"&&(r=I(d.text)))}let p={kind:"fn",name:o,lines:{start:e.startPosition.row+1,end:e.endPosition.row+1},params:a,returnType:r,isAsync:l||void 0},f=_e(e);if(f.length>0&&(p.decorators=f),n===2){let c=He(i);if(c){let d=Ke(c,t);d.validates.length>0&&(p.validates=d.validates),d.calls.length>0&&(p.calls=d.calls),d.throws.length>0&&(p.throws=d.throws),d.states.length>0&&(p.states=d.states),d.returns.length>0&&(p.returns=d.returns)}}return p}return null}function re(e,n){for(let t=0;t<e.childCount;t++){let s=e.child(t);if(s){if(s.type==="required_parameter"||s.type==="optional_parameter"||s.type==="parameter"||s.type==="identifier"){let i="",o="any";for(let a=0;a<s.childCount;a++){let r=s.child(a);r&&(r.type==="identifier"?i=r.text:r.type==="type_annotation"&&(o=I(r.text)))}i||(i=s.text.split(":")[0].trim()),i&&i!=="("&&i!==")"&&i!==","&&n.push({name:i,type:o})}else if(s.type==="parameter_declaration"||s.type==="variadic_parameter_declaration"){let i=s.type==="variadic_parameter_declaration",o=[],a=null;for(let r=0;r<s.childCount;r++){let l=s.child(r);!l||l.type===","||l.type==="..."||(l.type==="identifier"?o.push(l.text):a=l)}if(a){let r=I((i?"...":"")+a.text.replace(/\s+/g,""));if(o.length===0)n.push({name:"_",type:r});else for(let l of o)n.push({name:l,type:r})}else if(o.length>1){let r=o.pop(),l=I((i?"...":"")+r);for(let p of o)n.push({name:p,type:l})}else o.length===1&&n.push({name:o[0],type:"any"})}}}}function He(e){for(let n=0;n<e.childCount;n++){let t=e.child(n);if(t&&(t.type==="statement_block"||t.type==="block"||t.type==="compound_statement"))return t}return null}function _e(e){let n=[];function t(i){let o="",a=[],r=i.child(1)||i.child(0);if(r){if(r.type==="identifier")o=r.text;else if(r.type==="call_expression"){let l=r.child(0);o=l?l.text:"";let p=r.child(1);if(p)for(let f=0;f<p.childCount;f++){let c=p.child(f);if(c){if(c.type==="string"||c.type==="string_fragment"||c.type==="number"||c.type==="identifier"){let d=c.text.replace(/^['"]|['"]$/g,"").trim();d&&d!=="("&&d!==")"&&d!==","&&a.push(d)}else if(c.type==="object"||c.type==="object_expression")for(let d=0;d<c.childCount;d++){let h=c.child(d);if(h&&(h.type==="pair"||h.type==="property_assignment")){let y=h.child(0),v=h.child(2)||h.child(1),g=y?.text||"";if(!g)continue;if(v?.type==="string"||v?.type==="number"||v?.type==="identifier"){let S=v.text.replace(/^['"]|['"]$/g,"").trim();a.push(`${g}:${S}`)}else if(v?.type==="array"||v?.type==="array_expression"){let S=[];for(let $=0;$<v.childCount;$++){let m=v.child($);if(m){if(m.type==="identifier")S.push(m.text);else if(m.type==="call_expression"){let u=m.child(0)?.text||"",w=(m.child(1)?.text||"").match(/name:\s*['"]([^'"]+)['"]/);w?S.push(`${u.split(".").pop()}(${w[1]})`):S.push(u.split(".").pop()||u)}}}S.length>0&&a.push(`${g}:[${S.slice(0,8).join(",")}${S.length>8?`+${S.length-8}`:""}]`)}}}}}}else{let p=i.text.replace(/^@/,"").trim().match(/^([a-zA-Z0-9_$]+)(?:\((.*)\))?/);p&&(o=p[1],p[2]&&p[2].split(",").map(f=>f.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean).forEach(f=>a.push(f)))}o&&o!=="@"&&n.push({name:o,args:a.length>0?a:void 0})}}for(let i=0;i<e.childCount;i++){let o=e.child(i);o&&o.type==="decorator"&&t(o)}if(e.parent&&e.parent.type==="export_statement")for(let i=0;i<e.parent.childCount;i++){let o=e.parent.child(i);o&&o.type==="decorator"&&t(o)}let s=e.previousSibling;for(;s&&(s.type==="decorator"||s.type==="comment");)s.type==="decorator"&&t(s),s=s.previousSibling;for(let i=0;i<e.childCount;i++){let o=e.child(i);if(o&&(o.type==="formal_parameters"||o.type==="parameters"))for(let a=0;a<o.childCount;a++){let r=o.child(a);if(r)for(let l=0;l<r.childCount;l++){let p=r.child(l);p&&p.type==="decorator"&&t(p)}}}return n}function Ke(e,n){let t=new Set,s=new Set,i=new Set,o=new Set,a=new Set;function r(l){let p=l.type;if(p==="call_expression"||p==="call"){let f=jt(l);f&&!n.has(f)&&t.add(f);let c=l.child(1);if(c&&c.type==="arguments")for(let d=0;d<c.childCount;d++){let h=c.child(d);if(h&&(h.type==="string"||h.type==="string_fragment")){let y=h.text.replace(/^['"]|['"]$/g,"").trim();y&&y.length<=35&&/^[a-zA-Z0-9_\-:]+$/.test(y)&&o.size<12&&o.add(y)}}}if(p==="if_statement"){let f=l.child(1);f&&_t(f,s)}if(p==="string"||p==="string_fragment"){let f=l.text.replace(/^['"]|['"]$/g,"").trim();if(f&&f.length>=2&&f.length<=40){let c=l.parent;for(;c&&(c.type==="ternary_expression"||c.type==="conditional_expression"||c.type==="parenthesized_expression"||c.type==="string");)c=c.parent;if(c)if(c.type==="binary_expression")o.size<16&&o.add(f);else if(c.type==="pair"){let d=c.child(0)?.text;d&&/^(status|stage|state|code|category|mode|kind|type|reason|error|action|event|errorCode|syncStatus)$/i.test(d)&&o.size<16&&o.add(f)}else c.type==="switch_case"&&o.size<16&&o.add(f)}}if(p==="return_statement"){let f=l.child(1);if(f&&f.type==="object"){let c=f.text.replace(/\s+/g,"");c.length<=65&&a.size<4&&a.add(c)}}if(p==="throw_statement"||p==="raise_statement"){let f=Tt(l);f&&i.add(f)}for(let f=0;f<l.childCount;f++){let c=l.child(f);c&&r(c)}}return r(e),{validates:Array.from(s),calls:Array.from(t),throws:Array.from(i),states:Array.from(o),returns:Array.from(a)}}function jt(e){let n=e.child(0);if(!n)return null;if(n.type==="identifier")return n.text;if(n.type==="member_expression"||n.type==="selector_expression"||n.type==="attribute"||n.type==="field_expression"){let s=(n.childForFieldName("property")||n.child(n.childCount-1))?.text;if(!s||new Set(["where","andWhere","orWhere","set","orderBy","addOrderBy","limit","offset","select","addSelect","groupBy","addGroupBy","having","andHaving","then","catch","finally"]).has(s))return null;let o=n.childForFieldName("object")||n.child(0);for(;o&&o.type==="call_expression";){let r=o.child(0);if(r&&(r.type==="member_expression"||r.type==="selector_expression"))o=r.childForFieldName("object")||r.child(0);else break}let a=o?o.text.replace(/^this\./,"").replace(/\s+/g,""):"";return a&&!a.includes("(")&&!a.includes("[")?`${a}.${s}`:s}return null}function _t(e,n){let s=e.text.matchAll(/(?:!|not\s+)([a-zA-Z0-9_$]+)\s*\(/g);for(let i of s)n.add(i[1])}function Tt(e){let t=e.text.match(/(?:throw\s+(?:new\s+)?|raise\s+)([a-zA-Z0-9_$]+)/);return t?t[1]:null}function Pt(e,n,t){let s="",i,o=[],a=[];for(let l=0;l<e.childCount;l++){let p=e.child(l);if(p){if((p.type==="type_identifier"||p.type==="identifier"||p.type==="name")&&(s||(s=p.text)),p.type==="class_heritage"||p.type==="extends_clause"){let f=p.text.match(/extends\s+([a-zA-Z0-9_$]+)/);f&&(i=f[1]);let c=p.text.match(/implements\s+(.+)/);c&&c[1].split(",").forEach(d=>o.push(d.trim()))}if(p.type==="class_body"||p.type==="statement_block"||p.type==="declaration_list"||p.type==="block")for(let f=0;f<p.childCount;f++){let c=p.child(f);if(c&&(c.type==="method_definition"||c.type==="function_item"||c.type==="function_definition")){let d=Ue(c,n,t);d&&a.push(d)}}}}if(!s)return null;let r=_e(e);return{kind:"class",name:s,lines:{start:e.startPosition.row+1,end:e.endPosition.row+1},extends:i,implements:o.length>0?o:void 0,methods:a,decorators:r.length>0?r:void 0}}function Ft(e,n,t){if(t==="go"){let s=[...e.matchAll(/func\s+(Test[A-Za-z0-9_]+)\s*\(/g)].map(i=>i[1]);for(let i of s){let o=e.indexOf("func "+i);if(o===-1)continue;let a=e.indexOf(`
|
|
3
|
+
func Test`,o+1),r=e.slice(o,a!==-1?a:void 0);for(let l of n){let p=l.name.split(".").pop();(r.includes(`.${p}(`)||r.includes(`${p}(`))&&(l.tests||(l.tests=[]),!l.tests.includes(i)&&l.tests.length<5&&l.tests.push(i))}}}else{let s=[...e.matchAll(/(?:it|test)\s*\(\s*['"]([^'"]+)['"]/g)].map(i=>i[1]);for(let i of s)for(let o of n){let a=o.name.split(".").pop();if(e.includes(a)){o.tests||(o.tests=[]);let r=i.slice(0,35);!o.tests.includes(r)&&o.tests.length<5&&o.tests.push(r)}}}}import Y from"fs";import O from"path";import Et from"ignore";var It=new Set(["node_modules",".git",".next","dist","build","out","coverage",".turbo",".cache",".glyphier"]);async function pe(e,n={}){let t=O.resolve(n.rootPath||e),s=n.depth??1/0,i=n.config||W,o=Et();o.add(i.ignore),n.ignore&&n.ignore.length>0&&o.add(n.ignore);let a=O.join(t,".gitignore");if(Y.existsSync(a))try{let l=Y.readFileSync(a,"utf-8");o.add(l)}catch{}async function r(l,p){let f=O.relative(t,l)||".",c=O.basename(l)||O.basename(t),d=Y.statSync(l);if(!d.isDirectory()){let y=Je(l,f,d);return{name:c,type:"file",metadata:y,extension:O.extname(c)}}let h=[];if(p<s){let y=[];try{y=Y.readdirSync(l)}catch{y=[]}y.sort();for(let v of y){if(It.has(v))continue;let g=O.join(l,v),S=O.relative(t,g).replace(/\\/g,"/");if(!(o.ignores(S)||o.ignores(`${S}/`)))try{let $=Y.statSync(g);if($.isDirectory())h.push(await r(g,p+1));else if($.size<=i.maxFileSize){let m=Je(g,S,$);h.push({name:v,type:"file",metadata:m,extension:O.extname(v)})}}catch{}}}return{name:c,type:"directory",children:h}}return r(O.resolve(e),0)}function Je(e,n,t){let s=ie.get(e,t.mtimeMs);if(s)return{...s.metadata,path:n};let i=0,o=0,a=K(e)||"unknown";try{let r=Y.readFileSync(e,"utf-8");i=r.split(`
|
|
4
|
+
`).length;let p=r.match(/(?:function\s+[a-zA-Z0-9_$]+|def\s+[a-zA-Z0-9_$]+|fn\s+[a-zA-Z0-9_$]+|\b[a-zA-Z0-9_$]+\s*:\s*\([^)]*\)\s*=>)/g);o=p?p.length:0}catch{}return{path:n,language:a,lineCount:i,functionCount:o,mtime:t.mtimeMs,sizeBytes:t.size}}function Ze(e,n,t){let s={};typeof t=="string"?s={kind:t}:t&&(s=t);let i=[];Array.isArray(e)?i=e:e instanceof Map?i=Array.from(e.values()):"files"in e&&e.files instanceof Map&&(i=Array.from(e.files.values()));let o=n.toLowerCase(),a=s.kind,r=[];for(let l of i){let p=l.module,f=l.metadata.path;for(let c of p.functions){if((!a||a==="fn")&&c.name.toLowerCase().includes(o)&&r.push({file:f,symbol:c.name,kind:"fn",lines:c.lines,context:`(fn ${c.name} [...] -> ${c.returnType})`}),(!a||a==="calls")&&c.calls)for(let d of c.calls){let h=typeof d=="string"?d:d.name;h.toLowerCase().includes(o)&&r.push({file:f,symbol:`${c.name} -> ${h}`,kind:"calls",lines:c.lines,context:`calls ${h}`})}if(!a||a==="fn"||a==="calls"){if(c.decorators)for(let d of c.decorators)(d.name.toLowerCase().includes(o)||d.args?.some(h=>h.toLowerCase().includes(o)))&&r.push({file:f,symbol:`@${d.name} -> ${c.name}`,kind:"fn",lines:c.lines,context:`@${d.name}(${d.args?.join(",")||""})`});if(c.states)for(let d of c.states)d.toLowerCase().includes(o)&&r.push({file:f,symbol:`${c.name} :${d}`,kind:"fn",lines:c.lines,context:`(state :${d})`})}}for(let c of p.classes){if((!a||a==="type")&&(c.name.toLowerCase().includes(o)&&r.push({file:f,symbol:c.name,kind:"type",lines:c.lines,context:`class ${c.name}`}),c.decorators))for(let d of c.decorators)(d.name.toLowerCase().includes(o)||d.args?.some(h=>h.toLowerCase().includes(o)))&&r.push({file:f,symbol:`@${d.name} -> ${c.name}`,kind:"type",lines:c.lines,context:`@${d.name}(${d.args?.join(",")||""}) class ${c.name}`});for(let d of c.methods){if((!a||a==="fn")&&d.name.toLowerCase().includes(o)&&r.push({file:f,symbol:`${c.name}.${d.name}`,kind:"fn",lines:d.lines,context:`method ${c.name}.${d.name}`}),(!a||a==="calls")&&d.calls)for(let h of d.calls){let y=typeof h=="string"?h:h.name;y.toLowerCase().includes(o)&&r.push({file:f,symbol:`${c.name}.${d.name} -> ${y}`,kind:"calls",lines:d.lines,context:`calls ${y}`})}if(!a||a==="fn"||a==="calls"){if(d.decorators)for(let h of d.decorators)(h.name.toLowerCase().includes(o)||h.args?.some(y=>y.toLowerCase().includes(o)))&&r.push({file:f,symbol:`@${h.name} -> ${c.name}.${d.name}`,kind:"fn",lines:d.lines,context:`@${h.name}(${h.args?.join(",")||""})`});if(d.states)for(let h of d.states)h.toLowerCase().includes(o)&&r.push({file:f,symbol:`${c.name}.${d.name} :${h}`,kind:"fn",lines:d.lines,context:`(state :${h})`})}}}if(!a||a==="type"||a==="var"||a==="all")for(let c of p.types)c.name.toLowerCase().includes(o)&&r.push({file:f,symbol:c.name,kind:c.values?"var":"type",lines:c.lines,context:c.values?`var ${c.name} = ${c.values[0]}`:`type ${c.name}`});if(!a||a==="use"||a==="all")for(let c of p.imports)(c.path.toLowerCase().includes(o)||c.symbols.some(d=>d.toLowerCase().includes(o)))&&r.push({file:f,symbol:c.path,kind:"use",lines:{start:1,end:1},context:`(use ${c.path}:${c.symbols.join(",")})`});if(!a||a==="route"||a==="all"){let c=f.replace(/\\/g,"/"),d=c.lastIndexOf("app/");if(d!==-1&&(c.endsWith("/route.ts")||c.endsWith("/route.js")||c.endsWith("/page.tsx")||c.endsWith("/page.jsx"))){let h=c.slice(d+3).replace(/\/route\.(ts|js|mjs)$/,"").replace(/\/page\.(tsx|jsx|js|ts)$/,""),y=h.startsWith("/")?h:"/"+h;if(y.toLowerCase().includes(o)||c.toLowerCase().includes(o)||o.includes(y.toLowerCase())){let v=p.functions.map(g=>g.name).filter(g=>["GET","POST","PUT","DELETE","PATCH"].includes(g));r.push({file:f,symbol:y,kind:"route",lines:{start:1,end:l.metadata?.lineCount||1},context:`(route ${y} [${v.join(", ")||"GET"}])`})}}}}return r}function En(e,n){if(n.length===0)return`No matches found for "${e}".`;let t=[`Found ${n.length} matches for "${e}":`];for(let s of n)t.push(` ${s.file}:${s.symbol} :L${s.lines.start}-${s.lines.end}`);return t.join(`
|
|
5
|
+
`)}import ae from"fs";import Z from"path";async function B(e,n,t){let s,i={};typeof n=="string"?(s=n,i=t||{}):n&&(i=n,s=i.language);let o=Z.resolve(i.rootPath||process.cwd()),a=Z.isAbsolute(e)?e:Z.join(o,e),r=i.config||Ne(o),l=r.defaultLevel===0?2:r.defaultLevel,p=i.level??l??2,f=i.source,c=Date.now();if(!f){if(!ae.existsSync(a))return null;if(c=ae.statSync(a).mtimeMs,!i.noCache){let h=ie.get(a,c);if(h)return h}f=ae.readFileSync(a,"utf-8")}try{let d=s||K(a)||"typescript",h=await oe(f,d);if(!h)return null;let y=qe(h.tree,a,h.language,h.lineCount,{level:p,config:r,rootPath:o});try{h.tree.delete()}catch{}return i.noCache||ie.set(a,c,y),y}catch{return null}}async function G(e=process.cwd(),n={}){let t=Z.resolve(n.rootPath||e),s=n.config||Ne(t),i=await pe(e,{config:s,rootPath:t,depth:n.depth,ignore:n.ignore}),o=new Map;async function a(r,l=""){if(r.type==="file"){let p=l?Z.join(l,r.name).replace(/\\/g,"/"):r.name,f=Z.join(t,p),c=await B(f,{...n,config:s,rootPath:t});c&&(o.set(p,c),r.metadata&&(r.metadata.path=p,r.metadata.functionCount=c.metadata.functionCount,r.metadata.lineCount=c.metadata.lineCount))}else if(r.children)for(let p of r.children){let f=l?Z.join(l,p.type==="directory"?p.name:""):p.type==="directory"?p.name:"";await a(p,f)}}return await a(i,""),{tree:i,files:o,rootPath:t}}function Bn(e,n={}){if(!ae.existsSync(e))return null;let s=ae.readFileSync(e,"utf-8").split(`
|
|
6
|
+
`),i=Math.max(1,n.startLine??1),o=Math.min(s.length,n.endLine??s.length);return s.slice(i-1,o).map((r,l)=>`${i+l}: ${r}`).join(`
|
|
7
|
+
`)}import de from"path";async function Jn(e,n={},t={}){let s=process.cwd(),i=2,o;typeof n=="string"?(s=de.resolve(n),i=t.depth??2,o=t.project):(s=de.resolve(n.rootPath||process.cwd()),i=n.depth??2,o=n.project),o||(o=await G(s,{level:2,rootPath:s}));let a=e.trim(),r,l;for(let[g,S]of o.files){for(let $ of S.module.functions)if($.name===a){r=g,l="function";break}if(r)break;for(let $ of S.module.classes){if($.name===a){r=g,l="class";break}for(let m of $.methods)if(m.name===a||`${$.name}.${m.name}`===a){r=g,l="method";break}if(r)break}if(r)break;for(let $ of S.module.types)if($.name===a){r=g,l="type";break}if(r)break}let p=new Set,f=[];for(let[g,S]of o.files){for(let $ of S.module.imports)($.symbols.includes(a)||r&&$.path.includes(de.basename(r,de.extname(r))))&&p.add(g);ue(S.module.functions,g,a,f);for(let $ of S.module.classes)ue($.methods,g,a,f,$.name)}let c=[...f],d=new Set(c.map(g=>g.symbol));if(i>1){let g=new Set(c.map(S=>S.symbol));for(let S=2;S<=i;S++){let $=new Set;for(let[m,u]of o.files)for(let b of g){ue(u.module.functions,m,b,c);for(let w of u.module.classes)ue(w.methods,m,b,c,w.name)}for(let m of c)d.has(m.symbol)||(d.add(m.symbol),$.add(m.symbol));if($.size===0)break;g=$}}let h=new Map;for(let g of c){let S=`${g.file}:${g.symbol}:${g.lines.start}`;h.has(S)||h.set(S,g)}let y=Array.from(h.values()),v="low";return y.length>10||p.size>8?v="critical":y.length>=5||p.size>=4?v="high":(y.length>=2||p.size>=1)&&(v="med"),{target:a,file:r,kind:l,callers:y,transitiveCount:y.length,depth:i,risk:v,importers:Array.from(p)}}function ue(e,n,t,s,i){for(let o of e){if(!o.calls||o.calls.length===0)continue;if(o.calls.some(r=>{let l=typeof r=="string"?r:r.name;return!!(l===t||l.endsWith(`.${t}`)||l.startsWith(`${t}.`))})){let r=i?`${i}.${o.name}`:o.name;s.push({file:n,symbol:r,kind:i?"method":"function",lines:o.lines,callsTarget:t})}}}import Qe from"fs";import me from"path";import{execSync as Lt}from"child_process";async function ts(e,n={}){let t=me.resolve(n.rootPath||process.cwd()),s=me.isAbsolute(e)?e:me.join(t,e),i=me.relative(t,s),o=n.since||"HEAD",a=n.currentSource;a===void 0&&Qe.existsSync(s)&&(a=Qe.readFileSync(s,"utf-8"));let r=n.baseSource;if(r===void 0)try{r=Lt(`git show "${o}:${i}"`,{cwd:t,stdio:["pipe","pipe","ignore"],encoding:"utf-8"})}catch{r=""}let l=(a||"").split(`
|
|
8
|
+
`).length,p=(r||"").split(`
|
|
9
|
+
`).length,f=r?await B(s,{source:r,rootPath:t,noCache:!0,level:2}):null,c=a?await B(s,{source:a,rootPath:t,noCache:!0,level:2}):null,d=[],h=new Map;if(f)for(let m of f.module.functions)h.set(m.name,m);let y=new Map;if(c)for(let m of c.module.functions)y.set(m.name,m);for(let[m,u]of h)y.has(m)||d.push({name:m,kind:"function",status:"removed",lines:u.lines,oldSignature:he(u)});for(let[m,u]of y){let b=h.get(m);if(!b)d.push({name:m,kind:"function",status:"added",lines:u.lines,newSignature:he(u)});else{let w=he(b),k=he(u),x=E=>(E||[]).map(U=>typeof U=="string"?U:U.name),C=x(b.calls),j=x(u.calls),N=j.filter(E=>!C.includes(E)),_=C.filter(E=>!j.includes(E)),T=[];w!==k&&T.push(`${b.params.length}->${u.params.length} params`),(w!==k||N.length>0||_.length>0)&&d.push({name:m,kind:"function",status:"modified",lines:u.lines,oldSignature:w,newSignature:k,addedCalls:N.length>0?N:void 0,removedCalls:_.length>0?_:void 0,paramChanges:T.length>0?T:void 0})}}let v=new Set((f?.module.types||[]).map(m=>m.name)),g=new Set((c?.module.types||[]).map(m=>m.name));for(let m of f?.module.types||[])g.has(m.name)||d.push({name:m.name,kind:"type",status:"removed",lines:m.lines});for(let m of c?.module.types||[])v.has(m.name)||d.push({name:m.name,kind:"type",status:"added",lines:m.lines});let S=new Map((f?.module.classes||[]).map(m=>[m.name,m])),$=new Map((c?.module.classes||[]).map(m=>[m.name,m]));for(let[m,u]of S)$.has(m)||d.push({name:m,kind:"class",status:"removed",lines:u.lines});for(let[m,u]of $)S.has(m)||d.push({name:m,kind:"class",status:"added",lines:u.lines});return{file:i,revision:o,deltas:d,addedLinesCount:Math.max(0,l-p),deletedLinesCount:Math.max(0,p-l)}}function he(e){let n=e.params.map(t=>`${t.name}:${t.type}`).join(",");return`${e.name}(${n})->${e.returnType}`}function Ve(e){let n="tree"in e?e.tree:e;if(n.type==="file")return Xe(n);if(!n.children||n.children.length===0)return`${n.name}/`;let t=Ye(n.children);return`${n.name}/{${t}}`}function Ye(e){let n=e.filter(o=>o.type==="directory"),t=e.filter(o=>o.type==="file"),s=[];for(let o of n)if(!o.children||o.children.length===0)s.push(`${o.name}/`);else{let a=Ye(o.children);s.push(`${o.name}/{${a}}`)}let i=new Map;for(let o of t){let a=o.extension||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}for(let[o,a]of i.entries())if(!o||a.length===1)for(let r of a)s.push(Xe(r));else{let r=a.map(l=>{let p=l.name.slice(0,-o.length),f=et(l);return`${p}${f}`});s.push(`{${r.join(",")}}${o}`)}return s.join(",")}function Xe(e){let n=et(e);return e.extension?`${e.name.slice(0,-e.extension.length)}${n}${e.extension}`:`${e.name}${n}`}function et(e){if(!e.metadata)return"";let n=e.metadata.lineCount,t=e.metadata.functionCount;return n===0&&t===0?"":t===0?`(${n}L)`:`(${n}L,${t}fn)`}function L(e,n={}){let t=typeof n=="number"?n:n.level??2,s=e.module,i=[];if(i.push(`(mod ${s.name} :L${s.lines.start}-${s.lines.end}`),s.imports.length>0){let o=s.imports.map(Rt).filter(Boolean);o.length>0&&i.push(` (use ${o.join(" ")})`)}for(let o of s.types)i.push(` ${At(o)}`);for(let o of s.classes)i.push(Mt(o,t," "));for(let o of s.functions)i.push(nt(o,t," "));if(s.errors&&s.errors.length>0)for(let o of s.errors)i.push(` (error "${o.message}" :L${o.lines.start}-${o.lines.end})`);return i.push(")"),i.join(`
|
|
10
|
+
`)}function Rt(e){return e.path?e.symbols.length===0?e.path:e.symbols.length===1?`${e.path}:${e.symbols[0]}`:`${e.path}:{${e.symbols.join(",")}}`:""}function At(e){if(e.values&&e.values.length>0){let t=e.values.map(s=>s.replace(/^[|\s]+|[|\s]+$/g,"").trim()).filter(Boolean).join("|");return`(type ${e.name} (${t}) :L${e.lines.start}-${e.lines.end})`}if(e.fields.length===0)return`(type ${e.name} :L${e.lines.start}-${e.lines.end})`;let n=e.fields.map(t=>`${t.name}:${t.type}`).join(",");return`(type ${e.name} {${n}} :L${e.lines.start}-${e.lines.end})`}function tt(e){if(!e.args||e.args.length===0)return`(@${e.name})`;let n=e.args.map(t=>`"${t}"`).join(" ");return`(@${e.name} ${n})`}function nt(e,n,t){let s=[];if(e.decorators&&e.decorators.length>0)for(let r of e.decorators)s.push(`${t}${tt(r)}`);let i=e.params.map(r=>`${r.name}:${r.type}`).join(" "),o=`${t}(fn ${e.name} [${i}]->${e.returnType} :L${e.lines.start}-${e.lines.end}`;if(n===1)return s.push(`${o})`),s.join(`
|
|
11
|
+
`);let a=[];if(e.states&&e.states.length>0){let r=e.states.map(l=>/^[a-zA-Z0-9_\-]+$/.test(l)?`:${l}`:`"${l}"`).join(" ");a.push(`${t} (states ${r})`)}if(e.returns&&e.returns.length>0&&a.push(`${t} (returns ${e.returns.join(" ")})`),e.validates&&e.validates.length>0&&a.push(`${t} (validates ${e.validates.join(" ")})`),e.calls&&e.calls.length>0){let r=e.calls.map(l=>typeof l=="string"?l:l.scope==="self"?l.line?`(:self ${l.name} :L${l.line})`:`(:self ${l.name})`:l.scope==="local"?l.line?`(:local ${l.name} :L${l.line})`:`(:local ${l.name})`:l.scope==="ext"?l.target?`(ext/${l.target} ${l.name})`:`(ext ${l.name})`:l.name);a.push(`${t} (calls ${r.join(" ")})`)}return e.throws&&e.throws.length>0&&a.push(`${t} (throws ${e.throws.join(" ")})`),e.tests&&e.tests.length>0&&a.push(`${t} (tests ${e.tests.join(" ")})`),a.length===0?s.push(`${o})`):s.push(`${o}
|
|
12
|
+
${a.join(`
|
|
13
|
+
`)})`),s.join(`
|
|
14
|
+
`)}function Mt(e,n,t){let s=[];if(e.decorators&&e.decorators.length>0)for(let r of e.decorators)s.push(`${t}${tt(r)}`);let i=[`(class ${e.name}`];e.extends&&i.push(`:extends ${e.extends}`),e.implements&&e.implements.length>0&&i.push(`:implements ${e.implements.join(",")}`),i.push(`:L${e.lines.start}-${e.lines.end}`);let o=`${t}${i.join(" ")}`;if(e.methods.length===0)return s.push(`${o})`),s.join(`
|
|
15
|
+
`);let a=e.methods.map(r=>nt(r,n,`${t} `));return s.push(`${o}
|
|
16
|
+
${a.join(`
|
|
17
|
+
`)})`),s.join(`
|
|
18
|
+
`)}function rs(e){let n=[`(impact ${e.target}`,`:callers ${e.callers.length}`,`:transitive ${e.transitiveCount}`,`:depth ${e.depth}`,`:risk ${e.risk}`];e.file&&n.push(`:file "${e.file}"`),e.kind&&n.push(`:kind ${e.kind}`);let t=[n.join(" ")];if(e.importers&&e.importers.length>0&&t.push(` (importers ${e.importers.join(" ")})`),e.callers.length>0)for(let s of e.callers)t.push(` (caller ${s.file}:${s.symbol} :L${s.lines.start}-${s.lines.end} :calls ${s.callsTarget})`);return t.push(")"),t.join(`
|
|
19
|
+
`)}function as(e){let n=[`(diff ${e.file} :rev "${e.revision}" :deltas ${e.deltas.length} :+lines ${e.addedLinesCount} :-lines ${e.deletedLinesCount}`];for(let t of e.deltas)if(t.status==="added"){let s=t.newSignature?` "${t.newSignature}"`:"",i=t.lines?` :L${t.lines.start}-${t.lines.end}`:"";n.push(` (add-${t.kind} ${t.name}${s}${i})`)}else if(t.status==="removed")n.push(` (del-${t.kind} ${t.name})`);else{let s=[` (mod-${t.kind} ${t.name}`];t.lines&&s.push(`:L${t.lines.start}-${t.lines.end}`),t.paramChanges&&t.paramChanges.length>0&&s.push(`:params [${t.paramChanges.join(" ")}]`),t.addedCalls&&t.addedCalls.length>0&&s.push(`:added-calls [${t.addedCalls.join(" ")}]`),t.removedCalls&&t.removedCalls.length>0&&s.push(`:removed-calls [${t.removedCalls.join(" ")}]`),s.push(")"),n.push(s.join(" "))}return n.push(")"),n.join(`
|
|
20
|
+
`)}function ls(e){let n=e.valid?"valid":"error",t=[`(check "${e.file}" :status ${n} :syntax-errors ${e.syntaxErrors.length}`];if(e.syntaxErrors.length>0)for(let s of e.syntaxErrors)t.push(` (syntax-error :L${s.line} "${s.message}")`);return e.unresolvedImports.length>0&&t.push(` (unresolved-imports ${e.unresolvedImports.join(" ")})`),e.astSummary&&t.push(` (ast-summary "${e.astSummary}")`),t.push(")"),t.join(`
|
|
21
|
+
`)}function cs(e){let n=e.targetSymbol?` -> ${e.targetSymbol}`:"",t=[`(slice ${e.rootSymbol}${n} :depth ${e.depth} :nodes ${e.nodes.length} :files ${e.files.length} :tokens ${e.tokenEstimate}`];for(let s of e.nodes){let i=s.signature?` [${s.signature}]`:"",o=` :L${s.lines.start}-${s.lines.end}`,a=` (${s.file}:${s.kind} ${s.name}${i}${o}`,r=[];s.validates&&s.validates.length>0&&r.push(` (validates ${s.validates.join(" ")})`),s.calls&&s.calls.length>0&&r.push(` (calls ${s.calls.join(" ")})`),s.tests&&s.tests.length>0&&r.push(` (tests ${s.tests.join(" ")})`),r.length===0?t.push(`${a})`):t.push(`${a}
|
|
22
|
+
${r.join(`
|
|
23
|
+
`)})`)}return t.push(")"),t.join(`
|
|
24
|
+
`)}function fs(e){if(e.status==="unchanged")return`(same ${e.file} :session "${e.sessionId}" :fingerprint "${e.fingerprint}")`;let n=[`(delta ${e.file} :session "${e.sessionId}" :status ${e.status} :unchanged-fns ${e.unchangedCount||0}`];if(e.addedFunctions&&e.addedFunctions.length>0)for(let t of e.addedFunctions)n.push(` (add-fn ${t.name} :L${t.lines.start}-${t.lines.end})`);if(e.modifiedFunctions&&e.modifiedFunctions.length>0)for(let t of e.modifiedFunctions)n.push(` (mod-fn ${t.name} :L${t.lines.start}-${t.lines.end})`);if(e.removedFunctions&&e.removedFunctions.length>0)for(let t of e.removedFunctions)n.push(` (del-fn ${t})`);return n.push(")"),n.join(`
|
|
25
|
+
`)}import ge from"path";async function $s(e){let n=ge.resolve(e.rootPath||process.cwd()),t=e.budget,s=e.countTokens||(u=>Math.ceil(u.length/4)),i=e.project||await G(n,{level:2,rootPath:n}),o=new Map,a=new Map;for(let[u,b]of i.files){let w=new Set;for(let k of b.module.imports)w.add(k.path);a.set(u,w)}for(let[u,b]of i.files){let w=1;for(let[x,C]of a)if(x!==u)for(let j of C)j.includes(ge.basename(u,ge.extname(u)))&&(w+=3);let k=ge.basename(u).toLowerCase();k.includes("controller")||k.includes("service")||k.includes("app")?w+=5:k.includes("entity")||k.includes("model")||k.includes("type")?w+=3:k.startsWith("index.")||k.startsWith("main.")?w+=4:(k.includes("spec.")||k.includes("test."))&&(w*=.3),w+=(b.module.functions.length+b.module.classes.length)*.5,o.set(u,w)}let r=Array.from(o.entries()).map(([u,b])=>({file:u,score:b})).sort((u,b)=>b.score-u.score),l=i.tree||await pe(n,{depth:3,rootPath:n}),p=Ve(l),f=s(p),c=Math.max(50,t-f),d=[],h=[],y=[],v=new Map;for(let u of r){let b=i.files.get(u.file);if(!b){y.push(u.file);continue}let w=L(b,2),k=s(w);if(k<=c&&u.score>=5){d.push(u.file),c-=k,v.set(u.file,{level:2,text:w,tokens:k});continue}let x=L(b,1),C=s(x);if(C<=c&&u.score>=2){h.push(u.file),c-=C,v.set(u.file,{level:1,text:x,tokens:C});continue}y.push(u.file)}let g=[];g.push(";; ========================================================="),g.push(";; SHORTCODE 2.0 ADAPTIVE BUDGET PROJECTION"),g.push(`;; Budget: ${t} tokens | Priority Files: ${d.length} L2, ${h.length} L1, ${y.length} L0`),g.push(`;; =========================================================
|
|
26
|
+
`),g.push(";; --- [L0 TREE SKELETON] ---"),g.push(p),g.push(`
|
|
27
|
+
;; --- [PRIORITIZED SEMANTIC IR] ---`);for(let[u,b]of v)g.push(b.text);let S=g.join(`
|
|
28
|
+
`),$=s(S);return{plan:{targetBudget:t,projectedTokens:$,l0Files:y,l1Files:h,l2Files:d,centralityRankings:r.map(u=>({file:u.file,score:u.score,level:d.includes(u.file)?2:h.includes(u.file)?1:0}))},formattedOutput:S,totalTokens:$}}import Te from"fs";import X from"path";async function st(e,n,t={}){let s=X.resolve(t.rootPath||process.cwd()),i=X.isAbsolute(e)?e:X.join(s,e),o=X.relative(s,i),a=n;if(n.includes("@@")||n.startsWith("---")){let g=t.originalSource;g===void 0&&Te.existsSync(i)&&(g=Te.readFileSync(i,"utf-8")),a=Ot(g||"",n)}let l=K(i)||"typescript",p=await oe(a,l),f=[];if(!p||!p.tree)return f.push({line:1,message:"Tree-sitter parser failed to initialize or parse content"}),{file:o,valid:!1,syntaxErrors:f,unresolvedImports:[]};p.tree.rootNode.hasError&&it(p.tree.rootNode,f);let c=[],d=/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(a))!==null;){let g=h[1];if(g.startsWith(".")){let S=X.resolve(X.dirname(i),g);["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"].some(u=>Te.existsSync(S+u))||c.push(g)}}let y=f.length===0,v=`${l} CST: ${p.tree.rootNode.childCount} root declarations, ${p.lineCount} lines`;return{file:o,valid:y,syntaxErrors:f,unresolvedImports:c,astSummary:v}}function it(e,n,t=10){if(!(n.length>=t)){if(e.isError||e.type==="ERROR"){n.push({line:(e.startPosition?.row??0)+1,message:`Syntax error near token '${e.text?.slice(0,30)||"unknown"}'`});return}if(e.isMissing){n.push({line:(e.startPosition?.row??0)+1,message:`Missing expected token: '${e.type}'`});return}for(let s=0;s<e.childCount;s++){let i=e.child(s);i&&i.hasError&&it(i,n,t)}}}function Ot(e,n){let t=e.split(`
|
|
29
|
+
`),s=n.split(`
|
|
30
|
+
`);if(!n.includes("@@"))return n;let i=[],o=0;for(let a of s)if(a.startsWith("@@")){let r=a.match(/@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@/);if(r){let l=parseInt(r[1],10)-1;for(;o<l&&o<t.length;)i.push(t[o++])}}else a.startsWith("+")&&!a.startsWith("+++")?i.push(a.slice(1)):a.startsWith("-")&&!a.startsWith("---")?o++:a.startsWith(" ")&&(i.push(a.slice(1)),o++);for(;o<t.length;)i.push(t[o++]);return i.join(`
|
|
31
|
+
`)}import ee from"path";async function Ts(e,n={}){let t=ee.resolve(e),s=n.project||await G(t,{level:2,rootPath:t}),i=ee.basename(t),o,a=!1,r=new Set,l=new Map,p=new Map,f=[];function c(y){let v=y.trim().replace(/^['"]|['"]$/g,""),g=p.get(v);return g||(g={name:v},p.set(v,g)),g}for(let[y,v]of s.files){let g=v.module;for(let S of g.imports){let $=S.path,m=!1,u=$;if(!$.startsWith("."))!$.startsWith("node:")&&!$.startsWith("@nestjs/")&&(m=!0,u=$);else{let b=ee.dirname(ee.join(t,y)),w=ee.resolve(b,$);w.startsWith(t)||(m=!0,u=ee.relative(t,w).replace(/\\/g,"/"),u.startsWith(".")||(u="./"+u))}if(m){let b=l.get(u);b||(b=new Set,l.set(u,b));for(let w of S.symbols)w&&!w.startsWith("type ")&&b.add(w)}}for(let S of g.classes){let $=S.decorators?.find(b=>b.name==="Module");if($&&(o=S.name,S.decorators?.some(b=>b.name==="Global")&&(a=!0),$.args)){for(let b of $.args)if(b.startsWith("imports:")){let k=b.slice(8).replace(/^\[|\]$/g,"").split(",");for(let x of k){let C=x.trim();if(C)if(C.includes("registerQueue(")||C.startsWith("queue:")){let j=C.match(/(?:registerQueue\(|queue:)([^)]+)\)?/);j&&c(j[1])}else C.endsWith("Module")&&r.add(C)}}}let m=S.decorators?.find(b=>b.name==="Processor");if(m){let b=m.args?.[0]||"default",w=c(b);w.processor=S.name,w.processorFile=y;let k=[];for(let x of S.methods){let C=x.decorators?.find(j=>j.name==="Process");if(C){let j=C.args?.[0]||x.name;j&&!k.includes(j)&&k.push(j)}}k.length>0&&(w.jobs=k)}if(S.name.endsWith("Service")||S.name.endsWith("Processor")||S.name.endsWith("Gateway")||S.name.endsWith("Runner")){let b=new Set;for(let w of S.methods){if(w.decorators){for(let k of w.decorators)if(k.name==="InjectQueue"&&k.args?.[0]){let x=c(k.args[0]);x.injectedIn||(x.injectedIn=[]),x.injectedIn.includes(S.name)||x.injectedIn.push(S.name)}}if(w.calls)for(let k of w.calls)b.add(typeof k=="string"?k:k.name)}f.push({name:S.name,file:y,calls:Array.from(b)})}}}for(let[,y]of s.files)for(let v of y.module.classes)if(v.decorators){for(let g of v.decorators)if(g.args)for(let S of g.args){let $=S.matchAll(/name:([a-zA-Z0-9_-]+)/g);for(let m of $)c(m[1])}}let d=new Set(f.map(y=>y.name));for(let y of f){let v=[];for(let g of y.calls){let S=g.split("."),$=S[0],m=S[1],u=Array.from(d).find(w=>{if(w===y.name)return!1;let k=w.replace(/Service$|Processor$|Gateway$/,"").toLowerCase(),x=$.replace(/Service$|Processor$|Gateway$/,"").toLowerCase();return w===$||w.toLowerCase()===$.toLowerCase()||k===x});if(u){let w=m?`${u}.${m}`:u;v.includes(w)||v.push(w);continue}let b=Array.from(p.keys()).find(w=>{let k=w.replace(/-/g,"").toLowerCase(),x=$.replace(/Queue$/,"").toLowerCase();return x.includes(k)||k.includes(x)});if(b&&(m==="add"||m==="addBulk"||m?.startsWith("add"))){let w=`Queue[${b}]`;v.includes(w)||v.push(w)}}y.calls=v}let h=[];for(let[y,v]of l.entries())h.push({source:y,symbols:Array.from(v).slice(0,10)});return{name:i,path:t,fileCount:s.files.size,moduleName:o,isGlobal:a,importedModules:Array.from(r),externalDeps:h,queues:Array.from(p.values()),services:f}}function Ps(e){let n=[];if(n.push(`(graph ${e.name} :files ${e.fileCount}`),e.moduleName){let t=e.isGlobal?" :global":"";if(n.push(` (module ${e.moduleName}${t}`),e.importedModules&&e.importedModules.length>0&&n.push(` (imports ${e.importedModules.join(" ")})`),e.externalDeps.length>0){n.push(" (external");for(let s of e.externalDeps){let i=s.symbols.length>0?` ${s.symbols.slice(0,8).join(" ")}${s.symbols.length>8?` +${s.symbols.length-8}`:""}`:"";n.push(` (${s.source}${i})`)}n.push(" )")}n.push(" )")}else if(e.externalDeps.length>0){n.push(" (external");for(let t of e.externalDeps){let s=t.symbols.length>0?` ${t.symbols.slice(0,8).join(" ")}${t.symbols.length>8?` +${t.symbols.length-8}`:""}`:"";n.push(` (${t.source}${s})`)}n.push(" )")}if(e.queues.length>0){n.push(" (queues");for(let t of e.queues){let s=` (queue ${t.name}`;t.processor&&(s+=` :processor ${t.processor}`),t.jobs&&t.jobs.length>0&&(s+=` :jobs [${t.jobs.join(" ")}]`),t.injectedIn&&t.injectedIn.length>0&&(s+=` :injected [${t.injectedIn.join(" ")}]`),s+=")",n.push(s)}n.push(" )")}if(e.services.length>0){n.push(" (services");for(let t of e.services)t.calls.length>0?n.push(` (svc ${t.name} (calls ${t.calls.join(" ")}))`):n.push(` (svc ${t.name})`);n.push(" )")}return n.push(")"),n.join(`
|
|
32
|
+
`)}import ye from"path";import ot from"fs";async function Gs(e,n,t={}){let s=t.depth??2,i=ye.resolve(e),o=ot.existsSync(i)&&ot.statSync(i).isFile(),a=o?t.rootPath||Ge(i):i,r=t.rootPath||a,l;t.project?l=t.project.files:l=(await G(a,{level:2,rootPath:r})).files;let p=Array.from(l.values()),f=null;if(o){let g=ye.relative(r,i).replace(/\\/g,"/"),S=l.get(g)||Array.from(l.values()).find($=>$.metadata.path.endsWith(ye.basename(i)));if(S){let $=S.module.functions.find(m=>m.name===n||m.name.endsWith(`.${n}`));if($)f={ir:S,node:$};else{let m=S.module.types.find(u=>u.name===n);if(m)f={ir:S,node:m};else for(let u of S.module.classes){let b=u.methods.find(w=>w.name===n);if(b){f={ir:S,node:b};break}}}}}if(!f)for(let g of p){let S=g.module.functions.find(m=>m.name===n||m.name.endsWith(`.${n}`));if(S){f={ir:g,node:S};break}let $=g.module.types.find(m=>m.name===n);if($){f={ir:g,node:$};break}for(let m of g.module.classes){let u=m.methods.find(b=>b.name===n);if(u){f={ir:g,node:u};break}}if(f)break}if(!f){let g=Ze(p,n,{kind:"fn"});if(g.length>0){let S=g[0],$=l.get(S.file);if($){let m=$.module.functions.find(u=>u.name===S.symbol);m&&(f={ir:$,node:m})}}}if(!f)return{rootSymbol:n,targetSymbol:t.targetSymbol,depth:0,nodes:[],files:[],tokenEstimate:0};let c=[],d=new Set,h=new Set,y=[{symbolName:f.node.name,currentDepth:0,ir:f.ir,node:f.node}];for(d.add(f.node.name);y.length>0;){let g=y.shift(),S=ye.relative(r,g.ir.metadata.path).replace(/\\/g,"/");h.add(S);let $="params"in g.node?g.node:null,m=[];if($&&$.calls)for(let u of $.calls)m.push(typeof u=="string"?u:u.name);if(c.push({file:S,kind:$?"fn":"type",name:g.node.name,lines:g.node.lines,signature:$?`${$.params.map(u=>`${u.name}:${u.type}`).join(" ")}->${$.returnType}`:void 0,calls:m.length>0?m:void 0,validates:$?$.validates:void 0,tests:$?$.tests:void 0}),t.targetSymbol&&g.node.name===t.targetSymbol)break;if(g.currentDepth<s){if($&&$.calls)for(let u of $.calls){let b=typeof u=="string"?u:u.name,w=b.split(".").pop()||b;if(!d.has(w)&&!d.has(b))for(let k of p){let x=k.module.functions.find(C=>C.name===w||C.name===b||C.name.endsWith(`.${w}`));if(x){d.add(x.name),y.push({symbolName:x.name,currentDepth:g.currentDepth+1,ir:k,node:x});break}}}if(g.currentDepth===0)for(let u of p)for(let b of u.module.functions)b.calls&&b.calls.some(k=>{let x=typeof k=="string"?k:k.name;return x===g.symbolName||x.endsWith(`.${g.symbolName}`)||g.symbolName.endsWith(`.${x}`)})&&!d.has(b.name)&&(d.add(b.name),y.push({symbolName:b.name,currentDepth:g.currentDepth+1,ir:u,node:b}))}}let v=Math.ceil(JSON.stringify(c).length/4);return{rootSymbol:n,targetSymbol:t.targetSymbol,depth:s,nodes:c,files:Array.from(h),tokenEstimate:v}}import q from"fs";import xe from"path";import Gt from"os";import Dt from"crypto";var $e=new Map,Q=xe.join(Gt.tmpdir(),"glyphier-sessions");function Wt(e){let n=$e.get(e);if(n)return n;n=new Map;let t=xe.join(Q,`${encodeURIComponent(e)}.json`);if(q.existsSync(t))try{let s=JSON.parse(q.readFileSync(t,"utf-8"));for(let[i,o]of Object.entries(s)){let a=o;n.set(i,{fingerprint:a.fingerprint,mtime:a.mtime,functions:new Map(Object.entries(a.functions||{}))})}}catch{}return $e.set(e,n),n}function rt(e,n){try{q.existsSync(Q)||q.mkdirSync(Q,{recursive:!0});let t={};for(let[s,i]of n.entries())t[s]={fingerprint:i.fingerprint,mtime:i.mtime,functions:Object.fromEntries(i.functions.entries())};q.writeFileSync(xe.join(Q,`${encodeURIComponent(e)}.json`),JSON.stringify(t),"utf-8");try{let s=A();for(let[i,o]of n.entries())s.setSession(e,i,o.fingerprint,24);s.cleanExpiredSessions()}catch{}}catch{}}function Ks(e,n,t){if(!e)return{file:n,sessionId:"none",status:"new",fingerprint:at(t)};let s=Wt(e),i=at(t),o=s.get(n),a=new Map;for(let c of t.module.functions)a.set(c.name,c);for(let c of t.module.classes)for(let d of c.methods)a.set(`${c.name}.${d.name}`,d);if(!o)return s.set(n,{fingerprint:i,mtime:Date.now(),functions:a}),rt(e,s),{file:n,sessionId:e,status:"new",fingerprint:i};if(o.fingerprint===i)return{file:n,sessionId:e,status:"unchanged",fingerprint:i,unchangedCount:a.size};let r=[],l=[],p=[],f=0;for(let[c,d]of a){let h=o.functions.get(c);if(!h)r.push(d);else{let y=`${h.params.map(g=>g.type).join(",")}:${h.returnType}:${h.calls?.length||0}`,v=`${d.params.map(g=>g.type).join(",")}:${d.returnType}:${d.calls?.length||0}`;y!==v?l.push(d):f++}}for(let c of o.functions.keys())a.has(c)||p.push(c);return s.set(n,{fingerprint:i,mtime:Date.now(),functions:a}),rt(e,s),{file:n,sessionId:e,status:"modified",fingerprint:i,unchangedCount:f,modifiedFunctions:l.length>0?l:void 0,addedFunctions:r.length>0?r:void 0,removedFunctions:p.length>0?p:void 0}}function Js(e){try{let n=A();e&&n.clearSession(e)}catch{}if(e){$e.delete(e);try{let n=xe.join(Q,`${encodeURIComponent(e)}.json`);q.existsSync(n)&&q.unlinkSync(n)}catch{}}else{$e.clear();try{q.existsSync(Q)&&q.rmSync(Q,{recursive:!0,force:!0})}catch{}}}function at(e){let n=Dt.createHash("sha256");n.update(e.module.name);for(let t of e.module.functions)n.update(`${t.name}:${t.lines.start}-${t.lines.end}:${t.returnType}`),t.calls&&n.update(JSON.stringify(t.calls));for(let t of e.module.types)n.update(`${t.name}:${t.fields.length}:${t.values?.join("|")}`);return n.digest("hex").slice(0,16)}import Pe from"fs";async function ei(e,n,t={}){if(!Pe.existsSync(e))return{file:e,success:!1,appliedOps:0,error:`File not found: ${e}`};let s=typeof n=="string"?zt(n):n;if(s.length===0)return{file:e,success:!1,appliedOps:0,error:"No valid patch operations provided"};let o=Pe.readFileSync(e,"utf-8"),a=0;for(let l of s){let p=await We(e);if(!p)return{file:e,success:!1,appliedOps:a,error:"Failed to parse CST"};let f=p.tree.rootNode;if(l.action==="add-call"){let c=Se(f,l.target,["function_declaration","method_declaration","method_definition"]);if(!c)return{file:e,success:!1,appliedOps:a,error:`Function ${l.target} not found in CST`};let d=Bt(c);if(!d)return{file:e,success:!1,appliedOps:a,error:`Function ${l.target} has no body block`};let h=d.child(d.childCount-1),y=h?h.startIndex:d.endIndex-1,v=o.slice(0,y).split(`
|
|
33
|
+
`),S=v[v.length-1].match(/^\s*/)?.[0]||" ",$=l.code.trim();$.endsWith(";")||($+=";");let m=`
|
|
34
|
+
${S} ${$}`;o=o.slice(0,y)+m+`
|
|
35
|
+
`+o.slice(y),a++}else if(l.action==="add-field"){let c=Se(f,l.target,["type_spec","interface_declaration","struct_item","type_alias_declaration"]);if(!c)return{file:e,success:!1,appliedOps:a,error:`Type ${l.target} not found in CST`};let d=lt(c);if(!d)return{file:e,success:!1,appliedOps:a,error:`Type ${l.target} has no field block`};let h=d.child(d.childCount-1),y=h?h.startIndex:d.endIndex-1,v=o.slice(0,y).split(`
|
|
36
|
+
`),S=v[v.length-1].match(/^\s*/)?.[0]||" ",$=l.code.trim();!$.endsWith(";")&&!$.endsWith(",")&&($+=";");let m=`
|
|
37
|
+
${S} ${$}`;o=o.slice(0,y)+m+`
|
|
38
|
+
`+o.slice(y),a++}else if(l.action==="replace-call"){let c=Se(f,l.target,["function_declaration","method_declaration","method_definition"]);if(!c)return{file:e,success:!1,appliedOps:a,error:`Function ${l.target} not found in CST`};let d=o.slice(c.startIndex,c.endIndex),[h,y]=l.code.split("->").map(g=>g.trim());if(!h||!y||!d.includes(h))return{file:e,success:!1,appliedOps:a,error:`Target call "${h}" not found inside ${l.target}`};let v=d.replace(h,y);o=o.slice(0,c.startIndex)+v+o.slice(c.endIndex),a++}else l.action==="add-fn"&&(o=o.trimEnd()+`
|
|
39
|
+
|
|
40
|
+
`+l.code.trim()+`
|
|
41
|
+
`,a++)}let r=await st(e,o);if(!r.valid){let l=r.syntaxErrors.map(p=>`L${p.line}: ${p.message}`).join(", ");return{file:e,success:!1,appliedOps:0,error:`Patch rejected: Syntax error introduced (${l})`}}return t.dryRun||Pe.writeFileSync(e,o,"utf-8"),{file:e,success:!0,appliedOps:a,patchedCode:o}}function zt(e){let n=[],t=e.matchAll(/\((add-call|add-field|replace-call|add-fn)\s+([^\s)]+)(?:\s+(.+?))?\)(?=\s*\)|$|\s*\()/gs);for(let s of t){let i=(s[3]||"").trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'")||i.startsWith("`")&&i.endsWith("`"))&&(i=i.slice(1,-1)),n.push({action:s[1],target:s[2],code:i})}return n}function Se(e,n,t){for(let s=0;s<e.childCount;s++){let i=e.child(s);if(!i)continue;if(t.includes(i.type)&&(((i.childForFieldName("name")||i.child(1)||i.child(2))?.text||"")===n||i.text.includes(n)))return i;let o=Se(i,n,t);if(o)return o}return null}function Bt(e){for(let n=0;n<e.childCount;n++){let t=e.child(n);if(t&&(t.type==="block"||t.type==="statement_block"))return t}return null}function lt(e){for(let n=0;n<e.childCount;n++){let t=e.child(n);if(!t)continue;if(t.type==="struct_type"||t.type==="interface_type"||t.type==="interface_body"||t.type==="object_type"||t.type==="field_declaration_list")return t;let s=lt(t);if(s)return s}return null}import be from"fs";import D from"path";function te(e){return Math.ceil(e.length/4)}function ne(e){return e===0?"0.00":e>0&&e<.01?e.toFixed(4):e.toFixed(2)}async function ai(e,n){let t=D.resolve(n?.rootPath||process.cwd()),s=D.isAbsolute(e)?e:D.resolve(t,e);if(!be.existsSync(s))throw new Error(`Target path does not exist: ${e}`);let i=be.statSync(s),o=[],a={},r=0,l=0,p=0;if(i.isFile()){let m=be.readFileSync(s,"utf-8"),u=te(m),b=await B(s,{level:2,rootPath:t}),w=u,k=u;if(b){let T=L(b,{level:1}),E=L(b,{level:2});w=te(T),k=te(E)}let x=k>0?Number((u/k).toFixed(1)):0,C=D.relative(t,s).replace(/\\/g,"/"),N={path:C.startsWith("..")?D.basename(s):C,rawTokens:u,l1Tokens:w,l2Tokens:k,ratio:x};o.push(N),r+=u,l+=w,p+=k;let _=(D.extname(s)||"").replace(/^\./,"").toLowerCase()||"unknown";a[_]={files:1,rawTokens:u,l2Tokens:k}}else{let m=await G(s,{level:2});for(let[u,b]of m.files){let w=D.resolve(s,u),k="";try{k=be.readFileSync(w,"utf-8")}catch{continue}let x=te(k),C=L(b,{level:1}),j=L(b,{level:2}),N=te(C),_=te(j),T=_>0?Number((x/_).toFixed(1)):0,E=D.relative(t,w).replace(/\\/g,"/"),U=E.startsWith("..")?D.relative(s,w).replace(/\\/g,"/"):E;o.push({path:U,rawTokens:x,l1Tokens:N,l2Tokens:_,ratio:T}),r+=x,l+=N,p+=_;let H=(D.extname(w)||"").replace(/^\./,"").toLowerCase()||"unknown";a[H]||(a[H]={files:0,rawTokens:0,l2Tokens:0}),a[H].files+=1,a[H].rawTokens+=x,a[H].l2Tokens+=_}}let f=n?.topN??5,c=[...o].sort((m,u)=>u.rawTokens-m.rawTokens).slice(0,f),d=r>0?Number(((1-p/r)*100).toFixed(1)):0,h=r/1e6*3,y=p/1e6*3,v=(r-p)/1e6*3,g=r/1e6*2.5,S=p/1e6*2.5,$=(r-p)/1e6*2.5;return{targetPath:e,filesCount:o.length,rawTokens:r,l1Tokens:l,l2Tokens:p,compressionRatio:d,languageBreakdown:a,heaviestFiles:c,pricing:{sonnetRaw:ne(h),sonnetIr:ne(y),sonnetSaved:ne(v),gpt4oRaw:ne(g),gpt4oIr:ne(S),gpt4oSaved:ne($)}}}function li(e){let n=[];n.push(`(stats "${e.targetPath}"`),n.push(` (:files ${e.filesCount} :raw-tokens ${e.rawTokens} :l1-tokens ${e.l1Tokens} :l2-tokens ${e.l2Tokens} :compression "${e.compressionRatio}%")`);let t=i=>i.startsWith("$")?i:`$${i}`;n.push(" (pricing"),n.push(` (:sonnet-raw "${t(e.pricing.sonnetRaw)}" :sonnet-ir "${t(e.pricing.sonnetIr)}" :savings "${t(e.pricing.sonnetSaved)}")`),n.push(` (:gpt4o-raw "${t(e.pricing.gpt4oRaw)}" :gpt4o-ir "${t(e.pricing.gpt4oIr)}" :savings "${t(e.pricing.gpt4oSaved)}"))`);let s=Object.entries(e.languageBreakdown);return s.length===0?n.push(" (languages)"):(n.push(" (languages"),s.forEach(([i,o],a)=>{let r=i.replace(/^\./,""),l=a===s.length-1;n.push(` (:${r} :files ${o.files} :raw ${o.rawTokens} :l2 ${o.l2Tokens}${l?"))":")"}`)})),e.heaviestFiles.length===0?n.push(" (heaviest))"):(n.push(" (heaviest"),e.heaviestFiles.forEach((i,o)=>{let a=o===e.heaviestFiles.length-1;n.push(` (:file "${i.path}" :raw ${i.rawTokens} :l2 ${i.l2Tokens} :ratio ${i.ratio}x${a?")))":")"}`)})),n.join(`
|
|
42
|
+
`)}import*as R from"fs";import*as se from"os";import*as pt from"crypto";import*as we from"path";import{execSync as ft}from"child_process";import*as ct from"crypto";function Fe(e){return Array.isArray(e)?`[${e.map(Fe).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([n],[t])=>n.localeCompare(t)).map(([n,t])=>`${JSON.stringify(n)}:${Fe(t)}`).join(",")}}`:JSON.stringify(e)}function Ee(e,n,t=process.env.GLYPHIER_ENTITLEMENT_PUBLIC_KEY,s=new Date){if(!t||e.payload.version!==1||e.payload.machineFingerprint!==n||e.payload.plan!=="dev"&&e.payload.plan!=="enterprise"||!Number.isFinite(Date.parse(e.payload.issuedAt))||Date.parse(e.payload.expiresAt)<=s.getTime())return!1;try{return ct.verify(null,Buffer.from(Fe(e.payload)),t.replace(/\\n/g,`
|
|
43
|
+
`),Buffer.from(e.signature,"base64url"))}catch{return!1}}var Ie=we.join(se.homedir(),".glyphier","entitlement-v1.json");function qt(){try{if(process.platform==="darwin"){let t=ft("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(t&&t[1])return le(t[1])}else if(process.platform==="linux"){if(R.existsSync("/etc/machine-id"))return le(R.readFileSync("/etc/machine-id","utf8"));if(R.existsSync("/var/lib/dbus/machine-id"))return le(R.readFileSync("/var/lib/dbus/machine-id","utf8"))}else if(process.platform==="win32"){let t=ft("wmic csproduct get uuid",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().split(`
|
|
44
|
+
`);if(t.length>1)return le(t[1])}}catch{}let e=`${se.hostname()}-${se.userInfo().username}-${process.arch}-${process.platform}`;return le(e)}function le(e){return pt.createHash("sha256").update(e.trim()).digest("hex")}function dt(){return process.env.GLYPHIER_API_KEY?.trim()||null}function Ut(e){try{let n=R.readFileSync(Ie,"utf8"),t=JSON.parse(n);return Ee(t,e)?{valid:!0,plan:t.payload.plan,userId:t.payload.userId,expiresAt:t.payload.expiresAt,source:"lease"}:null}catch{return null}}function Ht(e,n){if(!e||typeof e!="object")return null;let t=e;if(!Ee(t,n))return null;try{R.mkdirSync(we.dirname(Ie),{recursive:!0,mode:448}),R.writeFileSync(Ie,JSON.stringify(t),{mode:384})}catch{}return{valid:!0,plan:t.payload.plan,userId:t.payload.userId,expiresAt:t.payload.expiresAt,source:"remote"}}async function Kt(){let e=dt(),n=process.env.GLYPHIER_API_URL||"https://glyphier.com",t=qt();if(!e)return{valid:!1,plan:"unknown",source:"missing-key"};try{let s=await fetch(`${n}/api/v1/license/verify`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({machineFingerprint:t})});if(!s.ok){let o=await s.json().catch(()=>({}));throw new Error(o.error||`HTTP ${s.status}: License verification failed`)}let i=await s.json();if(i.valid&&(i.plan==="dev"||i.plan==="enterprise")){let o=Ht(i.lease,t);return{valid:!0,plan:i.plan,userId:i.userId,expiresAt:o?.expiresAt??i.expiresAt,source:"remote"}}}catch(s){let i=Ut(t);if(i)return i;throw new Error(`[Glyphier] License verification failed: ${s.message}. Visit https://glyphier.com/billing to manage your license.`)}return{valid:!1,plan:"unknown",source:"remote"}}async function hi(){let e=await Kt();if(!e.valid)throw new Error("A valid paid Glyphier API key is required. Set GLYPHIER_API_KEY and subscribe at https://glyphier.com/billing.");return e}function gi(e){let n=dt();if(!n)return;let t=process.env.GLYPHIER_API_URL||"https://api.glyphier.com",s=Math.max(0,e.rawTokens-e.irTokens);fetch(`${t}/api/v1/telemetry/tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({rawTokens:e.rawTokens,irTokens:e.irTokens,savedTokens:s,source:e.source||"mcp"})}).catch(()=>{})}import ut from"path";var Jt=[/@generated\b/i,/autogenerated\b/i,/\bdo not edit\b/i,/\bcode generated by\b/i,/\bthis file is generated\b/i,/\bautomatically generated\b/i],Zt=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".webp",".woff",".woff2",".ttf",".eot",".otf",".mp4",".webm",".mp3",".wav",".wasm",".bin",".exe",".dll",".so",".dylib"]),Qt=new Set([".md",".markdown",".mdown",".mkdn",".txt",".rst",".adoc"]),Vt=new Set([".json",".yaml",".yml",".toml",".ini",".env",".dockerignore",".editorconfig"]);function mt(e,n){let t=e.replace(/\\/g,"/"),s=ut.basename(t).toLowerCase(),i=ut.extname(t).toLowerCase();if(t.includes("/dist/")||t.startsWith("dist/")||t.includes("/build/")||t.startsWith("build/")||t.includes("/out/")||t.startsWith("out/")||t.includes("/.next/")||t.includes("/target/")||i===".map"||s.includes(".min."))return"BUILD_OUTPUT";if(t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/vendor/")||t.startsWith("vendor/")||t.includes("/third_party/")||t.startsWith("third_party/")||t.includes("/.git/"))return"VENDOR";if(s==="package-lock.json"||s==="bun.lock"||s==="bun.lockb"||s==="yarn.lock"||s==="pnpm-lock.yaml"||s==="cargo.lock"||s==="go.sum"||s==="composer.lock"||s==="gemfile.lock")return"DEPENDENCY";if(t.includes("/test/")||t.startsWith("test/")||t.includes("/tests/")||t.startsWith("tests/")||t.includes("/spec/")||t.startsWith("spec/")||t.includes("/__tests__/")||s.includes(".test.")||s.includes(".spec.")||s.endsWith("_test.go")||s.startsWith("test_")||s.endsWith("_test.py"))return"TEST";if(t.includes("/migrations/")||t.startsWith("migrations/")||t.includes("/drizzle/")||t.startsWith("drizzle/")||t.includes("/prisma/migrations/")||t.startsWith("prisma/migrations/")||t.includes("/db/migrate/")||t.startsWith("db/migrate/"))return"MIGRATION";if(Zt.has(i))return"ASSET";if(Qt.has(i)||s==="license"||s==="changelog"||t.includes("/docs/")||t.startsWith("docs/"))return"DOCUMENTATION";if(s.includes(".generated.")||s.includes(".gen.")||s.endsWith(".pb.go")||s.endsWith("_grpc.pb.go")||s.endsWith(".g.dart"))return"GENERATED";if(n){let o=n.slice(0,1e3);for(let a of Jt)if(a.test(o))return"GENERATED"}return Vt.has(i)||s.startsWith(".")||s.includes(".config.")||s==="dockerfile"||s==="makefile"||s==="cmakelists.txt"?"CONFIGURATION":"SOURCE"}import gt from"crypto";function ce(e,n,t,s){let i=e.replace(/\\/g,"/");return gt.createHash("sha256").update(`${i}:${n}:${t}:${s}`).digest("hex").slice(0,16)}function ht(e){return`(${(e.params||[]).map(t=>`${t.name}:${t.type}`).join(", ")}) -> ${e.returnType||"void"}`}function Yt(e){return e.values&&e.values.length>0?e.values.join(" | "):`{${(e.fields||[]).map(t=>`${t.name}:${t.type}`).join(", ")}}`}function fe(e){return gt.createHash("sha256").update(e).digest("hex").slice(0,16)}function yt(e,n){let t=[],s=e.metadata?.language||"unknown",i=n.replace(/\\/g,"/");if(e.module){let o=e.module.lines||{start:1,end:e.metadata?.lineCount||1},a=ce(i,e.module.name,"mod",o.start);t.push({id:a,name:e.module.name,qualifiedName:e.module.name,kind:"mod",filePath:i,startLine:o.start,endLine:o.end,signature:`mod ${e.module.name}`,isExported:!0,hash:fe(`mod:${e.module.name}`),language:s});for(let r of e.module.functions||[]){let l=ht(r),f=r.name.startsWith("GET_")||r.name.startsWith("POST_")||r.name.startsWith("DELETE_")||r.name.startsWith("PUT_")?"route":"fn",c=ce(i,r.name,f,r.lines.start);t.push({id:c,name:r.name,qualifiedName:r.name,kind:f,filePath:i,startLine:r.lines.start,endLine:r.lines.end,signature:l,isExported:!!r.isExported,hash:fe(`${r.name}:${l}:${r.lines.start}-${r.lines.end}`),language:s})}for(let r of e.module.classes||[]){let l=ce(i,r.name,"class",r.lines.start);t.push({id:l,name:r.name,qualifiedName:r.name,kind:"class",filePath:i,startLine:r.lines.start,endLine:r.lines.end,signature:`class ${r.name}${r.extends?` extends ${r.extends}`:""}${r.implements?` implements ${r.implements}`:""}`,isExported:!!r.isExported,hash:fe(`class:${r.name}:${r.lines.start}`),language:s});for(let p of r.methods||[]){let f=`${r.name}.${p.name}`,c=ht(p),d=ce(i,f,"method",p.lines.start);t.push({id:d,name:p.name,qualifiedName:f,kind:"method",filePath:i,startLine:p.lines.start,endLine:p.lines.end,signature:c,isExported:!!r.isExported,hash:fe(`${f}:${c}:${p.lines.start}`),language:s})}}for(let r of e.module.types||[]){let l=Yt(r),p=r.values?"enum":"type",f=ce(i,r.name,p,r.lines.start);t.push({id:f,name:r.name,qualifiedName:r.name,kind:p,filePath:i,startLine:r.lines.start,endLine:r.lines.end,signature:l,isExported:!!r.isExported,hash:fe(`type:${r.name}:${l}`),language:s})}}return t}import V from"path";function xt(e,n,t,s){let i=[],o=n.replace(/\\/g,"/"),a=new Map;for(let l of t)a.set(l.name,l),a.set(l.qualifiedName,l);let r=new Map;for(let l of e.module.imports||[]){let p=l.path,f=Xt(o,p);for(let c of l.symbols||[]){let d=c.includes(":")?c.split(":")[0]:c;r.set(d,f)}}for(let l of e.module.classes||[]){let p=a.get(l.name);if(p){if(l.extends){let f=ve(l.extends,r,a,s,"class");f&&i.push({sourceId:p.id,targetId:f.id,kind:"extends",filePath:o,line:l.lines.start,confidence:.95})}if(l.implements&&l.implements.length>0)for(let f of l.implements){let c=ve(f.trim(),r,a,s,"type");c&&i.push({sourceId:p.id,targetId:c.id,kind:"implements",filePath:o,line:l.lines.start,confidence:.95})}for(let f of l.methods||[]){let c=a.get(`${l.name}.${f.name}`);if(c){for(let d of f.calls||[]){let h=typeof d=="string"?d:d.name,y=typeof d=="string"?f.lines.start:d.line||f.lines.start,v=$t(h,l.name,r,a,s);v&&v.id!==c.id&&(i.push({sourceId:c.id,targetId:v.id,kind:"calls",filePath:o,line:y,confidence:v.confidence}),i.push({sourceId:v.id,targetId:c.id,kind:"called_by",filePath:o,line:y,confidence:v.confidence}))}for(let d of f.validates||[]){let h=ve(d,r,a,s,"fn");h&&i.push({sourceId:c.id,targetId:h.id,kind:"validates",filePath:o,line:f.lines.start,confidence:.9})}}}}}for(let l of e.module.functions||[]){let p=a.get(l.name);if(p){for(let f of l.calls||[]){let c=typeof f=="string"?f:f.name,d=typeof f=="string"?l.lines.start:f.line||l.lines.start,h=$t(c,void 0,r,a,s);h&&h.id!==p.id&&(i.push({sourceId:p.id,targetId:h.id,kind:"calls",filePath:o,line:d,confidence:h.confidence}),i.push({sourceId:h.id,targetId:p.id,kind:"called_by",filePath:o,line:d,confidence:h.confidence}))}for(let f of l.validates||[]){let c=ve(f,r,a,s,"fn");c&&i.push({sourceId:p.id,targetId:c.id,kind:"validates",filePath:o,line:l.lines.start,confidence:.9})}}}return i}function $t(e,n,t,s,i){if(n&&(e.startsWith("this.")||!e.includes("."))){let p=e.replace(/^this\./,""),f=s.get(`${n}.${p}`);if(f)return{id:f.id,confidence:.98}}let o=s.get(e);if(o)return{id:o.id,confidence:.95};if(e.includes(".")){let p=e.split("."),f=p[0],c=p[1];if(t.get(f)){let h=`${f}.${c}`,y=i.findSymbols(h);if(y.length>0)return{id:y[0].id,confidence:.9}}}let a=t.get(e);if(a){let p=i.findSymbols(e),f=p.find(c=>a.includes(V.basename(c.filePath,V.extname(c.filePath))));if(f)return{id:f.id,confidence:.95};if(p.length===1)return{id:p[0].id,confidence:.85}}let r=e.split(".").pop()||e,l=i.findSymbols(r);return l.length===1?{id:l[0].id,confidence:.7}:null}function ve(e,n,t,s,i){let o=t.get(e);if(o)return{id:o.id};let a=s.findSymbols(e,i);if(a.length>0){let r=n.get(e);if(r){let l=a.find(p=>r.includes(V.basename(p.filePath,V.extname(p.filePath))));if(l)return{id:l.id}}return{id:a[0].id}}return null}function Xt(e,n){if(n.startsWith(".")){let t=V.dirname(e);return V.normalize(V.join(t,n))}return n}import ke from"fs";import Le from"path";import en from"crypto";import tn from"fast-glob";import nn from"ignore";var sn=["ts","tsx","js","jsx","mjs","cjs","py","go","rs","java","c","cpp","cs","rb","php"];async function Gi(e,n={}){let t=Date.now(),s=Le.resolve(e),i=n.storage||A(s),o=n.extensions||sn,a=nn();a.add(["node_modules/**","dist/**","build/**",".next/**",".git/**",".glyphier/**","**/*.min.js","**/*.map"]);let r=Le.join(s,".gitignore");if(ke.existsSync(r))try{let m=ke.readFileSync(r,"utf-8");a.add(m)}catch{}let l=`**/*.{${o.join(",")}}`,f=(await tn(l,{cwd:s,dot:!1,followSymbolicLinks:!1})).filter(m=>!a.ignores(m)),c=new Set(f),d=0,h=0,y=0,v=i.getAllFiles();for(let m of v)c.has(m.path)||(i.deleteFile(m.path),y++);let g=new Map;for(let m of f){let u=Le.join(s,m),b;try{b=ke.statSync(u)}catch{continue}let w=b.mtimeMs,k=i.getFile(m);if(!n.force&&k&&k.mtime===w){h++;continue}let x;try{x=ke.readFileSync(u,"utf-8")}catch{continue}let C=en.createHash("sha256").update(x).digest("hex");if(!n.force&&k&&k.hash===C){h++;continue}let j;try{j=await B(u,{rootPath:s,level:2})}catch{continue}if(!j)continue;let N;try{N=await B(u,{rootPath:s,level:1})}catch{N=j}N&&i.setIR(m,1,C,L(N)),i.setIR(m,2,C,L(j));let _=yt(j,m);i.deleteSymbolsByFile(m),i.deleteEdgesByFile(m),i.upsertSymbols(_);let T=mt(m,x);i.upsertFile({path:m,mtime:w,hash:C,language:j.metadata?.language||"unknown",classification:T,lineCount:x.split(`
|
|
45
|
+
`).length,tokenCount:Math.ceil(x.length/4)}),g.set(m,{ir:j,symbols:_}),d++}let S=0;for(let[m,{ir:u,symbols:b}]of g.entries()){let w=xt(u,m,b,i);w.length>0&&(i.upsertEdges(w),S+=w.length)}let $=Date.now()-t;return{indexedFiles:d,skippedFiles:h,deletedFiles:y,symbolCount:g.size,edgeCount:S,durationMs:$}}var Ae=class{sessionId;storage;sentMap=new Map;constructor(n,t){this.sessionId=n,this.storage=t}recordSent(n,t,s,i){this.sentMap.set(n,{symbolId:n,name:t,level:s,hash:i,sentAt:Date.now()})}isAlreadyKnown(n,t,s){let i=this.sentMap.get(n);return i?i.level>=t&&i.hash===s:!1}get knownCount(){return this.sentMap.size}formatReference(n){return`@${n}`}},Re=new Map;function St(e,n){return Re.has(e)||Re.set(e,new Ae(e,n)),Re.get(e)}import bt from"path";var on=new Set(["a","an","the","in","on","at","to","for","with","from","of","by","add","fix","update","implement","how","does","work","make","change","and","or","is","are","was","were","it","this","that","we","i"]);function rn(e){let t=e.toLowerCase().replace(/[^a-z0-9_\-\s]/g," ").split(/\s+/).filter(s=>s.length>1&&!on.has(s));return Array.from(new Set(t))}async function Ji(e){let n=e.rootPath||process.cwd(),t=e.storage||A(n),s=e.budget||2500,i=e.task,o=e.sessionId,a=o?St(o,t):null,r=rn(i),l=new Map;for(let u of r){let b=t.findSymbols(u);for(let w of b)l.set(w.id,w)}let p=new Map(l),f=Array.from(l.values()).slice(0,5);for(let u of f){let b=Oe(u.qualifiedName||u.name,{storage:t,direction:"both",depth:1});for(let w of b.nodes)p.set(w.symbol.id,w.symbol)}let c=Array.from(p.values()).map(u=>{let b=0,w=(u.qualifiedName||u.name).toLowerCase();for(let x of r)w===x?b+=5:w.includes(x)&&(b+=3);(u.kind==="fn"||u.kind==="method")&&(b+=2),u.isExported&&(b+=1);let k=t.getOutgoingEdges(u.id);return b+=Math.min(k.length*.5,3),{sym:u,score:b}});c.sort((u,b)=>b.score-u.score);let d=new Set,h=[],y=[],v=150,g=0;for(let{sym:u}of c){if(v>=s)break;if(d.add(u.filePath),g+=80,a&&a.isAlreadyKnown(u.id,2,u.hash))y.push(` @${u.qualifiedName||u.name}`),h.push({name:u.qualifiedName||u.name,isRef:!0}),v+=3;else{let b=` (${u.kind} ${u.qualifiedName||u.name} ${u.signature} :L${u.startLine}-${u.endLine})`,w=t.getOutgoingEdges(u.id,"calls");if(w.length>0){let k=w.map(x=>{let C=t.getSymbol(x.targetId);return C?C.qualifiedName||C.name:null}).filter(Boolean);k.length>0&&(b+=`
|
|
46
|
+
(calls ${k.slice(0,5).join(" ")})`)}y.push(b),h.push({name:u.qualifiedName||u.name,isRef:!1}),v+=Math.ceil(b.length/3.5),a&&a.recordSent(u.id,u.qualifiedName||u.name,2,u.hash)}}let S=[];for(let u of d){let b=bt.basename(u,bt.extname(u)),w=t.findSymbols(b);for(let k of w)(k.filePath.includes("test")||k.filePath.includes("spec"))&&S.push(k.filePath)}let $=Math.max(0,g*4-v),m=[];m.push(`<context task="${i}" budget="${s}" usedTokens="${v}" savedTokens="${$}">`),m.push("<files>");for(let u of d)m.push(` ${u}`);m.push("</files>"),m.push("<symbols>");for(let u of y)m.push(u);if(m.push("</symbols>"),S.length>0){m.push("<tests>");for(let u of Array.from(new Set(S)))m.push(` ${u}`);m.push("</tests>")}return m.push("</context>"),{task:i,budget:s,usedTokens:v,savedTokens:$,files:Array.from(d),symbols:h,renderedContext:m.join(`
|
|
47
|
+
`)}}export{W as a,Ne as b,Ge as c,Ce as d,ie as e,oe as f,We as g,I as h,qe as i,pe as j,Ze as k,En as l,B as m,G as n,Bn as o,Jn as p,ts as q,Ve as r,L as s,rs as t,as as u,ls as v,cs as w,fs as x,$s as y,st as z,Ts as A,Ps as B,Gs as C,Ks as D,Js as E,ei as F,ai as G,li as H,qt as I,dt as J,Kt as K,hi as L,gi as M,mt as N,ce as O,yt as P,xt as Q,Gi as R,Ae as S,St as T,rn as U,Ji as V};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d={policy:100,document_adr:100,test:90,source_file:80,symbol_definition:80,call_edge:70,import_edge:65,git_commit:60,git_blame:55,config:50,document:40,memory_record:30,inference:10};function l(e){return e.length===0?0:Math.max(...e.map(i=>d[i.sourceType]??20))}function h(e){return e.claimType==="outcome"}function v(e){let i=[],t=[];(!e.repositoryId||e.repositoryId.trim()==="")&&i.push("repositoryId is required for all memory records."),(!e.statement||e.statement.trim()==="")&&i.push("statement must not be empty."),(!e.id||e.id.trim()==="")&&i.push("id is required.");let f=e.evidenceRefs.filter(n=>n.sourceType!=="inference"),c=e.evidenceRefs.filter(n=>n.sourceType==="inference"),s=f.length>0,o=e.evidenceRefs.length>0,a=l(e.evidenceRefs);switch(e.claimType){case"fact":s||i.push(`fact claims require at least one non-inference EvidenceRef. Got ${c.length} inference-only refs.`),e.validationStatus==="validated"&&!s&&i.push("A fact cannot be marked validated without direct evidence.");break;case"inference":e.confidence===void 0||e.confidence===null?i.push("inference claims require a confidence value (0.0\u20131.0)."):(e.confidence<0||e.confidence>1)&&i.push(`confidence must be between 0.0 and 1.0, got ${e.confidence}.`),o||t.push("inference claim has no evidence refs; basis should be documented in statement."),c.length>0&&!s&&t.push(`inference claim is supported only by other inference refs (no direct source evidence). Authority score is low (${a}).`);break;case"decision":!s&&e.validationStatus!=="validated"&&i.push('decision claims require non-inference evidence OR validationStatus="validated" (explicit human validation). Inference-only is not sufficient for architectural decisions.'),a<d.document&&!s&&t.push(`decision claim has low evidence authority (${a}). Consider linking to ADR, source code, or test evidence.`);break;case"outcome":o||t.push("outcome claim has no evidence refs. Consider linking the task artifact or test result.");break;case"preference":e.validationStatus==="validated"&&t.push('preference claims cannot be validated by code evidence. validationStatus="validated" is misleading for preferences.');break}e.expiresAt&&new Date(e.expiresAt)<new Date&&t.push(`Memory record already expired at ${e.expiresAt}. It will be immediately stale.`);let r=e.evidenceRefs.filter(n=>n.freshness==="stale");return r.length>0&&t.push(`${r.length} evidence ref(s) have freshness=stale. The claim may be based on outdated source.`),{admitted:i.length===0,errors:i,warnings:t,maxEvidenceAuthority:a}}export{d as a,l as b,h as c,v as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z as e}from"zod";import{createHash as d}from"crypto";import{z as n}from"zod";var a=n.enum(["source_file","symbol_definition","call_edge","import_edge","git_commit","git_blame","memory_record","document","test","config","inference"]),p=n.enum(["fresh","stale","unknown"]),r=n.object({id:n.string(),sourceType:a,path:n.string(),snapshotRef:n.string(),startLine:n.number().int().positive().optional(),endLine:n.number().int().positive().optional(),excerptDigest:n.string().optional(),excerpt:n.string().optional(),retrievalReason:n.string(),freshness:p,inferenceConfidence:n.number().min(0).max(1).optional(),inferenceBasis:n.string().optional(),schemaVersion:n.literal("1.0.0")});var m=e.enum(["policy_adr","reviewed_design","generated_docs","docs_comments","third_party"]),T={policy_adr:100,reviewed_design:80,generated_docs:60,docs_comments:40,third_party:20},u=e.enum(["EXTRACTED","INFERRED"]),f=e.enum(["invariant","architecture","contract","convention","operational"]),l=e.enum(["verified","unverified","drifted","contradicted"]),y=e.object({id:e.string(),statement:e.string(),assertionType:f,rationaleLink:u,status:l.default("unverified"),docStartLine:e.number().int().positive().optional(),docEndLine:e.number().int().positive().optional(),evidenceRefs:e.array(r).default([]),driftDetails:e.string().optional(),confidence:e.number().min(0).max(1).default(1)}),h=e.object({id:e.string(),heading:e.string(),level:e.number().int().min(1).max(6),startLine:e.number().int().positive(),endLine:e.number().int().positive(),contentDigest:e.string()}),A=e.object({documentId:e.string(),repositoryId:e.string(),path:e.string(),title:e.string(),authorityTier:m,authorityScore:e.number().min(0).max(100),digest:e.string(),sections:e.array(h).default([]),assertions:e.array(y).default([]),snapshotRef:e.string(),capturedAt:e.string().datetime(),schemaVersion:e.literal("1.0.0").default("1.0.0")});function R(i){let t=i.toLowerCase();return t.includes("adr/")||t.includes("/adr-")||t.includes("threat-model")||t.includes("policy")?"policy_adr":t.includes("rfcs/")||t.includes("design/")||t.includes("architecture/")?"reviewed_design":t.includes("openapi")||t.includes("swagger")||t.includes("generated/")?"generated_docs":t.includes("vendor/")||t.includes("third-party/")?"third_party":"docs_comments"}function b(i,t,o){return d("sha256").update(`${i}:${t}:${o}`).digest("hex")}export{r as a,m as b,T as c,u as d,f as e,l as f,y as g,h,A as i,R as j,b as k};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function g(p){let{symbolName:s,signature:a,filePath:r,callers:i=[],callees:o=[],memoryRecords:l=[],docAssertions:c=[]}=p,t=[],n=[];for(let e of l)e.claimType==="decision"?t.push(`[${e.validationStatus.toUpperCase()}] ${e.statement}`):(e.claimType==="fact"||e.statement.toLowerCase().includes("invariant"))&&n.push(e.statement);for(let e of c)e.assertionType==="invariant"?n.push(`[DOC-${e.status.toUpperCase()}] ${e.statement}`):(e.assertionType==="architecture"||e.assertionType==="contract")&&t.push(`[DOC-${e.status.toUpperCase()}] ${e.statement}`);let m=l.length>0||c.length>0?.9:.6,u=[`# Glyphier Explanation: ${s}`,r?`Defined in: ${r}`:"",a?`Signature: \`${a}\``:"","","## Behavioral Graph:",`- Callers (${i.length}): ${i.slice(0,5).join(", ")||"No known internal callers"}`,`- Callees (${o.length}): ${o.slice(0,5).join(", ")||"No known internal callees"}`,"","## Architectural Rationale & Decisions:",...t.map(e=>`- ${e}`),t.length===0?"- (No explicit architectural decisions recorded for this symbol)":"","","## Invariants & Constraints:",...n.map(e=>`- ${e}`),n.length===0?"- (No specific invariants bound to this symbol)":""].filter(Boolean);return{symbolName:s,summary:`Explanation for ${s} (${i.length} callers, ${t.length} decisions, ${n.length} invariants)`,codeBehavior:{signature:a,filePath:r,callersCount:i.length,calleesCount:o.length},architecturalDecisions:t,activeInvariants:n,confidence:m,renderedExplanation:u.join(`
|
|
2
|
+
`)}}export{g as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-NZULHZGK.js";export{b as generateDocumentation,a as planDocumentation,c as validateDocAssertions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-FOZKI4M3.js";import"./chunk-NIXOREHQ.js";export{b as generateSanitizedSupportBundle,c as handleDoctor,a as runDiagnostics};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j}from"./chunk-Z4N35S7K.js";export{d as AssertionTypeSchema,e as AssertionVerificationStatusSchema,b as DOCUMENT_TIER_AUTHORITY,f as DocAssertionSchema,h as DocumentArtifactSchema,a as DocumentAuthorityTierSchema,g as DocumentSectionSchema,c as RationaleLinkKindSchema,i as classifyDocumentTier,j as computeDocumentId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-B6KCBY3J.js";export{a as detectDocumentationDrift};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-ZOFLEGRO.js";export{a as explainSymbol};
|