@promptci/cli 0.2.0 → 0.2.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.
Files changed (2) hide show
  1. package/dist/cli.cjs +105 -105
  2. package/package.json +2 -2
package/dist/cli.cjs CHANGED
@@ -1,128 +1,128 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Hg=Object.create;var tl=Object.defineProperty;var Bg=Object.getOwnPropertyDescriptor;var Wg=Object.getOwnPropertyNames;var Gg=Object.getPrototypeOf,Ug=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Vg=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wg(e))!Ug.call(t,i)&&i!==n&&tl(t,i,{get:()=>e[i],enumerable:!(s=Bg(e,i))||s.enumerable});return t};var x=(t,e,n)=>(n=t!=null?Hg(Gg(t)):{},Vg(e||!t||!t.__esModule?tl(n,"default",{value:t,enumerable:!0}):n,t));var ll=P(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.splitWhen=dn.flatten=void 0;function Yg(t){return t.reduce((e,n)=>[].concat(e,n),[])}dn.flatten=Yg;function Jg(t,e){let n=[[]],s=0;for(let i of t)e(i)?(s++,n[s]=[]):n[s].push(i);return n}dn.splitWhen=Jg});var ul=P(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.isEnoentCodeError=void 0;function Xg(t){return t.code==="ENOENT"}Ms.isEnoentCodeError=Xg});var fl=P(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.createDirentFromStats=void 0;var ar=class{constructor(e,n){this.name=e,this.isBlockDevice=n.isBlockDevice.bind(n),this.isCharacterDevice=n.isCharacterDevice.bind(n),this.isDirectory=n.isDirectory.bind(n),this.isFIFO=n.isFIFO.bind(n),this.isFile=n.isFile.bind(n),this.isSocket=n.isSocket.bind(n),this.isSymbolicLink=n.isSymbolicLink.bind(n)}};function Zg(t,e){return new ar(t,e)}Ds.createDirentFromStats=Zg});var ml=P(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.convertPosixPathToPattern=Q.convertWindowsPathToPattern=Q.convertPathToPattern=Q.escapePosixPath=Q.escapeWindowsPath=Q.escape=Q.removeLeadingDotSegment=Q.makeAbsolute=Q.unixify=void 0;var Qg=require("os"),ey=require("path"),dl=Qg.platform()==="win32",ty=2,ny=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,sy=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,iy=/^\\\\([.?])/,ry=/\\(?![!()+@[\]{}])/g;function oy(t){return t.replace(/\\/g,"/")}Q.unixify=oy;function ay(t,e){return ey.resolve(t,e)}Q.makeAbsolute=ay;function cy(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(ty)}return t}Q.removeLeadingDotSegment=cy;Q.escape=dl?cr:lr;function cr(t){return t.replace(sy,"\\$2")}Q.escapeWindowsPath=cr;function lr(t){return t.replace(ny,"\\$2")}Q.escapePosixPath=lr;Q.convertPathToPattern=dl?pl:hl;function pl(t){return cr(t).replace(iy,"//$1").replace(ry,"/")}Q.convertWindowsPathToPattern=pl;function hl(t){return lr(t)}Q.convertPosixPathToPattern=hl});var yl=P(($1,gl)=>{gl.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var vl=P((P1,wl)=>{var ly=yl(),bl={"{":"}","(":")","[":"]"},uy=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,s=-2,i=-2,r=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||s!==-1&&t[e]==="["&&t[e+1]!=="]"&&(s<e&&(s=t.indexOf("]",e)),s>e&&(o===-1||o>s||(o=t.indexOf("\\",e),o===-1||o>s)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||r!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(r=t.indexOf(")",e),r>e&&(o=t.indexOf("\\",e),o===-1||o>r))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(r=t.indexOf(")",n),r>n&&(o=t.indexOf("\\",n),o===-1||o>r))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=bl[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},fy=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var s=bl[n];if(s){var i=t.indexOf(s,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};wl.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(ly(e))return!0;var s=uy;return n&&n.strict===!1&&(s=fy),s(e)}});var _l=P((T1,xl)=>{"use strict";var dy=vl(),py=require("path").posix.dirname,hy=require("os").platform()==="win32",ur="/",my=/\\/g,gy=/[\{\[].*[\}\]]$/,yy=/(^|[^\\])([\{\[]|\([^\)]+$)/,by=/\\([\!\*\?\|\[\]\(\)\{\}])/g;xl.exports=function(e,n){var s=Object.assign({flipBackslashes:!0},n);s.flipBackslashes&&hy&&e.indexOf(ur)<0&&(e=e.replace(my,ur)),gy.test(e)&&(e+=ur),e+="a";do e=py(e);while(dy(e)||yy.test(e));return e.replace(by,"$1")}});var Fs=P(Fe=>{"use strict";Fe.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;Fe.find=(t,e)=>t.nodes.find(n=>n.type===e);Fe.exceedsLimit=(t,e,n=1,s)=>s===!1||!Fe.isInteger(t)||!Fe.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=s;Fe.escapeNode=(t,e=0,n)=>{let s=t.nodes[e];s&&(n&&s.type===n||s.type==="open"||s.type==="close")&&s.escaped!==!0&&(s.value="\\"+s.value,s.escaped=!0)};Fe.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;Fe.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;Fe.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;Fe.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);Fe.flatten=(...t)=>{let e=[],n=s=>{for(let i=0;i<s.length;i++){let r=s[i];if(Array.isArray(r)){n(r);continue}r!==void 0&&e.push(r)}return e};return n(t),e}});var Hs=P((O1,El)=>{"use strict";var Sl=Fs();El.exports=(t,e={})=>{let n=(s,i={})=>{let r=e.escapeInvalid&&Sl.isInvalidBrace(i),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(r||o)&&Sl.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let c of s.nodes)a+=n(c);return a};return n(t)}});var Rl=P((L1,kl)=>{"use strict";kl.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var Nl=P((N1,Ll)=>{"use strict";var Cl=Rl(),Bt=(t,e,n)=>{if(Cl(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Cl(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let s={relaxZeros:!0,...n};typeof s.strictZeros=="boolean"&&(s.relaxZeros=s.strictZeros===!1);let i=String(s.relaxZeros),r=String(s.shorthand),o=String(s.capture),a=String(s.wrap),c=t+":"+e+"="+i+r+o+a;if(Bt.cache.hasOwnProperty(c))return Bt.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let m=t+"|"+e;return s.capture?`(${m})`:s.wrap===!1?m:`(?:${m})`}let f=Ol(t)||Ol(e),d={min:t,max:e,a:l,b:u},p=[],h=[];if(f&&(d.isPadded=f,d.maxLen=String(d.max).length),l<0){let m=u<0?Math.abs(u):1;h=Al(m,Math.abs(l),d,s),l=d.a=0}return u>=0&&(p=Al(l,u,d,s)),d.negatives=h,d.positives=p,d.result=wy(h,p,s),s.capture===!0?d.result=`(${d.result})`:s.wrap!==!1&&p.length+h.length>1&&(d.result=`(?:${d.result})`),Bt.cache[c]=d,d.result};function wy(t,e,n){let s=fr(t,e,"-",!1,n)||[],i=fr(e,t,"",!1,n)||[],r=fr(t,e,"-?",!0,n)||[];return s.concat(r).concat(i).join("|")}function vy(t,e){let n=1,s=1,i=Pl(t,n),r=new Set([e]);for(;t<=i&&i<=e;)r.add(i),n+=1,i=Pl(t,n);for(i=Tl(e+1,s)-1;t<i&&i<=e;)r.add(i),s+=1,i=Tl(e+1,s)-1;return r=[...r],r.sort(Sy),r}function xy(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let s=_y(t,e),i=s.length,r="",o=0;for(let a=0;a<i;a++){let[c,l]=s[a];c===l?r+=c:c!=="0"||l!=="9"?r+=Ey(c,l,n):o++}return o&&(r+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:r,count:[o],digits:i}}function Al(t,e,n,s){let i=vy(t,e),r=[],o=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=xy(String(o),String(l),s),f="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Il(a.count),o=l+1;continue}n.isPadded&&(f=ky(l,n,s)),u.string=f+u.pattern+Il(u.count),r.push(u),o=l+1,a=u}return r}function fr(t,e,n,s,i){let r=[];for(let o of t){let{string:a}=o;!s&&!$l(e,"string",a)&&r.push(n+a),s&&$l(e,"string",a)&&r.push(n+a)}return r}function _y(t,e){let n=[];for(let s=0;s<t.length;s++)n.push([t[s],e[s]]);return n}function Sy(t,e){return t>e?1:e>t?-1:0}function $l(t,e,n){return t.some(s=>s[e]===n)}function Pl(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Tl(t,e){return t-t%Math.pow(10,e)}function Il(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function Ey(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Ol(t){return/^-?(0+)\d/.test(t)}function ky(t,e,n){if(!e.isPadded)return t;let s=Math.abs(e.maxLen-String(t).length),i=n.relaxZeros!==!1;switch(s){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${s}}`:`0{${s}}`}}Bt.cache={};Bt.clearCache=()=>Bt.cache={};Ll.exports=Bt});var hr=P((j1,Wl)=>{"use strict";var Ry=require("util"),Ml=Nl(),jl=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Cy=t=>e=>t===!0?Number(e):String(e),dr=t=>typeof t=="number"||typeof t=="string"&&t!=="",Fn=t=>Number.isInteger(+t),pr=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},Ay=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,$y=(t,e,n)=>{if(e>0){let s=t[0]==="-"?"-":"";s&&(t=t.slice(1)),t=s+t.padStart(s?e-1:e,"0")}return n===!1?String(t):t},Ws=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},Py=(t,e,n)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let s=e.capture?"":"?:",i="",r="",o;return t.positives.length&&(i=t.positives.map(a=>Ws(String(a),n)).join("|")),t.negatives.length&&(r=`-(${s}${t.negatives.map(a=>Ws(String(a),n)).join("|")})`),i&&r?o=`${i}|${r}`:o=i||r,e.wrap?`(${s}${o})`:o},Dl=(t,e,n,s)=>{if(n)return Ml(t,e,{wrap:!1,...s});let i=String.fromCharCode(t);if(t===e)return i;let r=String.fromCharCode(e);return`[${i}-${r}]`},Fl=(t,e,n)=>{if(Array.isArray(t)){let s=n.wrap===!0,i=n.capture?"":"?:";return s?`(${i}${t.join("|")})`:t.join("|")}return Ml(t,e,n)},Hl=(...t)=>new RangeError("Invalid range arguments: "+Ry.inspect(...t)),Bl=(t,e,n)=>{if(n.strictRanges===!0)throw Hl([t,e]);return[]},Ty=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},Iy=(t,e,n=1,s={})=>{let i=Number(t),r=Number(e);if(!Number.isInteger(i)||!Number.isInteger(r)){if(s.strictRanges===!0)throw Hl([t,e]);return[]}i===0&&(i=0),r===0&&(r=0);let o=i>r,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=pr(a)||pr(c)||pr(l),f=u?Math.max(a.length,c.length,l.length):0,d=u===!1&&Ay(t,e,s)===!1,p=s.transform||Cy(d);if(s.toRegex&&n===1)return Dl(Ws(t,f),Ws(e,f),!0,s);let h={negatives:[],positives:[]},m=w=>h[w<0?"negatives":"positives"].push(Math.abs(w)),g=[],b=0;for(;o?i>=r:i<=r;)s.toRegex===!0&&n>1?m(i):g.push($y(p(i,b),f,d)),i=o?i-n:i+n,b++;return s.toRegex===!0?n>1?Py(h,s,f):Fl(g,null,{wrap:!1,...s}):g},Oy=(t,e,n=1,s={})=>{if(!Fn(t)&&t.length>1||!Fn(e)&&e.length>1)return Bl(t,e,s);let i=s.transform||(d=>String.fromCharCode(d)),r=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=r>o,c=Math.min(r,o),l=Math.max(r,o);if(s.toRegex&&n===1)return Dl(c,l,!1,s);let u=[],f=0;for(;a?r>=o:r<=o;)u.push(i(r,f)),r=a?r-n:r+n,f++;return s.toRegex===!0?Fl(u,null,{wrap:!1,options:s}):u},Bs=(t,e,n,s={})=>{if(e==null&&dr(t))return[t];if(!dr(t)||!dr(e))return Bl(t,e,s);if(typeof n=="function")return Bs(t,e,1,{transform:n});if(jl(n))return Bs(t,e,0,n);let i={...s};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,Fn(n)?Fn(t)&&Fn(e)?Iy(t,e,n,i):Oy(t,e,Math.max(Math.abs(n),1),i):n!=null&&!jl(n)?Ty(n,i):Bs(t,e,1,n)};Wl.exports=Bs});var Vl=P((M1,Ul)=>{"use strict";var Ly=hr(),Gl=Fs(),Ny=(t,e={})=>{let n=(s,i={})=>{let r=Gl.isInvalidBrace(i),o=s.invalid===!0&&e.escapeInvalid===!0,a=r===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(s.isOpen===!0)return c+s.value;if(s.isClose===!0)return console.log("node.isClose",c,s.value),c+s.value;if(s.type==="open")return a?c+s.value:"(";if(s.type==="close")return a?c+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let u=Gl.reduce(s.nodes),f=Ly(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return u.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let u of s.nodes)l+=n(u,s);return l};return n(t)};Ul.exports=Ny});var Kl=P((D1,ql)=>{"use strict";var jy=hr(),zl=Hs(),pn=Fs(),Wt=(t="",e="",n=!1)=>{let s=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?pn.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let r of i)s.push(Wt(r,e,n));else for(let r of e)n===!0&&typeof r=="string"&&(r=`{${r}}`),s.push(Array.isArray(r)?Wt(i,r,n):i+r);return pn.flatten(s)},My=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(i,r={})=>{i.queue=[];let o=r,a=r.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(Wt(a.pop(),zl(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Wt(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let f=pn.reduce(i.nodes);if(pn.exceedsLimit(...f,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let d=jy(...f,e);d.length===0&&(d=zl(i,e)),a.push(Wt(a.pop(),d)),i.nodes=[];return}let c=pn.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let f=0;f<i.nodes.length;f++){let d=i.nodes[f];if(d.type==="comma"&&i.type==="brace"){f===1&&l.push(""),l.push("");continue}if(d.type==="close"){a.push(Wt(a.pop(),l,c));continue}if(d.value&&d.type!=="open"){l.push(Wt(l.pop(),d.value));continue}d.nodes&&s(d,i)}return l};return pn.flatten(s(t))};ql.exports=My});var Jl=P((F1,Yl)=>{"use strict";Yl.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
3
- `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var tu=P((H1,eu)=>{"use strict";var Dy=Hs(),{MAX_LENGTH:Xl,CHAR_BACKSLASH:mr,CHAR_BACKTICK:Fy,CHAR_COMMA:Hy,CHAR_DOT:By,CHAR_LEFT_PARENTHESES:Wy,CHAR_RIGHT_PARENTHESES:Gy,CHAR_LEFT_CURLY_BRACE:Uy,CHAR_RIGHT_CURLY_BRACE:Vy,CHAR_LEFT_SQUARE_BRACKET:Zl,CHAR_RIGHT_SQUARE_BRACKET:Ql,CHAR_DOUBLE_QUOTE:zy,CHAR_SINGLE_QUOTE:qy,CHAR_NO_BREAK_SPACE:Ky,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Yy}=Jl(),Jy=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},s=typeof n.maxLength=="number"?Math.min(Xl,n.maxLength):Xl;if(t.length>s)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${s})`);let i={type:"root",input:t,nodes:[]},r=[i],o=i,a=i,c=0,l=t.length,u=0,f=0,d,p=()=>t[u++],h=m=>{if(m.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&m.type==="text"){a.value+=m.value;return}return o.nodes.push(m),m.parent=o,m.prev=a,a=m,m};for(h({type:"bos"});u<l;)if(o=r[r.length-1],d=p(),!(d===Yy||d===Ky)){if(d===mr){h({type:"text",value:(e.keepEscaping?d:"")+p()});continue}if(d===Ql){h({type:"text",value:"\\"+d});continue}if(d===Zl){c++;let m;for(;u<l&&(m=p());){if(d+=m,m===Zl){c++;continue}if(m===mr){d+=p();continue}if(m===Ql&&(c--,c===0))break}h({type:"text",value:d});continue}if(d===Wy){o=h({type:"paren",nodes:[]}),r.push(o),h({type:"text",value:d});continue}if(d===Gy){if(o.type!=="paren"){h({type:"text",value:d});continue}o=r.pop(),h({type:"text",value:d}),o=r[r.length-1];continue}if(d===zy||d===qy||d===Fy){let m=d,g;for(e.keepQuotes!==!0&&(d="");u<l&&(g=p());){if(g===mr){d+=g+p();continue}if(g===m){e.keepQuotes===!0&&(d+=g);break}d+=g}h({type:"text",value:d});continue}if(d===Uy){f++;let g={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=h(g),r.push(o),h({type:"open",value:d});continue}if(d===Vy){if(o.type!=="brace"){h({type:"text",value:d});continue}let m="close";o=r.pop(),o.close=!0,h({type:m,value:d}),f--,o=r[r.length-1];continue}if(d===Hy&&f>0){if(o.ranges>0){o.ranges=0;let m=o.nodes.shift();o.nodes=[m,{type:"text",value:Dy(o)}]}h({type:"comma",value:d}),o.commas++;continue}if(d===By&&f>0&&o.commas===0){let m=o.nodes;if(f===0||m.length===0){h({type:"text",value:d});continue}if(a.type==="dot"){if(o.range=[],a.value+=d,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){m.pop();let g=m[m.length-1];g.value+=a.value+d,a=g,o.ranges--;continue}h({type:"dot",value:d});continue}h({type:"text",value:d})}do if(o=r.pop(),o.type!=="root"){o.nodes.forEach(b=>{b.nodes||(b.type==="open"&&(b.isOpen=!0),b.type==="close"&&(b.isClose=!0),b.nodes||(b.type="text"),b.invalid=!0)});let m=r[r.length-1],g=m.nodes.indexOf(o);m.nodes.splice(g,1,...o.nodes)}while(r.length>0);return h({type:"eos"}),i};eu.exports=Jy});var iu=P((B1,su)=>{"use strict";var nu=Hs(),Xy=Vl(),Zy=Kl(),Qy=tu(),Oe=(t,e={})=>{let n=[];if(Array.isArray(t))for(let s of t){let i=Oe.create(s,e);Array.isArray(i)?n.push(...i):n.push(i)}else n=[].concat(Oe.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};Oe.parse=(t,e={})=>Qy(t,e);Oe.stringify=(t,e={})=>nu(typeof t=="string"?Oe.parse(t,e):t,e);Oe.compile=(t,e={})=>(typeof t=="string"&&(t=Oe.parse(t,e)),Xy(t,e));Oe.expand=(t,e={})=>{typeof t=="string"&&(t=Oe.parse(t,e));let n=Zy(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};Oe.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Oe.compile(t,e):Oe.expand(t,e);su.exports=Oe});var Hn=P((W1,lu)=>{"use strict";var eb=require("path"),nt="\\\\/",ru=`[^${nt}]`,tb=0,pt="\\.",nb="\\+",sb="\\?",Gs="\\/",ib="(?=.)",ou="[^/]",gr=`(?:${Gs}|$)`,au=`(?:^|${Gs})`,yr=`${pt}{1,2}${gr}`,rb=`(?!${pt})`,ob=`(?!${au}${yr})`,ab=`(?!${pt}{0,1}${gr})`,cb=`(?!${yr})`,lb=`[^.${Gs}]`,ub=`${ou}*?`,cu={DOT_LITERAL:pt,PLUS_LITERAL:nb,QMARK_LITERAL:sb,SLASH_LITERAL:Gs,ONE_CHAR:ib,QMARK:ou,END_ANCHOR:gr,DOTS_SLASH:yr,NO_DOT:rb,NO_DOTS:ob,NO_DOT_SLASH:ab,NO_DOTS_SLASH:cb,QMARK_NO_DOT:lb,STAR:ub,START_ANCHOR:au},fb={...cu,SLASH_LITERAL:`[${nt}]`,QMARK:ru,STAR:`${ru}*?`,DOTS_SLASH:`${pt}{1,2}(?:[${nt}]|$)`,NO_DOT:`(?!${pt})`,NO_DOTS:`(?!(?:^|[${nt}])${pt}{1,2}(?:[${nt}]|$))`,NO_DOT_SLASH:`(?!${pt}{0,1}(?:[${nt}]|$))`,NO_DOTS_SLASH:`(?!${pt}{1,2}(?:[${nt}]|$))`,QMARK_NO_DOT:`[^.${nt}]`,START_ANCHOR:`(?:^|[${nt}])`,END_ANCHOR:`(?:[${nt}]|$)`},db={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};lu.exports={DEFAULT_MAX_EXTGLOB_RECURSION:tb,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:db,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:eb.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?fb:cu}}});var Bn=P(Ae=>{"use strict";var pb=require("path"),hb=process.platform==="win32",{REGEX_BACKSLASH:mb,REGEX_REMOVE_BACKSLASH:gb,REGEX_SPECIAL_CHARS:yb,REGEX_SPECIAL_CHARS_GLOBAL:bb}=Hn();Ae.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Ae.hasRegexChars=t=>yb.test(t);Ae.isRegexChar=t=>t.length===1&&Ae.hasRegexChars(t);Ae.escapeRegex=t=>t.replace(bb,"\\$1");Ae.toPosixSlashes=t=>t.replace(mb,"/");Ae.removeBackslashes=t=>t.replace(gb,e=>e==="\\"?"":e);Ae.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Ae.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:hb===!0||pb.sep==="\\";Ae.escapeLast=(t,e,n)=>{let s=t.lastIndexOf(e,n);return s===-1?t:t[s-1]==="\\"?Ae.escapeLast(t,e,s-1):`${t.slice(0,s)}\\${t.slice(s)}`};Ae.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};Ae.wrapOutput=(t,e={},n={})=>{let s=n.contains?"":"^",i=n.contains?"":"$",r=`${s}(?:${t})${i}`;return e.negated===!0&&(r=`(?:^(?!${r}).*$)`),r}});var yu=P((U1,gu)=>{"use strict";var uu=Bn(),{CHAR_ASTERISK:br,CHAR_AT:wb,CHAR_BACKWARD_SLASH:Wn,CHAR_COMMA:vb,CHAR_DOT:wr,CHAR_EXCLAMATION_MARK:vr,CHAR_FORWARD_SLASH:mu,CHAR_LEFT_CURLY_BRACE:xr,CHAR_LEFT_PARENTHESES:_r,CHAR_LEFT_SQUARE_BRACKET:xb,CHAR_PLUS:_b,CHAR_QUESTION_MARK:fu,CHAR_RIGHT_CURLY_BRACE:Sb,CHAR_RIGHT_PARENTHESES:du,CHAR_RIGHT_SQUARE_BRACKET:Eb}=Hn(),pu=t=>t===mu||t===Wn,hu=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},kb=(t,e)=>{let n=e||{},s=t.length-1,i=n.parts===!0||n.scanToEnd===!0,r=[],o=[],a=[],c=t,l=-1,u=0,f=0,d=!1,p=!1,h=!1,m=!1,g=!1,b=!1,w=!1,y=!1,v=!1,k=!1,R=0,I,C,N={value:"",depth:0,isGlob:!1},J=()=>l>=s,E=()=>c.charCodeAt(l+1),B=()=>(I=C,c.charCodeAt(++l));for(;l<s;){C=B();let j;if(C===Wn){w=N.backslashes=!0,C=B(),C===xr&&(b=!0);continue}if(b===!0||C===xr){for(R++;J()!==!0&&(C=B());){if(C===Wn){w=N.backslashes=!0,B();continue}if(C===xr){R++;continue}if(b!==!0&&C===wr&&(C=B())===wr){if(d=N.isBrace=!0,h=N.isGlob=!0,k=!0,i===!0)continue;break}if(b!==!0&&C===vb){if(d=N.isBrace=!0,h=N.isGlob=!0,k=!0,i===!0)continue;break}if(C===Sb&&(R--,R===0)){b=!1,d=N.isBrace=!0,k=!0;break}}if(i===!0)continue;break}if(C===mu){if(r.push(l),o.push(N),N={value:"",depth:0,isGlob:!1},k===!0)continue;if(I===wr&&l===u+1){u+=2;continue}f=l+1;continue}if(n.noext!==!0&&(C===_b||C===wb||C===br||C===fu||C===vr)===!0&&E()===_r){if(h=N.isGlob=!0,m=N.isExtglob=!0,k=!0,C===vr&&l===u&&(v=!0),i===!0){for(;J()!==!0&&(C=B());){if(C===Wn){w=N.backslashes=!0,C=B();continue}if(C===du){h=N.isGlob=!0,k=!0;break}}continue}break}if(C===br){if(I===br&&(g=N.isGlobstar=!0),h=N.isGlob=!0,k=!0,i===!0)continue;break}if(C===fu){if(h=N.isGlob=!0,k=!0,i===!0)continue;break}if(C===xb){for(;J()!==!0&&(j=B());){if(j===Wn){w=N.backslashes=!0,B();continue}if(j===Eb){p=N.isBracket=!0,h=N.isGlob=!0,k=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&C===vr&&l===u){y=N.negated=!0,u++;continue}if(n.noparen!==!0&&C===_r){if(h=N.isGlob=!0,i===!0){for(;J()!==!0&&(C=B());){if(C===_r){w=N.backslashes=!0,C=B();continue}if(C===du){k=!0;break}}continue}break}if(h===!0){if(k=!0,i===!0)continue;break}}n.noext===!0&&(m=!1,h=!1);let W=c,we="",_="";u>0&&(we=c.slice(0,u),c=c.slice(u),f-=u),W&&h===!0&&f>0?(W=c.slice(0,f),_=c.slice(f)):h===!0?(W="",_=c):W=c,W&&W!==""&&W!=="/"&&W!==c&&pu(W.charCodeAt(W.length-1))&&(W=W.slice(0,-1)),n.unescape===!0&&(_&&(_=uu.removeBackslashes(_)),W&&w===!0&&(W=uu.removeBackslashes(W)));let S={prefix:we,input:t,start:u,base:W,glob:_,isBrace:d,isBracket:p,isGlob:h,isExtglob:m,isGlobstar:g,negated:y,negatedExtglob:v};if(n.tokens===!0&&(S.maxDepth=0,pu(C)||o.push(N),S.tokens=o),n.parts===!0||n.tokens===!0){let j;for(let T=0;T<r.length;T++){let X=j?j+1:u,ee=r[T],ve=t.slice(X,ee);n.tokens&&(T===0&&u!==0?(o[T].isPrefix=!0,o[T].value=we):o[T].value=ve,hu(o[T]),S.maxDepth+=o[T].depth),(T!==0||ve!=="")&&a.push(ve),j=ee}if(j&&j+1<t.length){let T=t.slice(j+1);a.push(T),n.tokens&&(o[o.length-1].value=T,hu(o[o.length-1]),S.maxDepth+=o[o.length-1].depth)}S.slashes=r,S.parts=a}return S};gu.exports=kb});var _u=P((V1,xu)=>{"use strict";var Gn=Hn(),pe=Bn(),{MAX_LENGTH:Us,POSIX_REGEX_SOURCE:Rb,REGEX_NON_SPECIAL_CHARS:Cb,REGEX_SPECIAL_CHARS_BACKREF:Ab,REPLACEMENTS:bu}=Gn,$b=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(i=>pe.escapeRegex(i)).join("..")}return n},hn=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,wu=t=>{let e=[],n=0,s=0,i=0,r="",o=!1;for(let a of t){if(o===!0){r+=a,o=!1;continue}if(a==="\\"){r+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,r+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(r),r="";continue}}}r+=a}return e.push(r),e},Pb=t=>{let e=!1;for(let n of t){if(e===!0){e=!1;continue}if(n==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},vu=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(Pb(e))return e.replace(/\\(.)/g,"$1")},Tb=t=>{let e=t.map(vu).filter(Boolean);for(let n=0;n<e.length;n++)for(let s=n+1;s<e.length;s++){let i=e[n],r=e[s],o=i[0];if(!(!o||i!==o.repeat(i.length)||r!==o.repeat(r.length))&&(i===r||i.startsWith(r)||r.startsWith(i)))return!0}return!1},Sr=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,s=0,i=0,r=!1;for(let o=1;o<t.length;o++){let a=t[o];if(r===!0){r=!1;continue}if(a==="\\"){r=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},Ib=t=>{let e=0,n=[];for(;e<t.length;){let i=Sr(t.slice(e),!1);if(!i||i.type!=="*")return;let r=wu(i.body).map(a=>a.trim());if(r.length!==1)return;let o=vu(r[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?pe.escapeRegex(n[0]):`[${n.map(i=>pe.escapeRegex(i)).join("")}]`}*`},Ob=t=>{let e=0,n=t.trim(),s=Sr(n);for(;s;)e++,n=s.body.trim(),s=Sr(n);return e},Lb=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Gn.DEFAULT_MAX_EXTGLOB_RECURSION,s=wu(t).map(i=>i.trim());if(s.length>1&&(s.some(i=>i==="")||s.some(i=>/^[*?]+$/.test(i))||Tb(s)))return{risky:!0};for(let i of s){let r=Ib(i);if(r)return{risky:!0,safeOutput:r};if(Ob(i)>n)return{risky:!0}}return{risky:!1}},Er=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=bu[t]||t;let n={...e},s=typeof n.maxLength=="number"?Math.min(Us,n.maxLength):Us,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);let r={type:"bos",value:"",output:n.prepend||""},o=[r],a=n.capture?"":"?:",c=pe.isWindows(e),l=Gn.globChars(c),u=Gn.extglobChars(l),{DOT_LITERAL:f,PLUS_LITERAL:d,SLASH_LITERAL:p,ONE_CHAR:h,DOTS_SLASH:m,NO_DOT:g,NO_DOT_SLASH:b,NO_DOTS_SLASH:w,QMARK:y,QMARK_NO_DOT:v,STAR:k,START_ANCHOR:R}=l,I=$=>`(${a}(?:(?!${R}${$.dot?m:f}).)*?)`,C=n.dot?"":g,N=n.dot?y:v,J=n.bash===!0?I(n):k;n.capture&&(J=`(${J})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let E={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=pe.removePrefix(t,E),i=t.length;let B=[],W=[],we=[],_=r,S,j=()=>E.index===i-1,T=E.peek=($=1)=>t[E.index+$],X=E.advance=()=>t[++E.index]||"",ee=()=>t.slice(E.index+1),ve=($="",z=0)=>{E.consumed+=$,E.index+=z},dt=$=>{E.output+=$.output!=null?$.output:$.value,ve($.value)},Dg=()=>{let $=1;for(;T()==="!"&&(T(2)!=="("||T(3)==="?");)X(),E.start++,$++;return $%2===0?!1:(E.negated=!0,E.start++,!0)},Ts=$=>{E[$]++,we.push($)},_t=$=>{E[$]--,we.pop()},D=$=>{if(_.type==="globstar"){let z=E.braces>0&&($.type==="comma"||$.type==="brace"),A=$.extglob===!0||B.length&&($.type==="pipe"||$.type==="paren");$.type!=="slash"&&$.type!=="paren"&&!z&&!A&&(E.output=E.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=J,E.output+=_.output)}if(B.length&&$.type!=="paren"&&(B[B.length-1].inner+=$.value),($.value||$.output)&&dt($),_&&_.type==="text"&&$.type==="text"){_.value+=$.value,_.output=(_.output||"")+$.value;return}$.prev=_,o.push($),_=$},Is=($,z)=>{let A={...u[z],conditions:1,inner:""};A.prev=_,A.parens=E.parens,A.output=E.output,A.startIndex=E.index,A.tokensIndex=o.length;let M=(n.capture?"(":"")+A.open;Ts("parens"),D({type:$,value:z,output:E.output?"":h}),D({type:"paren",extglob:!0,value:X(),output:M}),B.push(A)},Fg=$=>{let z=t.slice($.startIndex,E.index+1),A=t.slice($.startIndex+2,E.index),M=Lb(A,n);if(($.type==="plus"||$.type==="star")&&M.risky){let G=M.safeOutput?($.output?"":h)+(n.capture?`(${M.safeOutput})`:M.safeOutput):void 0,Qe=o[$.tokensIndex];Qe.type="text",Qe.value=z,Qe.output=G||pe.escapeRegex(z);for(let et=$.tokensIndex+1;et<o.length;et++)o[et].value="",o[et].output="",delete o[et].suffix;E.output=$.output+Qe.output,E.backtrack=!0,D({type:"paren",extglob:!0,value:S,output:""}),_t("parens");return}let U=$.close+(n.capture?")":""),te;if($.type==="negate"){let G=J;if($.inner&&$.inner.length>1&&$.inner.includes("/")&&(G=I(n)),(G!==J||j()||/^\)+$/.test(ee()))&&(U=$.close=`)$))${G}`),$.inner.includes("*")&&(te=ee())&&/^\.[^\\/.]+$/.test(te)){let Qe=Er(te,{...e,fastpaths:!1}).output;U=$.close=`)${Qe})${G})`}$.prev.type==="bos"&&(E.negatedExtglob=!0)}D({type:"paren",extglob:!0,value:S,output:U}),_t("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let $=!1,z=t.replace(Ab,(A,M,U,te,G,Qe)=>te==="\\"?($=!0,A):te==="?"?M?M+te+(G?y.repeat(G.length):""):Qe===0?N+(G?y.repeat(G.length):""):y.repeat(U.length):te==="."?f.repeat(U.length):te==="*"?M?M+te+(G?J:""):J:M?A:`\\${A}`);return $===!0&&(n.unescape===!0?z=z.replace(/\\/g,""):z=z.replace(/\\+/g,A=>A.length%2===0?"\\\\":A?"\\":"")),z===t&&n.contains===!0?(E.output=t,E):(E.output=pe.wrapOutput(z,E,e),E)}for(;!j();){if(S=X(),S==="\0")continue;if(S==="\\"){let A=T();if(A==="/"&&n.bash!==!0||A==="."||A===";")continue;if(!A){S+="\\",D({type:"text",value:S});continue}let M=/^\\+/.exec(ee()),U=0;if(M&&M[0].length>2&&(U=M[0].length,E.index+=U,U%2!==0&&(S+="\\")),n.unescape===!0?S=X():S+=X(),E.brackets===0){D({type:"text",value:S});continue}}if(E.brackets>0&&(S!=="]"||_.value==="["||_.value==="[^")){if(n.posix!==!1&&S===":"){let A=_.value.slice(1);if(A.includes("[")&&(_.posix=!0,A.includes(":"))){let M=_.value.lastIndexOf("["),U=_.value.slice(0,M),te=_.value.slice(M+2),G=Rb[te];if(G){_.value=U+G,E.backtrack=!0,X(),!r.output&&o.indexOf(_)===1&&(r.output=h);continue}}}(S==="["&&T()!==":"||S==="-"&&T()==="]")&&(S=`\\${S}`),S==="]"&&(_.value==="["||_.value==="[^")&&(S=`\\${S}`),n.posix===!0&&S==="!"&&_.value==="["&&(S="^"),_.value+=S,dt({value:S});continue}if(E.quotes===1&&S!=='"'){S=pe.escapeRegex(S),_.value+=S,dt({value:S});continue}if(S==='"'){E.quotes=E.quotes===1?0:1,n.keepQuotes===!0&&D({type:"text",value:S});continue}if(S==="("){Ts("parens"),D({type:"paren",value:S});continue}if(S===")"){if(E.parens===0&&n.strictBrackets===!0)throw new SyntaxError(hn("opening","("));let A=B[B.length-1];if(A&&E.parens===A.parens+1){Fg(B.pop());continue}D({type:"paren",value:S,output:E.parens?")":"\\)"}),_t("parens");continue}if(S==="["){if(n.nobracket===!0||!ee().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(hn("closing","]"));S=`\\${S}`}else Ts("brackets");D({type:"bracket",value:S});continue}if(S==="]"){if(n.nobracket===!0||_&&_.type==="bracket"&&_.value.length===1){D({type:"text",value:S,output:`\\${S}`});continue}if(E.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(hn("opening","["));D({type:"text",value:S,output:`\\${S}`});continue}_t("brackets");let A=_.value.slice(1);if(_.posix!==!0&&A[0]==="^"&&!A.includes("/")&&(S=`/${S}`),_.value+=S,dt({value:S}),n.literalBrackets===!1||pe.hasRegexChars(A))continue;let M=pe.escapeRegex(_.value);if(E.output=E.output.slice(0,-_.value.length),n.literalBrackets===!0){E.output+=M,_.value=M;continue}_.value=`(${a}${M}|${_.value})`,E.output+=_.value;continue}if(S==="{"&&n.nobrace!==!0){Ts("braces");let A={type:"brace",value:S,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};W.push(A),D(A);continue}if(S==="}"){let A=W[W.length-1];if(n.nobrace===!0||!A){D({type:"text",value:S,output:S});continue}let M=")";if(A.dots===!0){let U=o.slice(),te=[];for(let G=U.length-1;G>=0&&(o.pop(),U[G].type!=="brace");G--)U[G].type!=="dots"&&te.unshift(U[G].value);M=$b(te,n),E.backtrack=!0}if(A.comma!==!0&&A.dots!==!0){let U=E.output.slice(0,A.outputIndex),te=E.tokens.slice(A.tokensIndex);A.value=A.output="\\{",S=M="\\}",E.output=U;for(let G of te)E.output+=G.output||G.value}D({type:"brace",value:S,output:M}),_t("braces"),W.pop();continue}if(S==="|"){B.length>0&&B[B.length-1].conditions++,D({type:"text",value:S});continue}if(S===","){let A=S,M=W[W.length-1];M&&we[we.length-1]==="braces"&&(M.comma=!0,A="|"),D({type:"comma",value:S,output:A});continue}if(S==="/"){if(_.type==="dot"&&E.index===E.start+1){E.start=E.index+1,E.consumed="",E.output="",o.pop(),_=r;continue}D({type:"slash",value:S,output:p});continue}if(S==="."){if(E.braces>0&&_.type==="dot"){_.value==="."&&(_.output=f);let A=W[W.length-1];_.type="dots",_.output+=S,_.value+=S,A.dots=!0;continue}if(E.braces+E.parens===0&&_.type!=="bos"&&_.type!=="slash"){D({type:"text",value:S,output:f});continue}D({type:"dot",value:S,output:f});continue}if(S==="?"){if(!(_&&_.value==="(")&&n.noextglob!==!0&&T()==="("&&T(2)!=="?"){Is("qmark",S);continue}if(_&&_.type==="paren"){let M=T(),U=S;if(M==="<"&&!pe.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(_.value==="("&&!/[!=<:]/.test(M)||M==="<"&&!/<([!=]|\w+>)/.test(ee()))&&(U=`\\${S}`),D({type:"text",value:S,output:U});continue}if(n.dot!==!0&&(_.type==="slash"||_.type==="bos")){D({type:"qmark",value:S,output:v});continue}D({type:"qmark",value:S,output:y});continue}if(S==="!"){if(n.noextglob!==!0&&T()==="("&&(T(2)!=="?"||!/[!=<:]/.test(T(3)))){Is("negate",S);continue}if(n.nonegate!==!0&&E.index===0){Dg();continue}}if(S==="+"){if(n.noextglob!==!0&&T()==="("&&T(2)!=="?"){Is("plus",S);continue}if(_&&_.value==="("||n.regex===!1){D({type:"plus",value:S,output:d});continue}if(_&&(_.type==="bracket"||_.type==="paren"||_.type==="brace")||E.parens>0){D({type:"plus",value:S});continue}D({type:"plus",value:d});continue}if(S==="@"){if(n.noextglob!==!0&&T()==="("&&T(2)!=="?"){D({type:"at",extglob:!0,value:S,output:""});continue}D({type:"text",value:S});continue}if(S!=="*"){(S==="$"||S==="^")&&(S=`\\${S}`);let A=Cb.exec(ee());A&&(S+=A[0],E.index+=A[0].length),D({type:"text",value:S});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=S,_.output=J,E.backtrack=!0,E.globstar=!0,ve(S);continue}let $=ee();if(n.noextglob!==!0&&/^\([^?]/.test($)){Is("star",S);continue}if(_.type==="star"){if(n.noglobstar===!0){ve(S);continue}let A=_.prev,M=A.prev,U=A.type==="slash"||A.type==="bos",te=M&&(M.type==="star"||M.type==="globstar");if(n.bash===!0&&(!U||$[0]&&$[0]!=="/")){D({type:"star",value:S,output:""});continue}let G=E.braces>0&&(A.type==="comma"||A.type==="brace"),Qe=B.length&&(A.type==="pipe"||A.type==="paren");if(!U&&A.type!=="paren"&&!G&&!Qe){D({type:"star",value:S,output:""});continue}for(;$.slice(0,3)==="/**";){let et=t[E.index+4];if(et&&et!=="/")break;$=$.slice(3),ve("/**",3)}if(A.type==="bos"&&j()){_.type="globstar",_.value+=S,_.output=I(n),E.output=_.output,E.globstar=!0,ve(S);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&!te&&j()){E.output=E.output.slice(0,-(A.output+_.output).length),A.output=`(?:${A.output}`,_.type="globstar",_.output=I(n)+(n.strictSlashes?")":"|$)"),_.value+=S,E.globstar=!0,E.output+=A.output+_.output,ve(S);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&$[0]==="/"){let et=$[1]!==void 0?"|$":"";E.output=E.output.slice(0,-(A.output+_.output).length),A.output=`(?:${A.output}`,_.type="globstar",_.output=`${I(n)}${p}|${p}${et})`,_.value+=S,E.output+=A.output+_.output,E.globstar=!0,ve(S+X()),D({type:"slash",value:"/",output:""});continue}if(A.type==="bos"&&$[0]==="/"){_.type="globstar",_.value+=S,_.output=`(?:^|${p}|${I(n)}${p})`,E.output=_.output,E.globstar=!0,ve(S+X()),D({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-_.output.length),_.type="globstar",_.output=I(n),_.value+=S,E.output+=_.output,E.globstar=!0,ve(S);continue}let z={type:"star",value:S,output:J};if(n.bash===!0){z.output=".*?",(_.type==="bos"||_.type==="slash")&&(z.output=C+z.output),D(z);continue}if(_&&(_.type==="bracket"||_.type==="paren")&&n.regex===!0){z.output=S,D(z);continue}(E.index===E.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(E.output+=b,_.output+=b):n.dot===!0?(E.output+=w,_.output+=w):(E.output+=C,_.output+=C),T()!=="*"&&(E.output+=h,_.output+=h)),D(z)}for(;E.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(hn("closing","]"));E.output=pe.escapeLast(E.output,"["),_t("brackets")}for(;E.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(hn("closing",")"));E.output=pe.escapeLast(E.output,"("),_t("parens")}for(;E.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(hn("closing","}"));E.output=pe.escapeLast(E.output,"{"),_t("braces")}if(n.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&D({type:"maybe_slash",value:"",output:`${p}?`}),E.backtrack===!0){E.output="";for(let $ of E.tokens)E.output+=$.output!=null?$.output:$.value,$.suffix&&(E.output+=$.suffix)}return E};Er.fastpaths=(t,e)=>{let n={...e},s=typeof n.maxLength=="number"?Math.min(Us,n.maxLength):Us,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);t=bu[t]||t;let r=pe.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:f,NO_DOTS_SLASH:d,STAR:p,START_ANCHOR:h}=Gn.globChars(r),m=n.dot?f:u,g=n.dot?d:u,b=n.capture?"":"?:",w={negated:!1,prefix:""},y=n.bash===!0?".*?":p;n.capture&&(y=`(${y})`);let v=C=>C.noglobstar===!0?y:`(${b}(?:(?!${h}${C.dot?l:o}).)*?)`,k=C=>{switch(C){case"*":return`${m}${c}${y}`;case".*":return`${o}${c}${y}`;case"*.*":return`${m}${y}${o}${c}${y}`;case"*/*":return`${m}${y}${a}${c}${g}${y}`;case"**":return m+v(n);case"**/*":return`(?:${m}${v(n)}${a})?${g}${c}${y}`;case"**/*.*":return`(?:${m}${v(n)}${a})?${g}${y}${o}${c}${y}`;case"**/.*":return`(?:${m}${v(n)}${a})?${o}${c}${y}`;default:{let N=/^(.*?)\.(\w+)$/.exec(C);if(!N)return;let J=k(N[1]);return J?J+o+N[2]:void 0}}},R=pe.removePrefix(t,w),I=k(R);return I&&n.strictSlashes!==!0&&(I+=`${a}?`),I};xu.exports=Er});var Eu=P((z1,Su)=>{"use strict";var Nb=require("path"),jb=yu(),kr=_u(),Rr=Bn(),Mb=Hn(),Db=t=>t&&typeof t=="object"&&!Array.isArray(t),Z=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(d=>Z(d,e,n));return d=>{for(let p of u){let h=p(d);if(h)return h}return!1}}let s=Db(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},r=Rr.isWindows(e),o=s?Z.compileRe(t,e):Z.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Z(i.ignore,u,n)}let l=(u,f=!1)=>{let{isMatch:d,match:p,output:h}=Z.test(u,o,e,{glob:t,posix:r}),m={glob:t,state:a,regex:o,posix:r,input:u,output:h,match:p,isMatch:d};return typeof i.onResult=="function"&&i.onResult(m),d===!1?(m.isMatch=!1,f?m:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=!1,f?m:!1):(typeof i.onMatch=="function"&&i.onMatch(m),f?m:!0)};return n&&(l.state=a),l};Z.test=(t,e,n,{glob:s,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let r=n||{},o=r.format||(i?Rr.toPosixSlashes:null),a=t===s,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===s),(a===!1||r.capture===!0)&&(r.matchBase===!0||r.basename===!0?a=Z.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Z.matchBase=(t,e,n,s=Rr.isWindows(n))=>(e instanceof RegExp?e:Z.makeRe(e,n)).test(Nb.basename(t));Z.isMatch=(t,e,n)=>Z(e,n)(t);Z.parse=(t,e)=>Array.isArray(t)?t.map(n=>Z.parse(n,e)):kr(t,{...e,fastpaths:!1});Z.scan=(t,e)=>jb(t,e);Z.compileRe=(t,e,n=!1,s=!1)=>{if(n===!0)return t.output;let i=e||{},r=i.contains?"":"^",o=i.contains?"":"$",a=`${r}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=Z.toRegex(a,e);return s===!0&&(c.state=t),c};Z.makeRe=(t,e={},n=!1,s=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=kr.fastpaths(t,e)),i.output||(i=kr(t,e)),Z.compileRe(i,e,n,s)};Z.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};Z.constants=Mb;Su.exports=Z});var Ru=P((q1,ku)=>{"use strict";ku.exports=Eu()});var Et=P((K1,Tu)=>{"use strict";var Au=require("util"),$u=iu(),st=Ru(),Cr=Bn(),Cu=t=>t===""||t==="./",Pu=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},V=(t,e,n)=>{e=[].concat(e),t=[].concat(t);let s=new Set,i=new Set,r=new Set,o=0,a=u=>{r.add(u.output),n&&n.onResult&&n.onResult(u)};for(let u=0;u<e.length;u++){let f=st(String(e[u]),{...n,onResult:a},!0),d=f.state.negated||f.state.negatedExtglob;d&&o++;for(let p of t){let h=f(p,!0);(d?!h.isMatch:h.isMatch)&&(d?s.add(h.output):(s.delete(h.output),i.add(h.output)))}}let l=(o===e.length?[...r]:[...i]).filter(u=>!s.has(u));if(n&&l.length===0){if(n.failglob===!0)throw new Error(`No matches found for "${e.join(", ")}"`);if(n.nonull===!0||n.nullglob===!0)return n.unescape?e.map(u=>u.replace(/\\/g,"")):e}return l};V.match=V;V.matcher=(t,e)=>st(t,e);V.isMatch=(t,e,n)=>st(e,n)(t);V.any=V.isMatch;V.not=(t,e,n={})=>{e=[].concat(e).map(String);let s=new Set,i=[],r=a=>{n.onResult&&n.onResult(a),i.push(a.output)},o=new Set(V(t,e,{...n,onResult:r}));for(let a of i)o.has(a)||s.add(a);return[...s]};V.contains=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Au.inspect(t)}"`);if(Array.isArray(e))return e.some(s=>V.contains(t,s,n));if(typeof e=="string"){if(Cu(t)||Cu(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return V.isMatch(t,e,{...n,contains:!0})};V.matchKeys=(t,e,n)=>{if(!Cr.isObject(t))throw new TypeError("Expected the first argument to be an object");let s=V(Object.keys(t),e,n),i={};for(let r of s)i[r]=t[r];return i};V.some=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let r=st(String(i),n);if(s.some(o=>r(o)))return!0}return!1};V.every=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let r=st(String(i),n);if(!s.every(o=>r(o)))return!1}return!0};V.all=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Au.inspect(t)}"`);return[].concat(e).every(s=>st(s,n)(t))};V.capture=(t,e,n)=>{let s=Cr.isWindows(n),r=st.makeRe(String(t),{...n,capture:!0}).exec(s?Cr.toPosixSlashes(e):e);if(r)return r.slice(1).map(o=>o===void 0?"":o)};V.makeRe=(...t)=>st.makeRe(...t);V.scan=(...t)=>st.scan(...t);V.parse=(t,e)=>{let n=[];for(let s of[].concat(t||[]))for(let i of $u(String(s),e))n.push(st.parse(i,e));return n};V.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!Pu(t)?[t]:$u(t,e)};V.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return V.braces(t,{...e,expand:!0})};V.hasBraces=Pu;Tu.exports=V});var Bu=P(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.isAbsolute=O.partitionAbsoluteAndRelative=O.removeDuplicateSlashes=O.matchAny=O.convertPatternsToRe=O.makeRe=O.getPatternParts=O.expandBraceExpansion=O.expandPatternsWithBraceExpansion=O.isAffectDepthOfReadingPattern=O.endsWithSlashGlobStar=O.hasGlobStar=O.getBaseDirectory=O.isPatternRelatedToParentDirectory=O.getPatternsOutsideCurrentDirectory=O.getPatternsInsideCurrentDirectory=O.getPositivePatterns=O.getNegativePatterns=O.isPositivePattern=O.isNegativePattern=O.convertToNegativePattern=O.convertToPositivePattern=O.isDynamicPattern=O.isStaticPattern=void 0;var Iu=require("path"),Fb=_l(),Ar=Et(),Ou="**",Hb="\\",Bb=/[*?]|^!/,Wb=/\[[^[]*]/,Gb=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Ub=/[!*+?@]\([^(]*\)/,Vb=/,|\.\./,zb=/(?!^)\/{2,}/g;function Lu(t,e={}){return!Nu(t,e)}O.isStaticPattern=Lu;function Nu(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(Hb)||Bb.test(t)||Wb.test(t)||Gb.test(t)||e.extglob!==!1&&Ub.test(t)||e.braceExpansion!==!1&&qb(t))}O.isDynamicPattern=Nu;function qb(t){let e=t.indexOf("{");if(e===-1)return!1;let n=t.indexOf("}",e+1);if(n===-1)return!1;let s=t.slice(e,n);return Vb.test(s)}function Kb(t){return Vs(t)?t.slice(1):t}O.convertToPositivePattern=Kb;function Yb(t){return"!"+t}O.convertToNegativePattern=Yb;function Vs(t){return t.startsWith("!")&&t[1]!=="("}O.isNegativePattern=Vs;function ju(t){return!Vs(t)}O.isPositivePattern=ju;function Jb(t){return t.filter(Vs)}O.getNegativePatterns=Jb;function Xb(t){return t.filter(ju)}O.getPositivePatterns=Xb;function Zb(t){return t.filter(e=>!$r(e))}O.getPatternsInsideCurrentDirectory=Zb;function Qb(t){return t.filter($r)}O.getPatternsOutsideCurrentDirectory=Qb;function $r(t){return t.startsWith("..")||t.startsWith("./..")}O.isPatternRelatedToParentDirectory=$r;function ew(t){return Fb(t,{flipBackslashes:!1})}O.getBaseDirectory=ew;function tw(t){return t.includes(Ou)}O.hasGlobStar=tw;function Mu(t){return t.endsWith("/"+Ou)}O.endsWithSlashGlobStar=Mu;function nw(t){let e=Iu.basename(t);return Mu(t)||Lu(e)}O.isAffectDepthOfReadingPattern=nw;function sw(t){return t.reduce((e,n)=>e.concat(Du(n)),[])}O.expandPatternsWithBraceExpansion=sw;function Du(t){let e=Ar.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((n,s)=>n.length-s.length),e.filter(n=>n!=="")}O.expandBraceExpansion=Du;function iw(t,e){let{parts:n}=Ar.scan(t,Object.assign(Object.assign({},e),{parts:!0}));return n.length===0&&(n=[t]),n[0].startsWith("/")&&(n[0]=n[0].slice(1),n.unshift("")),n}O.getPatternParts=iw;function Fu(t,e){return Ar.makeRe(t,e)}O.makeRe=Fu;function rw(t,e){return t.map(n=>Fu(n,e))}O.convertPatternsToRe=rw;function ow(t,e){return e.some(n=>n.test(t))}O.matchAny=ow;function aw(t){return t.replace(zb,"/")}O.removeDuplicateSlashes=aw;function cw(t){let e=[],n=[];for(let s of t)Hu(s)?e.push(s):n.push(s);return[e,n]}O.partitionAbsoluteAndRelative=cw;function Hu(t){return Iu.isAbsolute(t)}O.isAbsolute=Hu});var Vu=P((J1,Uu)=>{"use strict";var lw=require("stream"),Wu=lw.PassThrough,uw=Array.prototype.slice;Uu.exports=fw;function fw(){let t=[],e=uw.call(arguments),n=!1,s=e[e.length-1];s&&!Array.isArray(s)&&s.pipe==null?e.pop():s={};let i=s.end!==!1,r=s.pipeError===!0;s.objectMode==null&&(s.objectMode=!0),s.highWaterMark==null&&(s.highWaterMark=64*1024);let o=Wu(s);function a(){for(let u=0,f=arguments.length;u<f;u++)t.push(Gu(arguments[u],s));return c(),this}function c(){if(n)return;n=!0;let u=t.shift();if(!u){process.nextTick(l);return}Array.isArray(u)||(u=[u]);let f=u.length+1;function d(){--f>0||(n=!1,c())}function p(h){function m(){h.removeListener("merge2UnpipeEnd",m),h.removeListener("end",m),r&&h.removeListener("error",g),d()}function g(b){o.emit("error",b)}if(h._readableState.endEmitted)return d();h.on("merge2UnpipeEnd",m),h.on("end",m),r&&h.on("error",g),h.pipe(o,{end:!1}),h.resume()}for(let h=0;h<u.length;h++)p(u[h]);d()}function l(){n=!1,o.emit("queueDrain"),i&&o.end()}return o.setMaxListeners(0),o.add=a,o.on("unpipe",function(u){u.emit("merge2UnpipeEnd")}),e.length&&a.apply(null,e),o}function Gu(t,e){if(Array.isArray(t))for(let n=0,s=t.length;n<s;n++)t[n]=Gu(t[n],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(Wu(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var qu=P(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.merge=void 0;var dw=Vu();function pw(t){let e=dw(t);return t.forEach(n=>{n.once("error",s=>e.emit("error",s))}),e.once("close",()=>zu(t)),e.once("end",()=>zu(t)),e}zs.merge=pw;function zu(t){t.forEach(e=>e.emit("close"))}});var Ku=P(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.isEmpty=mn.isString=void 0;function hw(t){return typeof t=="string"}mn.isString=hw;function mw(t){return t===""}mn.isEmpty=mw});var ht=P(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.string=he.stream=he.pattern=he.path=he.fs=he.errno=he.array=void 0;var gw=ll();he.array=gw;var yw=ul();he.errno=yw;var bw=fl();he.fs=bw;var ww=ml();he.path=ww;var vw=Bu();he.pattern=vw;var xw=qu();he.stream=xw;var _w=Ku();he.string=_w});var Zu=P(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.convertPatternGroupToTask=me.convertPatternGroupsToTasks=me.groupPatternsByBaseDirectory=me.getNegativePatternsAsPositive=me.getPositivePatterns=me.convertPatternsToTasks=me.generate=void 0;var ze=ht();function Sw(t,e){let n=Yu(t,e),s=Yu(e.ignore,e),i=Ju(n),r=Xu(n,s),o=i.filter(u=>ze.pattern.isStaticPattern(u,e)),a=i.filter(u=>ze.pattern.isDynamicPattern(u,e)),c=Pr(o,r,!1),l=Pr(a,r,!0);return c.concat(l)}me.generate=Sw;function Yu(t,e){let n=t;return e.braceExpansion&&(n=ze.pattern.expandPatternsWithBraceExpansion(n)),e.baseNameMatch&&(n=n.map(s=>s.includes("/")?s:`**/${s}`)),n.map(s=>ze.pattern.removeDuplicateSlashes(s))}function Pr(t,e,n){let s=[],i=ze.pattern.getPatternsOutsideCurrentDirectory(t),r=ze.pattern.getPatternsInsideCurrentDirectory(t),o=Tr(i),a=Tr(r);return s.push(...Ir(o,e,n)),"."in a?s.push(Or(".",r,e,n)):s.push(...Ir(a,e,n)),s}me.convertPatternsToTasks=Pr;function Ju(t){return ze.pattern.getPositivePatterns(t)}me.getPositivePatterns=Ju;function Xu(t,e){return ze.pattern.getNegativePatterns(t).concat(e).map(ze.pattern.convertToPositivePattern)}me.getNegativePatternsAsPositive=Xu;function Tr(t){let e={};return t.reduce((n,s)=>{let i=ze.pattern.getBaseDirectory(s);return i in n?n[i].push(s):n[i]=[s],n},e)}me.groupPatternsByBaseDirectory=Tr;function Ir(t,e,n){return Object.keys(t).map(s=>Or(s,t[s],e,n))}me.convertPatternGroupsToTasks=Ir;function Or(t,e,n,s){return{dynamic:s,positive:e,negative:n,base:t,patterns:[].concat(e,n.map(ze.pattern.convertToNegativePattern))}}me.convertPatternGroupToTask=Or});var ef=P(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.read=void 0;function Ew(t,e,n){e.fs.lstat(t,(s,i)=>{if(s!==null){Qu(n,s);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){Lr(n,i);return}e.fs.stat(t,(r,o)=>{if(r!==null){if(e.throwErrorOnBrokenSymbolicLink){Qu(n,r);return}Lr(n,i);return}e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),Lr(n,o)})})}qs.read=Ew;function Qu(t,e){t(e)}function Lr(t,e){t(null,e)}});var tf=P(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.read=void 0;function kw(t,e){let n=e.fs.lstatSync(t);if(!n.isSymbolicLink()||!e.followSymbolicLink)return n;try{let s=e.fs.statSync(t);return e.markSymbolicLink&&(s.isSymbolicLink=()=>!0),s}catch(s){if(!e.throwErrorOnBrokenSymbolicLink)return n;throw s}}Ks.read=kw});var nf=P(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.createFileSystemAdapter=kt.FILE_SYSTEM_ADAPTER=void 0;var Ys=require("fs");kt.FILE_SYSTEM_ADAPTER={lstat:Ys.lstat,stat:Ys.stat,lstatSync:Ys.lstatSync,statSync:Ys.statSync};function Rw(t){return t===void 0?kt.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},kt.FILE_SYSTEM_ADAPTER),t)}kt.createFileSystemAdapter=Rw});var sf=P(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});var Cw=nf(),Nr=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=Cw.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue(e,n){return e??n}};jr.default=Nr});var Gt=P(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.statSync=Rt.stat=Rt.Settings=void 0;var rf=ef(),Aw=tf(),Mr=sf();Rt.Settings=Mr.default;function $w(t,e,n){if(typeof e=="function"){rf.read(t,Dr(),e);return}rf.read(t,Dr(e),n)}Rt.stat=$w;function Pw(t,e){let n=Dr(e);return Aw.read(t,n)}Rt.statSync=Pw;function Dr(t={}){return t instanceof Mr.default?t:new Mr.default(t)}});var cf=P((oT,af)=>{var of;af.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(of||(of=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var uf=P((aT,lf)=>{lf.exports=Iw;var Tw=cf();function Iw(t,e){let n,s,i,r=!0;Array.isArray(t)?(n=[],s=t.length):(i=Object.keys(t),n={},s=i.length);function o(c){function l(){e&&e(c,n),e=null}r?Tw(l):l()}function a(c,l,u){n[c]=u,(--s===0||l)&&o(l)}s?i?i.forEach(function(c){t[c](function(l,u){a(c,l,u)})}):t.forEach(function(c,l){c(function(u,f){a(l,u,f)})}):o(null),r=!1}});var Fr=P(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var Js=process.versions.node.split(".");if(Js[0]===void 0||Js[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var ff=Number.parseInt(Js[0],10),Ow=Number.parseInt(Js[1],10),df=10,Lw=10,Nw=ff>df,jw=ff===df&&Ow>=Lw;Xs.IS_SUPPORT_READDIR_WITH_FILE_TYPES=Nw||jw});var pf=P(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});Zs.createDirentFromStats=void 0;var Hr=class{constructor(e,n){this.name=e,this.isBlockDevice=n.isBlockDevice.bind(n),this.isCharacterDevice=n.isCharacterDevice.bind(n),this.isDirectory=n.isDirectory.bind(n),this.isFIFO=n.isFIFO.bind(n),this.isFile=n.isFile.bind(n),this.isSocket=n.isSocket.bind(n),this.isSymbolicLink=n.isSymbolicLink.bind(n)}};function Mw(t,e){return new Hr(t,e)}Zs.createDirentFromStats=Mw});var Br=P(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.fs=void 0;var Dw=pf();Qs.fs=Dw});var Wr=P(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.joinPathSegments=void 0;function Fw(t,e,n){return t.endsWith(n)?t+e:t+n+e}ei.joinPathSegments=Fw});var wf=P(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.readdir=Ct.readdirWithFileTypes=Ct.read=void 0;var Hw=Gt(),hf=uf(),Bw=Fr(),mf=Br(),gf=Wr();function Ww(t,e,n){if(!e.stats&&Bw.IS_SUPPORT_READDIR_WITH_FILE_TYPES){yf(t,e,n);return}bf(t,e,n)}Ct.read=Ww;function yf(t,e,n){e.fs.readdir(t,{withFileTypes:!0},(s,i)=>{if(s!==null){ti(n,s);return}let r=i.map(a=>({dirent:a,name:a.name,path:gf.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){Gr(n,r);return}let o=r.map(a=>Gw(a,e));hf(o,(a,c)=>{if(a!==null){ti(n,a);return}Gr(n,c)})})}Ct.readdirWithFileTypes=yf;function Gw(t,e){return n=>{if(!t.dirent.isSymbolicLink()){n(null,t);return}e.fs.stat(t.path,(s,i)=>{if(s!==null){if(e.throwErrorOnBrokenSymbolicLink){n(s);return}n(null,t);return}t.dirent=mf.fs.createDirentFromStats(t.name,i),n(null,t)})}}function bf(t,e,n){e.fs.readdir(t,(s,i)=>{if(s!==null){ti(n,s);return}let r=i.map(o=>{let a=gf.joinPathSegments(t,o,e.pathSegmentSeparator);return c=>{Hw.stat(a,e.fsStatSettings,(l,u)=>{if(l!==null){c(l);return}let f={name:o,path:a,dirent:mf.fs.createDirentFromStats(o,u)};e.stats&&(f.stats=u),c(null,f)})}});hf(r,(o,a)=>{if(o!==null){ti(n,o);return}Gr(n,a)})})}Ct.readdir=bf;function ti(t,e){t(e)}function Gr(t,e){t(null,e)}});var Ef=P(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.readdir=At.readdirWithFileTypes=At.read=void 0;var Uw=Gt(),Vw=Fr(),vf=Br(),xf=Wr();function zw(t,e){return!e.stats&&Vw.IS_SUPPORT_READDIR_WITH_FILE_TYPES?_f(t,e):Sf(t,e)}At.read=zw;function _f(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(s=>{let i={dirent:s,name:s.name,path:xf.joinPathSegments(t,s.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let r=e.fs.statSync(i.path);i.dirent=vf.fs.createDirentFromStats(i.name,r)}catch(r){if(e.throwErrorOnBrokenSymbolicLink)throw r}return i})}At.readdirWithFileTypes=_f;function Sf(t,e){return e.fs.readdirSync(t).map(s=>{let i=xf.joinPathSegments(t,s,e.pathSegmentSeparator),r=Uw.statSync(i,e.fsStatSettings),o={name:s,path:i,dirent:vf.fs.createDirentFromStats(s,r)};return e.stats&&(o.stats=r),o})}At.readdir=Sf});var kf=P($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.createFileSystemAdapter=$t.FILE_SYSTEM_ADAPTER=void 0;var gn=require("fs");$t.FILE_SYSTEM_ADAPTER={lstat:gn.lstat,stat:gn.stat,lstatSync:gn.lstatSync,statSync:gn.statSync,readdir:gn.readdir,readdirSync:gn.readdirSync};function qw(t){return t===void 0?$t.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},$t.FILE_SYSTEM_ADAPTER),t)}$t.createFileSystemAdapter=qw});var Rf=P(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});var Kw=require("path"),Yw=Gt(),Jw=kf(),Ur=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=Jw.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,Kw.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new Yw.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};Vr.default=Ur});var ni=P(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Settings=Pt.scandirSync=Pt.scandir=void 0;var Cf=wf(),Xw=Ef(),zr=Rf();Pt.Settings=zr.default;function Zw(t,e,n){if(typeof e=="function"){Cf.read(t,qr(),e);return}Cf.read(t,qr(e),n)}Pt.scandir=Zw;function Qw(t,e){let n=qr(e);return Xw.read(t,n)}Pt.scandirSync=Qw;function qr(t={}){return t instanceof zr.default?t:new zr.default(t)}});var $f=P((yT,Af)=>{"use strict";function ev(t){var e=new t,n=e;function s(){var r=e;return r.next?e=r.next:(e=new t,n=e),r.next=null,r}function i(r){n.next=r,n=r}return{get:s,release:i}}Af.exports=ev});var Tf=P((bT,Kr)=>{"use strict";var tv=$f();function Pf(t,e,n){if(typeof t=="function"&&(n=e,e=t,t=null),!(n>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var s=tv(nv),i=null,r=null,o=0,a=null,c={push:m,drain:$e,saturated:$e,pause:u,paused:!1,get concurrency(){return n},set concurrency(R){if(!(R>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=R,!c.paused)for(;i&&o<n;)o++,b()},running:l,resume:p,idle:h,length:f,getQueue:d,unshift:g,empty:$e,kill:w,killAndDrain:y,error:k,abort:v};return c;function l(){return o}function u(){c.paused=!0}function f(){for(var R=i,I=0;R;)R=R.next,I++;return I}function d(){for(var R=i,I=[];R;)I.push(R.value),R=R.next;return I}function p(){if(c.paused){if(c.paused=!1,i===null){o++,b();return}for(;i&&o<n;)o++,b()}}function h(){return o===0&&c.length()===0}function m(R,I){var C=s.get();C.context=t,C.release=b,C.value=R,C.callback=I||$e,C.errorHandler=a,o>=n||c.paused?r?(r.next=C,r=C):(i=C,r=C,c.saturated()):(o++,e.call(t,C.value,C.worked))}function g(R,I){var C=s.get();C.context=t,C.release=b,C.value=R,C.callback=I||$e,C.errorHandler=a,o>=n||c.paused?i?(C.next=i,i=C):(i=C,r=C,c.saturated()):(o++,e.call(t,C.value,C.worked))}function b(R){R&&s.release(R);var I=i;I&&o<=n?c.paused?o--:(r===i&&(r=null),i=I.next,I.next=null,e.call(t,I.value,I.worked),r===null&&c.empty()):--o===0&&c.drain()}function w(){i=null,r=null,c.drain=$e}function y(){i=null,r=null,c.drain(),c.drain=$e}function v(){var R=i;for(i=null,r=null;R;){var I=R.next,C=R.callback,N=R.errorHandler,J=R.value,E=R.context;R.value=null,R.callback=$e,R.errorHandler=null,N&&N(new Error("abort"),J),C.call(E,new Error("abort")),R.release(R),R=I}c.drain=$e}function k(R){a=R}}function $e(){}function nv(){this.value=null,this.callback=$e,this.next=null,this.release=$e,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,s){var i=t.callback,r=t.errorHandler,o=t.value;t.value=null,t.callback=$e,t.errorHandler&&r(n,o),i.call(t.context,n,s),t.release(t)}}function sv(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function s(u,f){e.call(this,u).then(function(d){f(null,d)},f)}var i=Pf(t,s,n),r=i.push,o=i.unshift;return i.push=a,i.unshift=c,i.drained=l,i;function a(u){var f=new Promise(function(d,p){r(u,function(h,m){if(h){p(h);return}d(m)})});return f.catch($e),f}function c(u){var f=new Promise(function(d,p){o(u,function(h,m){if(h){p(h);return}d(m)})});return f.catch($e),f}function l(){var u=new Promise(function(f){process.nextTick(function(){if(i.idle())f();else{var d=i.drain;i.drain=function(){typeof d=="function"&&d(),f(),i.drain=d}}})});return u}}Kr.exports=Pf;Kr.exports.promise=sv});var si=P(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.joinPathSegments=it.replacePathSegmentSeparator=it.isAppliedFilter=it.isFatalError=void 0;function iv(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}it.isFatalError=iv;function rv(t,e){return t===null||t(e)}it.isAppliedFilter=rv;function ov(t,e){return t.split(/[/\\]/).join(e)}it.replacePathSegmentSeparator=ov;function av(t,e,n){return t===""?e:t.endsWith(n)?t+e:t+n+e}it.joinPathSegments=av});var Xr=P(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});var cv=si(),Yr=class{constructor(e,n){this._root=e,this._settings=n,this._root=cv.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}};Jr.default=Yr});var eo=P(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});var lv=require("events"),uv=ni(),fv=Tf(),ii=si(),dv=Xr(),Zr=class extends dv.default{constructor(e,n){super(e,n),this._settings=n,this._scandir=uv.scandir,this._emitter=new lv.EventEmitter,this._queue=fv(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit("end")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw new Error("The reader is already destroyed");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on("entry",e)}onError(e){this._emitter.once("error",e)}onEnd(e){this._emitter.once("end",e)}_pushToQueue(e,n){let s={directory:e,base:n};this._queue.push(s,i=>{i!==null&&this._handleError(i)})}_worker(e,n){this._scandir(e.directory,this._settings.fsScandirSettings,(s,i)=>{if(s!==null){n(s,void 0);return}for(let r of i)this._handleEntry(r,e.base);n(null,void 0)})}_handleError(e){this._isDestroyed||!ii.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit("error",e))}_handleEntry(e,n){if(this._isDestroyed||this._isFatalError)return;let s=e.path;n!==void 0&&(e.path=ii.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ii.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&ii.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};Qr.default=Zr});var If=P(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});var pv=eo(),to=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new pv.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(n=>{hv(e,n)}),this._reader.onEntry(n=>{this._storage.push(n)}),this._reader.onEnd(()=>{mv(e,this._storage)}),this._reader.read()}};no.default=to;function hv(t,e){t(e)}function mv(t,e){t(null,e)}});var Of=P(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});var gv=require("stream"),yv=eo(),so=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new yv.default(this._root,this._settings),this._stream=new gv.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit("error",e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}};io.default=so});var Lf=P(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var bv=ni(),ri=si(),wv=Xr(),ro=class extends wv.default{constructor(){super(...arguments),this._scandir=bv.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,n){this._queue.add({directory:e,base:n})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,n){try{let s=this._scandir(e,this._settings.fsScandirSettings);for(let i of s)this._handleEntry(i,n)}catch(s){this._handleError(s)}}_handleError(e){if(ri.isFatalError(this._settings,e))throw e}_handleEntry(e,n){let s=e.path;n!==void 0&&(e.path=ri.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ri.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&ri.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};oo.default=ro});var Nf=P(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var vv=Lf(),ao=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new vv.default(this._root,this._settings)}read(){return this._reader.read()}};co.default=ao});var jf=P(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var xv=require("path"),_v=ni(),lo=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,xv.sep),this.fsScandirSettings=new _v.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};uo.default=lo});var ai=P(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.Settings=rt.walkStream=rt.walkSync=rt.walk=void 0;var Mf=If(),Sv=Of(),Ev=Nf(),fo=jf();rt.Settings=fo.default;function kv(t,e,n){if(typeof e=="function"){new Mf.default(t,oi()).read(e);return}new Mf.default(t,oi(e)).read(n)}rt.walk=kv;function Rv(t,e){let n=oi(e);return new Ev.default(t,n).read()}rt.walkSync=Rv;function Cv(t,e){let n=oi(e);return new Sv.default(t,n).read()}rt.walkStream=Cv;function oi(t={}){return t instanceof fo.default?t:new fo.default(t)}});var ci=P(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var Av=require("path"),$v=Gt(),Df=ht(),po=class{constructor(e){this._settings=e,this._fsStatSettings=new $v.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return Av.resolve(this._settings.cwd,e)}_makeEntry(e,n){let s={name:n,path:n,dirent:Df.fs.createDirentFromStats(n,e)};return this._settings.stats&&(s.stats=e),s}_isFatalError(e){return!Df.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};ho.default=po});var yo=P(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});var Pv=require("stream"),Tv=Gt(),Iv=ai(),Ov=ci(),mo=class extends Ov.default{constructor(){super(...arguments),this._walkStream=Iv.walkStream,this._stat=Tv.stat}dynamic(e,n){return this._walkStream(e,n)}static(e,n){let s=e.map(this._getFullEntryPath,this),i=new Pv.PassThrough({objectMode:!0});i._write=(r,o,a)=>this._getEntry(s[r],e[r],n).then(c=>{c!==null&&n.entryFilter(c)&&i.push(c),r===s.length-1&&i.end(),a()}).catch(a);for(let r=0;r<s.length;r++)i.write(r);return i}_getEntry(e,n,s){return this._getStat(e).then(i=>this._makeEntry(i,n)).catch(i=>{if(s.errorFilter(i))return null;throw i})}_getStat(e){return new Promise((n,s)=>{this._stat(e,this._fsStatSettings,(i,r)=>i===null?n(r):s(i))})}};go.default=mo});var Ff=P(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});var Lv=ai(),Nv=ci(),jv=yo(),bo=class extends Nv.default{constructor(){super(...arguments),this._walkAsync=Lv.walk,this._readerStream=new jv.default(this._settings)}dynamic(e,n){return new Promise((s,i)=>{this._walkAsync(e,n,(r,o)=>{r===null?s(o):i(r)})})}async static(e,n){let s=[],i=this._readerStream.static(e,n);return new Promise((r,o)=>{i.once("error",o),i.on("data",a=>s.push(a)),i.once("end",()=>r(s))})}};wo.default=bo});var Hf=P(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var Un=ht(),vo=class{constructor(e,n,s){this._patterns=e,this._settings=n,this._micromatchOptions=s,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let n=this._getPatternSegments(e),s=this._splitSegmentsIntoSections(n);this._storage.push({complete:s.length<=1,pattern:e,segments:n,sections:s})}}_getPatternSegments(e){return Un.pattern.getPatternParts(e,this._micromatchOptions).map(s=>Un.pattern.isDynamicPattern(s,this._settings)?{dynamic:!0,pattern:s,patternRe:Un.pattern.makeRe(s,this._micromatchOptions)}:{dynamic:!1,pattern:s})}_splitSegmentsIntoSections(e){return Un.array.splitWhen(e,n=>n.dynamic&&Un.pattern.hasGlobStar(n.pattern))}};xo.default=vo});var Bf=P(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});var Mv=Hf(),_o=class extends Mv.default{match(e){let n=e.split("/"),s=n.length,i=this._storage.filter(r=>!r.complete||r.segments.length>s);for(let r of i){let o=r.sections[0];if(!r.complete&&s>o.length||n.every((c,l)=>{let u=r.segments[l];return!!(u.dynamic&&u.patternRe.test(c)||!u.dynamic&&u.pattern===c)}))return!0}return!1}};So.default=_o});var Wf=P(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});var li=ht(),Dv=Bf(),Eo=class{constructor(e,n){this._settings=e,this._micromatchOptions=n}getFilter(e,n,s){let i=this._getMatcher(n),r=this._getNegativePatternsRe(s);return o=>this._filter(e,o,i,r)}_getMatcher(e){return new Dv.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(li.pattern.isAffectDepthOfReadingPattern);return li.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,s,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let r=li.path.removeLeadingDotSegment(n.path);return this._isSkippedByPositivePatterns(r,s)?!1:this._isSkippedByNegativePatterns(r,i)}_isSkippedByDeep(e,n){return this._settings.deep===1/0?!1:this._getEntryLevel(e,n)>=this._settings.deep}_getEntryLevel(e,n){let s=n.split("/").length;if(e==="")return s;let i=e.split("/").length;return s-i}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,n){return!this._settings.baseNameMatch&&!n.match(e)}_isSkippedByNegativePatterns(e,n){return!li.pattern.matchAny(e,n)}};ko.default=Eo});var Gf=P(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var Tt=ht(),Ro=class{constructor(e,n){this._settings=e,this._micromatchOptions=n,this.index=new Map}getFilter(e,n){let[s,i]=Tt.pattern.partitionAbsoluteAndRelative(n),r={positive:{all:Tt.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:Tt.pattern.convertPatternsToRe(s,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:Tt.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return o=>this._filter(o,r)}_filter(e,n){let s=Tt.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(s)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let i=this._isMatchToPatternsSet(s,n,e.dirent.isDirectory());return this._settings.unique&&i&&this._createIndexRecord(s),i}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isMatchToPatternsSet(e,n,s){return!(!this._isMatchToPatterns(e,n.positive.all,s)||this._isMatchToPatterns(e,n.negative.relative,s)||this._isMatchToAbsoluteNegative(e,n.negative.absolute,s))}_isMatchToAbsoluteNegative(e,n,s){if(n.length===0)return!1;let i=Tt.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,s)}_isMatchToPatterns(e,n,s){if(n.length===0)return!1;let i=Tt.pattern.matchAny(e,n);return!i&&s?Tt.pattern.matchAny(e+"/",n):i}};Co.default=Ro});var Uf=P($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var Fv=ht(),Ao=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return Fv.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};$o.default=Ao});var zf=P(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var Vf=ht(),Po=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=Vf.path.makeAbsolute(this._settings.cwd,n),n=Vf.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}};To.default=Po});var ui=P(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Hv=require("path"),Bv=Wf(),Wv=Gf(),Gv=Uf(),Uv=zf(),Io=class{constructor(e){this._settings=e,this.errorFilter=new Gv.default(this._settings),this.entryFilter=new Wv.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new Bv.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new Uv.default(this._settings)}_getRootDirectory(e){return Hv.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let n=e.base==="."?"":e.base;return{basePath:n,pathSegmentSeparator:"/",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(n,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}};Oo.default=Io});var qf=P(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var Vv=Ff(),zv=ui(),Lo=class extends zv.default{constructor(){super(...arguments),this._reader=new Vv.default(this._settings)}async read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e);return(await this.api(n,e,s)).map(r=>s.transform(r))}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};No.default=Lo});var Kf=P(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var qv=require("stream"),Kv=yo(),Yv=ui(),jo=class extends Yv.default{constructor(){super(...arguments),this._reader=new Kv.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e),i=this.api(n,e,s),r=new qv.Readable({objectMode:!0,read:()=>{}});return i.once("error",o=>r.emit("error",o)).on("data",o=>r.emit("data",s.transform(o))).once("end",()=>r.emit("end")),r.once("close",()=>i.destroy()),r}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};Mo.default=jo});var Yf=P(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});var Jv=Gt(),Xv=ai(),Zv=ci(),Do=class extends Zv.default{constructor(){super(...arguments),this._walkSync=Xv.walkSync,this._statSync=Jv.statSync}dynamic(e,n){return this._walkSync(e,n)}static(e,n){let s=[];for(let i of e){let r=this._getFullEntryPath(i),o=this._getEntry(r,i,n);o===null||!n.entryFilter(o)||s.push(o)}return s}_getEntry(e,n,s){try{let i=this._getStat(e);return this._makeEntry(i,n)}catch(i){if(s.errorFilter(i))return null;throw i}}_getStat(e){return this._statSync(e,this._fsStatSettings)}};Fo.default=Do});var Jf=P(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});var Qv=Yf(),e0=ui(),Ho=class extends e0.default{constructor(){super(...arguments),this._reader=new Qv.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e);return this.api(n,e,s).map(s.transform)}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};Bo.default=Ho});var Xf=P(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var yn=require("fs"),t0=require("os"),n0=Math.max(t0.cpus().length,1);bn.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:yn.lstat,lstatSync:yn.lstatSync,stat:yn.stat,statSync:yn.statSync,readdir:yn.readdir,readdirSync:yn.readdirSync};var Wo=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,n0),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,n){return e===void 0?n:e}_getFileSystemMethods(e={}){return Object.assign(Object.assign({},bn.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};bn.default=Wo});var wn=P((GT,Qf)=>{"use strict";var Zf=Zu(),s0=qf(),i0=Kf(),r0=Jf(),Go=Xf(),He=ht();async function Uo(t,e){qe(t);let n=Vo(t,s0.default,e),s=await Promise.all(n);return He.array.flatten(s)}(function(t){t.glob=t,t.globSync=e,t.globStream=n,t.async=t;function e(l,u){qe(l);let f=Vo(l,r0.default,u);return He.array.flatten(f)}t.sync=e;function n(l,u){qe(l);let f=Vo(l,i0.default,u);return He.stream.merge(f)}t.stream=n;function s(l,u){qe(l);let f=[].concat(l),d=new Go.default(u);return Zf.generate(f,d)}t.generateTasks=s;function i(l,u){qe(l);let f=new Go.default(u);return He.pattern.isDynamicPattern(l,f)}t.isDynamicPattern=i;function r(l){return qe(l),He.path.escape(l)}t.escapePath=r;function o(l){return qe(l),He.path.convertPathToPattern(l)}t.convertPathToPattern=o;let a;(function(l){function u(d){return qe(d),He.path.escapePosixPath(d)}l.escapePath=u;function f(d){return qe(d),He.path.convertPosixPathToPattern(d)}l.convertPathToPattern=f})(a=t.posix||(t.posix={}));let c;(function(l){function u(d){return qe(d),He.path.escapeWindowsPath(d)}l.escapePath=u;function f(d){return qe(d),He.path.convertWindowsPathToPattern(d)}l.convertPathToPattern=f})(c=t.win32||(t.win32={}))})(Uo||(Uo={}));function Vo(t,e,n){let s=[].concat(t),i=new Go.default(n),r=Zf.generate(s,i),o=new e(i);return r.map(o.read,o)}function qe(t){if(![].concat(t).every(s=>He.string.isString(s)&&!He.string.isEmpty(s)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}Qf.exports=Uo});var Xc=P((zj,DP)=>{DP.exports={name:"@promptci/cli",version:"0.2.0",description:"Instruction health for AI coding workflows \u2014 scan CLAUDE.md, AGENTS.md, .cursorrules and more for duplicates, conflicts, staleness, and context bloat",license:"Apache-2.0",type:"module",bin:{promptci:"./dist/cli.cjs"},files:["dist"],engines:{node:">=22"},repository:{type:"git",url:"git+https://github.com/SeriousGeese/PromptCI.git",directory:"packages/cli"},homepage:"https://github.com/SeriousGeese/PromptCI#readme",bugs:{url:"https://github.com/SeriousGeese/PromptCI/issues"},keywords:["ai","claude","cli","copilot","cursor","instructions","lint","prompt","scanner"],scripts:{build:"esbuild src/cli.ts --bundle --platform=node --format=cjs --minify --outfile=dist/cli.cjs",typecheck:"tsc -p tsconfig.json --noEmit",prepublishOnly:"pnpm run build"},devDependencies:{"@promptci/core":"workspace:*","@types/node":"^26.6.6",commander:"^15.0.0",esbuild:"^0.28.2",typescript:"*",vitest:"^5.0.5"},publishConfig:{access:"public"}}});var St=class extends Error{constructor(e,n,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Ht=class extends St{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var jn=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,s)=>{if(!this.argChoices.includes(n))throw new Ht(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,s):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Os(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}var ol=require("node:events"),Ns=x(require("node:child_process"),1),tt=x(require("node:path"),1),Dn=x(require("node:fs"),1),H=x(require("node:process"),1),al=require("node:util");var nl=require("node:util"),Mn=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let n=e.commands.filter(i=>!i._hidden),s=e._getHelpCommand();return s&&!s._hidden&&n.push(s),this.sortSubcommands&&n.sort((i,r)=>i.name().localeCompare(r.name())),n}compareOptions(e,n){let s=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return s(e).localeCompare(s(n))}visibleOptions(e){let n=e.options.filter(i=>!i.hidden),s=e._getHelpOption();if(s&&!s.hidden){let i=s.short&&e._findOption(s.short),r=s.long&&e._findOption(s.long);!i&&!r?n.push(s):s.long&&!r?n.push(e.createOption(s.long,s.description)):s.short&&!i&&n.push(e.createOption(s.short,s.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let s=e.parent;s;s=s.parent){let i=s.options.filter(r=>!r.hidden);n.push(...i)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(s=>Os(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(i)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleOptionTerm(n.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleOptionTerm(n.optionTerm(i)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(i)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let s="";for(let i=e.parent;i;i=i.parent)s=i.name()+" "+s;return s+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0){let s=`(${n.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let s=`(${n.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatItemList(e,n,s){return n.length===0?[]:[s.styleTitle(e),...n,""]}groupItems(e,n,s){let i=new Map;return e.forEach(r=>{let o=s(r);i.has(o)||i.set(o,[])}),n.forEach(r=>{let o=s(r);i.has(o)||i.set(o,[]),i.get(o).push(r)}),i}formatHelp(e,n){let s=n.padWidth(e,n),i=n.helpWidth??80;function r(f,d){return n.formatItem(f,s,d,n)}let o=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(o=o.concat([n.boxWrap(n.styleCommandDescription(a),i),""]));let c=n.visibleArguments(e).map(f=>r(n.styleArgumentTerm(n.argumentTerm(f)),n.styleArgumentDescription(n.argumentDescription(f))));if(o=o.concat(this.formatItemList("Arguments:",c,n)),this.groupItems(e.options,n.visibleOptions(e),f=>f.helpGroupHeading??"Options:").forEach((f,d)=>{let p=f.map(h=>r(n.styleOptionTerm(n.optionTerm(h)),n.styleOptionDescription(n.optionDescription(h))));o=o.concat(this.formatItemList(d,p,n))}),n.showGlobalOptions){let f=n.visibleGlobalOptions(e).map(d=>r(n.styleOptionTerm(n.optionTerm(d)),n.styleOptionDescription(n.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",f,n))}return this.groupItems(e.commands,n.visibleCommands(e),f=>f.helpGroup()||"Commands:").forEach((f,d)=>{let p=f.map(h=>r(n.styleSubcommandTerm(n.subcommandTerm(h)),n.styleSubcommandDescription(n.subcommandDescription(h))));o=o.concat(this.formatItemList(d,p,n))}),o.join(`
4
- `)}displayWidth(e){return(0,nl.stripVTControlCharacters)(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,n,s,i){let o=" ".repeat(2);if(!s)return o+e;let a=e.padEnd(n+e.length-i.displayWidth(e)),c=2,u=(this.helpWidth??80)-n-c-2,f;return u<this.minWidthToWrap||i.preformatted(s)?f=s:f=i.boxWrap(s,u).replace(/\n/g,`
2
+ "use strict";var Vg=Object.create;var il=Object.defineProperty;var zg=Object.getOwnPropertyDescriptor;var qg=Object.getOwnPropertyNames;var Kg=Object.getPrototypeOf,Yg=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Jg=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of qg(e))!Yg.call(t,i)&&i!==n&&il(t,i,{get:()=>e[i],enumerable:!(s=zg(e,i))||s.enumerable});return t};var x=(t,e,n)=>(n=t!=null?Vg(Kg(t)):{},Jg(e||!t||!t.__esModule?il(n,"default",{value:t,enumerable:!0}):n,t));var dl=P(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.splitWhen=dn.flatten=void 0;function ey(t){return t.reduce((e,n)=>[].concat(e,n),[])}dn.flatten=ey;function ty(t,e){let n=[[]],s=0;for(let i of t)e(i)?(s++,n[s]=[]):n[s].push(i);return n}dn.splitWhen=ty});var pl=P(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.isEnoentCodeError=void 0;function ny(t){return t.code==="ENOENT"}Ms.isEnoentCodeError=ny});var hl=P(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.createDirentFromStats=void 0;var lr=class{constructor(e,n){this.name=e,this.isBlockDevice=n.isBlockDevice.bind(n),this.isCharacterDevice=n.isCharacterDevice.bind(n),this.isDirectory=n.isDirectory.bind(n),this.isFIFO=n.isFIFO.bind(n),this.isFile=n.isFile.bind(n),this.isSocket=n.isSocket.bind(n),this.isSymbolicLink=n.isSymbolicLink.bind(n)}};function sy(t,e){return new lr(t,e)}Ds.createDirentFromStats=sy});var bl=P(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.convertPosixPathToPattern=ee.convertWindowsPathToPattern=ee.convertPathToPattern=ee.escapePosixPath=ee.escapeWindowsPath=ee.escape=ee.removeLeadingDotSegment=ee.makeAbsolute=ee.unixify=void 0;var iy=require("os"),ry=require("path"),ml=iy.platform()==="win32",oy=2,ay=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,cy=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,ly=/^\\\\([.?])/,uy=/\\(?![!()+@[\]{}])/g;function fy(t){return t.replace(/\\/g,"/")}ee.unixify=fy;function dy(t,e){return ry.resolve(t,e)}ee.makeAbsolute=dy;function py(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(oy)}return t}ee.removeLeadingDotSegment=py;ee.escape=ml?ur:fr;function ur(t){return t.replace(cy,"\\$2")}ee.escapeWindowsPath=ur;function fr(t){return t.replace(ay,"\\$2")}ee.escapePosixPath=fr;ee.convertPathToPattern=ml?gl:yl;function gl(t){return ur(t).replace(ly,"//$1").replace(uy,"/")}ee.convertWindowsPathToPattern=gl;function yl(t){return fr(t)}ee.convertPosixPathToPattern=yl});var vl=P((L1,wl)=>{wl.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var _l=P((N1,Sl)=>{var hy=vl(),xl={"{":"}","(":")","[":"]"},my=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,s=-2,i=-2,r=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||s!==-1&&t[e]==="["&&t[e+1]!=="]"&&(s<e&&(s=t.indexOf("]",e)),s>e&&(o===-1||o>s||(o=t.indexOf("\\",e),o===-1||o>s)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||r!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(r=t.indexOf(")",e),r>e&&(o=t.indexOf("\\",e),o===-1||o>r))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(r=t.indexOf(")",n),r>n&&(o=t.indexOf("\\",n),o===-1||o>r))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=xl[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},gy=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var s=xl[n];if(s){var i=t.indexOf(s,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};Sl.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(hy(e))return!0;var s=my;return n&&n.strict===!1&&(s=gy),s(e)}});var kl=P((j1,El)=>{"use strict";var yy=_l(),by=require("path").posix.dirname,wy=require("os").platform()==="win32",dr="/",vy=/\\/g,xy=/[\{\[].*[\}\]]$/,Sy=/(^|[^\\])([\{\[]|\([^\)]+$)/,_y=/\\([\!\*\?\|\[\]\(\)\{\}])/g;El.exports=function(e,n){var s=Object.assign({flipBackslashes:!0},n);s.flipBackslashes&&wy&&e.indexOf(dr)<0&&(e=e.replace(vy,dr)),xy.test(e)&&(e+=dr),e+="a";do e=by(e);while(yy(e)||Sy.test(e));return e.replace(_y,"$1")}});var Fs=P(Fe=>{"use strict";Fe.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;Fe.find=(t,e)=>t.nodes.find(n=>n.type===e);Fe.exceedsLimit=(t,e,n=1,s)=>s===!1||!Fe.isInteger(t)||!Fe.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=s;Fe.escapeNode=(t,e=0,n)=>{let s=t.nodes[e];s&&(n&&s.type===n||s.type==="open"||s.type==="close")&&s.escaped!==!0&&(s.value="\\"+s.value,s.escaped=!0)};Fe.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;Fe.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;Fe.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;Fe.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);Fe.flatten=(...t)=>{let e=[],n=s=>{for(let i=0;i<s.length;i++){let r=s[i];if(Array.isArray(r)){n(r);continue}r!==void 0&&e.push(r)}return e};return n(t),e}});var Hs=P((D1,Cl)=>{"use strict";var Rl=Fs();Cl.exports=(t,e={})=>{let n=(s,i={})=>{let r=e.escapeInvalid&&Rl.isInvalidBrace(i),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(r||o)&&Rl.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let c of s.nodes)a+=n(c);return a};return n(t)}});var $l=P((F1,Al)=>{"use strict";Al.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var Dl=P((H1,Ml)=>{"use strict";var Pl=$l(),Wt=(t,e,n)=>{if(Pl(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Pl(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let s={relaxZeros:!0,...n};typeof s.strictZeros=="boolean"&&(s.relaxZeros=s.strictZeros===!1);let i=String(s.relaxZeros),r=String(s.shorthand),o=String(s.capture),a=String(s.wrap),c=t+":"+e+"="+i+r+o+a;if(Wt.cache.hasOwnProperty(c))return Wt.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let m=t+"|"+e;return s.capture?`(${m})`:s.wrap===!1?m:`(?:${m})`}let f=jl(t)||jl(e),d={min:t,max:e,a:l,b:u},p=[],h=[];if(f&&(d.isPadded=f,d.maxLen=String(d.max).length),l<0){let m=u<0?Math.abs(u):1;h=Tl(m,Math.abs(l),d,s),l=d.a=0}return u>=0&&(p=Tl(l,u,d,s)),d.negatives=h,d.positives=p,d.result=Ey(h,p,s),s.capture===!0?d.result=`(${d.result})`:s.wrap!==!1&&p.length+h.length>1&&(d.result=`(?:${d.result})`),Wt.cache[c]=d,d.result};function Ey(t,e,n){let s=pr(t,e,"-",!1,n)||[],i=pr(e,t,"",!1,n)||[],r=pr(t,e,"-?",!0,n)||[];return s.concat(r).concat(i).join("|")}function ky(t,e){let n=1,s=1,i=Ol(t,n),r=new Set([e]);for(;t<=i&&i<=e;)r.add(i),n+=1,i=Ol(t,n);for(i=Ll(e+1,s)-1;t<i&&i<=e;)r.add(i),s+=1,i=Ll(e+1,s)-1;return r=[...r],r.sort(Ay),r}function Ry(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let s=Cy(t,e),i=s.length,r="",o=0;for(let a=0;a<i;a++){let[c,l]=s[a];c===l?r+=c:c!=="0"||l!=="9"?r+=$y(c,l,n):o++}return o&&(r+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:r,count:[o],digits:i}}function Tl(t,e,n,s){let i=ky(t,e),r=[],o=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=Ry(String(o),String(l),s),f="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Nl(a.count),o=l+1;continue}n.isPadded&&(f=Py(l,n,s)),u.string=f+u.pattern+Nl(u.count),r.push(u),o=l+1,a=u}return r}function pr(t,e,n,s,i){let r=[];for(let o of t){let{string:a}=o;!s&&!Il(e,"string",a)&&r.push(n+a),s&&Il(e,"string",a)&&r.push(n+a)}return r}function Cy(t,e){let n=[];for(let s=0;s<t.length;s++)n.push([t[s],e[s]]);return n}function Ay(t,e){return t>e?1:e>t?-1:0}function Il(t,e,n){return t.some(s=>s[e]===n)}function Ol(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Ll(t,e){return t-t%Math.pow(10,e)}function Nl(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function $y(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function jl(t){return/^-?(0+)\d/.test(t)}function Py(t,e,n){if(!e.isPadded)return t;let s=Math.abs(e.maxLen-String(t).length),i=n.relaxZeros!==!1;switch(s){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${s}}`:`0{${s}}`}}Wt.cache={};Wt.clearCache=()=>Wt.cache={};Ml.exports=Wt});var gr=P((B1,Vl)=>{"use strict";var Ty=require("util"),Hl=Dl(),Fl=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Iy=t=>e=>t===!0?Number(e):String(e),hr=t=>typeof t=="number"||typeof t=="string"&&t!=="",Fn=t=>Number.isInteger(+t),mr=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},Oy=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,Ly=(t,e,n)=>{if(e>0){let s=t[0]==="-"?"-":"";s&&(t=t.slice(1)),t=s+t.padStart(s?e-1:e,"0")}return n===!1?String(t):t},Ws=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},Ny=(t,e,n)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let s=e.capture?"":"?:",i="",r="",o;return t.positives.length&&(i=t.positives.map(a=>Ws(String(a),n)).join("|")),t.negatives.length&&(r=`-(${s}${t.negatives.map(a=>Ws(String(a),n)).join("|")})`),i&&r?o=`${i}|${r}`:o=i||r,e.wrap?`(${s}${o})`:o},Bl=(t,e,n,s)=>{if(n)return Hl(t,e,{wrap:!1,...s});let i=String.fromCharCode(t);if(t===e)return i;let r=String.fromCharCode(e);return`[${i}-${r}]`},Wl=(t,e,n)=>{if(Array.isArray(t)){let s=n.wrap===!0,i=n.capture?"":"?:";return s?`(${i}${t.join("|")})`:t.join("|")}return Hl(t,e,n)},Gl=(...t)=>new RangeError("Invalid range arguments: "+Ty.inspect(...t)),Ul=(t,e,n)=>{if(n.strictRanges===!0)throw Gl([t,e]);return[]},jy=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},My=(t,e,n=1,s={})=>{let i=Number(t),r=Number(e);if(!Number.isInteger(i)||!Number.isInteger(r)){if(s.strictRanges===!0)throw Gl([t,e]);return[]}i===0&&(i=0),r===0&&(r=0);let o=i>r,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=mr(a)||mr(c)||mr(l),f=u?Math.max(a.length,c.length,l.length):0,d=u===!1&&Oy(t,e,s)===!1,p=s.transform||Iy(d);if(s.toRegex&&n===1)return Bl(Ws(t,f),Ws(e,f),!0,s);let h={negatives:[],positives:[]},m=w=>h[w<0?"negatives":"positives"].push(Math.abs(w)),g=[],b=0;for(;o?i>=r:i<=r;)s.toRegex===!0&&n>1?m(i):g.push(Ly(p(i,b),f,d)),i=o?i-n:i+n,b++;return s.toRegex===!0?n>1?Ny(h,s,f):Wl(g,null,{wrap:!1,...s}):g},Dy=(t,e,n=1,s={})=>{if(!Fn(t)&&t.length>1||!Fn(e)&&e.length>1)return Ul(t,e,s);let i=s.transform||(d=>String.fromCharCode(d)),r=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=r>o,c=Math.min(r,o),l=Math.max(r,o);if(s.toRegex&&n===1)return Bl(c,l,!1,s);let u=[],f=0;for(;a?r>=o:r<=o;)u.push(i(r,f)),r=a?r-n:r+n,f++;return s.toRegex===!0?Wl(u,null,{wrap:!1,options:s}):u},Bs=(t,e,n,s={})=>{if(e==null&&hr(t))return[t];if(!hr(t)||!hr(e))return Ul(t,e,s);if(typeof n=="function")return Bs(t,e,1,{transform:n});if(Fl(n))return Bs(t,e,0,n);let i={...s};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,Fn(n)?Fn(t)&&Fn(e)?My(t,e,n,i):Dy(t,e,Math.max(Math.abs(n),1),i):n!=null&&!Fl(n)?jy(n,i):Bs(t,e,1,n)};Vl.exports=Bs});var Kl=P((W1,ql)=>{"use strict";var Fy=gr(),zl=Fs(),Hy=(t,e={})=>{let n=(s,i={})=>{let r=zl.isInvalidBrace(i),o=s.invalid===!0&&e.escapeInvalid===!0,a=r===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(s.isOpen===!0)return c+s.value;if(s.isClose===!0)return console.log("node.isClose",c,s.value),c+s.value;if(s.type==="open")return a?c+s.value:"(";if(s.type==="close")return a?c+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let u=zl.reduce(s.nodes),f=Fy(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return u.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let u of s.nodes)l+=n(u,s);return l};return n(t)};ql.exports=Hy});var Xl=P((G1,Jl)=>{"use strict";var By=gr(),Yl=Hs(),pn=Fs(),Gt=(t="",e="",n=!1)=>{let s=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?pn.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let r of i)s.push(Gt(r,e,n));else for(let r of e)n===!0&&typeof r=="string"&&(r=`{${r}}`),s.push(Array.isArray(r)?Gt(i,r,n):i+r);return pn.flatten(s)},Wy=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(i,r={})=>{i.queue=[];let o=r,a=r.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(Gt(a.pop(),Yl(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Gt(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let f=pn.reduce(i.nodes);if(pn.exceedsLimit(...f,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let d=By(...f,e);d.length===0&&(d=Yl(i,e)),a.push(Gt(a.pop(),d)),i.nodes=[];return}let c=pn.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let f=0;f<i.nodes.length;f++){let d=i.nodes[f];if(d.type==="comma"&&i.type==="brace"){f===1&&l.push(""),l.push("");continue}if(d.type==="close"){a.push(Gt(a.pop(),l,c));continue}if(d.value&&d.type!=="open"){l.push(Gt(l.pop(),d.value));continue}d.nodes&&s(d,i)}return l};return pn.flatten(s(t))};Jl.exports=Wy});var Ql=P((U1,Zl)=>{"use strict";Zl.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
3
+ `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var iu=P((V1,su)=>{"use strict";var Gy=Hs(),{MAX_LENGTH:eu,CHAR_BACKSLASH:yr,CHAR_BACKTICK:Uy,CHAR_COMMA:Vy,CHAR_DOT:zy,CHAR_LEFT_PARENTHESES:qy,CHAR_RIGHT_PARENTHESES:Ky,CHAR_LEFT_CURLY_BRACE:Yy,CHAR_RIGHT_CURLY_BRACE:Jy,CHAR_LEFT_SQUARE_BRACKET:tu,CHAR_RIGHT_SQUARE_BRACKET:nu,CHAR_DOUBLE_QUOTE:Xy,CHAR_SINGLE_QUOTE:Zy,CHAR_NO_BREAK_SPACE:Qy,CHAR_ZERO_WIDTH_NOBREAK_SPACE:eb}=Ql(),tb=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},s=typeof n.maxLength=="number"?Math.min(eu,n.maxLength):eu;if(t.length>s)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${s})`);let i={type:"root",input:t,nodes:[]},r=[i],o=i,a=i,c=0,l=t.length,u=0,f=0,d,p=()=>t[u++],h=m=>{if(m.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&m.type==="text"){a.value+=m.value;return}return o.nodes.push(m),m.parent=o,m.prev=a,a=m,m};for(h({type:"bos"});u<l;)if(o=r[r.length-1],d=p(),!(d===eb||d===Qy)){if(d===yr){h({type:"text",value:(e.keepEscaping?d:"")+p()});continue}if(d===nu){h({type:"text",value:"\\"+d});continue}if(d===tu){c++;let m;for(;u<l&&(m=p());){if(d+=m,m===tu){c++;continue}if(m===yr){d+=p();continue}if(m===nu&&(c--,c===0))break}h({type:"text",value:d});continue}if(d===qy){o=h({type:"paren",nodes:[]}),r.push(o),h({type:"text",value:d});continue}if(d===Ky){if(o.type!=="paren"){h({type:"text",value:d});continue}o=r.pop(),h({type:"text",value:d}),o=r[r.length-1];continue}if(d===Xy||d===Zy||d===Uy){let m=d,g;for(e.keepQuotes!==!0&&(d="");u<l&&(g=p());){if(g===yr){d+=g+p();continue}if(g===m){e.keepQuotes===!0&&(d+=g);break}d+=g}h({type:"text",value:d});continue}if(d===Yy){f++;let g={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=h(g),r.push(o),h({type:"open",value:d});continue}if(d===Jy){if(o.type!=="brace"){h({type:"text",value:d});continue}let m="close";o=r.pop(),o.close=!0,h({type:m,value:d}),f--,o=r[r.length-1];continue}if(d===Vy&&f>0){if(o.ranges>0){o.ranges=0;let m=o.nodes.shift();o.nodes=[m,{type:"text",value:Gy(o)}]}h({type:"comma",value:d}),o.commas++;continue}if(d===zy&&f>0&&o.commas===0){let m=o.nodes;if(f===0||m.length===0){h({type:"text",value:d});continue}if(a.type==="dot"){if(o.range=[],a.value+=d,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){m.pop();let g=m[m.length-1];g.value+=a.value+d,a=g,o.ranges--;continue}h({type:"dot",value:d});continue}h({type:"text",value:d})}do if(o=r.pop(),o.type!=="root"){o.nodes.forEach(b=>{b.nodes||(b.type==="open"&&(b.isOpen=!0),b.type==="close"&&(b.isClose=!0),b.nodes||(b.type="text"),b.invalid=!0)});let m=r[r.length-1],g=m.nodes.indexOf(o);m.nodes.splice(g,1,...o.nodes)}while(r.length>0);return h({type:"eos"}),i};su.exports=tb});var au=P((z1,ou)=>{"use strict";var ru=Hs(),nb=Kl(),sb=Xl(),ib=iu(),Oe=(t,e={})=>{let n=[];if(Array.isArray(t))for(let s of t){let i=Oe.create(s,e);Array.isArray(i)?n.push(...i):n.push(i)}else n=[].concat(Oe.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};Oe.parse=(t,e={})=>ib(t,e);Oe.stringify=(t,e={})=>ru(typeof t=="string"?Oe.parse(t,e):t,e);Oe.compile=(t,e={})=>(typeof t=="string"&&(t=Oe.parse(t,e)),nb(t,e));Oe.expand=(t,e={})=>{typeof t=="string"&&(t=Oe.parse(t,e));let n=sb(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};Oe.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Oe.compile(t,e):Oe.expand(t,e);ou.exports=Oe});var Hn=P((q1,du)=>{"use strict";var rb=require("path"),nt="\\\\/",cu=`[^${nt}]`,ob=0,pt="\\.",ab="\\+",cb="\\?",Gs="\\/",lb="(?=.)",lu="[^/]",br=`(?:${Gs}|$)`,uu=`(?:^|${Gs})`,wr=`${pt}{1,2}${br}`,ub=`(?!${pt})`,fb=`(?!${uu}${wr})`,db=`(?!${pt}{0,1}${br})`,pb=`(?!${wr})`,hb=`[^.${Gs}]`,mb=`${lu}*?`,fu={DOT_LITERAL:pt,PLUS_LITERAL:ab,QMARK_LITERAL:cb,SLASH_LITERAL:Gs,ONE_CHAR:lb,QMARK:lu,END_ANCHOR:br,DOTS_SLASH:wr,NO_DOT:ub,NO_DOTS:fb,NO_DOT_SLASH:db,NO_DOTS_SLASH:pb,QMARK_NO_DOT:hb,STAR:mb,START_ANCHOR:uu},gb={...fu,SLASH_LITERAL:`[${nt}]`,QMARK:cu,STAR:`${cu}*?`,DOTS_SLASH:`${pt}{1,2}(?:[${nt}]|$)`,NO_DOT:`(?!${pt})`,NO_DOTS:`(?!(?:^|[${nt}])${pt}{1,2}(?:[${nt}]|$))`,NO_DOT_SLASH:`(?!${pt}{0,1}(?:[${nt}]|$))`,NO_DOTS_SLASH:`(?!${pt}{1,2}(?:[${nt}]|$))`,QMARK_NO_DOT:`[^.${nt}]`,START_ANCHOR:`(?:^|[${nt}])`,END_ANCHOR:`(?:[${nt}]|$)`},yb={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};du.exports={DEFAULT_MAX_EXTGLOB_RECURSION:ob,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:yb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:rb.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?gb:fu}}});var Bn=P(Ae=>{"use strict";var bb=require("path"),wb=process.platform==="win32",{REGEX_BACKSLASH:vb,REGEX_REMOVE_BACKSLASH:xb,REGEX_SPECIAL_CHARS:Sb,REGEX_SPECIAL_CHARS_GLOBAL:_b}=Hn();Ae.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Ae.hasRegexChars=t=>Sb.test(t);Ae.isRegexChar=t=>t.length===1&&Ae.hasRegexChars(t);Ae.escapeRegex=t=>t.replace(_b,"\\$1");Ae.toPosixSlashes=t=>t.replace(vb,"/");Ae.removeBackslashes=t=>t.replace(xb,e=>e==="\\"?"":e);Ae.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Ae.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:wb===!0||bb.sep==="\\";Ae.escapeLast=(t,e,n)=>{let s=t.lastIndexOf(e,n);return s===-1?t:t[s-1]==="\\"?Ae.escapeLast(t,e,s-1):`${t.slice(0,s)}\\${t.slice(s)}`};Ae.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};Ae.wrapOutput=(t,e={},n={})=>{let s=n.contains?"":"^",i=n.contains?"":"$",r=`${s}(?:${t})${i}`;return e.negated===!0&&(r=`(?:^(?!${r}).*$)`),r}});var vu=P((Y1,wu)=>{"use strict";var pu=Bn(),{CHAR_ASTERISK:vr,CHAR_AT:Eb,CHAR_BACKWARD_SLASH:Wn,CHAR_COMMA:kb,CHAR_DOT:xr,CHAR_EXCLAMATION_MARK:Sr,CHAR_FORWARD_SLASH:bu,CHAR_LEFT_CURLY_BRACE:_r,CHAR_LEFT_PARENTHESES:Er,CHAR_LEFT_SQUARE_BRACKET:Rb,CHAR_PLUS:Cb,CHAR_QUESTION_MARK:hu,CHAR_RIGHT_CURLY_BRACE:Ab,CHAR_RIGHT_PARENTHESES:mu,CHAR_RIGHT_SQUARE_BRACKET:$b}=Hn(),gu=t=>t===bu||t===Wn,yu=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},Pb=(t,e)=>{let n=e||{},s=t.length-1,i=n.parts===!0||n.scanToEnd===!0,r=[],o=[],a=[],c=t,l=-1,u=0,f=0,d=!1,p=!1,h=!1,m=!1,g=!1,b=!1,w=!1,y=!1,v=!1,R=!1,k=0,T,C,N={value:"",depth:0,isGlob:!1},V=()=>l>=s,E=()=>c.charCodeAt(l+1),W=()=>(T=C,c.charCodeAt(++l));for(;l<s;){C=W();let M;if(C===Wn){w=N.backslashes=!0,C=W(),C===_r&&(b=!0);continue}if(b===!0||C===_r){for(k++;V()!==!0&&(C=W());){if(C===Wn){w=N.backslashes=!0,W();continue}if(C===_r){k++;continue}if(b!==!0&&C===xr&&(C=W())===xr){if(d=N.isBrace=!0,h=N.isGlob=!0,R=!0,i===!0)continue;break}if(b!==!0&&C===kb){if(d=N.isBrace=!0,h=N.isGlob=!0,R=!0,i===!0)continue;break}if(C===Ab&&(k--,k===0)){b=!1,d=N.isBrace=!0,R=!0;break}}if(i===!0)continue;break}if(C===bu){if(r.push(l),o.push(N),N={value:"",depth:0,isGlob:!1},R===!0)continue;if(T===xr&&l===u+1){u+=2;continue}f=l+1;continue}if(n.noext!==!0&&(C===Cb||C===Eb||C===vr||C===hu||C===Sr)===!0&&E()===Er){if(h=N.isGlob=!0,m=N.isExtglob=!0,R=!0,C===Sr&&l===u&&(v=!0),i===!0){for(;V()!==!0&&(C=W());){if(C===Wn){w=N.backslashes=!0,C=W();continue}if(C===mu){h=N.isGlob=!0,R=!0;break}}continue}break}if(C===vr){if(T===vr&&(g=N.isGlobstar=!0),h=N.isGlob=!0,R=!0,i===!0)continue;break}if(C===hu){if(h=N.isGlob=!0,R=!0,i===!0)continue;break}if(C===Rb){for(;V()!==!0&&(M=W());){if(M===Wn){w=N.backslashes=!0,W();continue}if(M===$b){p=N.isBracket=!0,h=N.isGlob=!0,R=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&C===Sr&&l===u){y=N.negated=!0,u++;continue}if(n.noparen!==!0&&C===Er){if(h=N.isGlob=!0,i===!0){for(;V()!==!0&&(C=W());){if(C===Er){w=N.backslashes=!0,C=W();continue}if(C===mu){R=!0;break}}continue}break}if(h===!0){if(R=!0,i===!0)continue;break}}n.noext===!0&&(m=!1,h=!1);let G=c,we="",S="";u>0&&(we=c.slice(0,u),c=c.slice(u),f-=u),G&&h===!0&&f>0?(G=c.slice(0,f),S=c.slice(f)):h===!0?(G="",S=c):G=c,G&&G!==""&&G!=="/"&&G!==c&&gu(G.charCodeAt(G.length-1))&&(G=G.slice(0,-1)),n.unescape===!0&&(S&&(S=pu.removeBackslashes(S)),G&&w===!0&&(G=pu.removeBackslashes(G)));let _={prefix:we,input:t,start:u,base:G,glob:S,isBrace:d,isBracket:p,isGlob:h,isExtglob:m,isGlobstar:g,negated:y,negatedExtglob:v};if(n.tokens===!0&&(_.maxDepth=0,gu(C)||o.push(N),_.tokens=o),n.parts===!0||n.tokens===!0){let M;for(let I=0;I<r.length;I++){let Z=M?M+1:u,te=r[I],ve=t.slice(Z,te);n.tokens&&(I===0&&u!==0?(o[I].isPrefix=!0,o[I].value=we):o[I].value=ve,yu(o[I]),_.maxDepth+=o[I].depth),(I!==0||ve!=="")&&a.push(ve),M=te}if(M&&M+1<t.length){let I=t.slice(M+1);a.push(I),n.tokens&&(o[o.length-1].value=I,yu(o[o.length-1]),_.maxDepth+=o[o.length-1].depth)}_.slashes=r,_.parts=a}return _};wu.exports=Pb});var ku=P((J1,Eu)=>{"use strict";var Gn=Hn(),pe=Bn(),{MAX_LENGTH:Us,POSIX_REGEX_SOURCE:Tb,REGEX_NON_SPECIAL_CHARS:Ib,REGEX_SPECIAL_CHARS_BACKREF:Ob,REPLACEMENTS:xu}=Gn,Lb=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(i=>pe.escapeRegex(i)).join("..")}return n},hn=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,Su=t=>{let e=[],n=0,s=0,i=0,r="",o=!1;for(let a of t){if(o===!0){r+=a,o=!1;continue}if(a==="\\"){r+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,r+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(r),r="";continue}}}r+=a}return e.push(r),e},Nb=t=>{let e=!1;for(let n of t){if(e===!0){e=!1;continue}if(n==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},_u=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(Nb(e))return e.replace(/\\(.)/g,"$1")},jb=t=>{let e=t.map(_u).filter(Boolean);for(let n=0;n<e.length;n++)for(let s=n+1;s<e.length;s++){let i=e[n],r=e[s],o=i[0];if(!(!o||i!==o.repeat(i.length)||r!==o.repeat(r.length))&&(i===r||i.startsWith(r)||r.startsWith(i)))return!0}return!1},kr=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,s=0,i=0,r=!1;for(let o=1;o<t.length;o++){let a=t[o];if(r===!0){r=!1;continue}if(a==="\\"){r=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},Mb=t=>{let e=0,n=[];for(;e<t.length;){let i=kr(t.slice(e),!1);if(!i||i.type!=="*")return;let r=Su(i.body).map(a=>a.trim());if(r.length!==1)return;let o=_u(r[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?pe.escapeRegex(n[0]):`[${n.map(i=>pe.escapeRegex(i)).join("")}]`}*`},Db=t=>{let e=0,n=t.trim(),s=kr(n);for(;s;)e++,n=s.body.trim(),s=kr(n);return e},Fb=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Gn.DEFAULT_MAX_EXTGLOB_RECURSION,s=Su(t).map(i=>i.trim());if(s.length>1&&(s.some(i=>i==="")||s.some(i=>/^[*?]+$/.test(i))||jb(s)))return{risky:!0};for(let i of s){let r=Mb(i);if(r)return{risky:!0,safeOutput:r};if(Db(i)>n)return{risky:!0}}return{risky:!1}},Rr=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=xu[t]||t;let n={...e},s=typeof n.maxLength=="number"?Math.min(Us,n.maxLength):Us,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);let r={type:"bos",value:"",output:n.prepend||""},o=[r],a=n.capture?"":"?:",c=pe.isWindows(e),l=Gn.globChars(c),u=Gn.extglobChars(l),{DOT_LITERAL:f,PLUS_LITERAL:d,SLASH_LITERAL:p,ONE_CHAR:h,DOTS_SLASH:m,NO_DOT:g,NO_DOT_SLASH:b,NO_DOTS_SLASH:w,QMARK:y,QMARK_NO_DOT:v,STAR:R,START_ANCHOR:k}=l,T=$=>`(${a}(?:(?!${k}${$.dot?m:f}).)*?)`,C=n.dot?"":g,N=n.dot?y:v,V=n.bash===!0?T(n):R;n.capture&&(V=`(${V})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let E={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=pe.removePrefix(t,E),i=t.length;let W=[],G=[],we=[],S=r,_,M=()=>E.index===i-1,I=E.peek=($=1)=>t[E.index+$],Z=E.advance=()=>t[++E.index]||"",te=()=>t.slice(E.index+1),ve=($="",K=0)=>{E.consumed+=$,E.index+=K},dt=$=>{E.output+=$.output!=null?$.output:$.value,ve($.value)},Gg=()=>{let $=1;for(;I()==="!"&&(I(2)!=="("||I(3)==="?");)Z(),E.start++,$++;return $%2===0?!1:(E.negated=!0,E.start++,!0)},Ts=$=>{E[$]++,we.push($)},St=$=>{E[$]--,we.pop()},F=$=>{if(S.type==="globstar"){let K=E.braces>0&&($.type==="comma"||$.type==="brace"),A=$.extglob===!0||W.length&&($.type==="pipe"||$.type==="paren");$.type!=="slash"&&$.type!=="paren"&&!K&&!A&&(E.output=E.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=V,E.output+=S.output)}if(W.length&&$.type!=="paren"&&(W[W.length-1].inner+=$.value),($.value||$.output)&&dt($),S&&S.type==="text"&&$.type==="text"){S.value+=$.value,S.output=(S.output||"")+$.value;return}$.prev=S,o.push($),S=$},Is=($,K)=>{let A={...u[K],conditions:1,inner:""};A.prev=S,A.parens=E.parens,A.output=E.output,A.startIndex=E.index,A.tokensIndex=o.length;let D=(n.capture?"(":"")+A.open;Ts("parens"),F({type:$,value:K,output:E.output?"":h}),F({type:"paren",extglob:!0,value:Z(),output:D}),W.push(A)},Ug=$=>{let K=t.slice($.startIndex,E.index+1),A=t.slice($.startIndex+2,E.index),D=Fb(A,n);if(($.type==="plus"||$.type==="star")&&D.risky){let U=D.safeOutput?($.output?"":h)+(n.capture?`(${D.safeOutput})`:D.safeOutput):void 0,Qe=o[$.tokensIndex];Qe.type="text",Qe.value=K,Qe.output=U||pe.escapeRegex(K);for(let et=$.tokensIndex+1;et<o.length;et++)o[et].value="",o[et].output="",delete o[et].suffix;E.output=$.output+Qe.output,E.backtrack=!0,F({type:"paren",extglob:!0,value:_,output:""}),St("parens");return}let z=$.close+(n.capture?")":""),ne;if($.type==="negate"){let U=V;if($.inner&&$.inner.length>1&&$.inner.includes("/")&&(U=T(n)),(U!==V||M()||/^\)+$/.test(te()))&&(z=$.close=`)$))${U}`),$.inner.includes("*")&&(ne=te())&&/^\.[^\\/.]+$/.test(ne)){let Qe=Rr(ne,{...e,fastpaths:!1}).output;z=$.close=`)${Qe})${U})`}$.prev.type==="bos"&&(E.negatedExtglob=!0)}F({type:"paren",extglob:!0,value:_,output:z}),St("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let $=!1,K=t.replace(Ob,(A,D,z,ne,U,Qe)=>ne==="\\"?($=!0,A):ne==="?"?D?D+ne+(U?y.repeat(U.length):""):Qe===0?N+(U?y.repeat(U.length):""):y.repeat(z.length):ne==="."?f.repeat(z.length):ne==="*"?D?D+ne+(U?V:""):V:D?A:`\\${A}`);return $===!0&&(n.unescape===!0?K=K.replace(/\\/g,""):K=K.replace(/\\+/g,A=>A.length%2===0?"\\\\":A?"\\":"")),K===t&&n.contains===!0?(E.output=t,E):(E.output=pe.wrapOutput(K,E,e),E)}for(;!M();){if(_=Z(),_==="\0")continue;if(_==="\\"){let A=I();if(A==="/"&&n.bash!==!0||A==="."||A===";")continue;if(!A){_+="\\",F({type:"text",value:_});continue}let D=/^\\+/.exec(te()),z=0;if(D&&D[0].length>2&&(z=D[0].length,E.index+=z,z%2!==0&&(_+="\\")),n.unescape===!0?_=Z():_+=Z(),E.brackets===0){F({type:"text",value:_});continue}}if(E.brackets>0&&(_!=="]"||S.value==="["||S.value==="[^")){if(n.posix!==!1&&_===":"){let A=S.value.slice(1);if(A.includes("[")&&(S.posix=!0,A.includes(":"))){let D=S.value.lastIndexOf("["),z=S.value.slice(0,D),ne=S.value.slice(D+2),U=Tb[ne];if(U){S.value=z+U,E.backtrack=!0,Z(),!r.output&&o.indexOf(S)===1&&(r.output=h);continue}}}(_==="["&&I()!==":"||_==="-"&&I()==="]")&&(_=`\\${_}`),_==="]"&&(S.value==="["||S.value==="[^")&&(_=`\\${_}`),n.posix===!0&&_==="!"&&S.value==="["&&(_="^"),S.value+=_,dt({value:_});continue}if(E.quotes===1&&_!=='"'){_=pe.escapeRegex(_),S.value+=_,dt({value:_});continue}if(_==='"'){E.quotes=E.quotes===1?0:1,n.keepQuotes===!0&&F({type:"text",value:_});continue}if(_==="("){Ts("parens"),F({type:"paren",value:_});continue}if(_===")"){if(E.parens===0&&n.strictBrackets===!0)throw new SyntaxError(hn("opening","("));let A=W[W.length-1];if(A&&E.parens===A.parens+1){Ug(W.pop());continue}F({type:"paren",value:_,output:E.parens?")":"\\)"}),St("parens");continue}if(_==="["){if(n.nobracket===!0||!te().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(hn("closing","]"));_=`\\${_}`}else Ts("brackets");F({type:"bracket",value:_});continue}if(_==="]"){if(n.nobracket===!0||S&&S.type==="bracket"&&S.value.length===1){F({type:"text",value:_,output:`\\${_}`});continue}if(E.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(hn("opening","["));F({type:"text",value:_,output:`\\${_}`});continue}St("brackets");let A=S.value.slice(1);if(S.posix!==!0&&A[0]==="^"&&!A.includes("/")&&(_=`/${_}`),S.value+=_,dt({value:_}),n.literalBrackets===!1||pe.hasRegexChars(A))continue;let D=pe.escapeRegex(S.value);if(E.output=E.output.slice(0,-S.value.length),n.literalBrackets===!0){E.output+=D,S.value=D;continue}S.value=`(${a}${D}|${S.value})`,E.output+=S.value;continue}if(_==="{"&&n.nobrace!==!0){Ts("braces");let A={type:"brace",value:_,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};G.push(A),F(A);continue}if(_==="}"){let A=G[G.length-1];if(n.nobrace===!0||!A){F({type:"text",value:_,output:_});continue}let D=")";if(A.dots===!0){let z=o.slice(),ne=[];for(let U=z.length-1;U>=0&&(o.pop(),z[U].type!=="brace");U--)z[U].type!=="dots"&&ne.unshift(z[U].value);D=Lb(ne,n),E.backtrack=!0}if(A.comma!==!0&&A.dots!==!0){let z=E.output.slice(0,A.outputIndex),ne=E.tokens.slice(A.tokensIndex);A.value=A.output="\\{",_=D="\\}",E.output=z;for(let U of ne)E.output+=U.output||U.value}F({type:"brace",value:_,output:D}),St("braces"),G.pop();continue}if(_==="|"){W.length>0&&W[W.length-1].conditions++,F({type:"text",value:_});continue}if(_===","){let A=_,D=G[G.length-1];D&&we[we.length-1]==="braces"&&(D.comma=!0,A="|"),F({type:"comma",value:_,output:A});continue}if(_==="/"){if(S.type==="dot"&&E.index===E.start+1){E.start=E.index+1,E.consumed="",E.output="",o.pop(),S=r;continue}F({type:"slash",value:_,output:p});continue}if(_==="."){if(E.braces>0&&S.type==="dot"){S.value==="."&&(S.output=f);let A=G[G.length-1];S.type="dots",S.output+=_,S.value+=_,A.dots=!0;continue}if(E.braces+E.parens===0&&S.type!=="bos"&&S.type!=="slash"){F({type:"text",value:_,output:f});continue}F({type:"dot",value:_,output:f});continue}if(_==="?"){if(!(S&&S.value==="(")&&n.noextglob!==!0&&I()==="("&&I(2)!=="?"){Is("qmark",_);continue}if(S&&S.type==="paren"){let D=I(),z=_;if(D==="<"&&!pe.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(S.value==="("&&!/[!=<:]/.test(D)||D==="<"&&!/<([!=]|\w+>)/.test(te()))&&(z=`\\${_}`),F({type:"text",value:_,output:z});continue}if(n.dot!==!0&&(S.type==="slash"||S.type==="bos")){F({type:"qmark",value:_,output:v});continue}F({type:"qmark",value:_,output:y});continue}if(_==="!"){if(n.noextglob!==!0&&I()==="("&&(I(2)!=="?"||!/[!=<:]/.test(I(3)))){Is("negate",_);continue}if(n.nonegate!==!0&&E.index===0){Gg();continue}}if(_==="+"){if(n.noextglob!==!0&&I()==="("&&I(2)!=="?"){Is("plus",_);continue}if(S&&S.value==="("||n.regex===!1){F({type:"plus",value:_,output:d});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||E.parens>0){F({type:"plus",value:_});continue}F({type:"plus",value:d});continue}if(_==="@"){if(n.noextglob!==!0&&I()==="("&&I(2)!=="?"){F({type:"at",extglob:!0,value:_,output:""});continue}F({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let A=Ib.exec(te());A&&(_+=A[0],E.index+=A[0].length),F({type:"text",value:_});continue}if(S&&(S.type==="globstar"||S.star===!0)){S.type="star",S.star=!0,S.value+=_,S.output=V,E.backtrack=!0,E.globstar=!0,ve(_);continue}let $=te();if(n.noextglob!==!0&&/^\([^?]/.test($)){Is("star",_);continue}if(S.type==="star"){if(n.noglobstar===!0){ve(_);continue}let A=S.prev,D=A.prev,z=A.type==="slash"||A.type==="bos",ne=D&&(D.type==="star"||D.type==="globstar");if(n.bash===!0&&(!z||$[0]&&$[0]!=="/")){F({type:"star",value:_,output:""});continue}let U=E.braces>0&&(A.type==="comma"||A.type==="brace"),Qe=W.length&&(A.type==="pipe"||A.type==="paren");if(!z&&A.type!=="paren"&&!U&&!Qe){F({type:"star",value:_,output:""});continue}for(;$.slice(0,3)==="/**";){let et=t[E.index+4];if(et&&et!=="/")break;$=$.slice(3),ve("/**",3)}if(A.type==="bos"&&M()){S.type="globstar",S.value+=_,S.output=T(n),E.output=S.output,E.globstar=!0,ve(_);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&!ne&&M()){E.output=E.output.slice(0,-(A.output+S.output).length),A.output=`(?:${A.output}`,S.type="globstar",S.output=T(n)+(n.strictSlashes?")":"|$)"),S.value+=_,E.globstar=!0,E.output+=A.output+S.output,ve(_);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&$[0]==="/"){let et=$[1]!==void 0?"|$":"";E.output=E.output.slice(0,-(A.output+S.output).length),A.output=`(?:${A.output}`,S.type="globstar",S.output=`${T(n)}${p}|${p}${et})`,S.value+=_,E.output+=A.output+S.output,E.globstar=!0,ve(_+Z()),F({type:"slash",value:"/",output:""});continue}if(A.type==="bos"&&$[0]==="/"){S.type="globstar",S.value+=_,S.output=`(?:^|${p}|${T(n)}${p})`,E.output=S.output,E.globstar=!0,ve(_+Z()),F({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-S.output.length),S.type="globstar",S.output=T(n),S.value+=_,E.output+=S.output,E.globstar=!0,ve(_);continue}let K={type:"star",value:_,output:V};if(n.bash===!0){K.output=".*?",(S.type==="bos"||S.type==="slash")&&(K.output=C+K.output),F(K);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&n.regex===!0){K.output=_,F(K);continue}(E.index===E.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(E.output+=b,S.output+=b):n.dot===!0?(E.output+=w,S.output+=w):(E.output+=C,S.output+=C),I()!=="*"&&(E.output+=h,S.output+=h)),F(K)}for(;E.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(hn("closing","]"));E.output=pe.escapeLast(E.output,"["),St("brackets")}for(;E.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(hn("closing",")"));E.output=pe.escapeLast(E.output,"("),St("parens")}for(;E.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(hn("closing","}"));E.output=pe.escapeLast(E.output,"{"),St("braces")}if(n.strictSlashes!==!0&&(S.type==="star"||S.type==="bracket")&&F({type:"maybe_slash",value:"",output:`${p}?`}),E.backtrack===!0){E.output="";for(let $ of E.tokens)E.output+=$.output!=null?$.output:$.value,$.suffix&&(E.output+=$.suffix)}return E};Rr.fastpaths=(t,e)=>{let n={...e},s=typeof n.maxLength=="number"?Math.min(Us,n.maxLength):Us,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);t=xu[t]||t;let r=pe.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:f,NO_DOTS_SLASH:d,STAR:p,START_ANCHOR:h}=Gn.globChars(r),m=n.dot?f:u,g=n.dot?d:u,b=n.capture?"":"?:",w={negated:!1,prefix:""},y=n.bash===!0?".*?":p;n.capture&&(y=`(${y})`);let v=C=>C.noglobstar===!0?y:`(${b}(?:(?!${h}${C.dot?l:o}).)*?)`,R=C=>{switch(C){case"*":return`${m}${c}${y}`;case".*":return`${o}${c}${y}`;case"*.*":return`${m}${y}${o}${c}${y}`;case"*/*":return`${m}${y}${a}${c}${g}${y}`;case"**":return m+v(n);case"**/*":return`(?:${m}${v(n)}${a})?${g}${c}${y}`;case"**/*.*":return`(?:${m}${v(n)}${a})?${g}${y}${o}${c}${y}`;case"**/.*":return`(?:${m}${v(n)}${a})?${o}${c}${y}`;default:{let N=/^(.*?)\.(\w+)$/.exec(C);if(!N)return;let V=R(N[1]);return V?V+o+N[2]:void 0}}},k=pe.removePrefix(t,w),T=R(k);return T&&n.strictSlashes!==!0&&(T+=`${a}?`),T};Eu.exports=Rr});var Cu=P((X1,Ru)=>{"use strict";var Hb=require("path"),Bb=vu(),Cr=ku(),Ar=Bn(),Wb=Hn(),Gb=t=>t&&typeof t=="object"&&!Array.isArray(t),Q=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(d=>Q(d,e,n));return d=>{for(let p of u){let h=p(d);if(h)return h}return!1}}let s=Gb(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},r=Ar.isWindows(e),o=s?Q.compileRe(t,e):Q.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Q(i.ignore,u,n)}let l=(u,f=!1)=>{let{isMatch:d,match:p,output:h}=Q.test(u,o,e,{glob:t,posix:r}),m={glob:t,state:a,regex:o,posix:r,input:u,output:h,match:p,isMatch:d};return typeof i.onResult=="function"&&i.onResult(m),d===!1?(m.isMatch=!1,f?m:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=!1,f?m:!1):(typeof i.onMatch=="function"&&i.onMatch(m),f?m:!0)};return n&&(l.state=a),l};Q.test=(t,e,n,{glob:s,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let r=n||{},o=r.format||(i?Ar.toPosixSlashes:null),a=t===s,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===s),(a===!1||r.capture===!0)&&(r.matchBase===!0||r.basename===!0?a=Q.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Q.matchBase=(t,e,n,s=Ar.isWindows(n))=>(e instanceof RegExp?e:Q.makeRe(e,n)).test(Hb.basename(t));Q.isMatch=(t,e,n)=>Q(e,n)(t);Q.parse=(t,e)=>Array.isArray(t)?t.map(n=>Q.parse(n,e)):Cr(t,{...e,fastpaths:!1});Q.scan=(t,e)=>Bb(t,e);Q.compileRe=(t,e,n=!1,s=!1)=>{if(n===!0)return t.output;let i=e||{},r=i.contains?"":"^",o=i.contains?"":"$",a=`${r}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=Q.toRegex(a,e);return s===!0&&(c.state=t),c};Q.makeRe=(t,e={},n=!1,s=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=Cr.fastpaths(t,e)),i.output||(i=Cr(t,e)),Q.compileRe(i,e,n,s)};Q.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};Q.constants=Wb;Ru.exports=Q});var $u=P((Z1,Au)=>{"use strict";Au.exports=Cu()});var Et=P((Q1,Lu)=>{"use strict";var Tu=require("util"),Iu=au(),st=$u(),$r=Bn(),Pu=t=>t===""||t==="./",Ou=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},q=(t,e,n)=>{e=[].concat(e),t=[].concat(t);let s=new Set,i=new Set,r=new Set,o=0,a=u=>{r.add(u.output),n&&n.onResult&&n.onResult(u)};for(let u=0;u<e.length;u++){let f=st(String(e[u]),{...n,onResult:a},!0),d=f.state.negated||f.state.negatedExtglob;d&&o++;for(let p of t){let h=f(p,!0);(d?!h.isMatch:h.isMatch)&&(d?s.add(h.output):(s.delete(h.output),i.add(h.output)))}}let l=(o===e.length?[...r]:[...i]).filter(u=>!s.has(u));if(n&&l.length===0){if(n.failglob===!0)throw new Error(`No matches found for "${e.join(", ")}"`);if(n.nonull===!0||n.nullglob===!0)return n.unescape?e.map(u=>u.replace(/\\/g,"")):e}return l};q.match=q;q.matcher=(t,e)=>st(t,e);q.isMatch=(t,e,n)=>st(e,n)(t);q.any=q.isMatch;q.not=(t,e,n={})=>{e=[].concat(e).map(String);let s=new Set,i=[],r=a=>{n.onResult&&n.onResult(a),i.push(a.output)},o=new Set(q(t,e,{...n,onResult:r}));for(let a of i)o.has(a)||s.add(a);return[...s]};q.contains=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Tu.inspect(t)}"`);if(Array.isArray(e))return e.some(s=>q.contains(t,s,n));if(typeof e=="string"){if(Pu(t)||Pu(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return q.isMatch(t,e,{...n,contains:!0})};q.matchKeys=(t,e,n)=>{if(!$r.isObject(t))throw new TypeError("Expected the first argument to be an object");let s=q(Object.keys(t),e,n),i={};for(let r of s)i[r]=t[r];return i};q.some=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let r=st(String(i),n);if(s.some(o=>r(o)))return!0}return!1};q.every=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let r=st(String(i),n);if(!s.every(o=>r(o)))return!1}return!0};q.all=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Tu.inspect(t)}"`);return[].concat(e).every(s=>st(s,n)(t))};q.capture=(t,e,n)=>{let s=$r.isWindows(n),r=st.makeRe(String(t),{...n,capture:!0}).exec(s?$r.toPosixSlashes(e):e);if(r)return r.slice(1).map(o=>o===void 0?"":o)};q.makeRe=(...t)=>st.makeRe(...t);q.scan=(...t)=>st.scan(...t);q.parse=(t,e)=>{let n=[];for(let s of[].concat(t||[]))for(let i of Iu(String(s),e))n.push(st.parse(i,e));return n};q.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!Ou(t)?[t]:Iu(t,e)};q.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return q.braces(t,{...e,expand:!0})};q.hasBraces=Ou;Lu.exports=q});var Uu=P(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.isAbsolute=O.partitionAbsoluteAndRelative=O.removeDuplicateSlashes=O.matchAny=O.convertPatternsToRe=O.makeRe=O.getPatternParts=O.expandBraceExpansion=O.expandPatternsWithBraceExpansion=O.isAffectDepthOfReadingPattern=O.endsWithSlashGlobStar=O.hasGlobStar=O.getBaseDirectory=O.isPatternRelatedToParentDirectory=O.getPatternsOutsideCurrentDirectory=O.getPatternsInsideCurrentDirectory=O.getPositivePatterns=O.getNegativePatterns=O.isPositivePattern=O.isNegativePattern=O.convertToNegativePattern=O.convertToPositivePattern=O.isDynamicPattern=O.isStaticPattern=void 0;var Nu=require("path"),Ub=kl(),Pr=Et(),ju="**",Vb="\\",zb=/[*?]|^!/,qb=/\[[^[]*]/,Kb=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Yb=/[!*+?@]\([^(]*\)/,Jb=/,|\.\./,Xb=/(?!^)\/{2,}/g;function Mu(t,e={}){return!Du(t,e)}O.isStaticPattern=Mu;function Du(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(Vb)||zb.test(t)||qb.test(t)||Kb.test(t)||e.extglob!==!1&&Yb.test(t)||e.braceExpansion!==!1&&Zb(t))}O.isDynamicPattern=Du;function Zb(t){let e=t.indexOf("{");if(e===-1)return!1;let n=t.indexOf("}",e+1);if(n===-1)return!1;let s=t.slice(e,n);return Jb.test(s)}function Qb(t){return Vs(t)?t.slice(1):t}O.convertToPositivePattern=Qb;function ew(t){return"!"+t}O.convertToNegativePattern=ew;function Vs(t){return t.startsWith("!")&&t[1]!=="("}O.isNegativePattern=Vs;function Fu(t){return!Vs(t)}O.isPositivePattern=Fu;function tw(t){return t.filter(Vs)}O.getNegativePatterns=tw;function nw(t){return t.filter(Fu)}O.getPositivePatterns=nw;function sw(t){return t.filter(e=>!Tr(e))}O.getPatternsInsideCurrentDirectory=sw;function iw(t){return t.filter(Tr)}O.getPatternsOutsideCurrentDirectory=iw;function Tr(t){return t.startsWith("..")||t.startsWith("./..")}O.isPatternRelatedToParentDirectory=Tr;function rw(t){return Ub(t,{flipBackslashes:!1})}O.getBaseDirectory=rw;function ow(t){return t.includes(ju)}O.hasGlobStar=ow;function Hu(t){return t.endsWith("/"+ju)}O.endsWithSlashGlobStar=Hu;function aw(t){let e=Nu.basename(t);return Hu(t)||Mu(e)}O.isAffectDepthOfReadingPattern=aw;function cw(t){return t.reduce((e,n)=>e.concat(Bu(n)),[])}O.expandPatternsWithBraceExpansion=cw;function Bu(t){let e=Pr.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((n,s)=>n.length-s.length),e.filter(n=>n!=="")}O.expandBraceExpansion=Bu;function lw(t,e){let{parts:n}=Pr.scan(t,Object.assign(Object.assign({},e),{parts:!0}));return n.length===0&&(n=[t]),n[0].startsWith("/")&&(n[0]=n[0].slice(1),n.unshift("")),n}O.getPatternParts=lw;function Wu(t,e){return Pr.makeRe(t,e)}O.makeRe=Wu;function uw(t,e){return t.map(n=>Wu(n,e))}O.convertPatternsToRe=uw;function fw(t,e){return e.some(n=>n.test(t))}O.matchAny=fw;function dw(t){return t.replace(Xb,"/")}O.removeDuplicateSlashes=dw;function pw(t){let e=[],n=[];for(let s of t)Gu(s)?e.push(s):n.push(s);return[e,n]}O.partitionAbsoluteAndRelative=pw;function Gu(t){return Nu.isAbsolute(t)}O.isAbsolute=Gu});var Ku=P((tT,qu)=>{"use strict";var hw=require("stream"),Vu=hw.PassThrough,mw=Array.prototype.slice;qu.exports=gw;function gw(){let t=[],e=mw.call(arguments),n=!1,s=e[e.length-1];s&&!Array.isArray(s)&&s.pipe==null?e.pop():s={};let i=s.end!==!1,r=s.pipeError===!0;s.objectMode==null&&(s.objectMode=!0),s.highWaterMark==null&&(s.highWaterMark=64*1024);let o=Vu(s);function a(){for(let u=0,f=arguments.length;u<f;u++)t.push(zu(arguments[u],s));return c(),this}function c(){if(n)return;n=!0;let u=t.shift();if(!u){process.nextTick(l);return}Array.isArray(u)||(u=[u]);let f=u.length+1;function d(){--f>0||(n=!1,c())}function p(h){function m(){h.removeListener("merge2UnpipeEnd",m),h.removeListener("end",m),r&&h.removeListener("error",g),d()}function g(b){o.emit("error",b)}if(h._readableState.endEmitted)return d();h.on("merge2UnpipeEnd",m),h.on("end",m),r&&h.on("error",g),h.pipe(o,{end:!1}),h.resume()}for(let h=0;h<u.length;h++)p(u[h]);d()}function l(){n=!1,o.emit("queueDrain"),i&&o.end()}return o.setMaxListeners(0),o.add=a,o.on("unpipe",function(u){u.emit("merge2UnpipeEnd")}),e.length&&a.apply(null,e),o}function zu(t,e){if(Array.isArray(t))for(let n=0,s=t.length;n<s;n++)t[n]=zu(t[n],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(Vu(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var Ju=P(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.merge=void 0;var yw=Ku();function bw(t){let e=yw(t);return t.forEach(n=>{n.once("error",s=>e.emit("error",s))}),e.once("close",()=>Yu(t)),e.once("end",()=>Yu(t)),e}zs.merge=bw;function Yu(t){t.forEach(e=>e.emit("close"))}});var Xu=P(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.isEmpty=mn.isString=void 0;function ww(t){return typeof t=="string"}mn.isString=ww;function vw(t){return t===""}mn.isEmpty=vw});var ht=P(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.string=he.stream=he.pattern=he.path=he.fs=he.errno=he.array=void 0;var xw=dl();he.array=xw;var Sw=pl();he.errno=Sw;var _w=hl();he.fs=_w;var Ew=bl();he.path=Ew;var kw=Uu();he.pattern=kw;var Rw=Ju();he.stream=Rw;var Cw=Xu();he.string=Cw});var tf=P(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.convertPatternGroupToTask=me.convertPatternGroupsToTasks=me.groupPatternsByBaseDirectory=me.getNegativePatternsAsPositive=me.getPositivePatterns=me.convertPatternsToTasks=me.generate=void 0;var ze=ht();function Aw(t,e){let n=Zu(t,e),s=Zu(e.ignore,e),i=Qu(n),r=ef(n,s),o=i.filter(u=>ze.pattern.isStaticPattern(u,e)),a=i.filter(u=>ze.pattern.isDynamicPattern(u,e)),c=Ir(o,r,!1),l=Ir(a,r,!0);return c.concat(l)}me.generate=Aw;function Zu(t,e){let n=t;return e.braceExpansion&&(n=ze.pattern.expandPatternsWithBraceExpansion(n)),e.baseNameMatch&&(n=n.map(s=>s.includes("/")?s:`**/${s}`)),n.map(s=>ze.pattern.removeDuplicateSlashes(s))}function Ir(t,e,n){let s=[],i=ze.pattern.getPatternsOutsideCurrentDirectory(t),r=ze.pattern.getPatternsInsideCurrentDirectory(t),o=Or(i),a=Or(r);return s.push(...Lr(o,e,n)),"."in a?s.push(Nr(".",r,e,n)):s.push(...Lr(a,e,n)),s}me.convertPatternsToTasks=Ir;function Qu(t){return ze.pattern.getPositivePatterns(t)}me.getPositivePatterns=Qu;function ef(t,e){return ze.pattern.getNegativePatterns(t).concat(e).map(ze.pattern.convertToPositivePattern)}me.getNegativePatternsAsPositive=ef;function Or(t){let e={};return t.reduce((n,s)=>{let i=ze.pattern.getBaseDirectory(s);return i in n?n[i].push(s):n[i]=[s],n},e)}me.groupPatternsByBaseDirectory=Or;function Lr(t,e,n){return Object.keys(t).map(s=>Nr(s,t[s],e,n))}me.convertPatternGroupsToTasks=Lr;function Nr(t,e,n,s){return{dynamic:s,positive:e,negative:n,base:t,patterns:[].concat(e,n.map(ze.pattern.convertToNegativePattern))}}me.convertPatternGroupToTask=Nr});var sf=P(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.read=void 0;function $w(t,e,n){e.fs.lstat(t,(s,i)=>{if(s!==null){nf(n,s);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){jr(n,i);return}e.fs.stat(t,(r,o)=>{if(r!==null){if(e.throwErrorOnBrokenSymbolicLink){nf(n,r);return}jr(n,i);return}e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),jr(n,o)})})}qs.read=$w;function nf(t,e){t(e)}function jr(t,e){t(null,e)}});var rf=P(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.read=void 0;function Pw(t,e){let n=e.fs.lstatSync(t);if(!n.isSymbolicLink()||!e.followSymbolicLink)return n;try{let s=e.fs.statSync(t);return e.markSymbolicLink&&(s.isSymbolicLink=()=>!0),s}catch(s){if(!e.throwErrorOnBrokenSymbolicLink)return n;throw s}}Ks.read=Pw});var of=P(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.createFileSystemAdapter=kt.FILE_SYSTEM_ADAPTER=void 0;var Ys=require("fs");kt.FILE_SYSTEM_ADAPTER={lstat:Ys.lstat,stat:Ys.stat,lstatSync:Ys.lstatSync,statSync:Ys.statSync};function Tw(t){return t===void 0?kt.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},kt.FILE_SYSTEM_ADAPTER),t)}kt.createFileSystemAdapter=Tw});var af=P(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});var Iw=of(),Mr=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=Iw.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue(e,n){return e??n}};Dr.default=Mr});var Ut=P(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.statSync=Rt.stat=Rt.Settings=void 0;var cf=sf(),Ow=rf(),Fr=af();Rt.Settings=Fr.default;function Lw(t,e,n){if(typeof e=="function"){cf.read(t,Hr(),e);return}cf.read(t,Hr(e),n)}Rt.stat=Lw;function Nw(t,e){let n=Hr(e);return Ow.read(t,n)}Rt.statSync=Nw;function Hr(t={}){return t instanceof Fr.default?t:new Fr.default(t)}});var ff=P((fT,uf)=>{var lf;uf.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(lf||(lf=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var pf=P((dT,df)=>{df.exports=Mw;var jw=ff();function Mw(t,e){let n,s,i,r=!0;Array.isArray(t)?(n=[],s=t.length):(i=Object.keys(t),n={},s=i.length);function o(c){function l(){e&&e(c,n),e=null}r?jw(l):l()}function a(c,l,u){n[c]=u,(--s===0||l)&&o(l)}s?i?i.forEach(function(c){t[c](function(l,u){a(c,l,u)})}):t.forEach(function(c,l){c(function(u,f){a(l,u,f)})}):o(null),r=!1}});var Br=P(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var Js=process.versions.node.split(".");if(Js[0]===void 0||Js[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var hf=Number.parseInt(Js[0],10),Dw=Number.parseInt(Js[1],10),mf=10,Fw=10,Hw=hf>mf,Bw=hf===mf&&Dw>=Fw;Xs.IS_SUPPORT_READDIR_WITH_FILE_TYPES=Hw||Bw});var gf=P(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});Zs.createDirentFromStats=void 0;var Wr=class{constructor(e,n){this.name=e,this.isBlockDevice=n.isBlockDevice.bind(n),this.isCharacterDevice=n.isCharacterDevice.bind(n),this.isDirectory=n.isDirectory.bind(n),this.isFIFO=n.isFIFO.bind(n),this.isFile=n.isFile.bind(n),this.isSocket=n.isSocket.bind(n),this.isSymbolicLink=n.isSymbolicLink.bind(n)}};function Ww(t,e){return new Wr(t,e)}Zs.createDirentFromStats=Ww});var Gr=P(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.fs=void 0;var Gw=gf();Qs.fs=Gw});var Ur=P(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.joinPathSegments=void 0;function Uw(t,e,n){return t.endsWith(n)?t+e:t+n+e}ei.joinPathSegments=Uw});var Sf=P(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.readdir=Ct.readdirWithFileTypes=Ct.read=void 0;var Vw=Ut(),yf=pf(),zw=Br(),bf=Gr(),wf=Ur();function qw(t,e,n){if(!e.stats&&zw.IS_SUPPORT_READDIR_WITH_FILE_TYPES){vf(t,e,n);return}xf(t,e,n)}Ct.read=qw;function vf(t,e,n){e.fs.readdir(t,{withFileTypes:!0},(s,i)=>{if(s!==null){ti(n,s);return}let r=i.map(a=>({dirent:a,name:a.name,path:wf.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){Vr(n,r);return}let o=r.map(a=>Kw(a,e));yf(o,(a,c)=>{if(a!==null){ti(n,a);return}Vr(n,c)})})}Ct.readdirWithFileTypes=vf;function Kw(t,e){return n=>{if(!t.dirent.isSymbolicLink()){n(null,t);return}e.fs.stat(t.path,(s,i)=>{if(s!==null){if(e.throwErrorOnBrokenSymbolicLink){n(s);return}n(null,t);return}t.dirent=bf.fs.createDirentFromStats(t.name,i),n(null,t)})}}function xf(t,e,n){e.fs.readdir(t,(s,i)=>{if(s!==null){ti(n,s);return}let r=i.map(o=>{let a=wf.joinPathSegments(t,o,e.pathSegmentSeparator);return c=>{Vw.stat(a,e.fsStatSettings,(l,u)=>{if(l!==null){c(l);return}let f={name:o,path:a,dirent:bf.fs.createDirentFromStats(o,u)};e.stats&&(f.stats=u),c(null,f)})}});yf(r,(o,a)=>{if(o!==null){ti(n,o);return}Vr(n,a)})})}Ct.readdir=xf;function ti(t,e){t(e)}function Vr(t,e){t(null,e)}});var Cf=P(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.readdir=At.readdirWithFileTypes=At.read=void 0;var Yw=Ut(),Jw=Br(),_f=Gr(),Ef=Ur();function Xw(t,e){return!e.stats&&Jw.IS_SUPPORT_READDIR_WITH_FILE_TYPES?kf(t,e):Rf(t,e)}At.read=Xw;function kf(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(s=>{let i={dirent:s,name:s.name,path:Ef.joinPathSegments(t,s.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let r=e.fs.statSync(i.path);i.dirent=_f.fs.createDirentFromStats(i.name,r)}catch(r){if(e.throwErrorOnBrokenSymbolicLink)throw r}return i})}At.readdirWithFileTypes=kf;function Rf(t,e){return e.fs.readdirSync(t).map(s=>{let i=Ef.joinPathSegments(t,s,e.pathSegmentSeparator),r=Yw.statSync(i,e.fsStatSettings),o={name:s,path:i,dirent:_f.fs.createDirentFromStats(s,r)};return e.stats&&(o.stats=r),o})}At.readdir=Rf});var Af=P($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.createFileSystemAdapter=$t.FILE_SYSTEM_ADAPTER=void 0;var gn=require("fs");$t.FILE_SYSTEM_ADAPTER={lstat:gn.lstat,stat:gn.stat,lstatSync:gn.lstatSync,statSync:gn.statSync,readdir:gn.readdir,readdirSync:gn.readdirSync};function Zw(t){return t===void 0?$t.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},$t.FILE_SYSTEM_ADAPTER),t)}$t.createFileSystemAdapter=Zw});var $f=P(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});var Qw=require("path"),ev=Ut(),tv=Af(),zr=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=tv.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,Qw.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new ev.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};qr.default=zr});var ni=P(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Settings=Pt.scandirSync=Pt.scandir=void 0;var Pf=Sf(),nv=Cf(),Kr=$f();Pt.Settings=Kr.default;function sv(t,e,n){if(typeof e=="function"){Pf.read(t,Yr(),e);return}Pf.read(t,Yr(e),n)}Pt.scandir=sv;function iv(t,e){let n=Yr(e);return nv.read(t,n)}Pt.scandirSync=iv;function Yr(t={}){return t instanceof Kr.default?t:new Kr.default(t)}});var If=P((ST,Tf)=>{"use strict";function rv(t){var e=new t,n=e;function s(){var r=e;return r.next?e=r.next:(e=new t,n=e),r.next=null,r}function i(r){n.next=r,n=r}return{get:s,release:i}}Tf.exports=rv});var Lf=P((_T,Jr)=>{"use strict";var ov=If();function Of(t,e,n){if(typeof t=="function"&&(n=e,e=t,t=null),!(n>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var s=ov(av),i=null,r=null,o=0,a=null,c={push:m,drain:$e,saturated:$e,pause:u,paused:!1,get concurrency(){return n},set concurrency(k){if(!(k>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=k,!c.paused)for(;i&&o<n;)o++,b()},running:l,resume:p,idle:h,length:f,getQueue:d,unshift:g,empty:$e,kill:w,killAndDrain:y,error:R,abort:v};return c;function l(){return o}function u(){c.paused=!0}function f(){for(var k=i,T=0;k;)k=k.next,T++;return T}function d(){for(var k=i,T=[];k;)T.push(k.value),k=k.next;return T}function p(){if(c.paused){if(c.paused=!1,i===null){o++,b();return}for(;i&&o<n;)o++,b()}}function h(){return o===0&&c.length()===0}function m(k,T){var C=s.get();C.context=t,C.release=b,C.value=k,C.callback=T||$e,C.errorHandler=a,o>=n||c.paused?r?(r.next=C,r=C):(i=C,r=C,c.saturated()):(o++,e.call(t,C.value,C.worked))}function g(k,T){var C=s.get();C.context=t,C.release=b,C.value=k,C.callback=T||$e,C.errorHandler=a,o>=n||c.paused?i?(C.next=i,i=C):(i=C,r=C,c.saturated()):(o++,e.call(t,C.value,C.worked))}function b(k){k&&s.release(k);var T=i;T&&o<=n?c.paused?o--:(r===i&&(r=null),i=T.next,T.next=null,e.call(t,T.value,T.worked),r===null&&c.empty()):--o===0&&c.drain()}function w(){i=null,r=null,c.drain=$e}function y(){i=null,r=null,c.drain(),c.drain=$e}function v(){var k=i;for(i=null,r=null;k;){var T=k.next,C=k.callback,N=k.errorHandler,V=k.value,E=k.context;k.value=null,k.callback=$e,k.errorHandler=null,N&&N(new Error("abort"),V),C.call(E,new Error("abort")),k.release(k),k=T}c.drain=$e}function R(k){a=k}}function $e(){}function av(){this.value=null,this.callback=$e,this.next=null,this.release=$e,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,s){var i=t.callback,r=t.errorHandler,o=t.value;t.value=null,t.callback=$e,t.errorHandler&&r(n,o),i.call(t.context,n,s),t.release(t)}}function cv(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function s(u,f){e.call(this,u).then(function(d){f(null,d)},f)}var i=Of(t,s,n),r=i.push,o=i.unshift;return i.push=a,i.unshift=c,i.drained=l,i;function a(u){var f=new Promise(function(d,p){r(u,function(h,m){if(h){p(h);return}d(m)})});return f.catch($e),f}function c(u){var f=new Promise(function(d,p){o(u,function(h,m){if(h){p(h);return}d(m)})});return f.catch($e),f}function l(){var u=new Promise(function(f){process.nextTick(function(){if(i.idle())f();else{var d=i.drain;i.drain=function(){typeof d=="function"&&d(),f(),i.drain=d}}})});return u}}Jr.exports=Of;Jr.exports.promise=cv});var si=P(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.joinPathSegments=it.replacePathSegmentSeparator=it.isAppliedFilter=it.isFatalError=void 0;function lv(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}it.isFatalError=lv;function uv(t,e){return t===null||t(e)}it.isAppliedFilter=uv;function fv(t,e){return t.split(/[/\\]/).join(e)}it.replacePathSegmentSeparator=fv;function dv(t,e,n){return t===""?e:t.endsWith(n)?t+e:t+n+e}it.joinPathSegments=dv});var Qr=P(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});var pv=si(),Xr=class{constructor(e,n){this._root=e,this._settings=n,this._root=pv.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}};Zr.default=Xr});var no=P(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var hv=require("events"),mv=ni(),gv=Lf(),ii=si(),yv=Qr(),eo=class extends yv.default{constructor(e,n){super(e,n),this._settings=n,this._scandir=mv.scandir,this._emitter=new hv.EventEmitter,this._queue=gv(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit("end")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw new Error("The reader is already destroyed");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on("entry",e)}onError(e){this._emitter.once("error",e)}onEnd(e){this._emitter.once("end",e)}_pushToQueue(e,n){let s={directory:e,base:n};this._queue.push(s,i=>{i!==null&&this._handleError(i)})}_worker(e,n){this._scandir(e.directory,this._settings.fsScandirSettings,(s,i)=>{if(s!==null){n(s,void 0);return}for(let r of i)this._handleEntry(r,e.base);n(null,void 0)})}_handleError(e){this._isDestroyed||!ii.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit("error",e))}_handleEntry(e,n){if(this._isDestroyed||this._isFatalError)return;let s=e.path;n!==void 0&&(e.path=ii.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ii.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&ii.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};to.default=eo});var Nf=P(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});var bv=no(),so=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new bv.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(n=>{wv(e,n)}),this._reader.onEntry(n=>{this._storage.push(n)}),this._reader.onEnd(()=>{vv(e,this._storage)}),this._reader.read()}};io.default=so;function wv(t,e){t(e)}function vv(t,e){t(null,e)}});var jf=P(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var xv=require("stream"),Sv=no(),ro=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new Sv.default(this._root,this._settings),this._stream=new xv.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit("error",e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}};oo.default=ro});var Mf=P(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var _v=ni(),ri=si(),Ev=Qr(),ao=class extends Ev.default{constructor(){super(...arguments),this._scandir=_v.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,n){this._queue.add({directory:e,base:n})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,n){try{let s=this._scandir(e,this._settings.fsScandirSettings);for(let i of s)this._handleEntry(i,n)}catch(s){this._handleError(s)}}_handleError(e){if(ri.isFatalError(this._settings,e))throw e}_handleEntry(e,n){let s=e.path;n!==void 0&&(e.path=ri.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ri.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&ri.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};co.default=ao});var Df=P(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var kv=Mf(),lo=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new kv.default(this._root,this._settings)}read(){return this._reader.read()}};uo.default=lo});var Ff=P(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});var Rv=require("path"),Cv=ni(),fo=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,Rv.sep),this.fsScandirSettings=new Cv.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};po.default=fo});var ai=P(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.Settings=rt.walkStream=rt.walkSync=rt.walk=void 0;var Hf=Nf(),Av=jf(),$v=Df(),ho=Ff();rt.Settings=ho.default;function Pv(t,e,n){if(typeof e=="function"){new Hf.default(t,oi()).read(e);return}new Hf.default(t,oi(e)).read(n)}rt.walk=Pv;function Tv(t,e){let n=oi(e);return new $v.default(t,n).read()}rt.walkSync=Tv;function Iv(t,e){let n=oi(e);return new Av.default(t,n).read()}rt.walkStream=Iv;function oi(t={}){return t instanceof ho.default?t:new ho.default(t)}});var ci=P(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});var Ov=require("path"),Lv=Ut(),Bf=ht(),mo=class{constructor(e){this._settings=e,this._fsStatSettings=new Lv.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return Ov.resolve(this._settings.cwd,e)}_makeEntry(e,n){let s={name:n,path:n,dirent:Bf.fs.createDirentFromStats(n,e)};return this._settings.stats&&(s.stats=e),s}_isFatalError(e){return!Bf.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};go.default=mo});var wo=P(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});var Nv=require("stream"),jv=Ut(),Mv=ai(),Dv=ci(),yo=class extends Dv.default{constructor(){super(...arguments),this._walkStream=Mv.walkStream,this._stat=jv.stat}dynamic(e,n){return this._walkStream(e,n)}static(e,n){let s=e.map(this._getFullEntryPath,this),i=new Nv.PassThrough({objectMode:!0});i._write=(r,o,a)=>this._getEntry(s[r],e[r],n).then(c=>{c!==null&&n.entryFilter(c)&&i.push(c),r===s.length-1&&i.end(),a()}).catch(a);for(let r=0;r<s.length;r++)i.write(r);return i}_getEntry(e,n,s){return this._getStat(e).then(i=>this._makeEntry(i,n)).catch(i=>{if(s.errorFilter(i))return null;throw i})}_getStat(e){return new Promise((n,s)=>{this._stat(e,this._fsStatSettings,(i,r)=>i===null?n(r):s(i))})}};bo.default=yo});var Wf=P(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var Fv=ai(),Hv=ci(),Bv=wo(),vo=class extends Hv.default{constructor(){super(...arguments),this._walkAsync=Fv.walk,this._readerStream=new Bv.default(this._settings)}dynamic(e,n){return new Promise((s,i)=>{this._walkAsync(e,n,(r,o)=>{r===null?s(o):i(r)})})}async static(e,n){let s=[],i=this._readerStream.static(e,n);return new Promise((r,o)=>{i.once("error",o),i.on("data",a=>s.push(a)),i.once("end",()=>r(s))})}};xo.default=vo});var Gf=P(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var Un=ht(),So=class{constructor(e,n,s){this._patterns=e,this._settings=n,this._micromatchOptions=s,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let n=this._getPatternSegments(e),s=this._splitSegmentsIntoSections(n);this._storage.push({complete:s.length<=1,pattern:e,segments:n,sections:s})}}_getPatternSegments(e){return Un.pattern.getPatternParts(e,this._micromatchOptions).map(s=>Un.pattern.isDynamicPattern(s,this._settings)?{dynamic:!0,pattern:s,patternRe:Un.pattern.makeRe(s,this._micromatchOptions)}:{dynamic:!1,pattern:s})}_splitSegmentsIntoSections(e){return Un.array.splitWhen(e,n=>n.dynamic&&Un.pattern.hasGlobStar(n.pattern))}};_o.default=So});var Uf=P(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});var Wv=Gf(),Eo=class extends Wv.default{match(e){let n=e.split("/"),s=n.length,i=this._storage.filter(r=>!r.complete||r.segments.length>s);for(let r of i){let o=r.sections[0];if(!r.complete&&s>o.length||n.every((c,l)=>{let u=r.segments[l];return!!(u.dynamic&&u.patternRe.test(c)||!u.dynamic&&u.pattern===c)}))return!0}return!1}};ko.default=Eo});var Vf=P(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var li=ht(),Gv=Uf(),Ro=class{constructor(e,n){this._settings=e,this._micromatchOptions=n}getFilter(e,n,s){let i=this._getMatcher(n),r=this._getNegativePatternsRe(s);return o=>this._filter(e,o,i,r)}_getMatcher(e){return new Gv.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(li.pattern.isAffectDepthOfReadingPattern);return li.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,s,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let r=li.path.removeLeadingDotSegment(n.path);return this._isSkippedByPositivePatterns(r,s)?!1:this._isSkippedByNegativePatterns(r,i)}_isSkippedByDeep(e,n){return this._settings.deep===1/0?!1:this._getEntryLevel(e,n)>=this._settings.deep}_getEntryLevel(e,n){let s=n.split("/").length;if(e==="")return s;let i=e.split("/").length;return s-i}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,n){return!this._settings.baseNameMatch&&!n.match(e)}_isSkippedByNegativePatterns(e,n){return!li.pattern.matchAny(e,n)}};Co.default=Ro});var zf=P($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var Tt=ht(),Ao=class{constructor(e,n){this._settings=e,this._micromatchOptions=n,this.index=new Map}getFilter(e,n){let[s,i]=Tt.pattern.partitionAbsoluteAndRelative(n),r={positive:{all:Tt.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:Tt.pattern.convertPatternsToRe(s,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:Tt.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return o=>this._filter(o,r)}_filter(e,n){let s=Tt.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(s)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let i=this._isMatchToPatternsSet(s,n,e.dirent.isDirectory());return this._settings.unique&&i&&this._createIndexRecord(s),i}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isMatchToPatternsSet(e,n,s){return!(!this._isMatchToPatterns(e,n.positive.all,s)||this._isMatchToPatterns(e,n.negative.relative,s)||this._isMatchToAbsoluteNegative(e,n.negative.absolute,s))}_isMatchToAbsoluteNegative(e,n,s){if(n.length===0)return!1;let i=Tt.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,s)}_isMatchToPatterns(e,n,s){if(n.length===0)return!1;let i=Tt.pattern.matchAny(e,n);return!i&&s?Tt.pattern.matchAny(e+"/",n):i}};$o.default=Ao});var qf=P(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var Uv=ht(),Po=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return Uv.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};To.default=Po});var Yf=P(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Kf=ht(),Io=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=Kf.path.makeAbsolute(this._settings.cwd,n),n=Kf.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}};Oo.default=Io});var ui=P(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var Vv=require("path"),zv=Vf(),qv=zf(),Kv=qf(),Yv=Yf(),Lo=class{constructor(e){this._settings=e,this.errorFilter=new Kv.default(this._settings),this.entryFilter=new qv.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new zv.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new Yv.default(this._settings)}_getRootDirectory(e){return Vv.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let n=e.base==="."?"":e.base;return{basePath:n,pathSegmentSeparator:"/",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(n,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}};No.default=Lo});var Jf=P(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var Jv=Wf(),Xv=ui(),jo=class extends Xv.default{constructor(){super(...arguments),this._reader=new Jv.default(this._settings)}async read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e);return(await this.api(n,e,s)).map(r=>s.transform(r))}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};Mo.default=jo});var Xf=P(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});var Zv=require("stream"),Qv=wo(),e0=ui(),Do=class extends e0.default{constructor(){super(...arguments),this._reader=new Qv.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e),i=this.api(n,e,s),r=new Zv.Readable({objectMode:!0,read:()=>{}});return i.once("error",o=>r.emit("error",o)).on("data",o=>r.emit("data",s.transform(o))).once("end",()=>r.emit("end")),r.once("close",()=>i.destroy()),r}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};Fo.default=Do});var Zf=P(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});var t0=Ut(),n0=ai(),s0=ci(),Ho=class extends s0.default{constructor(){super(...arguments),this._walkSync=n0.walkSync,this._statSync=t0.statSync}dynamic(e,n){return this._walkSync(e,n)}static(e,n){let s=[];for(let i of e){let r=this._getFullEntryPath(i),o=this._getEntry(r,i,n);o===null||!n.entryFilter(o)||s.push(o)}return s}_getEntry(e,n,s){try{let i=this._getStat(e);return this._makeEntry(i,n)}catch(i){if(s.errorFilter(i))return null;throw i}}_getStat(e){return this._statSync(e,this._fsStatSettings)}};Bo.default=Ho});var Qf=P(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var i0=Zf(),r0=ui(),Wo=class extends r0.default{constructor(){super(...arguments),this._reader=new i0.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e);return this.api(n,e,s).map(s.transform)}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};Go.default=Wo});var ed=P(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var yn=require("fs"),o0=require("os"),a0=Math.max(o0.cpus().length,1);bn.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:yn.lstat,lstatSync:yn.lstatSync,stat:yn.stat,statSync:yn.statSync,readdir:yn.readdir,readdirSync:yn.readdirSync};var Uo=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,a0),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,n){return e===void 0?n:e}_getFileSystemMethods(e={}){return Object.assign(Object.assign({},bn.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};bn.default=Uo});var wn=P((KT,nd)=>{"use strict";var td=tf(),c0=Jf(),l0=Xf(),u0=Qf(),Vo=ed(),He=ht();async function zo(t,e){qe(t);let n=qo(t,c0.default,e),s=await Promise.all(n);return He.array.flatten(s)}(function(t){t.glob=t,t.globSync=e,t.globStream=n,t.async=t;function e(l,u){qe(l);let f=qo(l,u0.default,u);return He.array.flatten(f)}t.sync=e;function n(l,u){qe(l);let f=qo(l,l0.default,u);return He.stream.merge(f)}t.stream=n;function s(l,u){qe(l);let f=[].concat(l),d=new Vo.default(u);return td.generate(f,d)}t.generateTasks=s;function i(l,u){qe(l);let f=new Vo.default(u);return He.pattern.isDynamicPattern(l,f)}t.isDynamicPattern=i;function r(l){return qe(l),He.path.escape(l)}t.escapePath=r;function o(l){return qe(l),He.path.convertPathToPattern(l)}t.convertPathToPattern=o;let a;(function(l){function u(d){return qe(d),He.path.escapePosixPath(d)}l.escapePath=u;function f(d){return qe(d),He.path.convertPosixPathToPattern(d)}l.convertPathToPattern=f})(a=t.posix||(t.posix={}));let c;(function(l){function u(d){return qe(d),He.path.escapeWindowsPath(d)}l.escapePath=u;function f(d){return qe(d),He.path.convertWindowsPathToPattern(d)}l.convertPathToPattern=f})(c=t.win32||(t.win32={}))})(zo||(zo={}));function qo(t,e,n){let s=[].concat(t),i=new Vo.default(n),r=td.generate(s,i),o=new e(i);return r.map(o.read,o)}function qe(t){if(![].concat(t).every(s=>He.string.isString(s)&&!He.string.isEmpty(s)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}nd.exports=zo});var el=P((Xj,GP)=>{GP.exports={name:"@promptci/cli",version:"0.2.1",description:"Instruction health for AI coding workflows \u2014 scan CLAUDE.md, AGENTS.md, .cursorrules and more for duplicates, conflicts, staleness, and context bloat",license:"Apache-2.0",type:"module",bin:{promptci:"./dist/cli.cjs"},files:["dist"],engines:{node:">=22"},repository:{type:"git",url:"git+https://github.com/SeriousGeese/PromptCI.git",directory:"packages/cli"},homepage:"https://github.com/SeriousGeese/PromptCI#readme",bugs:{url:"https://github.com/SeriousGeese/PromptCI/issues"},keywords:["ai","claude","cli","copilot","cursor","instructions","lint","prompt","scanner"],scripts:{build:"esbuild src/cli.ts --bundle --platform=node --format=cjs --minify --outfile=dist/cli.cjs",typecheck:"tsc -p tsconfig.json --noEmit",prepublishOnly:"pnpm run build"},devDependencies:{"@promptci/core":"workspace:*","@types/node":"^26.6.6",commander:"^15.0.0",esbuild:"^0.28.2",typescript:"*",vitest:"^5.1.0"},publishConfig:{access:"public"}}});var _t=class extends Error{constructor(e,n,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},Bt=class extends _t{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var jn=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,s)=>{if(!this.argChoices.includes(n))throw new Bt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,s):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Os(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}var ll=require("node:events"),Ns=x(require("node:child_process"),1),tt=x(require("node:path"),1),Dn=x(require("node:fs"),1),B=x(require("node:process"),1),ul=require("node:util");var rl=require("node:util"),Mn=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let n=e.commands.filter(i=>!i._hidden),s=e._getHelpCommand();return s&&!s._hidden&&n.push(s),this.sortSubcommands&&n.sort((i,r)=>i.name().localeCompare(r.name())),n}compareOptions(e,n){let s=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return s(e).localeCompare(s(n))}visibleOptions(e){let n=e.options.filter(i=>!i.hidden),s=e._getHelpOption();if(s&&!s.hidden){let i=s.short&&e._findOption(s.short),r=s.long&&e._findOption(s.long);!i&&!r?n.push(s):s.long&&!r?n.push(e.createOption(s.long,s.description)):s.short&&!i&&n.push(e.createOption(s.short,s.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let s=e.parent;s;s=s.parent){let i=s.options.filter(r=>!r.hidden);n.push(...i)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(s=>Os(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(i)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleOptionTerm(n.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleOptionTerm(n.optionTerm(i)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((s,i)=>Math.max(s,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(i)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let s="";for(let i=e.parent;i;i=i.parent)s=i.name()+" "+s;return s+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0){let s=`(${n.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let s=`(${n.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatItemList(e,n,s){return n.length===0?[]:[s.styleTitle(e),...n,""]}groupItems(e,n,s){let i=new Map;return e.forEach(r=>{let o=s(r);i.has(o)||i.set(o,[])}),n.forEach(r=>{let o=s(r);i.has(o)||i.set(o,[]),i.get(o).push(r)}),i}formatHelp(e,n){let s=n.padWidth(e,n),i=n.helpWidth??80;function r(f,d){return n.formatItem(f,s,d,n)}let o=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(o=o.concat([n.boxWrap(n.styleCommandDescription(a),i),""]));let c=n.visibleArguments(e).map(f=>r(n.styleArgumentTerm(n.argumentTerm(f)),n.styleArgumentDescription(n.argumentDescription(f))));if(o=o.concat(this.formatItemList("Arguments:",c,n)),this.groupItems(e.options,n.visibleOptions(e),f=>f.helpGroupHeading??"Options:").forEach((f,d)=>{let p=f.map(h=>r(n.styleOptionTerm(n.optionTerm(h)),n.styleOptionDescription(n.optionDescription(h))));o=o.concat(this.formatItemList(d,p,n))}),n.showGlobalOptions){let f=n.visibleGlobalOptions(e).map(d=>r(n.styleOptionTerm(n.optionTerm(d)),n.styleOptionDescription(n.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",f,n))}return this.groupItems(e.commands,n.visibleCommands(e),f=>f.helpGroup()||"Commands:").forEach((f,d)=>{let p=f.map(h=>r(n.styleSubcommandTerm(n.subcommandTerm(h)),n.styleSubcommandDescription(n.subcommandDescription(h))));o=o.concat(this.formatItemList(d,p,n))}),o.join(`
4
+ `)}displayWidth(e){return(0,rl.stripVTControlCharacters)(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n==="[command]"?this.styleSubcommandText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleCommandText(n)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(n=>n==="[options]"?this.styleOptionText(n):n[0]==="["||n[0]==="<"?this.styleArgumentText(n):this.styleSubcommandText(n)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,n,s,i){let o=" ".repeat(2);if(!s)return o+e;let a=e.padEnd(n+e.length-i.displayWidth(e)),c=2,u=(this.helpWidth??80)-n-c-2,f;return u<this.minWidthToWrap||i.preformatted(s)?f=s:f=i.boxWrap(s,u).replace(/\n/g,`
5
5
  `+" ".repeat(n+c)),o+a+" ".repeat(c)+f.replace(/\n/g,`
6
6
  ${o}`)}boxWrap(e,n){if(n<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,r=[];return s.forEach(o=>{let a=o.match(i);if(a===null){r.push("");return}let c=[a.shift()],l=this.displayWidth(c[0]);a.forEach(u=>{let f=this.displayWidth(u);if(l+f<=n){c.push(u),l+=f;return}r.push(c.join(""));let d=u.trimStart();c=[d],l=this.displayWidth(d)}),r.push(c.join(""))}),r.join(`
7
- `)}};var un=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=zg(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,s)=>{if(!this.argChoices.includes(n))throw new Ht(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,s):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?sl(this.name().replace(/^no-/,"")):sl(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ls=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,n){let s=n.attributeName();if(!this.dualOptions.has(s))return!0;let i=this.negativeOptions.get(s).presetArg,r=i!==void 0?i:!1;return n.negate===(r===e)}};function sl(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function zg(t){let e,n,s=/^-[^-]$/,i=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(s.test(r[0])&&(e=r.shift()),i.test(r[0])&&(n=r.shift()),!e&&s.test(r[0])&&(e=r.shift()),!e&&i.test(r[0])&&(e=n,n=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
7
+ `)}};var un=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Xg(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:(n.push(e),n)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,s)=>{if(!this.argChoices.includes(n))throw new Bt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,s):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?ol(this.name().replace(/^no-/,"")):ol(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ls=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,n){let s=n.attributeName();if(!this.dualOptions.has(s))return!0;let i=this.negativeOptions.get(s).presetArg,r=i!==void 0?i:!1;return n.negate===(r===e)}};function ol(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function Xg(t){let e,n,s=/^-[^-]$/,i=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(s.test(r[0])&&(e=r.shift()),i.test(r[0])&&(n=r.shift()),!e&&s.test(r[0])&&(e=r.shift()),!e&&i.test(r[0])&&(e=n,n=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
8
8
  - a short flag is a single dash and a single character
9
9
  - either use a single dash and a single character (for a short flag)
10
10
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(o)?new Error(`${a}
11
11
  - too many short flags`):i.test(o)?new Error(`${a}
12
12
  - too many long flags`):new Error(`${a}
13
- - unrecognised flag format`)}if(e===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}function qg(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let s=0;s<=t.length;s++)n[s]=[s];for(let s=0;s<=e.length;s++)n[0][s]=s;for(let s=1;s<=e.length;s++)for(let i=1;i<=t.length;i++){let r;t[i-1]===e[s-1]?r=0:r=1,n[i][s]=Math.min(n[i-1][s]+1,n[i][s-1]+1,n[i-1][s-1]+r),i>1&&s>1&&t[i-1]===e[s-2]&&t[i-2]===e[s-1]&&(n[i][s]=Math.min(n[i][s],n[i-2][s-2]+1))}return n[t.length][e.length]}function or(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let s=[],i=3,r=.4;return e.forEach(o=>{if(o.length<=1)return;let a=qg(t,o),c=Math.max(t.length,o.length);(c-a)/c>r&&(a<i?(i=a,s=[o]):a===i&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),n&&(s=s.map(o=>`--${o}`)),s.length>1?`
13
+ - unrecognised flag format`)}if(e===void 0&&n===void 0)throw new Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:n}}function Zg(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let s=0;s<=t.length;s++)n[s]=[s];for(let s=0;s<=e.length;s++)n[0][s]=s;for(let s=1;s<=e.length;s++)for(let i=1;i<=t.length;i++){let r;t[i-1]===e[s-1]?r=0:r=1,n[i][s]=Math.min(n[i-1][s]+1,n[i][s-1]+1,n[i-1][s-1]+r),i>1&&s>1&&t[i-1]===e[s-2]&&t[i-2]===e[s-1]&&(n[i][s]=Math.min(n[i][s],n[i-2][s-2]+1))}return n[t.length][e.length]}function cr(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let s=[],i=3,r=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Zg(t,o),c=Math.max(t.length,o.length);(c-a)/c>r&&(a<i?(i=a,s=[o]):a===i&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),n&&(s=s.map(o=>`--${o}`)),s.length>1?`
14
14
  (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
15
- (Did you mean ${s[0]}?)`:""}var fn=class t extends ol.EventEmitter{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>H.default.stdout.write(n),writeErr:n=>H.default.stderr.write(n),outputError:(n,s)=>s(n),getOutHelpWidth:()=>H.default.stdout.isTTY?H.default.stdout.columns:void 0,getErrHelpWidth:()=>H.default.stderr.isTTY?H.default.stderr.columns:void 0,getOutHasColors:()=>rl()??(H.default.stdout.isTTY&&H.default.stdout.hasColors?.()),getErrHasColors:()=>rl()??(H.default.stderr.isTTY&&H.default.stderr.hasColors?.()),stripColor:n=>(0,al.stripVTControlCharacters)(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,s){let i=n,r=s;typeof i=="object"&&i!==null&&(r=i,i=null),r=r||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),r.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(r.noHelp||r.hidden),c._executableFile=r.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Mn,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ (Did you mean ${s[0]}?)`:""}var fn=class t extends ll.EventEmitter{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>B.default.stdout.write(n),writeErr:n=>B.default.stderr.write(n),outputError:(n,s)=>s(n),getOutHelpWidth:()=>B.default.stdout.isTTY?B.default.stdout.columns:void 0,getErrHelpWidth:()=>B.default.stderr.isTTY?B.default.stderr.columns:void 0,getOutHasColors:()=>cl()??(B.default.stdout.isTTY&&B.default.stdout.hasColors?.()),getErrHasColors:()=>cl()??(B.default.stderr.isTTY&&B.default.stderr.hasColors?.()),stripColor:n=>(0,ul.stripVTControlCharacters)(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,s){let i=n,r=s;typeof i=="object"&&i!==null&&(r=i,i=null),r=r||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return i&&(c.description(i),c._executableHandler=!0),r.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(r.noHelp||r.hidden),c._executableFile=r.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),i?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Mn,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
16
16
  - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new jn(e,n)}argument(e,n,s,i){let r=this.createArgument(e,n);return typeof s=="function"?r.default(i).argParser(s):r.default(s),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n?.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let s=e??"help [command]",[,i,r]=s.match(/([^ ]+) *(.*)/),o=n??"display help for command",a=this.createCommand(i);return a.helpOption(!1),r&&a.arguments(r),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||n)&&this._initCommandGroup(a),this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
17
- Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,s){this._exitCallback&&this._exitCallback(new St(e,n,s)),H.default.exit(e)}action(e){let n=s=>{let i=this.registeredArguments.length,r=s.slice(0,i);return this._storeOptionsAsProperties?r[i]=this:r[i]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=n,this}createOption(e,n){return new un(e,n)}_callParseArg(e,n,s,i){try{return e.parseArg(n,s)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${i} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
18
- - already used by option '${n.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let n=i=>[i.name()].concat(i.aliases()),s=n(e).find(i=>this._findCommand(i));if(s){let i=n(this._findCommand(s)).join("|"),r=n(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),s=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let i=(r,o,a)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let c=this.getOptionValue(s);r!==null&&e.parseArg?r=this._callParseArg(e,r,c,o):r!==null&&e.variadic&&(r=e._collectValue(r,c)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,a)};return this.on("option:"+n,r=>{let o=`error: option '${e.flags}' argument '${r}' is invalid.`;i(r,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,r=>{let o=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;i(r,o,"env")}),this}_optionEx(e,n,s,i,r){if(typeof n=="object"&&n instanceof un)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,s);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(r).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(r).argParser(i)}else o.default(i);return this.addOption(o)}option(e,n,s,i){return this._optionEx({},e,n,s,i)}requiredOption(e,n,s,i){return this._optionEx({mandatory:!0},e,n,s,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,s){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(n=s.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){H.default.versions?.electron&&(n.from="electron");let i=H.default.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(n.from="eval")}e===void 0&&(e=H.default.argv),this.rawArgs=e.slice();let s;switch(n.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":H.default.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,n){this._prepareForParse();let s=this._prepareUserArgs(e,n);return this._parseCommand([],s),this}async parseAsync(e,n){this._prepareForParse();let s=this._prepareUserArgs(e,n);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17
+ Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,s){this._exitCallback&&this._exitCallback(new _t(e,n,s)),B.default.exit(e)}action(e){let n=s=>{let i=this.registeredArguments.length,r=s.slice(0,i);return this._storeOptionsAsProperties?r[i]=this:r[i]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=n,this}createOption(e,n){return new un(e,n)}_callParseArg(e,n,s,i){try{return e.parseArg(n,s)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${i} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
18
+ - already used by option '${n.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let n=i=>[i.name()].concat(i.aliases()),s=n(e).find(i=>this._findCommand(i));if(s){let i=n(this._findCommand(s)).join("|"),r=n(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),s=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let i=(r,o,a)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let c=this.getOptionValue(s);r!==null&&e.parseArg?r=this._callParseArg(e,r,c,o):r!==null&&e.variadic&&(r=e._collectValue(r,c)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,a)};return this.on("option:"+n,r=>{let o=`error: option '${e.flags}' argument '${r}' is invalid.`;i(r,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,r=>{let o=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;i(r,o,"env")}),this}_optionEx(e,n,s,i,r){if(typeof n=="object"&&n instanceof un)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,s);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(r).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(r).argParser(i)}else o.default(i);return this.addOption(o)}option(e,n,s,i){return this._optionEx({},e,n,s,i)}requiredOption(e,n,s,i){return this._optionEx({mandatory:!0},e,n,s,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,s){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(n=s.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){B.default.versions?.electron&&(n.from="electron");let i=B.default.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(n.from="eval")}e===void 0&&(e=B.default.argv),this.rawArgs=e.slice();let s;switch(n.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":B.default.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,n){this._prepareForParse();let s=this._prepareUserArgs(e,n);return this._parseCommand([],s),this}async parseAsync(e,n){this._prepareForParse();let s=this._prepareUserArgs(e,n);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
19
19
  - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,n,s){if(Dn.default.existsSync(e))return;let i=n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
20
20
  - if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
21
21
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
22
- - ${i}`;throw new Error(r)}_executeSubCommand(e,n){n=n.slice();let s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,f){let d=tt.default.resolve(u,f);if(Dn.default.existsSync(d))return d;if(s.includes(tt.default.extname(f)))return;let p=s.find(h=>Dn.default.existsSync(`${d}${h}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let u;try{u=Dn.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}o=tt.default.resolve(tt.default.dirname(u),o)}if(o){let u=i(o,r);if(!u&&!e._executableFile&&this._scriptPath){let f=tt.default.basename(this._scriptPath,tt.default.extname(this._scriptPath));f!==this._name&&(u=i(o,`${f}-${e._name}`))}r=u||r}let a=s.includes(tt.default.extname(r)),c;H.default.platform!=="win32"?a?(n.unshift(r),n=il(H.default.execArgv).concat(n),c=Ns.default.spawn(H.default.argv[0],n,{stdio:"inherit"})):c=Ns.default.spawn(r,n,{stdio:"inherit"}):(this._checkForMissingExecutable(r,o,e._name),n.unshift(r),n=il(H.default.execArgv).concat(n),c=Ns.default.spawn(H.default.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{H.default.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new St(u,"commander.executeSubCommandAsync","(close)")):H.default.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(r,o,e._name);else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!l)H.default.exit(1);else{let f=new St(1,"commander.executeSubCommandAsync","(error)");f.nestedError=u,l(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,s){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,i,"preSubcommand"),r=this._chainOrCall(r,()=>{if(i._executableHandler)this._executeSubCommand(i,n.concat(s));else return i._parseCommand(n,s)}),r}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,i,r)=>{let o=i;if(i!==null&&s.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,i,r,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((s,i)=>{let r=s.defaultValue;s.variadic?i<this.args.length?(r=this.args.slice(i),s.parseArg&&(r=r.reduce((o,a)=>e(s,a,o),s.defaultValue))):r===void 0&&(r=[]):i<this.args.length&&(r=this.args[i],s.parseArg&&(r=e(s,r,s.defaultValue))),n[i]=r}),this.processedArgs=n}_chainOrCall(e,n){return e?.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let s=e,i=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[n]!==void 0).forEach(r=>{r._lifeCycleHooks[n].forEach(o=>{i.push({hookedCommand:r,callback:o})})}),n==="postAction"&&i.reverse(),i.forEach(r=>{s=this._chainOrCall(s,()=>r.callback(r.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,n,s){let i=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(r=>{i=this._chainOrCall(i,()=>r(this,n))}),i}_parseCommand(e,n){let s=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),n=s.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,e,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(r))i(),this._processArguments(),this.parent.emit(r,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let i=s.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let i=e.find(r=>s.conflictsWith.includes(r.attributeName()));i&&this._conflictingOption(s,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],s=[],i=n;function r(u){return u.length>1&&u[0]==="-"}let o=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(f=>f.options.map(d=>d.short).some(d=>/^-\d$/.test(d))):!1,a=null,c=null,l=0;for(;l<e.length||c;){let u=c??e[l++];if(c=null,u==="--"){i===s&&i.push(u),i.push(...e.slice(l));break}if(a&&(!r(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,r(u)){let f=this._findOption(u);if(f){if(f.required){let d=e[l++];d===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,d)}else if(f.optional){let d=null;l<e.length&&(!r(e[l])||o(e[l]))&&(d=e[l++]),this.emit(`option:${f.name()}`,d)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let f=this._findOption(`-${u[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,u.slice(2)):(this.emit(`option:${f.name()}`),c=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let f=u.indexOf("="),d=this._findOption(u.slice(0,f));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(f+1));continue}}if(i===n&&r(u)&&!(this.commands.length===0&&o(u))&&(i=s),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&s.length===0){if(this._findCommand(u)){n.push(u),s.push(...e.slice(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){n.push(u,...e.slice(l));break}else if(this._defaultCommandName){s.push(u,...e.slice(l));break}}if(this._passThroughOptions){i.push(u,...e.slice(l));break}i.push(u)}return{operands:n,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let s=0;s<n;s++){let i=this.options[s].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
22
+ - ${i}`;throw new Error(r)}_executeSubCommand(e,n){n=n.slice();let s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,f){let d=tt.default.resolve(u,f);if(Dn.default.existsSync(d))return d;if(s.includes(tt.default.extname(f)))return;let p=s.find(h=>Dn.default.existsSync(`${d}${h}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let u;try{u=Dn.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}o=tt.default.resolve(tt.default.dirname(u),o)}if(o){let u=i(o,r);if(!u&&!e._executableFile&&this._scriptPath){let f=tt.default.basename(this._scriptPath,tt.default.extname(this._scriptPath));f!==this._name&&(u=i(o,`${f}-${e._name}`))}r=u||r}let a=s.includes(tt.default.extname(r)),c;B.default.platform!=="win32"?a?(n.unshift(r),n=al(B.default.execArgv).concat(n),c=Ns.default.spawn(B.default.argv[0],n,{stdio:"inherit"})):c=Ns.default.spawn(r,n,{stdio:"inherit"}):(this._checkForMissingExecutable(r,o,e._name),n.unshift(r),n=al(B.default.execArgv).concat(n),c=Ns.default.spawn(B.default.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{B.default.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new _t(u,"commander.executeSubCommandAsync","(close)")):B.default.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(r,o,e._name);else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!l)B.default.exit(1);else{let f=new _t(1,"commander.executeSubCommandAsync","(error)");f.nestedError=u,l(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,s){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,i,"preSubcommand"),r=this._chainOrCall(r,()=>{if(i._executableHandler)this._executeSubCommand(i,n.concat(s));else return i._parseCommand(n,s)}),r}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,i,r)=>{let o=i;if(i!==null&&s.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,i,r,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((s,i)=>{let r=s.defaultValue;s.variadic?i<this.args.length?(r=this.args.slice(i),s.parseArg&&(r=r.reduce((o,a)=>e(s,a,o),s.defaultValue))):r===void 0&&(r=[]):i<this.args.length&&(r=this.args[i],s.parseArg&&(r=e(s,r,s.defaultValue))),n[i]=r}),this.processedArgs=n}_chainOrCall(e,n){return e?.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let s=e,i=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[n]!==void 0).forEach(r=>{r._lifeCycleHooks[n].forEach(o=>{i.push({hookedCommand:r,callback:o})})}),n==="postAction"&&i.reverse(),i.forEach(r=>{s=this._chainOrCall(s,()=>r.callback(r.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,n,s){let i=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(r=>{i=this._chainOrCall(i,()=>r(this,n))}),i}_parseCommand(e,n){let s=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),n=s.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,e,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(r))i(),this._processArguments(),this.parent.emit(r,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let i=s.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let i=e.find(r=>s.conflictsWith.includes(r.attributeName()));i&&this._conflictingOption(s,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],s=[],i=n;function r(u){return u.length>1&&u[0]==="-"}let o=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(f=>f.options.map(d=>d.short).some(d=>/^-\d$/.test(d))):!1,a=null,c=null,l=0;for(;l<e.length||c;){let u=c??e[l++];if(c=null,u==="--"){i===s&&i.push(u),i.push(...e.slice(l));break}if(a&&(!r(u)||o(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,r(u)){let f=this._findOption(u);if(f){if(f.required){let d=e[l++];d===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,d)}else if(f.optional){let d=null;l<e.length&&(!r(e[l])||o(e[l]))&&(d=e[l++]),this.emit(`option:${f.name()}`,d)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let f=this._findOption(`-${u[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,u.slice(2)):(this.emit(`option:${f.name()}`),c=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let f=u.indexOf("="),d=this._findOption(u.slice(0,f));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(f+1));continue}}if(i===n&&r(u)&&!(this.commands.length===0&&o(u))&&(i=s),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&s.length===0){if(this._findCommand(u)){n.push(u),s.push(...e.slice(l));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){n.push(u,...e.slice(l));break}else if(this._defaultCommandName){s.push(u,...e.slice(l));break}}if(this._passThroughOptions){i.push(u,...e.slice(l));break}i.push(u)}return{operands:n,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let s=0;s<n;s++){let i=this.options[s].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
23
23
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
24
24
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
25
- `),this.outputHelp({error:!0}));let s=n||{},i=s.exitCode||1,r=s.code||"commander.error";this._exit(i,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in H.default.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,H.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ls(this.options),n=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&n(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(i=>!n(i)).forEach(i=>{this.setOptionValueWithSource(i,s.implied[i],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let s=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(f=>f.negate&&a===f.attributeName()),u=this.options.find(f=>!f.negate&&a===f.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},i=o=>{let a=s(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${i(e)} cannot be used with ${i(n)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);i=i.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);n=or(e,i)}let s=`error: unknown option '${e}'${n}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,s=n===1?"":"s",i=e.length,r=this.parent?` for '${this.name()}'`:"",o=e.join(", "),a=`error: too many arguments${r}. Expected ${n} argument${s} but got ${i}: ${o}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(r=>{i.push(r.name()),r.alias()&&i.push(r.alias())}),n=or(e,i)}let s=`error: unknown command '${e}'${n}`;this.error(s,{code:"commander.unknownCommand"})}version(e,n,s){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",s=s||"output the version number";let i=this.createOption(n,s);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
- `),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let i=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(s=>Os(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=tt.default.basename(e,tt.default.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp(),s=this._getOutputContext(e);n.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let i=n.formatHelp(this,n);return s.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let n=!!e.error,s,i,r;return n?(s=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:i,helpWidth:r}}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let s=this._getOutputContext(e),i={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let r=this.helpInformation({error:s.error});if(n&&(r=n(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,n){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",n??"display help for command"),(e||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let n=Number(H.default.exitCode??0);n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
25
+ `),this.outputHelp({error:!0}));let s=n||{},i=s.exitCode||1,r=s.code||"commander.error";this._exit(i,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in B.default.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,B.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ls(this.options),n=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&n(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(i=>!n(i)).forEach(i=>{this.setOptionValueWithSource(i,s.implied[i],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let s=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(f=>f.negate&&a===f.attributeName()),u=this.options.find(f=>!f.negate&&a===f.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},i=o=>{let a=s(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${i(e)} cannot be used with ${i(n)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);i=i.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);n=cr(e,i)}let s=`error: unknown option '${e}'${n}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,s=n===1?"":"s",i=e.length,r=this.parent?` for '${this.name()}'`:"",o=e.join(", "),a=`error: too many arguments${r}. Expected ${n} argument${s} but got ${i}: ${o}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(r=>{i.push(r.name()),r.alias()&&i.push(r.alias())}),n=cr(e,i)}let s=`error: unknown command '${e}'${n}`;this.error(s,{code:"commander.unknownCommand"})}version(e,n,s){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",s=s||"output the version number";let i=this.createOption(n,s);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
26
+ `),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let i=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(s=>Os(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=tt.default.basename(e,tt.default.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp(),s=this._getOutputContext(e);n.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let i=n.formatHelp(this,n);return s.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let n=!!e.error,s,i,r;return n?(s=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:i,helpWidth:r}}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let s=this._getOutputContext(e),i={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let r=this.helpInformation({error:s.error});if(n&&(r=n(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,n){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",n??"display help for command"),(e||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let n=Number(B.default.exitCode??0);n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
27
27
  Expecting one of '${s.join("', '")}'`);let i=`${e}Help`;return this.on(i,r=>{let o;typeof n=="function"?o=n({error:r.error,command:r.command}):o=n,o&&r.write(`${o}
28
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(i=>n.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function il(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,s="127.0.0.1",i="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?n=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=r[1],/^\d+$/.test(r[3])?i=r[3]:s=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=r[1],s=r[3],i=r[4]),n&&i!=="0"?`${n}=${s}:${parseInt(i)+1}`:e})}function rl(){if(H.default.env.NO_COLOR||H.default.env.FORCE_COLOR==="0"||H.default.env.FORCE_COLOR==="false")return!1;if(H.default.env.FORCE_COLOR||H.default.env.CLICOLOR_FORCE!==void 0)return!0}var _1=new fn;var jt=x(require("node:fs/promises"),1),xt=x(require("node:path"),1);var Ce=new Set(["claude","agents","cursor","windsurf","copilot","gemini","cline","persona","prompt"]),Kg=new Set(["skill","agent"]);function cl(t){return Kg.has(t)}var js=["auto","typescript","nextjs","unity","dotnet","python","go","rust","unknown"];var ld=x(wn(),1),qn=x(require("node:fs"),1),di=x(require("node:fs/promises"),1),Le=x(require("node:path"),1);var o0=/^ {0,3}([`~]{3,})\s*([^\s`]*)/,a0=/^ {0,3}([`~]{3,})\s*$/,ed=/(`+)([^`]+)\1/g;function xe(t){let e=t.split(`
29
- `),n=[],s=!1,i=null,r=0,o="",a=-1;for(let c=0;c<e.length;c++){let l=e[c]??"",u=c+1;if(!s){let d=o0.exec(l);if(d){s=!0,i=d[1][0]??null,r=d[1].length,o=(d[2]??"").toLowerCase(),a=n.length,n.push({text:l,lineNumber:u,kind:"open",inFence:!0,lang:o,closed:!0});continue}n.push({text:l,lineNumber:u,kind:"text",inFence:!1,lang:"",closed:!0});continue}let f=a0.exec(l);if(f&&f[1][0]===i&&f[1].length>=r){n.push({text:l,lineNumber:u,kind:"close",inFence:!0,lang:o,closed:!0}),s=!1,i=null,r=0,o="",a=-1;continue}n.push({text:l,lineNumber:u,kind:"content",inFence:!0,lang:o,closed:!0})}if(s&&a>=0)for(let c=a;c<n.length;c++)n[c].closed=!1;return n}function Vn(t){let e=[],n=null;for(let s of xe(t)){if(s.kind==="open"){n={lang:s.lang,closed:s.closed,openLine:s.lineNumber,contentStartLine:s.lineNumber+1,lines:[]},e.push(n);continue}if(s.kind==="content"&&n){n.lines.push(s.text);continue}s.kind==="close"&&(n=null)}return e}function Ke(t,e={}){let n=xe(t).filter(s=>!s.inFence).map(s=>s.text).join(`
30
- `);return e.stripInlineCode?n.replace(/`[^`\n]+`/g,""):n}function td(t){return xe(t).map(e=>e.inFence?"":e.text).join(`
31
- `)}function nd(t,e={}){let n=e.closedOnly??!0;return Vn(t).filter(s=>n?s.closed:!0).map(s=>s.lines.join(`
28
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(i=>n.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function al(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,s="127.0.0.1",i="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?n=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=r[1],/^\d+$/.test(r[3])?i=r[3]:s=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=r[1],s=r[3],i=r[4]),n&&i!=="0"?`${n}=${s}:${parseInt(i)+1}`:e})}function cl(){if(B.default.env.NO_COLOR||B.default.env.FORCE_COLOR==="0"||B.default.env.FORCE_COLOR==="false")return!1;if(B.default.env.FORCE_COLOR||B.default.env.CLICOLOR_FORCE!==void 0)return!0}var C1=new fn;var Mt=x(require("node:fs/promises"),1),xt=x(require("node:path"),1);var Ce=new Set(["claude","agents","cursor","windsurf","copilot","gemini","cline","persona","prompt"]),Qg=new Set(["skill","agent"]);function fl(t){return Qg.has(t)}var js=["auto","typescript","nextjs","unity","dotnet","python","go","rust","unknown"];var dd=x(wn(),1),qn=x(require("node:fs"),1),di=x(require("node:fs/promises"),1),Le=x(require("node:path"),1);var f0=/^ {0,3}([`~]{3,})\s*([^\s`]*)/,d0=/^ {0,3}([`~]{3,})\s*$/,sd=/(`+)([^`]+)\1/g;function xe(t){let e=t.split(`
29
+ `),n=[],s=!1,i=null,r=0,o="",a=-1;for(let c=0;c<e.length;c++){let l=e[c]??"",u=c+1;if(!s){let d=f0.exec(l);if(d){s=!0,i=d[1][0]??null,r=d[1].length,o=(d[2]??"").toLowerCase(),a=n.length,n.push({text:l,lineNumber:u,kind:"open",inFence:!0,lang:o,closed:!0});continue}n.push({text:l,lineNumber:u,kind:"text",inFence:!1,lang:"",closed:!0});continue}let f=d0.exec(l);if(f&&f[1][0]===i&&f[1].length>=r){n.push({text:l,lineNumber:u,kind:"close",inFence:!0,lang:o,closed:!0}),s=!1,i=null,r=0,o="",a=-1;continue}n.push({text:l,lineNumber:u,kind:"content",inFence:!0,lang:o,closed:!0})}if(s&&a>=0)for(let c=a;c<n.length;c++)n[c].closed=!1;return n}function Vn(t){let e=[],n=null;for(let s of xe(t)){if(s.kind==="open"){n={lang:s.lang,closed:s.closed,openLine:s.lineNumber,contentStartLine:s.lineNumber+1,lines:[]},e.push(n);continue}if(s.kind==="content"&&n){n.lines.push(s.text);continue}s.kind==="close"&&(n=null)}return e}function Ke(t,e={}){let n=xe(t).filter(s=>!s.inFence).map(s=>s.text).join(`
30
+ `);return e.stripInlineCode?n.replace(/`[^`\n]+`/g,""):n}function id(t){return xe(t).map(e=>e.inFence?"":e.text).join(`
31
+ `)}function rd(t,e={}){let n=e.closedOnly??!0;return Vn(t).filter(s=>n?s.closed:!0).map(s=>s.lines.join(`
32
32
  `)).join(`
33
- `)}function sd(t){let e=new Array(t.length).fill(!1),n=0;for(let s of xe(t)){if(s.inFence)e.fill(!0,n,n+s.text.length);else{let i,r=new RegExp(ed.source,ed.flags);for(;(i=r.exec(s.text))!==null;)e.fill(!0,n+i.index,n+i.index+i[0].length)}n+=s.text.length+1}return e}var fi=x(require("node:fs"),1),oe=x(require("node:path"),1);function se(t,e){let n=oe.resolve(t),s=oe.resolve(e),i=oe.relative(n,s);return i===""||i!==".."&&!i.startsWith(`..${oe.sep}`)&&!oe.isAbsolute(i)}function It(t,e){try{let n=oe.resolve(t),s=oe.isAbsolute(e)?oe.resolve(e):oe.resolve(n,e);return se(n,s)?s:null}catch{return null}}function vn(t){try{let e=fi.realpathSync.native(t);return typeof e=="string"?e:null}catch{return null}}function ae(t,e){let n=vn(e);if(n===null)return!0;let s=vn(t)??oe.resolve(t);return se(s,n)}function K(t,e){let n=It(t,e);return n===null?null:ae(t,n)?n:null}function zn(t,e){let n=oe.resolve(e);if(!se(t,n))return!0;let s=n;for(;;){if(vn(s)!==null)return ae(t,s);try{if(fi.lstatSync(s).isSymbolicLink())return!1}catch{}let i=oe.dirname(s);if(i===s)return!0;s=i}}var mt=x(require("node:fs"),1),ge=x(require("node:path"),1),c0=1024*1024,l0=128*1024*1024,u0=2e6,f0=24;function d0(t){let e=ge.resolve(t);for(let n=0;n<f0;n++){let s=ge.join(e,".git");try{let r=mt.statSync(s);if(r.isDirectory())return{workTree:e,gitDir:s,commonDir:s};if(r.isFile()&&r.size<4096){let o=/^gitdir:\s*(.+?)\s*$/m.exec(mt.readFileSync(s,"utf8"))?.[1];if(o){let a=ge.resolve(e,o),c=a;try{let l=mt.readFileSync(ge.join(a,"commondir"),"utf8").trim();l&&(c=ge.resolve(a,l))}catch{}return{workTree:e,gitDir:a,commonDir:c}}}}catch{}let i=ge.dirname(e);if(i===e)break;e=i}}function p0(t){let e=!1,n;for(let s of t.split(/\r?\n/)){let i=s.trim(),r=/^\[\s*([A-Za-z0-9.-]+)(?:\s+"[^"]*")?\s*\]/.exec(i);if(r){e=r[1].toLowerCase()==="core"&&!i.includes('"');continue}if(!e)continue;let o=/^symlinks\s*(?:=\s*(.*?))?\s*(?:[;#].*)?$/i.exec(i);o&&(n=o[1]===void 0?"true":o[1].replace(/^"|"$/g,"").trim())}return n!==void 0&&/^(?:false|no|off|0)$/i.test(n)}function h0(t){if(t.length<12||t.toString("latin1",0,4)!=="DIRC")return;let e=t.readUInt32BE(4);if(e!==2&&e!==3)return;let n=t.readUInt32BE(8);if(n>u0)return;let s=new Set,i=12;for(let r=0;r<n;r++){if(i+62>t.length)return;let o=t.readUInt32BE(i+24),a=t.readUInt16BE(i+60),l=e===3&&(a&16384)!==0?64:62,u=a&4095;if(u===4095){let f=t.indexOf(0,i+l);if(f<0)return;u=f-(i+l)}if(i+l+u>t.length)return;(o&61440)===40960&&s.add(t.toString("utf8",i+l,i+l+u)),i+=Math.ceil((l+u+1)/8)*8}return s}function id(t){let e,n=()=>{if(e!==void 0)return e;e=null;let s=d0(t);if(!s)return e;let i=!1;try{let o=ge.join(s.commonDir,"config");mt.statSync(o).size<=c0&&(i=p0(mt.readFileSync(o,"utf8")))}catch{}let r;try{let o=ge.join(s.gitDir,"index");mt.statSync(o).size<=l0&&(r=h0(mt.readFileSync(o)))}catch{}return e={git:s,links:r,configFalse:i},e};return{isSymlink(s){let i=n();if(!i)return!1;if(i.links){let r=ge.relative(i.git.workTree,ge.resolve(t,s)).split(ge.sep).join("/");return i.links.has(r)}return i.configFalse}}}var rd=["CLAUDE.md","AGENTS.md",".cursorrules",".windsurfrules","GEMINI.md",".clinerules",".clinerules/**/*.md","!.clinerules/workflows/**","SOUL.md","USER.md","TOOLS.md",".cursor/rules/**",".github/copilot-instructions.md",".github/instructions/**/*.md",".claude/**/*.md","README.md","QA.md","CONTRIBUTING.md","ARCHITECTURE.md","DEVELOPMENT.md","CODING_STANDARDS.md","CONVENTIONS.md","GUIDELINES.md","ai/**/*.md","ai-instructions/**/*.md","prompts/**/*.md","system-prompts/**/*.md"],m0=[".git","node_modules","Library","Temp","bin","obj","dist","build","worktrees",".worktrees"],ce=500*1024,Kn=512,g0=new Set(["/SOUL.md","/USER.md","/TOOLS.md"]);function y0(t){let e="/"+t.replace(/\\/g,"/").replace(/^\/+/,""),n=e.slice(e.lastIndexOf("/")+1);return n==="AGENTS.md"?"agents":n===".cursorrules"||e.includes("/.cursor/rules/")?"cursor":n===".windsurfrules"?"windsurf":n==="copilot-instructions.md"||e.includes("/.github/instructions/")?"copilot":e==="/GEMINI.md"?"gemini":e==="/.clinerules"||e.startsWith("/.clinerules/")?"cline":g0.has(e)?"persona":e.includes("/.claude/agents/")?"agent":e.includes("/.claude/skills/")?"skill":n==="CLAUDE.md"||e.includes("/.claude/")?"claude":n==="README.md"?"readme":e.includes("/docs/")&&n.endsWith(".md")?"docs":(e.includes("/ai/")||e.includes("/prompts/"))&&n.endsWith(".md")?"prompt":"unknown"}function b0(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function ud(t){let e=t.split(`
33
+ `)}function od(t){let e=new Array(t.length).fill(!1),n=0;for(let s of xe(t)){if(s.inFence)e.fill(!0,n,n+s.text.length);else{let i,r=new RegExp(sd.source,sd.flags);for(;(i=r.exec(s.text))!==null;)e.fill(!0,n+i.index,n+i.index+i[0].length)}n+=s.text.length+1}return e}var fi=x(require("node:fs"),1),oe=x(require("node:path"),1);function X(t,e){let n=oe.resolve(t),s=oe.resolve(e),i=oe.relative(n,s);return i===""||i!==".."&&!i.startsWith(`..${oe.sep}`)&&!oe.isAbsolute(i)}function Ot(t,e){try{let n=oe.resolve(t),s=oe.isAbsolute(e)?oe.resolve(e):oe.resolve(n,e);return X(n,s)?s:null}catch{return null}}function It(t){try{let e=fi.realpathSync.native(t);return typeof e=="string"?e:null}catch{return null}}function ae(t,e){let n=It(e);if(n===null)return!0;let s=It(t)??oe.resolve(t);return X(s,n)}function J(t,e){let n=Ot(t,e);return n===null?null:ae(t,n)?n:null}function zn(t,e){let n=oe.resolve(e);if(!X(t,n))return!0;let s=n;for(;;){if(It(s)!==null)return ae(t,s);try{if(fi.lstatSync(s).isSymbolicLink())return!1}catch{}let i=oe.dirname(s);if(i===s)return!0;s=i}}var mt=x(require("node:fs"),1),ge=x(require("node:path"),1),p0=1024*1024,h0=128*1024*1024,m0=2e6,g0=24;function y0(t){let e=ge.resolve(t);for(let n=0;n<g0;n++){let s=ge.join(e,".git");try{let r=mt.statSync(s);if(r.isDirectory())return{workTree:e,gitDir:s,commonDir:s};if(r.isFile()&&r.size<4096){let o=/^gitdir:\s*(.+?)\s*$/m.exec(mt.readFileSync(s,"utf8"))?.[1];if(o){let a=ge.resolve(e,o),c=a;try{let l=mt.readFileSync(ge.join(a,"commondir"),"utf8").trim();l&&(c=ge.resolve(a,l))}catch{}return{workTree:e,gitDir:a,commonDir:c}}}}catch{}let i=ge.dirname(e);if(i===e)break;e=i}}function b0(t){let e=!1,n;for(let s of t.split(/\r?\n/)){let i=s.trim(),r=/^\[\s*([A-Za-z0-9.-]+)(?:\s+"[^"]*")?\s*\]/.exec(i);if(r){e=r[1].toLowerCase()==="core"&&!i.includes('"');continue}if(!e)continue;let o=/^symlinks\s*(?:=\s*(.*?))?\s*(?:[;#].*)?$/i.exec(i);o&&(n=o[1]===void 0?"true":o[1].replace(/^"|"$/g,"").trim())}return n!==void 0&&/^(?:false|no|off|0)$/i.test(n)}function w0(t){if(t.length<12||t.toString("latin1",0,4)!=="DIRC")return;let e=t.readUInt32BE(4);if(e!==2&&e!==3)return;let n=t.readUInt32BE(8);if(n>m0)return;let s=new Set,i=12;for(let r=0;r<n;r++){if(i+62>t.length)return;let o=t.readUInt32BE(i+24),a=t.readUInt16BE(i+60),l=e===3&&(a&16384)!==0?64:62,u=a&4095;if(u===4095){let f=t.indexOf(0,i+l);if(f<0)return;u=f-(i+l)}if(i+l+u>t.length)return;(o&61440)===40960&&s.add(t.toString("utf8",i+l,i+l+u)),i+=Math.ceil((l+u+1)/8)*8}return s}function ad(t){let e,n=()=>{if(e!==void 0)return e;e=null;let s=y0(t);if(!s)return e;let i=!1;try{let o=ge.join(s.commonDir,"config");mt.statSync(o).size<=p0&&(i=b0(mt.readFileSync(o,"utf8")))}catch{}let r;try{let o=ge.join(s.gitDir,"index");mt.statSync(o).size<=h0&&(r=w0(mt.readFileSync(o)))}catch{}return e={git:s,links:r,configFalse:i},e};return{isSymlink(s){let i=n();if(!i)return!1;if(i.links){let r=ge.relative(i.git.workTree,ge.resolve(t,s)).split(ge.sep).join("/");return i.links.has(r)}return i.configFalse}}}var cd=["CLAUDE.md","AGENTS.md",".cursorrules",".windsurfrules","GEMINI.md",".clinerules",".clinerules/**/*.md","!.clinerules/workflows/**","SOUL.md","USER.md","TOOLS.md",".cursor/rules/**",".github/copilot-instructions.md",".github/instructions/**/*.md",".claude/**/*.md","README.md","QA.md","CONTRIBUTING.md","ARCHITECTURE.md","DEVELOPMENT.md","CODING_STANDARDS.md","CONVENTIONS.md","GUIDELINES.md","ai/**/*.md","ai-instructions/**/*.md","prompts/**/*.md","system-prompts/**/*.md"],v0=[".git","node_modules","Library","Temp","bin","obj","dist","build","worktrees",".worktrees"],ce=500*1024,Kn=512,x0=new Set(["/SOUL.md","/USER.md","/TOOLS.md"]);function S0(t){let e="/"+t.replace(/\\/g,"/").replace(/^\/+/,""),n=e.slice(e.lastIndexOf("/")+1);return n==="AGENTS.md"?"agents":n===".cursorrules"||e.includes("/.cursor/rules/")?"cursor":n===".windsurfrules"?"windsurf":n==="copilot-instructions.md"||e.includes("/.github/instructions/")?"copilot":e==="/GEMINI.md"?"gemini":e==="/.clinerules"||e.startsWith("/.clinerules/")?"cline":x0.has(e)?"persona":e.includes("/.claude/agents/")?"agent":e.includes("/.claude/skills/")?"skill":n==="CLAUDE.md"||e.includes("/.claude/")?"claude":n==="README.md"?"readme":e.includes("/docs/")&&n.endsWith(".md")?"docs":(e.includes("/ai/")||e.includes("/prompts/"))&&n.endsWith(".md")?"prompt":"unknown"}function _0(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function pd(t){let e=t.split(`
34
34
  `);return t.length>0&&t.endsWith(`
35
- `)&&e.pop(),e}function Ut(t,e,n){let s=ud(t),i=[],r,o=1,a=[],c=u=>{let f=a.join(`
36
- `),d=r!==void 0?b0(r):`${e}:0`;i.push({id:d,filePath:e,...n!==void 0?{relativePath:n}:{},heading:r,startLine:o,endLine:u,text:f,normalizedText:f.toLowerCase().trim()})},l=xe(t);for(let u=0;u<s.length;u++){let f=u+1,d=s[u]??"";if(l[u]?.inFence){a.push(d);continue}let p=/^ {0,3}(#{1,3})\s+(.+)/.exec(d);p?((a.length>0||r!==void 0)&&c(f-1),r=p[2].trim(),o=f,a=[d]):a.push(d)}return(a.length>0||r!==void 0)&&c(s.length),i}function Vt(t){let e=Math.min(t.length,Kn);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var w0=new Set([".clinerules/**/*.md","!.clinerules/workflows/**"]);async function v0(t){let e=!1;try{e=(await di.stat(Le.join(t,".clinerules"))).isDirectory()}catch{}return e?rd:rd.filter(n=>!w0.has(n))}function fd(t){try{return qn.realpathSync.native(t)}catch{return null}}async function od(t,e,n,s){let i=fd(n);if(i===null||!se(e,i))return;let r;try{let o=qn.constants.O_NOFOLLOW??0;r=await di.open(i,qn.constants.O_RDONLY|o);let a=await r.stat();if(!a.isFile()||a.size>ce)return;let c=await r.readFile();if(Vt(c))return;let l=c.toString("utf-8"),u=Le.relative(t,n).replace(/\\/g,"/"),f=Ut(l,n,u),d=ud(l).length,p=l.length;return{path:n,relativePath:u,fileType:y0(s),content:l,sections:f,lineCount:d,charCount:p,estimatedTokens:Math.round(p/4)}}catch{return}finally{await r?.close().catch(()=>{})}}var ad=260,x0=8;function _0(t,e,n){let s=t.relativePath;if(s===void 0||t.charCount>ad+16)return;let i=t.content.replace(/^\u{FEFF}/u,"").trim();if(i===""||i.length>ad||/[\r\n]/.test(i)||i.startsWith("/")||/^[A-Za-z]:/.test(i)||i.includes("\\"))return;let r=Le.posix.normalize(Le.posix.join(Le.posix.dirname(s),i));if(!(r===".."||r.startsWith("../")||r===s||!e.has(r)))return n.isSymlink(s)?r:void 0}function cd(t,e){return{...e,path:t.path,relativePath:t.relativePath,fileType:t.fileType,sections:Ut(e.content,t.path,t.relativePath),aliasOf:e.relativePath}}function S0(t,e,n){let s=new Map;for(let c of t)c.relativePath!==void 0&&s.set(c.relativePath,c);let i=new Map;for(let c of t){let l=_0(c,s,n);l!==void 0&&i.set(c.relativePath,l)}if(i.size===0)return{files:t,aliases:e};let r=new Map;for(let c of i.keys()){let l=i.get(c),u=1;for(;i.has(l)&&u<x0;)l=i.get(l),u++;i.has(l)||r.set(c,s.get(l))}if(r.size===0)return{files:t,aliases:e};let o=t.filter(c=>c.relativePath===void 0||!r.has(c.relativePath)),a=e.map(c=>{let l=c.aliasOf===void 0?void 0:r.get(c.aliasOf);return l===void 0?c:cd(c,l)});for(let[c,l]of r)a.push(cd(s.get(c),l));return{files:o,aliases:a}}async function pi(t){let e=Le.resolve(t.repoPath),n=fd(e)??e,s=t.include&&t.include.length>0?t.include:await v0(e),i=[...m0.map(p=>`**/${p}/**`),...t.exclude??[]],r;try{r=await(0,ld.default)(s,{cwd:e,ignore:i,dot:!0,absolute:!1,onlyFiles:!1,objectMode:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{return{files:[],aliases:[]}}let o=[],a=[];for(let p of r)p.dirent.isSymbolicLink()?a.push(p.path):p.dirent.isFile()&&o.push(p.path);a.sort();let c=[],l=[],u=new Map,f=[];for(let p of o){let h=Le.resolve(e,p);if(!se(e,h)||!ae(e,h))continue;let m=vn(h);f.push({relPath:p,absPath:h,real:m,direct:m!==null&&m===Le.join(n,p)})}f.sort((p,h)=>Number(h.direct)-Number(p.direct)||p.relPath.localeCompare(h.relPath));for(let{relPath:p,absPath:h,real:m}of f){let g=await od(e,n,h,p);if(!g)continue;let b=m!==null?u.get(m):void 0;if(b){l.push({...g,aliasOf:b.relativePath});continue}c.push(g),m!==null&&u.set(m,g)}for(let p of a){let h=Le.resolve(e,p);if(!se(e,h)||!ae(e,h))continue;let m=await od(e,n,h,p);if(!m)continue;let g=vn(h),b=g!==null?u.get(g):void 0;if(b){l.push({...m,aliasOf:b.relativePath});continue}c.push(m),g!==null&&u.set(g,m)}let d=S0(c,l,id(e));return d.files.sort((p,h)=>p.path.localeCompare(h.path)),d.aliases.sort((p,h)=>p.path.localeCompare(h.path)),d}async function zo(t){return(await pi(t)).files}var hi=x(require("node:fs/promises"),1),ye=x(require("node:path"),1),Ko=x(wn(),1);async function ot(t){try{return await hi.access(t),!0}catch{return!1}}async function qo(t){try{return(await hi.stat(t)).isDirectory()}catch{return!1}}async function Yn(t){let e=ye.resolve(t);if((await(0,Ko.default)("next.config.*",{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"nextjs";let s=await ot(ye.join(e,"package.json"));if(s){let m=await qo(ye.join(e,"app")),g=await qo(ye.join(e,"pages"));if(m||g)return"nextjs"}let i=await qo(ye.join(e,"Assets")),r=await ot(ye.join(e,"ProjectSettings","ProjectVersion.txt"));if(i&&r)return"unity";if((await(0,Ko.default)(["*.sln","*.csproj"],{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"dotnet";let a=await ot(ye.join(e,"tsconfig.json"));if(s||a)return"typescript";let c=await ot(ye.join(e,"pyproject.toml")),l=await ot(ye.join(e,"requirements.txt")),u=await ot(ye.join(e,"Pipfile")),f=await ot(ye.join(e,"environment.yml")),d=await ot(ye.join(e,"setup.py"));return c||l||u||f||d?"python":await ot(ye.join(e,"go.mod"))?"go":await ot(ye.join(e,"Cargo.toml"))?"rust":"unknown"}function Yo(t){let e=t.map(n=>n.content).join(`
37
- `);return/\bnext\.?js\b|\bapp\s+router\b|\bpages?\s+router\b|\bnext\s+build\b|\bnext\s+dev\b/i.test(e)?"nextjs":/\bunity\b/i.test(e)&&/\b(lts|editor|hub|engine)\b/i.test(e)||/\bmonobehaviour\b|\bunityengine\b|\bgameobject\b|\bprefab\b|\bscriptableobject\b/i.test(e)?"unity":/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(e)?"dotnet":/\btypescript\b|\btsconfig\b|\btsc\s|\bpnpm\b|\bnpm\s+run\b|\bvitest\b|\bjest\b/i.test(e)?"typescript":/\bpython\b|\bpip\b|\bpoetry\b|\bvenv\b|\bpytest\b|\bpyproject\.toml\b/i.test(e)?"python":/\bgo\.mod\b|\bgo\s+(build|test|run|get|mod)\b|\bgolang\b/i.test(e)?"go":/\bcargo\.toml\b|\bcargo\s+(build|test|run|clippy|fmt)\b|\brustc\b/i.test(e)?"rust":"unknown"}var md=x(require("node:crypto"),1);var E0=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}]/u;function mi(t){return`<U+${t.toString(16).toUpperCase().padStart(4,"0")}>`}function k0(t,e=t.codePointAt(0)){return e===9||e>=32&&e<127?!1:E0.test(t)||e===8232||e===8233||e===12644||e===65440||e===4447||e===4448||e===847||e===6068||e===6069||e>=65024&&e<=65039||e>=917760&&e<=917999||e>=6155&&e<=6159}function gi(t){let e="",n="",s=()=>{n&&(e+=`<TAGS:"${n}">`),n=""};for(let i of t){let r=i.codePointAt(0);if(r>=917504&&r<=917631){n+=r>=917536&&r<=917630?String.fromCharCode(r-917504):mi(r);continue}s(),e+=k0(i,r)?mi(r):i}return s(),e}function q(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function R0(t,e,n=120){let i=new RegExp(e.source,e.flags.replace("g","")).exec(t);return i?q(i[0],n):void 0}function xn(t,e,n,s=120){let i=R0(t,e,s);return i?`${n}: "${i}"`:n}function dd(t){return t.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function L(t){return dd(t.relativePath??t.path)}function Be(t){return dd(t.relativePath??t.filePath)}var yi=150,C0=80,A0=10,$0=.8,P0=.6,T0=.6,pd=new Set(["introduction","overview","notes","note","about","background","context","disclaimer","warning","important","readme","summary","project summary","project overview","project description","description","what is this","table of contents","contents","license","changelog"]);function gd(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}function Jo(t){let e=t.match(/\b\w+\b/g)??[];return new Set(e)}function I0(t,e){if(t.size===0&&e.size===0)return 1;if(t.size===0||e.size===0)return 0;let n=0;for(let s of t)e.has(s)&&n++;return n/(t.size+e.size-n)}function Xo(t){if(!t)return!1;let e=t.toLowerCase().trim();if(pd.has(e))return!0;for(let n of pd)if(e.startsWith(n))return!0;return!1}function hd(t){return t?.toLowerCase().replace(/\s+/g," ").trim()??""}function O0(t,e){let n=hd(t.heading),s=hd(e.heading);return n.length>0&&n===s}function Jn(t,e){if(!t.has(e))return e;let n=Jn(t,t.get(e));return t.set(e,n),n}function L0(t,e,n){let s=Jn(t,e),i=Jn(t,n);s!==i&&t.set(s,i)}function Zo(t){let e=[...t].sort().join("|");return`duplicate-${md.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Qo(t){let e=[];for(let u of t)for(let f of u.sections){let d=gd(f.text);d.length<C0||Jo(d).size<A0||e.push({...f,normalizedText:d})}let n=new Map,s=new Map,i=[];for(let u=0;u<e.length;u++)for(let f=u+1;f<e.length;f++){let d=e[u],p=e[f];if(d.filePath===p.filePath&&d.startLine===p.startLine)continue;let h=`${Be(d)}:${d.startLine}`,m=`${Be(p)}:${p.startLine}`,g=d.normalizedText,b=p.normalizedText,w=null,y=0;if(Xo(d.heading)||Xo(p.heading))continue;let v=d.filePath===p.filePath;if(g===b){if(!v&&(g.length<yi||b.length<yi)&&!O0(d,p))continue;w="high",y=.95}else{if(!v&&(g.length<yi||b.length<yi))continue;let k=v?T0:$0,R=I0(Jo(g),Jo(b));R>=k?(w="warning",y=v?.8:.75):!v&&R>=P0&&(w="info",y=.5)}w!==null&&(s.set(h,d),s.set(m,p),L0(n,h,m),i.push({keyA:h,keyB:m,severity:w,confidence:y}))}let r=new Map;for(let u of s.keys()){let f=Jn(n,u);r.has(f)||r.set(f,[]),r.get(f).push(u)}let o={info:0,warning:1,high:2,critical:3},a=new Map,c=new Map;for(let u of i){let f=Jn(n,u.keyA),d=a.get(f);(!d||o[u.severity]>o[d])&&(a.set(f,u.severity),c.set(f,u.confidence))}let l=[];for(let[u,f]of r){if(f.length<2)continue;let d=f.map(R=>s.get(R)),p=a.get(u)??"warning",h=c.get(u)??.75,m=[...new Set(d.map(R=>R.filePath))],g=[...new Set(d.map(R=>R.heading??"(untitled)"))],b=g.length===1?g[0]:g.slice(0,2).join(" / "),w=m.length,y=w>2?`Possible duplicate: ${b} (${w} files)`:`Possible duplicate: ${b}`,v=d.slice(1).reduce((R,I)=>R+Math.round(I.text.length/4),0),k=w>2?`This section appears highly similar in ${w} files. Consider consolidating into one canonical location.`:"These sections appear highly similar. Consider consolidating them into one canonical location.";l.push({id:Zo(f),severity:p,category:"duplicate",title:y,summary:k,filePaths:m,locations:d.map(R=>({filePath:R.filePath,startLine:R.startLine,endLine:R.endLine})),evidence:[q(d[0].normalizedText,200),`Duplicated size: ~${v} tokens`],recommendation:`Consolidate these sections into one canonical location (e.g. AGENTS.md) and use forwarding pointers to save ~${v} tokens per session. If both are intentional, add a comment clarifying the distinction.`,autoApplySafe:w>=2,confidence:h})}return l}function ea(t){let e=[];for(let n of t){let s=new Map;for(let o of n.sections){if(!o.heading||Xo(o.heading))continue;let a=o.heading.toLowerCase().replace(/^#+\s*/,"").replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim();a.length<3||(s.has(a)||s.set(a,[]),s.get(a).push(o))}for(let[,o]of s){if(o.length<2||new Set(o.map(f=>{let d=/^(#{1,6})\s/.exec(f.text);return d?d[1].length:0})).size>1)continue;let c=o.map(f=>`${L(n)}:${f.startLine}`),l=Zo(c),u=o[0].heading??"(untitled)";e.push({id:l,severity:"warning",category:"duplicate",title:`Duplicate section heading in one file: "${u}"`,summary:`The heading "${u}" appears ${o.length} times in this file. This is likely an accidental duplicate \u2014 consider consolidating into one section.`,filePaths:[n.path],locations:o.map(f=>({filePath:n.path,startLine:f.startLine,endLine:f.endLine})),evidence:[`Heading "${u}" found at lines: ${o.map(f=>f.startLine).join(", ")}`],recommendation:"Merge the duplicate sections into one, or rename one if the distinction is intentional.",confidence:.85})}let i=[...s.keys()],r=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a],u=c.length<=l.length?c:l,f=c.length<=l.length?l:c;if(u.length<4||!f.startsWith(u))continue;let d=f.slice(u.length);if(!/^\s/.test(d)||!d.trimStart())continue;let h=[c,l].sort().join("|");if(r.has(h))continue;r.add(h);let m=s.get(c),g=s.get(l),b=[...m,...g].sort((y,v)=>y.startLine-v.startLine),w=b.map(y=>`${L(n)}:${y.startLine}`);e.push({id:Zo(w),severity:"warning",category:"duplicate",title:`Overlapping section headings in one file: "${m[0].heading}" / "${g[0].heading}"`,summary:"These section headings appear to cover the same topic \u2014 one is a prefix/subset of the other. This is likely an accidental split. Consider merging into one canonical section.",filePaths:[n.path],locations:b.map(y=>({filePath:n.path,startLine:y.startLine,endLine:y.endLine})),evidence:[`"${m[0].heading}" at line ${m[0].startLine}`,`"${g[0].heading}" at line ${g[0].startLine}`],recommendation:"Consolidate these sections into one. If the distinction is intentional, rename one to make the difference clear.",confidence:.75})}}return e}var wi=x(require("node:crypto"),1),ta=x(require("node:path"),1);var N0=1,kd=new Set(["for","to","when","in","with","as","from","the","and","or","but","if","are","is","has","have","had","will","was","were","by","of","at","on","an","a","all","any","this","that","these","those","our","your","their","its","so","than","be"]),j0=new Set(["for","when","if","unless","except"]),M0=new Set(["it","them","they","we","code","sure","careful","good","clean","simple","easy","proper","consistent","clear","correct","possible","necessary","appropriate"]),Rd=new Set(["use","run","write","call","create","add","implement","put","keep","follow","apply","make","define","ensure","check","test","build","deploy","configure","handle","prefer","avoid","include","return","pass","store","log","load","fetch","set","get","import"]);function yd(t,e,n=3,s=!1){let i=t.slice(e).replace(/^\s+/,"");if(s){let a=/^([a-zA-Z]+)\s+/.exec(i);a&&Rd.has(a[1].toLowerCase())&&(i=i.slice(a[0].length))}let r=[],o=i.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim();for(let a of o.split(/\s+/)){let c=a.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g,"").toLowerCase();if(c&&(kd.has(c)||!/^[a-z]/i.test(c)&&!/^[0-9]+[a-z]/i.test(c)||(r.push(c),r.length>=n)))break}return r.join(" ")}var Xn=[{label:"use / do not use",positivePattern:/\buse\s+/i,negativePattern:/\b(?:do\s+not|don['']t|never)\s+use\s+|[—–]\s*not\s+/i,skipLeadingVerb:!1},{label:"use / migrating away from",positivePattern:/\buse\s+/i,negativePattern:/\b(?:migrat(?:ing|e|ed)\s+(?:away\s+from|off\s+of)\s+|moving\s+away\s+from\s+|switch(?:ing|ed)?\s+(?:away\s+from|off\s+of)\s+|dropping\s+)/i,skipLeadingVerb:!1,allowSingleTokenMatch:!0},{label:"acceptable / never",positivePattern:/\b(?:is|are)\s+acceptable\b/i,negativePattern:/\bnever\s+use\s+|\b(?:do\s+not|don['']t)\s+use\s+/i,skipLeadingVerb:!1,extractPositiveSubjectBefore:!0},{label:"use / avoid",positivePattern:/\buses?\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!1,allowSingleTokenMatch:!0},{label:"declared stack / not",positivePattern:/\b(?:framework|library|runtime|sdk|engine|package|tool|stack|lang(?:uage)?|cli)\b[^:\n]{0,20}:\s*/i,negativePattern:/[—–]\s*not\s+|\bnot\s+using\s+/i,skipLeadingVerb:!1},{label:"always / never",positivePattern:/\balways\s+/i,negativePattern:/\bnever\s+/i,skipLeadingVerb:!0},{label:"always / avoid",positivePattern:/\balways\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!0},{label:"must / avoid",positivePattern:/\bmust\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!0},{label:"prefer / avoid",positivePattern:/\bprefer\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!0},{label:"preferred / only acceptable",positivePattern:/\b(?:is|are)\s+(?:generally\s+|usually\s+)?preferred\b/i,negativePattern:/\b(?:is|are)\s+only\s+acceptable\b|\b(?:acceptable|allowed)\s+only\b/i,skipLeadingVerb:!1,extractSubjectBefore:!0}];function D0(t,e,n,s){let i=t.slice(e).replace(/^\s+/,"");if(s){let l=/^([a-zA-Z]+)\s+/.exec(i);l&&Rd.has(l[1].toLowerCase())&&(i=i.slice(l[0].length))}let r=i.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim(),o=n.split(" ").filter(Boolean),a=r;for(let l of o){let u=a.toLowerCase().indexOf(l);if(u<0)return!1;a=a.slice(u+l.length).trimStart()}a=a.replace(/^[^a-zA-Z]+/,"");let c=/^([a-zA-Z]+)/.exec(a)?.[1]?.toLowerCase()??"";return j0.has(c)}function bi(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}function bd(t){if(!t||t.length<2)return!0;let e=t.split(" ").filter(Boolean);return e.length===0?!0:e.every(n=>M0.has(n))}function F0(t,e){let n=new Set(t.split(" ").filter(Boolean)),s=new Set(e.split(" ").filter(Boolean));if(n.size===0||s.size===0)return 0;let i=0;for(let o of n)s.has(o)&&i++;let r=n.size+s.size-i;return i/r}function wd(t,e,n=4){let s=t.slice(0,e).trimEnd();if(!s)return"";let i=0;for(let a=s.length-1;a>=0;a--)if(/[,;.]/.test(s[a])){i=a+1;break}let r=s.slice(i).trim(),o=[];for(let a of r.split(/\s+/).reverse()){let c=a.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g,"").toLowerCase();if(c&&!kd.has(c)&&(o.unshift(c),o.length>=n))break}return o.join(" ")}function H0(t){let e=t.text.split(`
38
- `).map(i=>i.trim()),n=[],s="";for(let i of e){let r=/^ {0,3}#{1,6}\s/.test(i),o=/^(?:[-*+]\s+|\d+[.)]\s+)/.test(i);if(!i||i.startsWith("|")||r){s&&(n.push(s),s=""),r&&n.push(i);continue}o&&s&&(n.push(s),s=""),s=s?`${s} ${i}`:i,/[.!?:;]$/.test(i)&&(n.push(s),s="")}return s&&n.push(s),n}function vd(t,e){let n=t.flags.includes("g")?t.flags:`${t.flags}g`,s=new RegExp(t.source,n),i=[],r;for(;(r=s.exec(e))!==null;)i.push({index:r.index,text:r[0]}),r[0].length===0&&s.lastIndex++;return i}function B0(t){let e=[],n=H0({...t,text:Ke(t.text)});for(let s=0;s<Xn.length;s++){let i=Xn[s];for(let r of n){let o=i.skipLeadingVerb??!1,a=i.extractSubjectBefore??!1,c=vd(i.negativePattern,r),l=r;for(let f of c){let d=f.index+f.text.length,p=a,h=bi(p?wd(r,f.index,4):yd(r,d,3,o));if(h.length>=2&&!bd(h)){let m=!p&&D0(r,d,h,o);e.push({section:t,pairIndex:s,polarity:"negative",subject:h,matchedLine:r,hasQualifier:m})}l=l.slice(0,f.index)+" ".repeat(f.text.length)+l.slice(d)}let u=vd(i.positivePattern,l);for(let f of u){let d=a||(i.extractPositiveSubjectBefore??!1),p=bi(d?wd(r,f.index,4):yd(r,f.index+f.text.length,3,o));p.length>=2&&!bd(p)&&e.push({section:t,pairIndex:s,polarity:"positive",subject:p,matchedLine:r})}}}return e}function xd(t,e,n,s,i,r){let o=[`${t}:${e}`,`${n}:${s}`].sort(),a=`${o[0]}|${o[1]}|${i}|${r}`;return`conflict-${wi.createHash("sha1").update(a).digest("hex").slice(0,12)}`}function na(t){let e=[];for(let a of t)for(let c of a.sections)c.text.trim().length>=N0&&e.push(c);let n=[];for(let a of e)n.push(...B0(a));let s=[],i=new Set;for(let a=0;a<n.length;a++)for(let c=a+1;c<n.length;c++){let l=n[a],u=n[c];if(l.pairIndex!==u.pairIndex||l.polarity===u.polarity)continue;let f=l.polarity==="positive"?l:u,d=l.polarity==="negative"?l:u,p=f.subject===d.subject?1:F0(f.subject,d.subject),h;if(f.subject===d.subject){let k=f.subject.split(" ").filter(Boolean).length===1&&(new RegExp(`\`${f.subject}\\.[a-z]`,"i").test(f.matchedLine)||new RegExp(`\`${d.subject}\\.[a-z]`,"i").test(d.matchedLine)),R=Xn[l.pairIndex];h=d.hasQualifier&&/\balways\b/i.test(f.matchedLine)&&R.label.includes("always")?.5:d.hasQualifier?.35:k?.5:.8}else if(p>=.5){let v=Xn[l.pairIndex],k=f.subject.split(" ").filter(Boolean),R=d.subject.split(" ").filter(Boolean);if(k.length<2||R.length<2){if(!v.allowSingleTokenMatch)continue;let I=k.length<=R.length?k[0]:R[0];if(!(k.length>R.length?f.subject:d.subject).startsWith(I))continue}h=d.hasQualifier?.3:.5}else continue;if(h<.4)continue;let m=xd(Be(f.section),f.section.startLine,Be(d.section),d.section.startLine,l.pairIndex,f.subject);if(i.has(m))continue;i.add(m);let g=h>=.7?"high":"warning",b=Xn[l.pairIndex],w=f.subject.length<=d.subject.length?f.subject:d.subject,y=Array.from(new Set([f.section.filePath,d.section.filePath]));s.push({id:m,severity:g,category:"conflict",title:`Possible conflicting instruction: ${w}`,summary:`Possible conflict \u2014 review these together. A "${b.label}" directive pattern was found pointing in opposite directions for the subject "${w}".`,filePaths:y,locations:[{filePath:f.section.filePath,startLine:f.section.startLine,endLine:f.section.endLine},{filePath:d.section.filePath,startLine:d.section.startLine,endLine:d.section.endLine}],evidence:[f.matchedLine,d.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:h})}let r=new Map,o=new Map;for(let a of n)a.polarity==="positive"?(r.has(a.subject)||r.set(a.subject,[]),r.get(a.subject).push(a)):(o.has(a.subject)||o.set(a.subject,[]),o.get(a.subject).push(a));for(let[a,c]of r){let l=o.get(a);if(l)for(let u of c)for(let f of l){if(u.pairIndex===f.pairIndex||u.section.filePath===f.section.filePath&&u.section.startLine===f.section.startLine)continue;{let h=u.subject.split(" ").filter(Boolean).length,m=f.subject.split(" ").filter(Boolean).length;if(h<2||m<2)continue}if(f.hasQualifier)continue;let d=xd(Be(u.section),u.section.startLine,Be(f.section),f.section.startLine,-1,a);if(i.has(d))continue;i.add(d);let p=Array.from(new Set([u.section.filePath,f.section.filePath]));s.push({id:d,severity:"warning",category:"conflict",title:`Possible conflicting instruction: ${a}`,summary:`Possible conflict \u2014 review these together. Opposing directives for "${a}" were found across instruction files.`,filePaths:p,locations:[{filePath:u.section.filePath,startLine:u.section.startLine,endLine:u.section.endLine},{filePath:f.section.filePath,startLine:f.section.startLine,endLine:f.section.endLine}],evidence:[u.matchedLine,f.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:.5})}}return s}var W0=[{re:/\.NET\s+v?(\d+)(?:\.\d+)*/gi,name:".NET",normalize:t=>t.split(".")[0]},{re:/ASP\.NET\s+Core\s+v?(\d+)/gi,name:"ASP.NET Core",normalize:t=>t.split(".")[0]},{re:/\bNode(?:\.?js)?\s+v?(\d+)/gi,name:"Node.js",normalize:t=>t.split(".")[0]},{re:/\bReact\s+v?(\d+)/gi,name:"React",normalize:t=>t.split(".")[0]},{re:/\bNext\.?js\s+v?(\d+)/gi,name:"Next.js",normalize:t=>t.split(".")[0]},{re:/\bPython\s+v?(\d+\.\d+|\d+)/gi,name:"Python",normalize:t=>t.split(".")[0]},{re:/\bGo\s+v?(\d+\.\d+)/gi,name:"Go",normalize:t=>t},{re:/\bUnity\s+v?(20\d{2}\.\d+|\d+)/gi,name:"Unity",normalize:t=>t.split(".")[0]},{re:/\bMirror(?:\s+Networking)?\s+v?(\d{2,4}(?:\.\d+)?)/gi,name:"Mirror",normalize:t=>t.split(".")[0]},{re:/\bTypeScript\s+v?(\d+)/gi,name:"TypeScript",normalize:t=>t.split(".")[0]},{re:/\bDjango\s+v?(\d+)/gi,name:"Django",normalize:t=>t.split(".")[0]},{re:/\bRails?\s+v?(\d+)/gi,name:"Rails",normalize:t=>t.split(".")[0]},{re:/\bLaravel\s+v?(\d+)/gi,name:"Laravel",normalize:t=>t.split(".")[0]},{re:/\bRust\s*\(?\s*v?(20\d{2})\s+edition\b/gi,name:"Rust edition",normalize:t=>t},{re:/\bedition\s*=\s*["']?(20\d{2})["']?/gi,name:"Rust edition",normalize:t=>t},{re:/\btokio`?\s+v?(\d+(?:\.\d+)?)/gi,name:"tokio",normalize:t=>{let[e,n]=t.split(".");return e==="0"&&n?`0.${n}`:e??t}},{re:/\baxum`?\s+v?(\d+(?:\.\d+)?)/gi,name:"axum",normalize:t=>{let[e,n]=t.split(".");return e==="0"&&n?`0.${n}`:e??t}},{re:/\b(?:MSRV|minimum\s+supported\s+rust\s+version)\s+v?(\d+\.\d+)/gi,name:"Rust MSRV",normalize:t=>t},{re:/\bPhoenix\s+v?(\d+(?:\.\d+)?)/gi,name:"Phoenix",normalize:t=>t.split(".")[0]},{re:/\bElixir\s+v?(\d+(?:\.\d+)?)/gi,name:"Elixir",normalize:t=>t.split(".")[0]},{re:/\bSpring\s+Boot\s+v?(\d+)/gi,name:"Spring Boot",normalize:t=>t.split(".")[0]},{re:/\bJava\s+v?(\d+)/gi,name:"Java",normalize:t=>t.split(".")[0]},{re:/\bKotlin\s+v?(\d+)/gi,name:"Kotlin",normalize:t=>t.split(".")[0]}];function G0(t,e){let n=t.slice(Math.max(0,e-50),e).toLowerCase();return/\bnot\s+$|\bnot\s*\($|\(not\s/.test(n)||n.trimEnd().endsWith("not")||/\b(?:deprecated|removed|introduced|added)\s+in\s+\S*\s*$/.test(n)}function U0(t){let e=new Map;for(let{re:n,name:s,normalize:i}of W0){let r=new RegExp(n.source,n.flags),o;for(;(o=r.exec(t))!==null;){if(G0(t,o.index))continue;let a=i(o[1]);e.has(s)||e.set(s,new Set),e.get(s).add(a)}}return e}function V0(t,e){let n=`version-conflict:${t}:${[...e].sort().join("|")}`;return`version-conflict-${wi.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function sa(t){if(t.length<2)return[];let e=t.map(r=>({file:r,versions:U0(Ke(r.content))})),n=new Map;for(let{file:r,versions:o}of e)for(let[a,c]of o){n.has(a)||n.set(a,new Map);let l=n.get(a);for(let u of c)l.has(u)||l.set(u,[]),l.get(u).push(r.path)}let s=[],i=r=>r.split(/[\\/]/).pop()??r;for(let[r,o]of n){if(o.size<=1)continue;let a=[...o.keys()],c=[...new Set([...o.values()].flat())];if(a.map(p=>o.get(p)).every(p=>p.every(h=>h===c[0])))continue;let f=V0(r,a),d=a.map(p=>`${r} ${p} referenced in: ${o.get(p).map(i).join(", ")}`);s.push({id:f,severity:"high",category:"conflict",title:`Version conflict: ${r} (${a.join(" vs ")})`,summary:`Possible conflict \u2014 review these together. Different instruction files specify different versions of ${r}: ${a.join(" vs ")}.`,filePaths:c,locations:c.map(p=>({filePath:p})),evidence:d,recommendation:`Ensure all instruction files agree on which version of ${r} this project targets. Remove or update whichever reference is out of date.`,confidence:.75})}return s}function z0(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var q0={"kebab-case":["kebab-case","kebab case","kebabcase"],camelcase:["camelcase","camel case","camel-case"],pascalcase:["pascalcase","pascal case","pascal-case"]};function _d(t){let e=q0[t.toLowerCase()]??[t];return new RegExp(`\\b(?:${e.map(z0).join("|")})\\b`,"i")}var K0=[{termA:"kebab-case",termB:"camelcase",dimension:"file naming convention"},{termA:"kebab-case",termB:"pascalcase",dimension:"file naming convention"},{termA:"camelcase",termB:"pascalcase",dimension:"file naming convention"},{termA:"ef core",termB:"dapper",dimension:"data access library"},{termA:"entity framework",termB:"dapper",dimension:"data access library"},{termA:"redux",termB:"zustand",dimension:"state management library"},{termA:"redux",termB:"mobx",dimension:"state management library"},{termA:"pip",termB:"poetry",dimension:"Python package manager"},{termA:"pages router",termB:"app router",dimension:"Next.js routing strategy"},{termA:"named exports",termB:"default exports",dimension:"module export style"},{termA:"coroutine",termB:"unitask",dimension:"Unity async pattern"},{termA:"coroutine",termB:"async/await",dimension:"Unity async pattern"},{termA:"coroutines",termB:"unitask",dimension:"Unity async pattern"},{termA:"coroutines",termB:"async/await",dimension:"Unity async pattern"},{termA:"unit tests only",termB:"integration suite",dimension:"test scope"},{termA:"unit tests only",termB:"full test suite",dimension:"test scope"},{termA:"lightweight unit tests",termB:"integration suite",dimension:"test scope"},{termA:"cobra",termB:"urfave",dimension:"Go CLI framework"},{termA:"gorm",termB:"sqlx",dimension:"Go data-access library"}],Sd=/\b(?:use|prefer|always|must|should|follow|rely\s+on|stick\s+to|require)\b/i;function Ed(t,e){let n=t.split(`
39
- `).map(s=>s.trim());for(let s=0;s<n.length;s++){let i=n[s];if(e.test(i)&&Sd.test(i))return!0;let r=n[s+1];if(i&&r){let o=`${i} ${r}`;if(e.test(o)&&Sd.test(o))return!0}}return!1}function ia(t){if(t.length<2)return[];let e=[],n=new Set,s=new Map(t.map(r=>[r.path,Ke(r.content)])),i=r=>s.get(r.path)??r.content;for(let r of K0){let o=_d(r.termA),a=_d(r.termB),c=t.filter(w=>o.test(i(w))),l=t.filter(w=>a.test(i(w)));if(c.length===0||l.length===0)continue;let u=new Set(c.map(w=>w.path)),f=new Set(l.map(w=>w.path));if([...u].every(w=>f.has(w))&&[...f].every(w=>u.has(w)))continue;let p=c.some(w=>Ed(i(w),o)),h=l.some(w=>Ed(i(w),a));if(!p&&!h)continue;let m=[r.termA.toLowerCase(),r.termB.toLowerCase()].sort().join("|");if(n.has(m))continue;n.add(m);let g=[...new Set([...c,...l].map(w=>w.path))],b=`competing-tech-${wi.createHash("sha1").update(m).digest("hex").slice(0,12)}`;e.push({id:b,severity:"warning",category:"conflict",title:`Possible ${r.dimension} conflict: "${r.termA}" vs "${r.termB}"`,summary:`Possible conflict \u2014 review these together. Different instruction files reference competing ${r.dimension} choices: "${r.termA}" and "${r.termB}".`,filePaths:g,locations:g.map(w=>({filePath:w})),evidence:[`"${r.termA}" referenced in: ${c.map(w=>ta.basename(w.path)).join(", ")}`,`"${r.termB}" referenced in: ${l.map(w=>ta.basename(w.path)).join(", ")}`],recommendation:`Review both instruction files and decide which ${r.dimension} is canonical. Remove or update whichever reference contradicts the team's actual choice.`,confidence:.6})}return e}var Kt=x(require("node:fs"),1),Y=x(require("node:path"),1),qd=x(require("node:crypto"),1),fa=x(wn(),1);var Pe=x(require("node:fs"),1),vi=x(require("node:path"),1),Td=x(require("node:crypto"),1),Id=x(wn(),1),xi=x(Et(),1);function qt(t){return t.replace(/\\/g,"/")}function at(t,e){let n=K(t,e);if(!n)return!1;try{return Pe.statSync(n).isFile()}catch{return!1}}function ie(t,e){let n=K(t,e);if(n)try{return Pe.readFileSync(n,"utf8")}catch{return}}var Od=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/worktrees/**","**/.worktrees/**"];function ct(t,e,n=Od){let s;try{s=Id.default.sync(e,{cwd:t,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,ignore:n})}catch{return[]}return s.map(qt).sort()}var Cd=[".claude/**/SKILL.md",".agents/skills/**/SKILL.md","skills/*/SKILL.md","plugins/*/skills/*/SKILL.md"],zt={skills:Cd,allSkills:Cd,agents:[".claude/agents/**/*.md"],settings:[".claude/settings.json",".claude/settings.local.json"],mcp:[".mcp.json"],cursorRules:[".cursor/rules/**/*.mdc"],copilotInstructions:[".github/instructions/**/*.md"]};var Y0=new Set([".",".claude",".agents",".claude/skills",".agents/skills",".claude/plugins","skills","plugins"]);function aa(t){return Y0.has(t)}var Ad=200,J0=2e4,ra=1e3,X0=new Set(["node_modules",".git","worktrees",".worktrees"]),oa=100,Z0=new RegExp(String.raw`(?:^|\/)(?:[^/.]+|package\.json|requirements[^/]{0,40}\.txt|(?:GNU)?makefile|Dockerfile[^/]{0,40}|Containerfile|Justfile)$|`+String.raw`\.(?:sh|bash|zsh|ksh|fish|command|js|mjs|cjs|ts|mts|cts|jsx|tsx|py|pyw|rb|ps1|psm1|pl|php|lua|bat|cmd|mk|`+String.raw`vbs|vba|vbe|hta|applescript|wsf|jse|reg|exe|dll|so|dylib|wasm|jar|war|class|zip|tar|gz|tgz|bz2|xz|7z|rar|`+String.raw`msi|dmg|pkg|deb|rpm|appimage|apk|bin|o|a|lnk|scr|com|pif|scpt|node|env)$`,"i");function $d(t){return Z0.test(t)}function Q0(t,e){let n=[],s=r=>{let o=K(t,r);if(!o)return[];try{return Pe.readdirSync(o,{withFileTypes:!0})}catch{return[]}},i=r=>{let o=`${r}/package.json`;n.length<oa&&at(t,o)&&n.push(o)};for(let r of s(e).sort((o,a)=>o.name<a.name?-1:1)){if(n.length>=oa)break;if(!(!r.isDirectory()||r.name.startsWith(".")))if(r.name.startsWith("@"))for(let o of s(`${e}/${r.name}`).sort((a,c)=>a.name<c.name?-1:1))o.isDirectory()&&i(`${e}/${r.name}/${o.name}`);else i(`${e}/${r.name}`)}return n}function ex(t,e){if(e.length===0)return!1;let n=t.split("/"),s=[t];for(let i=1;i<n.length;i++){let r=n.slice(0,i).join("/");s.push(r,`${r}/`)}return s.some(i=>xi.default.isMatch(i,e,{dot:!0}))}function tx(t,e,n){let s=[...new Set(e.map(c=>vi.posix.dirname(c)).filter(c=>!aa(c)))].sort(),i=new Set(s),r=[],o=[],a=[];for(let c of s){let l=[],u=[],f=0,d=0,p=!1,h=[c];for(;h.length>0;){let g=h.pop(),b=K(t,g);if(!b)continue;let w;try{w=Pe.readdirSync(b,{withFileTypes:!0})}catch{continue}w.sort((y,v)=>y.name<v.name?1:y.name>v.name?-1:0);for(let y of w){if(++d>J0){p=!0;break}let v=`${g}/${y.name}`;if(!y.isSymbolicLink()&&!ex(v,n.exclude)){if(y.isDirectory()){if(i.has(v))continue;if(X0.has(y.name)){a.push({path:v,kind:"dependency-dir"}),y.name==="node_modules"&&u.push(...Q0(t,v));continue}h.push(v)}else if(y.isFile()&&y.name!=="SKILL.md"){if(n.include&&!xi.default.isMatch(v,n.include,{dot:!0})){f++;continue}l.push(v)}}}if(p)break}l.sort((g,b)=>Number($d(b))-Number($d(g))||(g<b?-1:g>b?1:0)),r.push(...l.slice(0,Ad)),r.push(...u.sort().slice(0,oa));let m=l.slice(Ad);o.push(...m.slice(0,ra)),(m.length>ra||p)&&a.push({path:c,kind:"listing-limit",count:Math.max(0,m.length-ra)}),f>0&&a.push({path:c,kind:"include",count:f})}return{files:r.sort(),overCap:o.sort(),skips:a}}function nx(t,e){let n=K(t,e);if(!n)return!1;try{let s=Pe.statSync(n);if(!s.isFile()||s.size>ce)return!1;let i=Pe.openSync(n,"r");try{let r=Buffer.alloc(Math.min(s.size,Kn)),o=Pe.readSync(i,r,0,r.length,0);return!Vt(r.subarray(0,o))}finally{Pe.closeSync(i)}}catch{return!1}}function ca(t,e={}){let n=[...Od,...e.exclude??[]],s=e.include&&e.include.length>0?e.include:void 0,i=c=>{let l=ct(t,[...c],n);return s?(0,xi.default)(l,s,{dot:!0}).sort():l},r=c=>i(c).filter(l=>nx(t,l)),o=i(zt.allSkills),a=tx(t,o,{include:s,exclude:e.exclude??[]});return{skills:r(zt.skills),allSkills:o,skillFiles:a.files,skillFilesOverCap:a.overCap,skillBundleSkips:a.skips,agents:r(zt.agents),settings:r(zt.settings),mcp:r(zt.mcp),cursorRules:r(zt.cursorRules),copilotInstructions:r(zt.copilotInstructions)}}function le(t){return Td.createHash("sha1").update(t).digest("hex").slice(0,12)}function Te(t,e){let n=s=>vi.resolve(t,s);return e.map(s=>({...s,filePaths:s.filePaths.map(n),locations:s.locations.map(i=>({...i,filePath:n(i.filePath)}))}))}var Zn=/\.(sh|bash|zsh|js|mjs|cjs|ts|py|rb|ps1)$/i;function Ye(t,e){let n=t.indexOf(e);return n<0&&(n=t.indexOf(JSON.stringify(e).slice(1,-1))),n<0?1:t.slice(0,n).split(/\r?\n/).length}function sx(t){return t.charCodeAt(0)===65279?t.slice(1):t}var Pd=/^(?:---|\.\.\.)[ \t]*$/;function Ld(t){let e="",n="";for(let s=0;s<t.length;s++){let i=t[s];if(e)i===e&&(e="");else if((i==='"'||i==="'")&&(n===""||/[\s[{(,]/.test(n)))e=i;else if(i==="#"&&(n===""||/\s/.test(n)))return t.slice(0,s).trimEnd();n=i}return t}function Nd(t){let e=[],n="",s=0,i="";for(let r of t){if(i){n+=r,r===i&&(i="");continue}if((r==='"'||r==="'")&&n.trim()===""){i=r,n+=r;continue}if(r==="["||r==="{"||r==="("){s++,n+=r;continue}if(r==="]"||r==="}"||r===")"){s>0&&s--,n+=r;continue}if(r===","&&s===0){e.push(n),n="";continue}n+=r}return e.push(n),e.map(r=>la(r.trim())).filter(r=>r!=="")}function la(t){return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function ix(t){let e=Ld(t).trim();if(e==="")return null;let n=la(e);if(n!==e)return n;if(e.startsWith("[")&&e.endsWith("]")){let s=e.slice(1,-1).trim();return s===""?[]:Nd(s)}return e==="true"?!0:e==="false"?!1:e==="null"||e==="~"?null:/^-?\d+(\.\d+)?$/.test(e)?Number(e):e}function gt(t){let n=sx(t).split(/\r?\n/),s={present:!1,closed:!1,data:{},keyLines:{},fenceEndLine:-1,bodyStartLine:1,errors:[]};if(n.length===0||n[0].trim()!=="---")return s;s.present=!0;let i=null,r=null,o=!1,a=[],c=()=>{if(r===null)return;let u=o?a.join(" "):a.join(`
40
- `);s.data[r]=u.trim(),r=null,a=[]},l=1;for(;l<n.length;l++){let u=n[l],f=u.trim();if(r!==null){if(Pd.test(u)){c(),s.closed=!0,s.fenceEndLine=l+1,s.bodyStartLine=l+2;break}if(f===""||/^\s/.test(u)){a.push(f);continue}c()}if(Pd.test(u)){s.closed=!0,s.fenceEndLine=l+1,s.bodyStartLine=l+2;break}if(f===""||f.startsWith("#"))continue;let d=/^(\s*)-\s+(.*)$/.exec(u);if(d&&i){let w=s.data[i],y=la(Ld(d[2]).trim());y!==""&&(Array.isArray(w)?w.push(y):s.data[i]=[y]);continue}let p=/^(\s*)([^:\s][^:]*):\s?(.*)$/.exec(u);if(!p){s.errors.push(`Unparseable frontmatter line ${l+1}: ${f.slice(0,60)}`);continue}let h=p[1].length,m=p[2].trim(),g=p[3];if(h>0){s.errors.push(`Nested frontmatter key "${m}" on line ${l+1} is not supported`);continue}Object.prototype.hasOwnProperty.call(s.data,m)?s.errors.push(`Duplicate frontmatter key "${m}" (line ${l+1})`):s.keyLines[m]=l+1;let b=g.trim();if(b==="|"||b==="|-"||b==="|+"||b===">"||b===">-"||b===">+"){r=m,o=b.startsWith(">"),a=[],i=null;continue}if(b===""){s.data[m]=null,i=m;continue}s.data[m]=ix(g),i=null}return r!==null&&c(),s.closed||(s.bodyStartLine=n.length+1),s}function _n(t){return t==null?[]:Array.isArray(t)?t.map(e=>String(e).trim()).filter(Boolean):typeof t=="string"?t.split(`
41
- `).flatMap(e=>Nd(e)):[String(t)]}function F(t){return{severity:"warning",category:"ai_config",confidence:.8,...t}}function Ot(t,e,n,s){let i=(o,a)=>`ai-config-${s.idPrefix}-${o}-${le(a)}`;if(!n.present)return[F({id:i("no-frontmatter",t),severity:s.noFrontmatterSeverity??"high",title:s.noFrontmatterTitle??`${s.noun} is missing YAML frontmatter`,summary:`${t} has no \`---\` frontmatter block. ${s.why}`,filePaths:[t],locations:[{filePath:t,startLine:1,endLine:1}],evidence:[`First line: ${e.split(/\r?\n/)[0]?.slice(0,60)??"(empty)"}`],recommendation:s.recommendation,confidence:s.noFrontmatterConfidence??.85})];let r=[];n.closed||r.push(F({id:i("unterminated",t),severity:"high",title:`${s.noun} frontmatter is not closed`,summary:`${t} opens a \`---\` frontmatter block that is never closed.`,filePaths:[t],locations:[{filePath:t,startLine:1,endLine:1}],evidence:["Opening `---` on line 1 has no closing `---`."],recommendation:"Close the frontmatter block with a `---` line.",confidence:.9}));for(let o of n.errors){let a=/"([^"]+)"/.exec(o)?.[1],c=Number(/\bline (\d+)\b/.exec(o)?.[1]),l=Number.isInteger(c)&&c>0?c:n.fenceEndLine>0?n.fenceEndLine:1;r.push(F({id:i("fm-error",`${t}|${o}`),title:a?`${s.noun} frontmatter has an unsupported key "${a}"`:`${s.noun} frontmatter has a structural problem`,summary:`${t}: ${o}.`,filePaths:[t],locations:[{filePath:t,startLine:l,endLine:l}],evidence:[o],recommendation:"Fix the frontmatter so it is valid YAML with flat, unique keys. Nested maps are not supported \u2014 flatten the offending key or move it into the body.",confidence:.7}))}return r}function jd(t){return/[\\^$.*+?()[\]{}|/]/.test(t)?`\\${t}`:t}function rx(t){let e="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")n+1<t.length&&(e+=jd(t[n+1])),n+=2;else if(s==="*")if(t[n+1]==="*"){let i=n===0||t[n-1]==="/",r=n+2;for(;t[r]==="*";)r++;i&&t[r]==="/"?(e+="(?:.*/)?",n=r+1):i&&r===t.length?(e+=".*",n=r):(e+="[^/]*",n=r)}else e+="[^/]*",n++;else if(s==="?")e+="[^/]",n++;else if(s==="["){let i=t.indexOf("]",n+2);if(i===-1)e+="\\[",n++;else{let r=t.slice(n+1,i),o=!1;(r.startsWith("!")||r.startsWith("^"))&&(o=!0,r=r.slice(1)),r=r.replace(/[\\^\]]/g,a=>`\\${a}`),e+=`[${o?"^":""}${r}]`,n=i+1}}else e+=jd(s),n++}return e}function ox(t){let e=[];for(let n of t.split(/\r?\n/)){let s=n.replace(/(?<!\\)[ \t]+$/,"");if(s===""||s.startsWith("#"))continue;let i=!1;s.startsWith("!")&&(i=!0,s=s.slice(1));let r=!1;s.endsWith("/")&&(r=!0,s=s.slice(0,-1));let o=s.includes("/");if(s=s.replace(/^\//,""),s!=="")try{e.push({negate:i,dirOnly:r,anchored:o,regex:new RegExp(`^${rx(s)}$`)})}catch{}}return e}function ax(t,e,n){if(t.dirOnly&&!n)return!1;let s=t.anchored?e:e.split("/").pop();return t.regex.test(s)}function _i(t){let e=new Map,n=s=>{let i=e.get(s);if(!i){let r=ie(t,s===""?".gitignore":`${s}/.gitignore`);i=r===void 0?[]:ox(r),e.set(s,i)}return i};return s=>{let i=s.replace(/\\/g,"/").replace(/^\.\//,"").split("/").filter(Boolean);for(let r=1;r<=i.length;r++){let o=r<i.length,a;for(let c=0;c<r;c++){let l=i.slice(c,r).join("/");for(let u of n(i.slice(0,c).join("/")))ax(u,l,o)&&(a=!u.negate)}if(a===!0)return!0}return!1}}var Md=/\[(?:[^\]]*)\]\(([^)]+)\)/g,Dd=/\[(?:[^\]]|\]\([^)]*\))*\]\(([^)]+)\)/g,Fd=/^[ \t]{0,3}\[[^\]]+\]:\s*(\S+)/gm,Hd=/(?<!\w)@((?:\.{1,2}\/)?[\w./\\-]+\.(?:md|ts|js|mjs|cjs|tsx|jsx|json|yml|yaml|toml|txt|sh|py|cs|go|rs))/g,Bd=/`([^\s`\n]+\.(?:md|sh|py|ts|js|tsx|jsx|mjs|cjs|json|yml|yaml|toml|cs|go|rs|txt|lock|env|png|jpg|jpeg|gif|svg|webp|pdf))(?::\d+(?::\d+)?)?`/g,Wd=/`((?:\.\/)?[\w@.()[\]-]+(?:\/[\w@.()[\]-]+)+\/?)`/g,cx=/\b(?:branch(?:es)?|checkout|rebase|merge|cherry-pick|route[sd]?|routing|endpoints?|urls?|uris?|http\s+(?:get|post|put|patch|delete))\b/i,lx=new Set(["feat","feature","features","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","perf","build","release","releases","style","wip","dependabot"]),Kd=new Set(["dist","build","out",".next","coverage","target","bin","obj","node_modules",".turbo"]),Gd=/^[ \t]*[-*+]\s+((?:[\w.-]+\/)+[\w.-]+\.(?:md|ts|js|tsx|jsx|mjs|cjs|json|yml|yaml|toml|sh|py|cs|go|rs|txt|png|jpg|jpeg|gif|svg|webp|pdf))\b/gm,Ud="repository\\s+layout|project\\s+structure|file\\s+structure|folder\\s+structure|directory\\s+(?:structure|layout|tree|overview)|project\\s+tree|repo\\s+(?:structure|layout|map)|file\\s+tree|files?\\s+overview|codebase\\s+(?:map|overview|structure|layout)|layout",ux=new RegExp(`^(?:#{1,4}\\s+.*\\b(?:${Ud})\\b|\\*\\*[^*\\n]*\\b(?:${Ud})\\b[^*\\n]*\\*\\*\\s*)`,"im"),fx=/\b(?:create|add|generate|scaffold|place|put|save|make)\s+(?:a\s+|an\s+|the\s+|your\s+|this\s+|new\s+)*(?:file|workflow|config(?:uration)?|script|action|manifest|template|module|component)\b[^.\n]*?\b(?:named|called|at|as|in|to|like)\s+[`'"(]*([^\s`'"()]+)/i;function Vd(t){return lt(t).replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase()}var dx=new Set([".md",".ts",".js",".mjs",".cjs",".tsx",".jsx",".json",".yml",".yaml",".toml",".txt",".sh",".py",".cs",".go",".rs",".png",".jpg",".jpeg",".gif",".svg",".webp",".pdf"]);function Si(t){return/^https?:\/\/|^mailto:|^#|^data:/.test(t.trimStart())}function zd(t){let e=t.trim(),n=/^<([^>]+)>(?:\s+(?:"[^"]*"|'[^']*'))?\s*$/.exec(e);if(n)return n[1];let s=/^(\S+)\s+(?:"[^"]*"|'[^']*')\s*$/.exec(e);return s?s[1]:e}var px=/^(foo|bar|baz|qux|quux|example|sample|placeholder|stub|demo|test|your[-_]?file|my[-_]?file|filename|file[-_]?name)(\.\w+)?$/i,hx=new Set(["tokens.json","config.json","settings.json","schema.json","manifest.json","types.ts","types.d.ts","index.ts","index.js","main.ts","main.go","app.ts","app.js","constants.ts","utils.ts","helpers.ts","globals.ts","routes.ts","store.ts","models.ts","services.ts","package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","tsconfig.json","tsconfig.base.json","pyproject.toml","cargo.toml","next.config.js","next.config.ts","next.config.mjs","vite.config.ts","vite.config.js","vite.config.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json",".eslintrc.js",".eslintrc.yml","jest.config.ts","jest.config.js","jest.config.mjs","vitest.config.ts","vitest.config.mts"]),mx=/^(ComponentName|MyComponent|YourComponent|WidgetName|FeatureName|ModuleName|ServiceName|ModelName|EntityName|ResourceName|DomainName|ControllerName|ScreenName|PageName)(?:\.\w+)*$/i;function gx(t){if(/<[A-Za-z][A-Za-z0-9_-]*>/.test(t)||/\{[A-Za-z][A-Za-z0-9_-]*\}/.test(t)||t.split("/").includes("..."))return!0;let e=Y.basename(lt(t)),n=Y.dirname(lt(t)),s=n!=="."&&n!==""&&n!==".\\"&&n!=="./";return!!(!s&&px.test(e)||mx.test(e)||!s&&hx.has(e.toLowerCase())||/camelCase|CamelCase|PascalCase|pascalCase|kebab[-_]?[Cc]ase|snake_?[Cc]ase/.test(e))}var yx=[/(?:^|[/\\])\.promptci[/\\]/,/(?:^|[\\/])secrets?\.\w+$/i,/(?:^|[\\/])credentials?\.\w+$/i,/appsettings\.(?:Development|Production|Staging|Local)\.\w+$/i,/(?:^|[\\/])\.env(?:\.\w+)?$/i,/(?:^|[\\/])local\.(?:json|yaml|yml|toml|ini|conf|config)$/i,/\.local\.\w+$/i,/(?:^|[\\/])(?:private(?:key)?|id_rsa|id_ed25519)(?:\.\w+)?$/i,/\.(?:pem|key|pfx|p12)$/i];function bx(t){let e=t.replace(/\\/g,"/");return yx.some(n=>n.test(e))}var wx=/^(?:~(?:[/\\]|$)|\$\{?(?:HOME|USERPROFILE|XDG_CONFIG_HOME|XDG_DATA_HOME)\}?(?:[/\\]|$)|\$env:(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA)(?:[/\\]|$)|%(?:USERPROFILE|HOMEPATH|APPDATA|LOCALAPPDATA)%(?:[/\\]|$))/i;function pa(t){return wx.test(t.trim())}function vx(t){let e=Y.extname(t.split("#")[0]??"").toLowerCase();return dx.has(e)}function xx(t){if(!t||/^[a-z][a-z0-9+.-]*:/i.test(t)||t.startsWith("/")||/[\s*?$%<>{}|"'`~\\]/.test(t)||!/[A-Za-z]/.test(t)||!t.includes("/")&&!t.startsWith("."))return!1;let e=t.replace(/\/+$/,"").split("/").pop()??"";return t.endsWith("/")||Y.extname(e)===""}function lt(t){return t.split("#")[0].split("?")[0].trim()}function ua(t){try{return Kt.existsSync(t)}catch{return!1}}var _x=new Set([".go",".cs",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".sh",".java",".kt",".swift"]),Sx=new Set([".go",".rs",".cs",".java",".kt",".swift",".ts",".tsx"]),Ex=/(?:^|[/\\])(?:legacy|old|deprecated|archive|archived)(?:[/\\]|[-_.])/i,kx=new Set(["readme","claude","agents","cursor","windsurf","copilot","gemini","cline","persona","docs","prompt","unknown"]),Rx=.45;function Cx(t){try{return Kt.existsSync(Y.dirname(t))}catch{return!1}}function Ax(t){let e=`dead-ref:${t}`;return`dead-ref-${qd.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function $x(t){let e=[0];for(let n=0;n<t.length;n++)t[n]===`
42
- `&&e.push(n+1);return e}function Lt(t,e){let n=0,s=t.length-1;for(;n<s;){let i=n+s+1>>1;t[i]<=e?n=i:s=i-1}return n+1}var Px=/\.(?:md|png|jpg|jpeg|gif|svg|webp|pdf)$/i;function Tx(t){let e=t.replace(/\s*#.*$/,""),s=(e.match(/^[ \t│|]*/)?.[0]??"").replace(/[│|]/g," ").length,i=e.trim();if(!i)return null;let r=/^(?:[│|]\s*)*(?:[├└][-─\s]+|[|+`][-─]+\s*)(.+)$/.exec(i),o=(r?r[1]:i)?.trim()??"";return!o||!r&&/\s/.test(o)?null:{entry:o,indent:s,hasConnector:!!r}}function Yd(t,e,n){let s=[],i=[],r=n;for(let o of t){let a=r;r+=o.length+1;let c=Tx(o);if(!c)continue;let l=c.entry;if(/\/$/.test(l)){let h=`${[...i].reverse().find(m=>m.indent<c.indent||m.indent===c.indent&&m.plain)?.path??""}${l}`;for(;i.length>0&&i[i.length-1].indent>=c.indent;)i.pop();i.push({indent:c.indent,path:h,plain:!c.hasConnector});continue}if(!Px.test(l))continue;let f=[...i].reverse().find(p=>p.indent<c.indent||p.indent===c.indent&&p.plain),d=/[/\\]/.test(l)?l:`${f?.path??""}${l}`;s.push({ref:d,evidence:o.trim(),line:Lt(e,a)})}return s}function Ix(t,e){let n=[];for(let s of Vn(t)){if(!s.closed)continue;let i=e[s.contentStartLine-1]??t.length;n.push(...Yd(s.lines,e,i))}return n}function Ox(t,e){return Yd(t.split(`
43
- `),e,0)}function Lx(t,e={}){let n=[],s=$x(t),i=xe(t),r=m=>{let g=Lt(s,m);return i[g-1]?.inFence?!0:(t.slice(s[g-1]??0,m).match(/`/g)?.length??0)%2===1},o=(m,g,b)=>{if(!m||Si(m))return;let w=Lt(s,b);vx(m)?n.push({ref:m,evidence:g,line:w,kind:"file"}):xx(m)&&!r(b)&&n.push({ref:m,evidence:g,line:w,kind:"linkPath"})},a,c=new RegExp(Md.source,Md.flags);for(;(a=c.exec(t))!==null;){if(a.index>=2&&t[a.index-2]==="["&&t[a.index-1]==="!")continue;let m=a[1]??"";o(lt(zd(m)),`[...](${m})`,a.index)}let l=new RegExp(Dd.source,Dd.flags);for(;(a=l.exec(t))!==null;){if(!a[0].slice(0,a[0].lastIndexOf("](")).includes("]("))continue;let g=a[1]??"";o(lt(zd(g)),`[...](${g})`,a.index)}let u=new RegExp(Fd.source,Fd.flags);for(;(a=u.exec(t))!==null;){let m=a[1]??"";/^[ \t]*\[\^/.test(a[0])||o(lt(m),a[0].trim(),a.index)}let f=new RegExp(Hd.source,Hd.flags);for(;(a=f.exec(t))!==null;){let m=a[1]??"";m&&!Si(m)&&n.push({ref:m,evidence:`@${m}`,line:Lt(s,a.index),kind:"file"})}let d=new RegExp(Bd.source,Bd.flags);for(;(a=d.exec(t))!==null;){let m=a[1]??"";if(m&&!Si(m)&&!m.includes("*")&&!m.includes("?")){let g=Y.extname(m).toLowerCase(),b=e.skipSourceBackticks&&Sx.has(g)&&!Ex.test(m);n.push({ref:m,evidence:`\`${m}\``,line:Lt(s,a.index),kind:b?"rootedSource":"file"})}}let p=new RegExp(Wd.source,Wd.flags);for(;(a=p.exec(t))!==null;){let m=a[1]??"",g=m.replace(/\/+$/,"").split("/").pop()??"";if(!m.endsWith("/")&&Y.extname(g)!=="")continue;let b=Lt(s,a.index),w=t.slice(s[b-1]??0,s[b]??t.length);cx.test(w)||n.push({ref:m,evidence:`\`${m}\``,line:Lt(s,a.index),kind:"rootedPath"})}if(ux.test(t)){let m=new RegExp(Gd.source,Gd.flags);for(;(a=m.exec(t))!==null;){let g=a[1]??"";g&&!Si(g)&&n.push({ref:g,evidence:a[0].trim(),line:Lt(s,a.index),kind:"file"})}for(let g of Ox(t,s))n.push({...g,kind:"file"});for(let g of Ix(t,s))n.push({...g,kind:"file"})}let h=t.split(`
44
- `);return n.filter(({ref:m,line:g})=>{let b=h[g-1]??"",w=fx.exec(b);if(!w)return!0;let y=Vd(w[1]??"");if(!y)return!0;let v=Vd(m);return!(v===y||v.endsWith(`/${y}`)||y.endsWith(`/${v}`))})}function da(t){return lt(t).replace(/\\/g,"/").split("/").filter(e=>e!==""&&e!==".")}function Nx(t){return da(t).some(e=>Kd.has(e.toLowerCase()))}function jx(t){try{let e=Y.basename(t);return Kt.readdirSync(Y.dirname(t)).some(n=>n.startsWith(`${e}.`))}catch{return!1}}var Mx=[...[...Kd,".git","worktrees",".worktrees","Library","Temp","Logs","vendor",".venv","venv","__pycache__","Pods",".gradle",".cache",".idea"].map(t=>`**/${t}/**`)];function Dx(t,e,n,s){let i=e.join("/"),r=`${n?"m":"x"}:${i}`,o=s.get(r);if(o!==void 0)return o;let a=fa.default.escapePath(i),c=[`**/${a}`];n&&c.push(`**/${a}.*`);let l;try{l=fa.default.sync(c,{cwd:t,dot:!0,onlyFiles:!1,followSymbolicLinks:!1,suppressErrors:!0,ignore:Mx}).length>0}catch{l=!1}return s.set(r,l),l}var Fx="__promptci_dir_probe__";function Hx(t,e,n,s,i,r){if(da(t)[0]===".git"||e!=="file"&&Nx(t))return null;let o=e==="rootedPath"||e==="linkPath",a=o?lt(t):t,c=[...new Set([Y.resolve(n,a),Y.resolve(s,a)])],l=c.filter(p=>se(s,p));for(let p of l){let h=Y.relative(s,p).replace(/\\/g,"/");if(h&&(i(h)||o&&i(`${h}/${Fx}`)))return null}if(e==="file"){if(c.some(ua))return null;let p=Y.extname(t.split("#")[0]??"").toLowerCase(),h=_x.has(p),m=c.some(Cx);return h&&m?.5:.85}if(l.length===0)return null;let u=o&&!a.endsWith("/");if(l.some(p=>ua(p)||u&&jx(p)))return null;if(e==="linkPath")return .8;let f=da(t);if(f.length<2||f[0]==="..")return null;let d=[n,s].filter(p=>Bx(Y.join(p,f[0])));return d.length===0||e==="rootedPath"&&(lx.has(f[0].toLowerCase())&&!a.endsWith("/")||f.length===2&&d.some(p=>ua(Y.join(p,f[1]))))||Dx(s,f,u,r)?null:.6}function Bx(t){try{return Kt.statSync(t).isDirectory()}catch{return!1}}function ha(t,e){let n=new Map,s,i=new Map;for(let a of t){let c=Y.dirname(a.path),l=Lx(a.content,{skipSourceBackticks:kx.has(a.fileType)});for(let{ref:u,evidence:f,line:d,kind:p}of l){if(gx(u)||bx(u)||pa(u))continue;s??=_i(e);let h=Hx(u,p,c,e,s,i);if(h===null)continue;let m=u.toLowerCase().replace(/\\/g,"/"),g=p==="rootedPath"||p==="linkPath"?m.replace(/^\.\//,"").replace(/\/+$/,""):m,b=`Reference: ${f}`;n.has(g)||n.set(g,{displayRef:u,kind:p,filePaths:new Set,fileLines:new Map,evidenceLines:[],minConfidence:h});let w=n.get(g);w.filePaths.add(a.path);let y=w.fileLines.get(a.path);(y===void 0||d<y)&&w.fileLines.set(a.path,d),w.evidenceLines.includes(b)||w.evidenceLines.push(b),w.minConfidence=Math.min(w.minConfidence,h)}}let r=[],o=Rx;for(let[a,{displayRef:c,kind:l,filePaths:u,fileLines:f,evidenceLines:d,minConfidence:p}]of n){if(p<o)continue;let h=[...u],m=l==="rootedPath"||l==="linkPath",g=m&&lt(c).endsWith("/"),b=g?"directory":m?"path":"file",w=Y.basename(lt(c).replace(/\/+$/,""));r.push({id:Ax(a),severity:"warning",category:"structure",title:`Broken ${b} reference: ${w}${g?"/":""}`,summary:`This instruction file references "${c}" which does not appear to exist. The ${b} may have been renamed, moved, or deleted.`,filePaths:h,locations:h.map(y=>{let v=f.get(y);return v!==void 0?{filePath:y,startLine:v}:{filePath:y}}),evidence:d,recommendation:"Verify the path is correct relative to the instruction file location, or remove the reference if the file no longer exists.",confidence:p})}return r}var Nt=x(require("node:crypto"),1),Ne=x(require("node:path"),1);function Yt(t,e,n){if(e.length===0)return[];let s=new Map;for(let i of t)i.relativePath!==void 0&&s.set(i.relativePath,i);return e.filter(i=>{if(!n(i.fileType))return!1;let r=i.aliasOf===void 0?void 0:s.get(i.aliasOf);return r===void 0||!n(r.fileType)})}function Qn(t){let e=new Map;for(let n of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=n.aliasOf??n.path,i=e.get(s);i?i.push(n):e.set(s,[n])}return[...e.values()]}function Jd(t,e,n){let s=Qn(Yt(t,e??[],n)).map(i=>i[0]);return s.length===0?t:[...t,...s]}var Sn=[{id:"no-verification-loop",title:"No verification loop instruction",summary:'No instruction found asking the agent to run lint, typecheck, or tests before marking work complete. Without this, agents commonly report "done" without validating that changes compile or pass tests.',patterns:[/run\s+(pnpm|npm|yarn)\s+(lint|test|build|typecheck)/i,/pnpm\s+(lint|test|build|typecheck)\b(?!\s+(?:outputs?|generates?|creates?|produces?|writes?|emits?|runs?)\b)/i,/\bnpm\s+(run\s+)?(lint|test|build)/i,/before\s+(you\s+)?(say|mark|call|consider|report)\s+(it\s+)?(done|complete|finished)/i,/before\s+(finishing|completing|submitting|pushing|closing)/i,/work\s+is\s+not\s+complete\s+until/i],recommendation:'Add an explicit rule such as: "Before saying done, run pnpm lint && pnpm typecheck && pnpm test && pnpm build. Work is not complete until all checks pass."',severity:"warning",confidence:.75,fixRecipe:"Before saying work is complete, run pnpm lint, pnpm typecheck, pnpm test, and pnpm build. If any command fails, report the failure and stop."},{id:"no-honesty-policy",title:'No "report failures honestly" instruction',summary:"No instruction found requiring the agent to report test failures, errors, or build breakage honestly. Without this, agents may claim success when commands actually fail.",patterns:[/report\s+(the\s+)?(fail|error|break)/i,/don.?t\s+(fake|claim|pretend)\s+success/i,/(?<!to\s+be\s+)\bhonestly?\b/i,/if\s+(a\s+)?(test|build|check)s?\s+(fail|break|error)/i,/never\s+skip\s+(failing\s+)?test/i,/never\s+hide\s+(error|fail)/i],recommendation:'Add a rule such as: "If tests fail, report the failure. Never claim success when commands error or tests are skipped."',severity:"warning",confidence:.75,fixRecipe:"If tests or commands fail, report the failure honestly. Never claim success when checks are skipped or error."},{id:"no-ask-when-unsure",title:'No "ask when unsure" instruction',summary:"No instruction found telling the agent to surface uncertainty \u2014 to ask or say so when it is unsure \u2014 instead of guessing. Without this, agents may proceed on assumptions and produce confidently wrong work.",patterns:[/\bif\s+(?:you(?:'|’)?re\s+|you\s+are\s+|ever\s+)?unsure\b/i,/\bif\s+in\s+(?:any\s+)?doubt\b/i,/\bwhen\s+(?:you(?:'|’)?re\s+|you\s+are\s+)?(?:unsure|uncertain)\b/i,/\bif\s+(?:you(?:'|’)?re\s+|you\s+are\s+|it(?:'|’)?s\s+)?uncertain\b/i,/\bif\s+you\s+(?:don(?:'|’)?t|do\s+not|dont)\s+know\b/i,/\bask\s+(?:before|first|for\s+clarification|the\s+user|a\s+question|questions)\b/i,/\bclarify\s+(?:before|first|with)\b/i,/\b(?:don(?:'|’)?t|do\s+not|dont)\s+guess\b/i,/\bsay\s+(?:you|that\s+you)\s+(?:don(?:'|’)?t|do\s+not|dont)\s+know\b/i,/\breport\s+uncertainty\b/i,/\backnowledge\s+(?:when|uncertainty|any\s+uncertainty)\b/i],recommendation:'Add a rule such as: "If you are uncertain about the correct approach, say so and ask before proceeding rather than guessing."',severity:"warning",confidence:.75,fixRecipe:"If you are uncertain about the correct approach, say so before proceeding rather than guessing."},{id:"no-read-before-edit",title:'No "read before edit" instruction',summary:"No instruction found requiring the agent to read a file before editing it. Agents that edit files they haven't read may clobber context or introduce inconsistencies.",patterns:[/read\s+(the\s+|a\s+|any\s+)?file\s+(fully\s+|first\s+)?before\s+(edit|modif|chang)/i,/read\s+(the\s+|a\s+)?file.*before\s+(edit|modif|chang)/i,/must\s+(first\s+)?read\s+(the\s+|a\s+|any\s+)?(file|source|code)/i,/always\s+read\s+(the\s+|a\s+)?(file|source|code)/i,/inspect\s+(the\s+|a\s+)?file\s+before/i,/read.*before.*edit/i,/before\s+(?:you\s+)?(?:edit|modif|chang)\w*\b[^.\n]{0,40}\bread(?:ing)?\b/i],recommendation:'Add a rule such as: "Always read a file fully before editing it."',severity:"warning",confidence:.75,fixRecipe:"Read a file before editing it. Preserve unrelated user changes."},{id:"no-scope-control",title:"No scope-control instruction",summary:"No instruction found telling the agent to avoid rewriting unrelated systems or making sweeping changes. Unconstrained agents often refactor things they were not asked to touch.",patterns:[/focused\s+(diff|change|edit|pr|commit)/i,/don.?t\s+rewrite\s+unrelated/i,/do\s+not\s+rewrite\s+unrelated/i,/avoid\s+unrelated\s+(change|edit|refactor)/i,/minimal\s+(change|diff|edit)/i,/small\s+(change|diff|edit|pr|commit)/i,/targeted\s+(change|edit|fix)/i,/prefer\s+(small|focused|minimal)\s+(diff|change|pr)/i],recommendation:'Add a rule such as: "Prefer focused, minimal diffs. Do not rewrite or refactor code unrelated to the current task."',severity:"warning",confidence:.7,fixRecipe:"Prefer focused, minimal diffs. Do not rewrite or refactor code unrelated to the current task."},{id:"no-preserve-scope",title:"No code-preservation instruction",summary:"No instruction found telling the agent to preserve existing code and only change what the task requires. Without this, agents may delete working code, drop tests, or overwrite unrelated edits to reach a passing state.",patterns:[/\bpreserve\s+(?:existing|unrelated|the\s+existing|current|working|any\s+existing)\b/i,/\bpreserve\s+(?:unrelated\s+changes|the\s+user(?:'|’)?s?\s+(?:changes|edits|work))\b/i,/\b(?:don(?:'|’)?t|do\s+not|dont|never)\s+(?:delete|remove|drop|strip)\s+(?:existing|working|unrelated|any)\b/i,/\bkeep\s+(?:existing|the\s+existing|current|working)\s+(?:code|behaviou?r|functionality|logic|tests?)\b/i,/\bonly\s+(?:change|modify|touch|edit|update)\s+(?:what|the\s+code\s+(?:that|you)|files?\s+(?:that|you)|lines?)\b/i,/\b(?:don(?:'|’)?t|do\s+not|dont)\s+(?:modify|change|touch)\s+code\s+outside\b/i,/\bleave\s+(?:unrelated|existing|working|other)\s+(?:code|files?|logic|behaviou?r)\s+(?:untouched|alone|intact|as[- ]is)\b/i],recommendation:'Add a rule such as: "Preserve existing code and only change what the task requires. Do not delete working code, tests, or unrelated edits."',severity:"warning",confidence:.7,fixRecipe:"Preserve existing code and only change what the task requires. Do not delete working code, tests, or unrelated edits."},{id:"no-plan-first",title:'No "plan before implementing" instruction',summary:"No instruction found asking the agent to outline an approach for complex tasks before writing code. Planning prompts significantly reduce wasted implementation effort on multi-file changes.",patterns:[/plan\s+(first|before|ahead)/i,/outline\s+(the\s+)?(approach|plan|design|steps)\s+before/i,/think\s+(?:through|it\s+through)\s+(?:the\s+)?(?:approach|plan|design|steps|task|problem)/i,/propose\s+(a\s+)?(plan|approach|design)/i,/before\s+implement\w+.*\b(plan|outline|design)\b/i,/design\s+before\s+(implement|cod)/i],recommendation:'Add a rule such as: "For complex or multi-file tasks, outline the approach and get confirmation before writing code."',severity:"info",confidence:.65,fixRecipe:"For complex or multi-file tasks, outline the approach and get confirmation before writing code."}],Wx=/\bdo\s+not\s+(edit|modify|change)\b/im,Gx=/<!--\s*auto[- ]?generated|auto[- ]?generated|<!--\s*generated\s*(?:by\s+\w+)?|this\s+file\s+is\s+generated|generated\s+by\s+\w+/i,Ux=/<\/?claude:[\w-]+|<instructions-for-claude[\s>]/i,Xd=/(?:follow|use|see|refer\s+to|canonical\s+(?:source|instructions?)|pointer\s+to)\s+[`'"*]*(?:\.?\/)?(?:\.github\/)?(?:AGENTS|CLAUDE)\.md\b/i,Vx=/\b(AGENTS|CLAUDE)\.md\b[^\n]{0,60}?\b(?:single\s+source\s+of\s+truth|canonical)\b/i;function zx(t){return`agent-practice-${Nt.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function qx(t){return`do-not-edit-${Nt.createHash("sha1").update(`do-not-edit:${t}`).digest("hex").slice(0,12)}`}function Kx(t){return`per-file-behavior-${Nt.createHash("sha1").update(`per-file-behavior:${t}`).digest("hex").slice(0,12)}`}function es(t,e){return e.some(n=>n.test(t))}function Yx(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
45
- `&&n++;return n}function Ei(t){return t.split(`
35
+ `)&&e.pop(),e}function Vt(t,e,n){let s=pd(t),i=[],r,o=1,a=[],c=u=>{let f=a.join(`
36
+ `),d=r!==void 0?_0(r):`${e}:0`;i.push({id:d,filePath:e,...n!==void 0?{relativePath:n}:{},heading:r,startLine:o,endLine:u,text:f,normalizedText:f.toLowerCase().trim()})},l=xe(t);for(let u=0;u<s.length;u++){let f=u+1,d=s[u]??"";if(l[u]?.inFence){a.push(d);continue}let p=/^ {0,3}(#{1,3})\s+(.+)/.exec(d);p?((a.length>0||r!==void 0)&&c(f-1),r=p[2].trim(),o=f,a=[d]):a.push(d)}return(a.length>0||r!==void 0)&&c(s.length),i}function zt(t){let e=Math.min(t.length,Kn);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}var E0=new Set([".clinerules/**/*.md","!.clinerules/workflows/**"]);async function k0(t){let e=!1;try{e=(await di.stat(Le.join(t,".clinerules"))).isDirectory()}catch{}return e?cd:cd.filter(n=>!E0.has(n))}function hd(t){try{return qn.realpathSync.native(t)}catch{return null}}async function ld(t,e,n,s){let i=hd(n);if(i===null||!X(e,i))return;let r;try{let o=qn.constants.O_NOFOLLOW??0;r=await di.open(i,qn.constants.O_RDONLY|o);let a=await r.stat();if(!a.isFile()||a.size>ce)return;let c=await r.readFile();if(zt(c))return;let l=c.toString("utf-8"),u=Le.relative(t,n).replace(/\\/g,"/"),f=Vt(l,n,u),d=pd(l).length,p=l.length;return{path:n,relativePath:u,fileType:S0(s),content:l,sections:f,lineCount:d,charCount:p,estimatedTokens:Math.round(p/4)}}catch{return}finally{await r?.close().catch(()=>{})}}var ud=260,R0=8;function C0(t,e,n){let s=t.relativePath;if(s===void 0||t.charCount>ud+16)return;let i=t.content.replace(/^\u{FEFF}/u,"").trim();if(i===""||i.length>ud||/[\r\n]/.test(i)||i.startsWith("/")||/^[A-Za-z]:/.test(i)||i.includes("\\"))return;let r=Le.posix.normalize(Le.posix.join(Le.posix.dirname(s),i));if(!(r===".."||r.startsWith("../")||r===s||!e.has(r)))return n.isSymlink(s)?r:void 0}function fd(t,e){return{...e,path:t.path,relativePath:t.relativePath,fileType:t.fileType,sections:Vt(e.content,t.path,t.relativePath),aliasOf:e.relativePath}}function A0(t,e,n){let s=new Map;for(let c of t)c.relativePath!==void 0&&s.set(c.relativePath,c);let i=new Map;for(let c of t){let l=C0(c,s,n);l!==void 0&&i.set(c.relativePath,l)}if(i.size===0)return{files:t,aliases:e};let r=new Map;for(let c of i.keys()){let l=i.get(c),u=1;for(;i.has(l)&&u<R0;)l=i.get(l),u++;i.has(l)||r.set(c,s.get(l))}if(r.size===0)return{files:t,aliases:e};let o=t.filter(c=>c.relativePath===void 0||!r.has(c.relativePath)),a=e.map(c=>{let l=c.aliasOf===void 0?void 0:r.get(c.aliasOf);return l===void 0?c:fd(c,l)});for(let[c,l]of r)a.push(fd(s.get(c),l));return{files:o,aliases:a}}async function pi(t){let e=Le.resolve(t.repoPath),n=hd(e)??e,s=t.include&&t.include.length>0?t.include:await k0(e),i=[...v0.map(p=>`**/${p}/**`),...t.exclude??[]],r;try{r=await(0,dd.default)(s,{cwd:e,ignore:i,dot:!0,absolute:!1,onlyFiles:!1,objectMode:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{return{files:[],aliases:[]}}let o=[],a=[];for(let p of r)p.dirent.isSymbolicLink()?a.push(p.path):p.dirent.isFile()&&o.push(p.path);a.sort();let c=[],l=[],u=new Map,f=[];for(let p of o){let h=Le.resolve(e,p);if(!X(e,h)||!ae(e,h))continue;let m=It(h);f.push({relPath:p,absPath:h,real:m,direct:m!==null&&m===Le.join(n,p)})}f.sort((p,h)=>Number(h.direct)-Number(p.direct)||p.relPath.localeCompare(h.relPath));for(let{relPath:p,absPath:h,real:m}of f){let g=await ld(e,n,h,p);if(!g)continue;let b=m!==null?u.get(m):void 0;if(b){l.push({...g,aliasOf:b.relativePath});continue}c.push(g),m!==null&&u.set(m,g)}for(let p of a){let h=Le.resolve(e,p);if(!X(e,h)||!ae(e,h))continue;let m=await ld(e,n,h,p);if(!m)continue;let g=It(h),b=g!==null?u.get(g):void 0;if(b){l.push({...m,aliasOf:b.relativePath});continue}c.push(m),g!==null&&u.set(g,m)}let d=A0(c,l,ad(e));return d.files.sort((p,h)=>p.path.localeCompare(h.path)),d.aliases.sort((p,h)=>p.path.localeCompare(h.path)),d}async function Ko(t){return(await pi(t)).files}var hi=x(require("node:fs/promises"),1),ye=x(require("node:path"),1),Jo=x(wn(),1);async function ot(t){try{return await hi.access(t),!0}catch{return!1}}async function Yo(t){try{return(await hi.stat(t)).isDirectory()}catch{return!1}}async function Yn(t){let e=ye.resolve(t);if((await(0,Jo.default)("next.config.*",{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"nextjs";let s=await ot(ye.join(e,"package.json"));if(s){let m=await Yo(ye.join(e,"app")),g=await Yo(ye.join(e,"pages"));if(m||g)return"nextjs"}let i=await Yo(ye.join(e,"Assets")),r=await ot(ye.join(e,"ProjectSettings","ProjectVersion.txt"));if(i&&r)return"unity";if((await(0,Jo.default)(["*.sln","*.csproj"],{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"dotnet";let a=await ot(ye.join(e,"tsconfig.json"));if(s||a)return"typescript";let c=await ot(ye.join(e,"pyproject.toml")),l=await ot(ye.join(e,"requirements.txt")),u=await ot(ye.join(e,"Pipfile")),f=await ot(ye.join(e,"environment.yml")),d=await ot(ye.join(e,"setup.py"));return c||l||u||f||d?"python":await ot(ye.join(e,"go.mod"))?"go":await ot(ye.join(e,"Cargo.toml"))?"rust":"unknown"}function Xo(t){let e=t.map(n=>n.content).join(`
37
+ `);return/\bnext\.?js\b|\bapp\s+router\b|\bpages?\s+router\b|\bnext\s+build\b|\bnext\s+dev\b/i.test(e)?"nextjs":/\bunity\b/i.test(e)&&/\b(lts|editor|hub|engine)\b/i.test(e)||/\bmonobehaviour\b|\bunityengine\b|\bgameobject\b|\bprefab\b|\bscriptableobject\b/i.test(e)?"unity":/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(e)?"dotnet":/\btypescript\b|\btsconfig\b|\btsc\s|\bpnpm\b|\bnpm\s+run\b|\bvitest\b|\bjest\b/i.test(e)?"typescript":/\bpython\b|\bpip\b|\bpoetry\b|\bvenv\b|\bpytest\b|\bpyproject\.toml\b/i.test(e)?"python":/\bgo\.mod\b|\bgo\s+(build|test|run|get|mod)\b|\bgolang\b/i.test(e)?"go":/\bcargo\.toml\b|\bcargo\s+(build|test|run|clippy|fmt)\b|\brustc\b/i.test(e)?"rust":"unknown"}var bd=x(require("node:crypto"),1);var $0=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}]/u;function mi(t){return`<U+${t.toString(16).toUpperCase().padStart(4,"0")}>`}function P0(t,e=t.codePointAt(0)){return e===9||e>=32&&e<127?!1:$0.test(t)||e===8232||e===8233||e===12644||e===65440||e===4447||e===4448||e===847||e===6068||e===6069||e>=65024&&e<=65039||e>=917760&&e<=917999||e>=6155&&e<=6159}function gi(t){let e="",n="",s=()=>{n&&(e+=`<TAGS:"${n}">`),n=""};for(let i of t){let r=i.codePointAt(0);if(r>=917504&&r<=917631){n+=r>=917536&&r<=917630?String.fromCharCode(r-917504):mi(r);continue}s(),e+=P0(i,r)?mi(r):i}return s(),e}function Y(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function T0(t,e,n=120){let i=new RegExp(e.source,e.flags.replace("g","")).exec(t);return i?Y(i[0],n):void 0}function vn(t,e,n,s=120){let i=T0(t,e,s);return i?`${n}: "${i}"`:n}function md(t){return t.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function L(t){return md(t.relativePath??t.path)}function Be(t){return md(t.relativePath??t.filePath)}var yi=150,I0=80,O0=10,L0=.8,N0=.6,j0=.6,gd=new Set(["introduction","overview","notes","note","about","background","context","disclaimer","warning","important","readme","summary","project summary","project overview","project description","description","what is this","table of contents","contents","license","changelog"]);function wd(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}function Zo(t){let e=t.match(/\b\w+\b/g)??[];return new Set(e)}function M0(t,e){if(t.size===0&&e.size===0)return 1;if(t.size===0||e.size===0)return 0;let n=0;for(let s of t)e.has(s)&&n++;return n/(t.size+e.size-n)}function Qo(t){if(!t)return!1;let e=t.toLowerCase().trim();if(gd.has(e))return!0;for(let n of gd)if(e.startsWith(n))return!0;return!1}function yd(t){return t?.toLowerCase().replace(/\s+/g," ").trim()??""}function D0(t,e){let n=yd(t.heading),s=yd(e.heading);return n.length>0&&n===s}function Jn(t,e){if(!t.has(e))return e;let n=Jn(t,t.get(e));return t.set(e,n),n}function F0(t,e,n){let s=Jn(t,e),i=Jn(t,n);s!==i&&t.set(s,i)}function ea(t){let e=[...t].sort().join("|");return`duplicate-${bd.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function ta(t){let e=[];for(let u of t)for(let f of u.sections){let d=wd(f.text);d.length<I0||Zo(d).size<O0||e.push({...f,normalizedText:d})}let n=new Map,s=new Map,i=[];for(let u=0;u<e.length;u++)for(let f=u+1;f<e.length;f++){let d=e[u],p=e[f];if(d.filePath===p.filePath&&d.startLine===p.startLine)continue;let h=`${Be(d)}:${d.startLine}`,m=`${Be(p)}:${p.startLine}`,g=d.normalizedText,b=p.normalizedText,w=null,y=0;if(Qo(d.heading)||Qo(p.heading))continue;let v=d.filePath===p.filePath;if(g===b){if(!v&&(g.length<yi||b.length<yi)&&!D0(d,p))continue;w="high",y=.95}else{if(!v&&(g.length<yi||b.length<yi))continue;let R=v?j0:L0,k=M0(Zo(g),Zo(b));k>=R?(w="warning",y=v?.8:.75):!v&&k>=N0&&(w="info",y=.5)}w!==null&&(s.set(h,d),s.set(m,p),F0(n,h,m),i.push({keyA:h,keyB:m,severity:w,confidence:y}))}let r=new Map;for(let u of s.keys()){let f=Jn(n,u);r.has(f)||r.set(f,[]),r.get(f).push(u)}let o={info:0,warning:1,high:2,critical:3},a=new Map,c=new Map;for(let u of i){let f=Jn(n,u.keyA),d=a.get(f);(!d||o[u.severity]>o[d])&&(a.set(f,u.severity),c.set(f,u.confidence))}let l=[];for(let[u,f]of r){if(f.length<2)continue;let d=f.map(k=>s.get(k)),p=a.get(u)??"warning",h=c.get(u)??.75,m=[...new Set(d.map(k=>k.filePath))],g=[...new Set(d.map(k=>k.heading??"(untitled)"))],b=g.length===1?g[0]:g.slice(0,2).join(" / "),w=m.length,y=w>2?`Possible duplicate: ${b} (${w} files)`:`Possible duplicate: ${b}`,v=d.slice(1).reduce((k,T)=>k+Math.round(T.text.length/4),0),R=w>2?`This section appears highly similar in ${w} files. Consider consolidating into one canonical location.`:"These sections appear highly similar. Consider consolidating them into one canonical location.";l.push({id:ea(f),severity:p,category:"duplicate",title:y,summary:R,filePaths:m,locations:d.map(k=>({filePath:k.filePath,startLine:k.startLine,endLine:k.endLine})),evidence:[Y(d[0].normalizedText,200),`Duplicated size: ~${v} tokens`],recommendation:`Consolidate these sections into one canonical location (e.g. AGENTS.md) and use forwarding pointers to save ~${v} tokens per session. If both are intentional, add a comment clarifying the distinction.`,autoApplySafe:w>=2,confidence:h})}return l}function na(t){let e=[];for(let n of t){let s=new Map;for(let o of n.sections){if(!o.heading||Qo(o.heading))continue;let a=o.heading.toLowerCase().replace(/^#+\s*/,"").replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim();a.length<3||(s.has(a)||s.set(a,[]),s.get(a).push(o))}for(let[,o]of s){if(o.length<2||new Set(o.map(f=>{let d=/^(#{1,6})\s/.exec(f.text);return d?d[1].length:0})).size>1)continue;let c=o.map(f=>`${L(n)}:${f.startLine}`),l=ea(c),u=o[0].heading??"(untitled)";e.push({id:l,severity:"warning",category:"duplicate",title:`Duplicate section heading in one file: "${u}"`,summary:`The heading "${u}" appears ${o.length} times in this file. This is likely an accidental duplicate \u2014 consider consolidating into one section.`,filePaths:[n.path],locations:o.map(f=>({filePath:n.path,startLine:f.startLine,endLine:f.endLine})),evidence:[`Heading "${u}" found at lines: ${o.map(f=>f.startLine).join(", ")}`],recommendation:"Merge the duplicate sections into one, or rename one if the distinction is intentional.",confidence:.85})}let i=[...s.keys()],r=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a],u=c.length<=l.length?c:l,f=c.length<=l.length?l:c;if(u.length<4||!f.startsWith(u))continue;let d=f.slice(u.length);if(!/^\s/.test(d)||!d.trimStart())continue;let h=[c,l].sort().join("|");if(r.has(h))continue;r.add(h);let m=s.get(c),g=s.get(l),b=[...m,...g].sort((y,v)=>y.startLine-v.startLine),w=b.map(y=>`${L(n)}:${y.startLine}`);e.push({id:ea(w),severity:"warning",category:"duplicate",title:`Overlapping section headings in one file: "${m[0].heading}" / "${g[0].heading}"`,summary:"These section headings appear to cover the same topic \u2014 one is a prefix/subset of the other. This is likely an accidental split. Consider merging into one canonical section.",filePaths:[n.path],locations:b.map(y=>({filePath:n.path,startLine:y.startLine,endLine:y.endLine})),evidence:[`"${m[0].heading}" at line ${m[0].startLine}`,`"${g[0].heading}" at line ${g[0].startLine}`],recommendation:"Consolidate these sections into one. If the distinction is intentional, rename one to make the difference clear.",confidence:.75})}}return e}var wi=x(require("node:crypto"),1),sa=x(require("node:path"),1);var H0=1,Ad=new Set(["for","to","when","in","with","as","from","the","and","or","but","if","are","is","has","have","had","will","was","were","by","of","at","on","an","a","all","any","this","that","these","those","our","your","their","its","so","than","be"]),B0=new Set(["for","when","if","unless","except"]),W0=new Set(["it","them","they","we","code","sure","careful","good","clean","simple","easy","proper","consistent","clear","correct","possible","necessary","appropriate"]),$d=new Set(["use","run","write","call","create","add","implement","put","keep","follow","apply","make","define","ensure","check","test","build","deploy","configure","handle","prefer","avoid","include","return","pass","store","log","load","fetch","set","get","import"]);function vd(t,e,n=3,s=!1){let i=t.slice(e).replace(/^\s+/,"");if(s){let a=/^([a-zA-Z]+)\s+/.exec(i);a&&$d.has(a[1].toLowerCase())&&(i=i.slice(a[0].length))}let r=[],o=i.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim();for(let a of o.split(/\s+/)){let c=a.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g,"").toLowerCase();if(c&&(Ad.has(c)||!/^[a-z]/i.test(c)&&!/^[0-9]+[a-z]/i.test(c)||(r.push(c),r.length>=n)))break}return r.join(" ")}var Xn=[{label:"use / do not use",positivePattern:/\buse\s+/i,negativePattern:/\b(?:do\s+not|don['']t|never)\s+use\s+|[—–]\s*not\s+/i,skipLeadingVerb:!1},{label:"use / migrating away from",positivePattern:/\buse\s+/i,negativePattern:/\b(?:migrat(?:ing|e|ed)\s+(?:away\s+from|off\s+of)\s+|moving\s+away\s+from\s+|switch(?:ing|ed)?\s+(?:away\s+from|off\s+of)\s+|dropping\s+)/i,skipLeadingVerb:!1,allowSingleTokenMatch:!0},{label:"acceptable / never",positivePattern:/\b(?:is|are)\s+acceptable\b/i,negativePattern:/\bnever\s+use\s+|\b(?:do\s+not|don['']t)\s+use\s+/i,skipLeadingVerb:!1,extractPositiveSubjectBefore:!0},{label:"use / avoid",positivePattern:/\buses?\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!1,allowSingleTokenMatch:!0},{label:"declared stack / not",positivePattern:/\b(?:framework|library|runtime|sdk|engine|package|tool|stack|lang(?:uage)?|cli)\b[^:\n]{0,20}:\s*/i,negativePattern:/[—–]\s*not\s+|\bnot\s+using\s+/i,skipLeadingVerb:!1},{label:"always / never",positivePattern:/\balways\s+/i,negativePattern:/\bnever\s+/i,skipLeadingVerb:!0},{label:"always / avoid",positivePattern:/\balways\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!0},{label:"must / avoid",positivePattern:/\bmust\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!0},{label:"prefer / avoid",positivePattern:/\bprefer\s+/i,negativePattern:/\bavoid\s+/i,skipLeadingVerb:!0},{label:"preferred / only acceptable",positivePattern:/\b(?:is|are)\s+(?:generally\s+|usually\s+)?preferred\b/i,negativePattern:/\b(?:is|are)\s+only\s+acceptable\b|\b(?:acceptable|allowed)\s+only\b/i,skipLeadingVerb:!1,extractSubjectBefore:!0}];function G0(t,e,n,s){let i=t.slice(e).replace(/^\s+/,"");if(s){let l=/^([a-zA-Z]+)\s+/.exec(i);l&&$d.has(l[1].toLowerCase())&&(i=i.slice(l[0].length))}let r=i.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim(),o=n.split(" ").filter(Boolean),a=r;for(let l of o){let u=a.toLowerCase().indexOf(l);if(u<0)return!1;a=a.slice(u+l.length).trimStart()}a=a.replace(/^[^a-zA-Z]+/,"");let c=/^([a-zA-Z]+)/.exec(a)?.[1]?.toLowerCase()??"";return B0.has(c)}function bi(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}function xd(t){if(!t||t.length<2)return!0;let e=t.split(" ").filter(Boolean);return e.length===0?!0:e.every(n=>W0.has(n))}function U0(t,e){let n=new Set(t.split(" ").filter(Boolean)),s=new Set(e.split(" ").filter(Boolean));if(n.size===0||s.size===0)return 0;let i=0;for(let o of n)s.has(o)&&i++;let r=n.size+s.size-i;return i/r}function Sd(t,e,n=4){let s=t.slice(0,e).trimEnd();if(!s)return"";let i=0;for(let a=s.length-1;a>=0;a--)if(/[,;.]/.test(s[a])){i=a+1;break}let r=s.slice(i).trim(),o=[];for(let a of r.split(/\s+/).reverse()){let c=a.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g,"").toLowerCase();if(c&&!Ad.has(c)&&(o.unshift(c),o.length>=n))break}return o.join(" ")}function V0(t){let e=t.text.split(`
38
+ `).map(i=>i.trim()),n=[],s="";for(let i of e){let r=/^ {0,3}#{1,6}\s/.test(i),o=/^(?:[-*+]\s+|\d+[.)]\s+)/.test(i);if(!i||i.startsWith("|")||r){s&&(n.push(s),s=""),r&&n.push(i);continue}o&&s&&(n.push(s),s=""),s=s?`${s} ${i}`:i,/[.!?:;]$/.test(i)&&(n.push(s),s="")}return s&&n.push(s),n}function _d(t,e){let n=t.flags.includes("g")?t.flags:`${t.flags}g`,s=new RegExp(t.source,n),i=[],r;for(;(r=s.exec(e))!==null;)i.push({index:r.index,text:r[0]}),r[0].length===0&&s.lastIndex++;return i}function z0(t){let e=[],n=V0({...t,text:Ke(t.text)});for(let s=0;s<Xn.length;s++){let i=Xn[s];for(let r of n){let o=i.skipLeadingVerb??!1,a=i.extractSubjectBefore??!1,c=_d(i.negativePattern,r),l=r;for(let f of c){let d=f.index+f.text.length,p=a,h=bi(p?Sd(r,f.index,4):vd(r,d,3,o));if(h.length>=2&&!xd(h)){let m=!p&&G0(r,d,h,o);e.push({section:t,pairIndex:s,polarity:"negative",subject:h,matchedLine:r,hasQualifier:m})}l=l.slice(0,f.index)+" ".repeat(f.text.length)+l.slice(d)}let u=_d(i.positivePattern,l);for(let f of u){let d=a||(i.extractPositiveSubjectBefore??!1),p=bi(d?Sd(r,f.index,4):vd(r,f.index+f.text.length,3,o));p.length>=2&&!xd(p)&&e.push({section:t,pairIndex:s,polarity:"positive",subject:p,matchedLine:r})}}}return e}function Ed(t,e,n,s,i,r){let o=[`${t}:${e}`,`${n}:${s}`].sort(),a=`${o[0]}|${o[1]}|${i}|${r}`;return`conflict-${wi.createHash("sha1").update(a).digest("hex").slice(0,12)}`}function ia(t){let e=[];for(let a of t)for(let c of a.sections)c.text.trim().length>=H0&&e.push(c);let n=[];for(let a of e)n.push(...z0(a));let s=[],i=new Set;for(let a=0;a<n.length;a++)for(let c=a+1;c<n.length;c++){let l=n[a],u=n[c];if(l.pairIndex!==u.pairIndex||l.polarity===u.polarity)continue;let f=l.polarity==="positive"?l:u,d=l.polarity==="negative"?l:u,p=f.subject===d.subject?1:U0(f.subject,d.subject),h;if(f.subject===d.subject){let R=f.subject.split(" ").filter(Boolean).length===1&&(new RegExp(`\`${f.subject}\\.[a-z]`,"i").test(f.matchedLine)||new RegExp(`\`${d.subject}\\.[a-z]`,"i").test(d.matchedLine)),k=Xn[l.pairIndex];h=d.hasQualifier&&/\balways\b/i.test(f.matchedLine)&&k.label.includes("always")?.5:d.hasQualifier?.35:R?.5:.8}else if(p>=.5){let v=Xn[l.pairIndex],R=f.subject.split(" ").filter(Boolean),k=d.subject.split(" ").filter(Boolean);if(R.length<2||k.length<2){if(!v.allowSingleTokenMatch)continue;let T=R.length<=k.length?R[0]:k[0];if(!(R.length>k.length?f.subject:d.subject).startsWith(T))continue}h=d.hasQualifier?.3:.5}else continue;if(h<.4)continue;let m=Ed(Be(f.section),f.section.startLine,Be(d.section),d.section.startLine,l.pairIndex,f.subject);if(i.has(m))continue;i.add(m);let g=h>=.7?"high":"warning",b=Xn[l.pairIndex],w=f.subject.length<=d.subject.length?f.subject:d.subject,y=Array.from(new Set([f.section.filePath,d.section.filePath]));s.push({id:m,severity:g,category:"conflict",title:`Possible conflicting instruction: ${w}`,summary:`Possible conflict \u2014 review these together. A "${b.label}" directive pattern was found pointing in opposite directions for the subject "${w}".`,filePaths:y,locations:[{filePath:f.section.filePath,startLine:f.section.startLine,endLine:f.section.endLine},{filePath:d.section.filePath,startLine:d.section.startLine,endLine:d.section.endLine}],evidence:[f.matchedLine,d.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:h})}let r=new Map,o=new Map;for(let a of n)a.polarity==="positive"?(r.has(a.subject)||r.set(a.subject,[]),r.get(a.subject).push(a)):(o.has(a.subject)||o.set(a.subject,[]),o.get(a.subject).push(a));for(let[a,c]of r){let l=o.get(a);if(l)for(let u of c)for(let f of l){if(u.pairIndex===f.pairIndex||u.section.filePath===f.section.filePath&&u.section.startLine===f.section.startLine)continue;{let h=u.subject.split(" ").filter(Boolean).length,m=f.subject.split(" ").filter(Boolean).length;if(h<2||m<2)continue}if(f.hasQualifier)continue;let d=Ed(Be(u.section),u.section.startLine,Be(f.section),f.section.startLine,-1,a);if(i.has(d))continue;i.add(d);let p=Array.from(new Set([u.section.filePath,f.section.filePath]));s.push({id:d,severity:"warning",category:"conflict",title:`Possible conflicting instruction: ${a}`,summary:`Possible conflict \u2014 review these together. Opposing directives for "${a}" were found across instruction files.`,filePaths:p,locations:[{filePath:u.section.filePath,startLine:u.section.startLine,endLine:u.section.endLine},{filePath:f.section.filePath,startLine:f.section.startLine,endLine:f.section.endLine}],evidence:[u.matchedLine,f.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:.5})}}return s}var q0=[{re:/\.NET\s+v?(\d+)(?:\.\d+)*/gi,name:".NET",normalize:t=>t.split(".")[0]},{re:/ASP\.NET\s+Core\s+v?(\d+)/gi,name:"ASP.NET Core",normalize:t=>t.split(".")[0]},{re:/\bNode(?:\.?js)?\s+v?(\d+)/gi,name:"Node.js",normalize:t=>t.split(".")[0]},{re:/\bReact\s+v?(\d+)/gi,name:"React",normalize:t=>t.split(".")[0]},{re:/\bNext\.?js\s+v?(\d+)/gi,name:"Next.js",normalize:t=>t.split(".")[0]},{re:/\bPython\s+v?(\d+\.\d+|\d+)/gi,name:"Python",normalize:t=>t.split(".")[0]},{re:/\bGo\s+v?(\d+\.\d+)/gi,name:"Go",normalize:t=>t},{re:/\bUnity\s+v?(20\d{2}\.\d+|\d+)/gi,name:"Unity",normalize:t=>t.split(".")[0]},{re:/\bMirror(?:\s+Networking)?\s+v?(\d{2,4}(?:\.\d+)?)/gi,name:"Mirror",normalize:t=>t.split(".")[0]},{re:/\bTypeScript\s+v?(\d+)/gi,name:"TypeScript",normalize:t=>t.split(".")[0]},{re:/\bDjango\s+v?(\d+)/gi,name:"Django",normalize:t=>t.split(".")[0]},{re:/\bRails?\s+v?(\d+)/gi,name:"Rails",normalize:t=>t.split(".")[0]},{re:/\bLaravel\s+v?(\d+)/gi,name:"Laravel",normalize:t=>t.split(".")[0]},{re:/\bRust\s*\(?\s*v?(20\d{2})\s+edition\b/gi,name:"Rust edition",normalize:t=>t},{re:/\bedition\s*=\s*["']?(20\d{2})["']?/gi,name:"Rust edition",normalize:t=>t},{re:/\btokio`?\s+v?(\d+(?:\.\d+)?)/gi,name:"tokio",normalize:t=>{let[e,n]=t.split(".");return e==="0"&&n?`0.${n}`:e??t}},{re:/\baxum`?\s+v?(\d+(?:\.\d+)?)/gi,name:"axum",normalize:t=>{let[e,n]=t.split(".");return e==="0"&&n?`0.${n}`:e??t}},{re:/\b(?:MSRV|minimum\s+supported\s+rust\s+version)\s+v?(\d+\.\d+)/gi,name:"Rust MSRV",normalize:t=>t},{re:/\bPhoenix\s+v?(\d+(?:\.\d+)?)/gi,name:"Phoenix",normalize:t=>t.split(".")[0]},{re:/\bElixir\s+v?(\d+(?:\.\d+)?)/gi,name:"Elixir",normalize:t=>t.split(".")[0]},{re:/\bSpring\s+Boot\s+v?(\d+)/gi,name:"Spring Boot",normalize:t=>t.split(".")[0]},{re:/\bJava\s+v?(\d+)/gi,name:"Java",normalize:t=>t.split(".")[0]},{re:/\bKotlin\s+v?(\d+)/gi,name:"Kotlin",normalize:t=>t.split(".")[0]}];function K0(t,e){let n=t.slice(Math.max(0,e-50),e).toLowerCase();return/\bnot\s+$|\bnot\s*\($|\(not\s/.test(n)||n.trimEnd().endsWith("not")||/\b(?:deprecated|removed|introduced|added)\s+in\s+\S*\s*$/.test(n)}function Y0(t){let e=new Map;for(let{re:n,name:s,normalize:i}of q0){let r=new RegExp(n.source,n.flags),o;for(;(o=r.exec(t))!==null;){if(K0(t,o.index))continue;let a=i(o[1]);e.has(s)||e.set(s,new Set),e.get(s).add(a)}}return e}function J0(t,e){let n=`version-conflict:${t}:${[...e].sort().join("|")}`;return`version-conflict-${wi.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function ra(t){if(t.length<2)return[];let e=t.map(r=>({file:r,versions:Y0(Ke(r.content))})),n=new Map;for(let{file:r,versions:o}of e)for(let[a,c]of o){n.has(a)||n.set(a,new Map);let l=n.get(a);for(let u of c)l.has(u)||l.set(u,[]),l.get(u).push(r.path)}let s=[],i=r=>r.split(/[\\/]/).pop()??r;for(let[r,o]of n){if(o.size<=1)continue;let a=[...o.keys()],c=[...new Set([...o.values()].flat())];if(a.map(p=>o.get(p)).every(p=>p.every(h=>h===c[0])))continue;let f=J0(r,a),d=a.map(p=>`${r} ${p} referenced in: ${o.get(p).map(i).join(", ")}`);s.push({id:f,severity:"high",category:"conflict",title:`Version conflict: ${r} (${a.join(" vs ")})`,summary:`Possible conflict \u2014 review these together. Different instruction files specify different versions of ${r}: ${a.join(" vs ")}.`,filePaths:c,locations:c.map(p=>({filePath:p})),evidence:d,recommendation:`Ensure all instruction files agree on which version of ${r} this project targets. Remove or update whichever reference is out of date.`,confidence:.75})}return s}function X0(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z0={"kebab-case":["kebab-case","kebab case","kebabcase"],camelcase:["camelcase","camel case","camel-case"],pascalcase:["pascalcase","pascal case","pascal-case"]};function kd(t){let e=Z0[t.toLowerCase()]??[t];return new RegExp(`\\b(?:${e.map(X0).join("|")})\\b`,"i")}var Q0=[{termA:"kebab-case",termB:"camelcase",dimension:"file naming convention"},{termA:"kebab-case",termB:"pascalcase",dimension:"file naming convention"},{termA:"camelcase",termB:"pascalcase",dimension:"file naming convention"},{termA:"ef core",termB:"dapper",dimension:"data access library"},{termA:"entity framework",termB:"dapper",dimension:"data access library"},{termA:"redux",termB:"zustand",dimension:"state management library"},{termA:"redux",termB:"mobx",dimension:"state management library"},{termA:"pip",termB:"poetry",dimension:"Python package manager"},{termA:"pages router",termB:"app router",dimension:"Next.js routing strategy"},{termA:"named exports",termB:"default exports",dimension:"module export style"},{termA:"coroutine",termB:"unitask",dimension:"Unity async pattern"},{termA:"coroutine",termB:"async/await",dimension:"Unity async pattern"},{termA:"coroutines",termB:"unitask",dimension:"Unity async pattern"},{termA:"coroutines",termB:"async/await",dimension:"Unity async pattern"},{termA:"unit tests only",termB:"integration suite",dimension:"test scope"},{termA:"unit tests only",termB:"full test suite",dimension:"test scope"},{termA:"lightweight unit tests",termB:"integration suite",dimension:"test scope"},{termA:"cobra",termB:"urfave",dimension:"Go CLI framework"},{termA:"gorm",termB:"sqlx",dimension:"Go data-access library"}],Rd=/\b(?:use|prefer|always|must|should|follow|rely\s+on|stick\s+to|require)\b/i;function Cd(t,e){let n=t.split(`
39
+ `).map(s=>s.trim());for(let s=0;s<n.length;s++){let i=n[s];if(e.test(i)&&Rd.test(i))return!0;let r=n[s+1];if(i&&r){let o=`${i} ${r}`;if(e.test(o)&&Rd.test(o))return!0}}return!1}function oa(t){if(t.length<2)return[];let e=[],n=new Set,s=new Map(t.map(r=>[r.path,Ke(r.content)])),i=r=>s.get(r.path)??r.content;for(let r of Q0){let o=kd(r.termA),a=kd(r.termB),c=t.filter(w=>o.test(i(w))),l=t.filter(w=>a.test(i(w)));if(c.length===0||l.length===0)continue;let u=new Set(c.map(w=>w.path)),f=new Set(l.map(w=>w.path));if([...u].every(w=>f.has(w))&&[...f].every(w=>u.has(w)))continue;let p=c.some(w=>Cd(i(w),o)),h=l.some(w=>Cd(i(w),a));if(!p&&!h)continue;let m=[r.termA.toLowerCase(),r.termB.toLowerCase()].sort().join("|");if(n.has(m))continue;n.add(m);let g=[...new Set([...c,...l].map(w=>w.path))],b=`competing-tech-${wi.createHash("sha1").update(m).digest("hex").slice(0,12)}`;e.push({id:b,severity:"warning",category:"conflict",title:`Possible ${r.dimension} conflict: "${r.termA}" vs "${r.termB}"`,summary:`Possible conflict \u2014 review these together. Different instruction files reference competing ${r.dimension} choices: "${r.termA}" and "${r.termB}".`,filePaths:g,locations:g.map(w=>({filePath:w})),evidence:[`"${r.termA}" referenced in: ${c.map(w=>sa.basename(w.path)).join(", ")}`,`"${r.termB}" referenced in: ${l.map(w=>sa.basename(w.path)).join(", ")}`],recommendation:`Review both instruction files and decide which ${r.dimension} is canonical. Remove or update whichever reference contradicts the team's actual choice.`,confidence:.6})}return e}var Sn=x(require("node:fs"),1),j=x(require("node:path"),1),Jd=x(require("node:crypto"),1),ma=x(wn(),1);var Pe=x(require("node:fs"),1),vi=x(require("node:path"),1),Ld=x(require("node:crypto"),1),Nd=x(wn(),1),xi=x(Et(),1);function Kt(t){return t.replace(/\\/g,"/")}function at(t,e){let n=J(t,e);if(!n)return!1;try{return Pe.statSync(n).isFile()}catch{return!1}}function ie(t,e){let n=J(t,e);if(n)try{return Pe.readFileSync(n,"utf8")}catch{return}}var jd=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/worktrees/**","**/.worktrees/**"];function ct(t,e,n=jd){let s;try{s=Nd.default.sync(e,{cwd:t,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,ignore:n})}catch{return[]}return s.map(Kt).sort()}var Pd=[".claude/**/SKILL.md",".agents/skills/**/SKILL.md","skills/*/SKILL.md","plugins/*/skills/*/SKILL.md"],qt={skills:Pd,allSkills:Pd,agents:[".claude/agents/**/*.md"],settings:[".claude/settings.json",".claude/settings.local.json"],mcp:[".mcp.json"],cursorRules:[".cursor/rules/**/*.mdc"],copilotInstructions:[".github/instructions/**/*.md"]};var ex=new Set([".",".claude",".agents",".claude/skills",".agents/skills",".claude/plugins","skills","plugins"]);function la(t){return ex.has(t)}var Td=200,tx=2e4,aa=1e3,nx=new Set(["node_modules",".git","worktrees",".worktrees"]),ca=100,sx=new RegExp(String.raw`(?:^|\/)(?:[^/.]+|package\.json|requirements[^/]{0,40}\.txt|(?:GNU)?makefile|Dockerfile[^/]{0,40}|Containerfile|Justfile)$|`+String.raw`\.(?:sh|bash|zsh|ksh|fish|command|js|mjs|cjs|ts|mts|cts|jsx|tsx|py|pyw|rb|ps1|psm1|pl|php|lua|bat|cmd|mk|`+String.raw`vbs|vba|vbe|hta|applescript|wsf|jse|reg|exe|dll|so|dylib|wasm|jar|war|class|zip|tar|gz|tgz|bz2|xz|7z|rar|`+String.raw`msi|dmg|pkg|deb|rpm|appimage|apk|bin|o|a|lnk|scr|com|pif|scpt|node|env)$`,"i");function Id(t){return sx.test(t)}function ix(t,e){let n=[],s=r=>{let o=J(t,r);if(!o)return[];try{return Pe.readdirSync(o,{withFileTypes:!0})}catch{return[]}},i=r=>{let o=`${r}/package.json`;n.length<ca&&at(t,o)&&n.push(o)};for(let r of s(e).sort((o,a)=>o.name<a.name?-1:1)){if(n.length>=ca)break;if(!(!r.isDirectory()||r.name.startsWith(".")))if(r.name.startsWith("@"))for(let o of s(`${e}/${r.name}`).sort((a,c)=>a.name<c.name?-1:1))o.isDirectory()&&i(`${e}/${r.name}/${o.name}`);else i(`${e}/${r.name}`)}return n}function rx(t,e){if(e.length===0)return!1;let n=t.split("/"),s=[t];for(let i=1;i<n.length;i++){let r=n.slice(0,i).join("/");s.push(r,`${r}/`)}return s.some(i=>xi.default.isMatch(i,e,{dot:!0}))}function ox(t,e,n){let s=[...new Set(e.map(c=>vi.posix.dirname(c)).filter(c=>!la(c)))].sort(),i=new Set(s),r=[],o=[],a=[];for(let c of s){let l=[],u=[],f=0,d=0,p=!1,h=[c];for(;h.length>0;){let g=h.pop(),b=J(t,g);if(!b)continue;let w;try{w=Pe.readdirSync(b,{withFileTypes:!0})}catch{continue}w.sort((y,v)=>y.name<v.name?1:y.name>v.name?-1:0);for(let y of w){if(++d>tx){p=!0;break}let v=`${g}/${y.name}`;if(!y.isSymbolicLink()&&!rx(v,n.exclude)){if(y.isDirectory()){if(i.has(v))continue;if(nx.has(y.name)){a.push({path:v,kind:"dependency-dir"}),y.name==="node_modules"&&u.push(...ix(t,v));continue}h.push(v)}else if(y.isFile()&&y.name!=="SKILL.md"){if(n.include&&!xi.default.isMatch(v,n.include,{dot:!0})){f++;continue}l.push(v)}}}if(p)break}l.sort((g,b)=>Number(Id(b))-Number(Id(g))||(g<b?-1:g>b?1:0)),r.push(...l.slice(0,Td)),r.push(...u.sort().slice(0,ca));let m=l.slice(Td);o.push(...m.slice(0,aa)),(m.length>aa||p)&&a.push({path:c,kind:"listing-limit",count:Math.max(0,m.length-aa)}),f>0&&a.push({path:c,kind:"include",count:f})}return{files:r.sort(),overCap:o.sort(),skips:a}}function ax(t,e){let n=J(t,e);if(!n)return!1;try{let s=Pe.statSync(n);if(!s.isFile()||s.size>ce)return!1;let i=Pe.openSync(n,"r");try{let r=Buffer.alloc(Math.min(s.size,Kn)),o=Pe.readSync(i,r,0,r.length,0);return!zt(r.subarray(0,o))}finally{Pe.closeSync(i)}}catch{return!1}}function ua(t,e={}){let n=[...jd,...e.exclude??[]],s=e.include&&e.include.length>0?e.include:void 0,i=c=>{let l=ct(t,[...c],n);return s?(0,xi.default)(l,s,{dot:!0}).sort():l},r=c=>i(c).filter(l=>ax(t,l)),o=i(qt.allSkills),a=ox(t,o,{include:s,exclude:e.exclude??[]});return{skills:r(qt.skills),allSkills:o,skillFiles:a.files,skillFilesOverCap:a.overCap,skillBundleSkips:a.skips,agents:r(qt.agents),settings:r(qt.settings),mcp:r(qt.mcp),cursorRules:r(qt.cursorRules),copilotInstructions:r(qt.copilotInstructions)}}function le(t){return Ld.createHash("sha1").update(t).digest("hex").slice(0,12)}function Te(t,e){let n=s=>vi.resolve(t,s);return e.map(s=>({...s,filePaths:s.filePaths.map(n),locations:s.locations.map(i=>({...i,filePath:n(i.filePath)}))}))}var Zn=/\.(sh|bash|zsh|js|mjs|cjs|ts|py|rb|ps1)$/i;function Ye(t,e){let n=t.indexOf(e);return n<0&&(n=t.indexOf(JSON.stringify(e).slice(1,-1))),n<0?1:t.slice(0,n).split(/\r?\n/).length}function cx(t){return t.charCodeAt(0)===65279?t.slice(1):t}var Od=/^(?:---|\.\.\.)[ \t]*$/;function Md(t){let e="",n="";for(let s=0;s<t.length;s++){let i=t[s];if(e)i===e&&(e="");else if((i==='"'||i==="'")&&(n===""||/[\s[{(,]/.test(n)))e=i;else if(i==="#"&&(n===""||/\s/.test(n)))return t.slice(0,s).trimEnd();n=i}return t}function Dd(t){let e=[],n="",s=0,i="";for(let r of t){if(i){n+=r,r===i&&(i="");continue}if((r==='"'||r==="'")&&n.trim()===""){i=r,n+=r;continue}if(r==="["||r==="{"||r==="("){s++,n+=r;continue}if(r==="]"||r==="}"||r===")"){s>0&&s--,n+=r;continue}if(r===","&&s===0){e.push(n),n="";continue}n+=r}return e.push(n),e.map(r=>fa(r.trim())).filter(r=>r!=="")}function fa(t){return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function lx(t){let e=Md(t).trim();if(e==="")return null;let n=fa(e);if(n!==e)return n;if(e.startsWith("[")&&e.endsWith("]")){let s=e.slice(1,-1).trim();return s===""?[]:Dd(s)}return e==="true"?!0:e==="false"?!1:e==="null"||e==="~"?null:/^-?\d+(\.\d+)?$/.test(e)?Number(e):e}function gt(t){let n=cx(t).split(/\r?\n/),s={present:!1,closed:!1,data:{},keyLines:{},fenceEndLine:-1,bodyStartLine:1,errors:[]};if(n.length===0||n[0].trim()!=="---")return s;s.present=!0;let i=null,r=null,o=!1,a=[],c=()=>{if(r===null)return;let u=o?a.join(" "):a.join(`
40
+ `);s.data[r]=u.trim(),r=null,a=[]},l=1;for(;l<n.length;l++){let u=n[l],f=u.trim();if(r!==null){if(Od.test(u)){c(),s.closed=!0,s.fenceEndLine=l+1,s.bodyStartLine=l+2;break}if(f===""||/^\s/.test(u)){a.push(f);continue}c()}if(Od.test(u)){s.closed=!0,s.fenceEndLine=l+1,s.bodyStartLine=l+2;break}if(f===""||f.startsWith("#"))continue;let d=/^(\s*)-\s+(.*)$/.exec(u);if(d&&i){let w=s.data[i],y=fa(Md(d[2]).trim());y!==""&&(Array.isArray(w)?w.push(y):s.data[i]=[y]);continue}let p=/^(\s*)([^:\s][^:]*):\s?(.*)$/.exec(u);if(!p){s.errors.push(`Unparseable frontmatter line ${l+1}: ${f.slice(0,60)}`);continue}let h=p[1].length,m=p[2].trim(),g=p[3];if(h>0){s.errors.push(`Nested frontmatter key "${m}" on line ${l+1} is not supported`);continue}Object.prototype.hasOwnProperty.call(s.data,m)?s.errors.push(`Duplicate frontmatter key "${m}" (line ${l+1})`):s.keyLines[m]=l+1;let b=g.trim();if(b==="|"||b==="|-"||b==="|+"||b===">"||b===">-"||b===">+"){r=m,o=b.startsWith(">"),a=[],i=null;continue}if(b===""){s.data[m]=null,i=m;continue}s.data[m]=lx(g),i=null}return r!==null&&c(),s.closed||(s.bodyStartLine=n.length+1),s}function xn(t){return t==null?[]:Array.isArray(t)?t.map(e=>String(e).trim()).filter(Boolean):typeof t=="string"?t.split(`
41
+ `).flatMap(e=>Dd(e)):[String(t)]}function H(t){return{severity:"warning",category:"ai_config",confidence:.8,...t}}function Lt(t,e,n,s){let i=(o,a)=>`ai-config-${s.idPrefix}-${o}-${le(a)}`;if(!n.present)return[H({id:i("no-frontmatter",t),severity:s.noFrontmatterSeverity??"high",title:s.noFrontmatterTitle??`${s.noun} is missing YAML frontmatter`,summary:`${t} has no \`---\` frontmatter block. ${s.why}`,filePaths:[t],locations:[{filePath:t,startLine:1,endLine:1}],evidence:[`First line: ${e.split(/\r?\n/)[0]?.slice(0,60)??"(empty)"}`],recommendation:s.recommendation,confidence:s.noFrontmatterConfidence??.85})];let r=[];n.closed||r.push(H({id:i("unterminated",t),severity:"high",title:`${s.noun} frontmatter is not closed`,summary:`${t} opens a \`---\` frontmatter block that is never closed.`,filePaths:[t],locations:[{filePath:t,startLine:1,endLine:1}],evidence:["Opening `---` on line 1 has no closing `---`."],recommendation:"Close the frontmatter block with a `---` line.",confidence:.9}));for(let o of n.errors){let a=/"([^"]+)"/.exec(o)?.[1],c=Number(/\bline (\d+)\b/.exec(o)?.[1]),l=Number.isInteger(c)&&c>0?c:n.fenceEndLine>0?n.fenceEndLine:1;r.push(H({id:i("fm-error",`${t}|${o}`),title:a?`${s.noun} frontmatter has an unsupported key "${a}"`:`${s.noun} frontmatter has a structural problem`,summary:`${t}: ${o}.`,filePaths:[t],locations:[{filePath:t,startLine:l,endLine:l}],evidence:[o],recommendation:"Fix the frontmatter so it is valid YAML with flat, unique keys. Nested maps are not supported \u2014 flatten the offending key or move it into the body.",confidence:.7}))}return r}function Fd(t){return/[\\^$.*+?()[\]{}|/]/.test(t)?`\\${t}`:t}function ux(t){let e="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")n+1<t.length&&(e+=Fd(t[n+1])),n+=2;else if(s==="*")if(t[n+1]==="*"){let i=n===0||t[n-1]==="/",r=n+2;for(;t[r]==="*";)r++;i&&t[r]==="/"?(e+="(?:.*/)?",n=r+1):i&&r===t.length?(e+=".*",n=r):(e+="[^/]*",n=r)}else e+="[^/]*",n++;else if(s==="?")e+="[^/]",n++;else if(s==="["){let i=t.indexOf("]",n+2);if(i===-1)e+="\\[",n++;else{let r=t.slice(n+1,i),o=!1;(r.startsWith("!")||r.startsWith("^"))&&(o=!0,r=r.slice(1)),r=r.replace(/[\\^\]]/g,a=>`\\${a}`),e+=`[${o?"^":""}${r}]`,n=i+1}}else e+=Fd(s),n++}return e}function fx(t){let e=[];for(let n of t.split(/\r?\n/)){let s=n.replace(/(?<!\\)[ \t]+$/,"");if(s===""||s.startsWith("#"))continue;let i=!1;s.startsWith("!")&&(i=!0,s=s.slice(1));let r=!1;s.endsWith("/")&&(r=!0,s=s.slice(0,-1));let o=s.includes("/");if(s=s.replace(/^\//,""),s!=="")try{e.push({negate:i,dirOnly:r,anchored:o,regex:new RegExp(`^${ux(s)}$`)})}catch{}}return e}function dx(t,e,n){if(t.dirOnly&&!n)return!1;let s=t.anchored?e:e.split("/").pop();return t.regex.test(s)}function Si(t){let e=new Map,n=s=>{let i=e.get(s);if(!i){let r=ie(t,s===""?".gitignore":`${s}/.gitignore`);i=r===void 0?[]:fx(r),e.set(s,i)}return i};return s=>{let i=s.replace(/\\/g,"/").replace(/^\.\//,"").split("/").filter(Boolean);for(let r=1;r<=i.length;r++){let o=r<i.length,a;for(let c=0;c<r;c++){let l=i.slice(c,r).join("/");for(let u of n(i.slice(0,c).join("/")))dx(u,l,o)&&(a=!u.negate)}if(a===!0)return!0}return!1}}var Hd=/\[(?:[^\]]*)\]\(([^)]+)\)/g,Bd=/\[(?:[^\]]|\]\([^)]*\))*\]\(([^)]+)\)/g,Wd=/^[ \t]{0,3}\[[^\]]+\]:\s*(\S+)/gm,Gd=/(?<!\w)@((?:\.{1,2}\/)?[\w./\\-]+\.(?:md|ts|js|mjs|cjs|tsx|jsx|json|yml|yaml|toml|txt|sh|py|cs|go|rs))/g,Ud=/`([^\s`\n]+\.(?:md|sh|py|ts|js|tsx|jsx|mjs|cjs|json|yml|yaml|toml|cs|go|rs|txt|lock|env|png|jpg|jpeg|gif|svg|webp|pdf))(?::\d+(?::\d+)?)?`/g,Vd=/`((?:\.\/)?[\w@.()[\]-]+(?:\/[\w@.()[\]-]+)+\/?)`/g,px=/\b(?:branch(?:es)?|checkout|rebase|merge|cherry-pick|route[sd]?|routing|endpoints?|urls?|uris?|http\s+(?:get|post|put|patch|delete))\b/i,hx=new Set(["feat","feature","features","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","perf","build","release","releases","style","wip","dependabot"]),Xd=new Set(["dist","build","out",".next","coverage","target","bin","obj","node_modules",".turbo"]),zd=/^[ \t]*[-*+]\s+((?:[\w.-]+\/)+[\w.-]+\.(?:md|ts|js|tsx|jsx|mjs|cjs|json|yml|yaml|toml|sh|py|cs|go|rs|txt|png|jpg|jpeg|gif|svg|webp|pdf))\b/gm,qd="repository\\s+layout|project\\s+structure|file\\s+structure|folder\\s+structure|directory\\s+(?:structure|layout|tree|overview)|project\\s+tree|repo\\s+(?:structure|layout|map)|file\\s+tree|files?\\s+overview|codebase\\s+(?:map|overview|structure|layout)|layout",mx=new RegExp(`^(?:#{1,4}\\s+.*\\b(?:${qd})\\b|\\*\\*[^*\\n]*\\b(?:${qd})\\b[^*\\n]*\\*\\*\\s*)`,"im"),gx=/\b(?:create|add|generate|scaffold|place|put|save|make)\s+(?:a\s+|an\s+|the\s+|your\s+|this\s+|new\s+)*(?:file|workflow|config(?:uration)?|script|action|manifest|template|module|component)\b[^.\n]*?\b(?:named|called|at|as|in|to|like)\s+[`'"(]*([^\s`'"()]+)/i;function Kd(t){return lt(t).replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase()}var yx=new Set([".md",".ts",".js",".mjs",".cjs",".tsx",".jsx",".json",".yml",".yaml",".toml",".txt",".sh",".py",".cs",".go",".rs",".png",".jpg",".jpeg",".gif",".svg",".webp",".pdf"]);function _i(t){return/^https?:\/\/|^mailto:|^#|^data:/.test(t.trimStart())}function Yd(t){let e=t.trim(),n=/^<([^>]+)>(?:\s+(?:"[^"]*"|'[^']*'))?\s*$/.exec(e);if(n)return n[1];let s=/^(\S+)\s+(?:"[^"]*"|'[^']*')\s*$/.exec(e);return s?s[1]:e}var bx=/^(foo|bar|baz|qux|quux|example|sample|placeholder|stub|demo|test|your[-_]?file|my[-_]?file|filename|file[-_]?name)(\.\w+)?$/i,wx=new Set(["tokens.json","config.json","settings.json","schema.json","manifest.json","types.ts","types.d.ts","index.ts","index.js","main.ts","main.go","app.ts","app.js","constants.ts","utils.ts","helpers.ts","globals.ts","routes.ts","store.ts","models.ts","services.ts","package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","tsconfig.json","tsconfig.base.json","pyproject.toml","cargo.toml","next.config.js","next.config.ts","next.config.mjs","vite.config.ts","vite.config.js","vite.config.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs",".eslintrc.json",".eslintrc.js",".eslintrc.yml","jest.config.ts","jest.config.js","jest.config.mjs","vitest.config.ts","vitest.config.mts"]),vx=/^(ComponentName|MyComponent|YourComponent|WidgetName|FeatureName|ModuleName|ServiceName|ModelName|EntityName|ResourceName|DomainName|ControllerName|ScreenName|PageName)(?:\.\w+)*$/i;function xx(t){if(/<[A-Za-z][A-Za-z0-9_-]*>/.test(t)||/\{[A-Za-z][A-Za-z0-9_-]*\}/.test(t)||/\{[^{}/\\]*,[^{}/\\]*\}/.test(t)||t.split("/").includes("..."))return!0;let e=j.basename(lt(t)),n=j.dirname(lt(t)),s=n!=="."&&n!==""&&n!==".\\"&&n!=="./";return!!(!s&&bx.test(e)||vx.test(e)||!s&&wx.has(e.toLowerCase())||/camelCase|CamelCase|PascalCase|pascalCase|kebab[-_]?[Cc]ase|snake_?[Cc]ase/.test(e))}var Sx=[/(?:^|[/\\])\.promptci[/\\]/,/(?:^|[\\/])secrets?\.\w+$/i,/(?:^|[\\/])credentials?\.\w+$/i,/appsettings\.(?:Development|Production|Staging|Local)\.\w+$/i,/(?:^|[\\/])\.env(?:\.\w+)?$/i,/(?:^|[\\/])local\.(?:json|yaml|yml|toml|ini|conf|config)$/i,/\.local\.\w+$/i,/(?:^|[\\/])(?:private(?:key)?|id_rsa|id_ed25519)(?:\.\w+)?$/i,/\.(?:pem|key|pfx|p12)$/i];function _x(t){let e=t.replace(/\\/g,"/");return Sx.some(n=>n.test(e))}var Ex=/^(?:~(?:[/\\]|$)|\$\{?(?:HOME|USERPROFILE|XDG_CONFIG_HOME|XDG_DATA_HOME)\}?(?:[/\\]|$)|\$env:(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA)(?:[/\\]|$)|%(?:USERPROFILE|HOMEPATH|APPDATA|LOCALAPPDATA)%(?:[/\\]|$))/i;function ga(t){return Ex.test(t.trim())}function kx(t){let e=j.extname(t.split("#")[0]??"").toLowerCase();return yx.has(e)}function Rx(t){if(!t||/^[a-z][a-z0-9+.-]*:/i.test(t)||t.startsWith("/")||/[\s*?$%<>{}|"'`~\\]/.test(t)||!/[A-Za-z]/.test(t)||!t.includes("/")&&!t.startsWith("."))return!1;let e=t.replace(/\/+$/,"").split("/").pop()??"";return t.endsWith("/")||j.extname(e)===""}function lt(t){return t.split("#")[0].split("?")[0].trim()}var Cx=new Set([".go",".cs",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".sh",".java",".kt",".swift"]),Ax=new Set([".go",".rs",".cs",".java",".kt",".swift",".ts",".tsx"]),$x=/(?:^|[/\\])(?:legacy|old|deprecated|archive|archived)(?:[/\\]|[-_.])/i,Px=new Set(["readme","claude","agents","cursor","windsurf","copilot","gemini","cline","persona","docs","prompt","unknown"]),Tx=2,Ix=.45;function Zd(t){let e=`dead-ref:${t}`;return`dead-ref-${Jd.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Ox(t){let e=[0];for(let n=0;n<t.length;n++)t[n]===`
42
+ `&&e.push(n+1);return e}function Nt(t,e){let n=0,s=t.length-1;for(;n<s;){let i=n+s+1>>1;t[i]<=e?n=i:s=i-1}return n+1}var Lx=/\.(?:md|png|jpg|jpeg|gif|svg|webp|pdf)$/i;function Nx(t){let e=t.replace(/\s*#.*$/,""),s=(e.match(/^[ \t│|]*/)?.[0]??"").replace(/[│|]/g," ").length,i=e.trim();if(!i)return null;let r=/^(?:[│|]\s*)*(?:[├└][-─\s]+|[|+`][-─]+\s*)(.+)$/.exec(i),o=(r?r[1]:i)?.trim()??"";return!o||!r&&/\s/.test(o)?null:{entry:o,indent:s,hasConnector:!!r}}function Qd(t,e,n){let s=[],i=[],r=n;for(let o of t){let a=r;r+=o.length+1;let c=Nx(o);if(!c)continue;let l=c.entry;if(/\/$/.test(l)){let h=`${[...i].reverse().find(m=>m.indent<c.indent||m.indent===c.indent&&m.plain)?.path??""}${l}`;for(;i.length>0&&i[i.length-1].indent>=c.indent;)i.pop();i.push({indent:c.indent,path:h,plain:!c.hasConnector});continue}if(!Lx.test(l))continue;let f=[...i].reverse().find(p=>p.indent<c.indent||p.indent===c.indent&&p.plain),d=/[/\\]/.test(l)?l:`${f?.path??""}${l}`;s.push({ref:d,evidence:o.trim(),line:Nt(e,a)})}return s}function jx(t,e){let n=[];for(let s of Vn(t)){if(!s.closed)continue;let i=e[s.contentStartLine-1]??t.length;n.push(...Qd(s.lines,e,i))}return n}function Mx(t,e){return Qd(t.split(`
43
+ `),e,0)}function Dx(t,e={}){let n=[],s=Ox(t),i=xe(t),r=m=>{let g=Nt(s,m);return i[g-1]?.inFence?!0:(t.slice(s[g-1]??0,m).match(/`/g)?.length??0)%2===1},o=(m,g,b)=>{if(!m||_i(m))return;let w=Nt(s,b);kx(m)?n.push({ref:m,evidence:g,line:w,kind:"file"}):Rx(m)&&!r(b)&&n.push({ref:m,evidence:g,line:w,kind:"linkPath"})},a,c=new RegExp(Hd.source,Hd.flags);for(;(a=c.exec(t))!==null;){if(a.index>=2&&t[a.index-2]==="["&&t[a.index-1]==="!")continue;let m=a[1]??"";o(lt(Yd(m)),`[...](${m})`,a.index)}let l=new RegExp(Bd.source,Bd.flags);for(;(a=l.exec(t))!==null;){if(!a[0].slice(0,a[0].lastIndexOf("](")).includes("]("))continue;let g=a[1]??"";o(lt(Yd(g)),`[...](${g})`,a.index)}let u=new RegExp(Wd.source,Wd.flags);for(;(a=u.exec(t))!==null;){let m=a[1]??"";/^[ \t]*\[\^/.test(a[0])||o(lt(m),a[0].trim(),a.index)}let f=new RegExp(Gd.source,Gd.flags);for(;(a=f.exec(t))!==null;){let m=a[1]??"";m&&!_i(m)&&n.push({ref:m,evidence:`@${m}`,line:Nt(s,a.index),kind:"file"})}let d=new RegExp(Ud.source,Ud.flags);for(;(a=d.exec(t))!==null;){let m=a[1]??"";if(m&&!_i(m)&&!m.includes("*")&&!m.includes("?")){let g=j.extname(m).toLowerCase(),b=e.skipSourceBackticks&&Ax.has(g)&&!$x.test(m);n.push({ref:m,evidence:`\`${m}\``,line:Nt(s,a.index),kind:b?"rootedSource":"file",codeSpan:!0})}}let p=new RegExp(Vd.source,Vd.flags);for(;(a=p.exec(t))!==null;){let m=a[1]??"",g=m.replace(/\/+$/,"").split("/").pop()??"";if(!m.endsWith("/")&&j.extname(g)!=="")continue;let b=Nt(s,a.index),w=t.slice(s[b-1]??0,s[b]??t.length);px.test(w)||n.push({ref:m,evidence:`\`${m}\``,line:Nt(s,a.index),kind:"rootedPath"})}if(mx.test(t)){let m=new RegExp(zd.source,zd.flags);for(;(a=m.exec(t))!==null;){let g=a[1]??"";g&&!_i(g)&&n.push({ref:g,evidence:a[0].trim(),line:Nt(s,a.index),kind:"file"})}for(let g of Mx(t,s))n.push({...g,kind:"file"});for(let g of jx(t,s))n.push({...g,kind:"file"})}let h=t.split(`
44
+ `);return n.filter(({ref:m,line:g})=>{let b=h[g-1]??"",w=gx.exec(b);if(!w)return!0;let y=Kd(w[1]??"");if(!y)return!0;let v=Kd(m);return!(v===y||v.endsWith(`/${y}`)||y.endsWith(`/${v}`))})}function pa(t){return lt(t).replace(/\\/g,"/").split("/").filter(e=>e!==""&&e!==".")}function Fx(t){return pa(t).some(e=>Xd.has(e.toLowerCase()))}function Ei(t){let e=t?.code;return typeof e=="string"?e:void 0}var Hx=40,ha=class{root;realRoot;listings=new Map;unreadable=new Map;constructor(e){this.root=j.resolve(e);let n=It(this.root);this.realRoot=n!==null&&n!==this.root?n:void 0}relative(e){return j.relative(this.root,e).split(j.sep).join("/")||"."}noteUnreadable(e,n,s="dir"){let i=j.resolve(this.root,e);if(!X(this.root,i))return;let r=this.relative(i),o=s==="link"?r:r==="."?"./":`${r}/`;this.unreadable.has(o)||this.unreadable.set(o,n)}list(e){let n=this.listings.get(e);if(n===void 0){try{n=new Map(Sn.readdirSync(e,{withFileTypes:!0}).map(s=>[s.name,s]))}catch(s){let i=Ei(s);i==="ENOENT"||i==="ENOTDIR"?n="missing":(n="unreadable",this.noteUnreadable(e,i??"error"))}this.listings.set(e,n)}return n}fromRealRoot(e){return this.realRoot===void 0||X(this.root,e)||!X(this.realRoot,e)?e:j.join(this.root,j.relative(this.realRoot,e))}lookup(e){let n=j.resolve(this.root,e),s="";for(let i=0;i<=Hx;i++){if(!X(this.root,n))return{state:"outside"};let r=j.relative(this.root,n).split(j.sep).filter(Boolean),o=this.root,a=!0,c;for(let l=0;l<r.length;l++){if(!a)return{state:"missing"};let u=this.list(o);if(u==="missing")return{state:"missing"};if(u==="unreadable")return{state:"unreadable"};let f=r[l],d=u.get(f);if(!d)return{state:"missing"};let p=j.join(o,f);if(d.isSymbolicLink()){let h;try{h=Sn.readlinkSync(p)}catch(m){return this.noteUnreadable(p,Ei(m)??"unreadable link","link"),{state:"unreadable"}}s=p,c=j.join(this.fromRealRoot(j.resolve(o,h)),...r.slice(l+1));break}a=d.isDirectory(),o=p}if(c===void 0)return{state:"found",path:o,isDir:a};n=c}return this.noteUnreadable(s,"symlink loop","link"),{state:"unreadable"}}isDir(e){let n=this.lookup(e);return n.state==="found"&&n.isDir}hasStemSibling(e){let n=this.lookup(j.dirname(e));if(n.state!=="found"||!n.isDir)return!1;let s=this.list(n.path);if(typeof s=="string")return!1;let i=`${j.basename(e)}.`;for(let r of s.keys())if(r.startsWith(i))return!0;return!1}walkFs(e){return{readdirSync:(s,i)=>{try{return i?Sn.readdirSync(s,i):Sn.readdirSync(s)}catch(r){let o=Ei(r);throw o!=="ENOENT"&&(this.noteUnreadable(s,o??"error"),e()),r}}}}},Bx=[...[...Xd,".git","worktrees",".worktrees","Library","Temp","Logs","vendor",".venv","venv","__pycache__","Pods",".gradle",".cache",".idea"].map(t=>`**/${t}/**`)];function ep(t,e,n){let s=!0,i=[];try{i=ma.default.sync(e,{cwd:t.root,dot:!0,onlyFiles:n,followSymbolicLinks:!1,suppressErrors:!0,ignore:Bx,fs:t.walkFs(()=>{s=!1})})}catch(r){t.noteUnreadable(".",Ei(r)??"walk failed"),s=!1}return{entries:i,complete:s}}function Wx(t,e,n,s){let i=e.join("/"),r=`${n?"m":"x"}:${i}`,o=s.get(r);if(o!==void 0)return o;let a=ma.default.escapePath(i),c=[`**/${a}`];n&&c.push(`**/${a}.*`);let{entries:l,complete:u}=ep(t,c,!1),f=l.length>0?!0:u?!1:"unknown";return s.set(r,f),f}function Gx(t){let e=new Map,{entries:n,complete:s}=ep(t,["**"],!0);for(let i of n){let r=i.slice(i.lastIndexOf("/")+1),o=e.get(r);o?o.push(i):e.set(r,[i])}return{paths:e,complete:s}}var Ux="__promptci_dir_probe__",ki="unjudged";function Vx(t,e,n,s,i){let{tree:r,isIgnored:o}=i;if(pa(t)[0]===".git"||e!=="file"&&Fx(t))return null;let a=e==="rootedPath"||e==="linkPath",c=a?lt(t):t;if(j.posix.isAbsolute(c)||j.win32.isAbsolute(c)||/^[A-Za-z]:/.test(c))return null;let l=[];for(let h of new Set([j.resolve(s,c),j.resolve(r.root,c)])){if(!X(r.root,h))continue;let m=r.lookup(h);m.state!=="outside"&&l.push({abs:h,found:m})}if(l.length===0)return null;for(let{abs:h}of l){let m=j.relative(r.root,h).replace(/\\/g,"/");if(m&&(o(m)||a&&o(`${m}/${Ux}`)))return null}let u=a&&!c.endsWith("/");if(l.some(({abs:h,found:m})=>m.state==="found"||u&&r.hasStemSibling(h)))return null;if(l.some(({found:h})=>h.state==="unreadable"))return ki;if(e==="file"){if(n&&!/[/\\]/.test(c)){let b=i.nameIndex();if(b.paths.get(c)?.some(w=>!o(w)))return null;if(!b.complete)return ki}let h=j.extname(t.split("#")[0]??"").toLowerCase(),m=Cx.has(h),g=l.some(({abs:b})=>r.isDir(j.dirname(b)));return m&&g?.5:.85}if(e==="linkPath")return .8;let f=pa(t);if(f.length<2||f.includes(".."))return null;let d=[s,r.root].filter(h=>r.isDir(j.join(h,f[0])));if(d.length===0||f.length-1>Tx&&!d.some(h=>r.isDir(j.join(h,f[0],f[1])))||e==="rootedPath"&&(hx.has(f[0].toLowerCase())&&!c.endsWith("/")||f.length===2&&d.some(h=>r.lookup(j.join(h,f[1])).state==="found")))return null;let p=Wx(r,f,u,i.suffixCache);return p===!0?null:p==="unknown"?ki:.6}function ya(t,e){let n=new Map,s=new ha(e),i,r,o=()=>r??=Gx(s),a=new Map;for(let u of t){let f=j.dirname(u.path),d=Dx(u.content,{skipSourceBackticks:Px.has(u.fileType)});for(let{ref:p,evidence:h,line:m,kind:g,codeSpan:b}of d){if(xx(p)||_x(p)||ga(p))continue;i??={tree:s,isIgnored:Si(e),suffixCache:new Map,nameIndex:o};let w=Vx(p,g,b??!1,f,i);if(w===null)continue;if(w===ki){let C=`Not checked: ${h}`,N=a.get(C)??{filePaths:new Set,fileLines:new Map,evidence:C};N.filePaths.add(u.path);let V=N.fileLines.get(u.path);(V===void 0||m<V)&&N.fileLines.set(u.path,m),a.set(C,N);continue}let y=p.toLowerCase().replace(/\\/g,"/"),v=g==="rootedPath"||g==="linkPath"?y.replace(/^\.\//,"").replace(/\/+$/,""):y,R=`Reference: ${h}`;n.has(v)||n.set(v,{displayRef:p,kind:g,filePaths:new Set,fileLines:new Map,evidenceLines:[],minConfidence:w});let k=n.get(v);k.filePaths.add(u.path);let T=k.fileLines.get(u.path);(T===void 0||m<T)&&k.fileLines.set(u.path,m),k.evidenceLines.includes(R)||k.evidenceLines.push(R),k.minConfidence=Math.min(k.minConfidence,w)}}let c=[],l=Ix;for(let[u,{displayRef:f,kind:d,filePaths:p,fileLines:h,evidenceLines:m,minConfidence:g}]of n){if(g<l)continue;let b=[...p],w=d==="rootedPath"||d==="linkPath",y=w&&lt(f).endsWith("/"),v=y?"directory":w?"path":"file",R=j.basename(lt(f).replace(/\/+$/,""));c.push({id:Zd(u),severity:"warning",category:"structure",title:`Broken ${v} reference: ${R}${y?"/":""}`,summary:`This instruction file references "${f}" which does not appear to exist. The ${v} may have been renamed, moved, or deleted.`,filePaths:b,locations:b.map(k=>{let T=h.get(k);return T!==void 0?{filePath:k,startLine:T}:{filePath:k}}),evidence:m,recommendation:"Verify the path is correct relative to the instruction file location, or remove the reference if the file no longer exists.",confidence:g})}return a.size>0&&c.push(zx(s,[...a.values()])),c}var da=10;function zx(t,e){let n=(a,c)=>a.length>da?[...a.slice(0,da),`\u2026and ${a.length-da} more ${c}`]:a,s=[...t.unreadable].sort(([a],[c])=>a.localeCompare(c)),i=s.map(([a,c])=>`Could not read: ${a} (${c})`),r=[...new Set(e.flatMap(a=>[...a.filePaths]))],o=new Map;for(let a of e)for(let[c,l]of a.fileLines){let u=o.get(c);(u===void 0||l<u)&&o.set(c,l)}return{id:Zd("(dead-reference check incomplete)"),severity:"warning",category:"structure",title:"Dead-reference check incomplete: part of the repository could not be read",summary:`${e.length} reference(s) were not checked because part of the repository could not be read (${s.length} location${s.length===1?"":"s"}). They may or may not exist; no broken-reference finding was reported for them.`,filePaths:r,locations:r.map(a=>{let c=o.get(a);return c!==void 0?{filePath:a,startLine:c}:{filePath:a}}),evidence:[...n(i,"locations"),...n(e.map(a=>a.evidence),"references")],recommendation:"Make the listed locations readable by the user running the scan (or fix the symlink), then scan again to check these references.",confidence:.8}}var jt=x(require("node:crypto"),1),Ne=x(require("node:path"),1);function Yt(t,e,n){if(e.length===0)return[];let s=new Map;for(let i of t)i.relativePath!==void 0&&s.set(i.relativePath,i);return e.filter(i=>{if(!n(i.fileType))return!1;let r=i.aliasOf===void 0?void 0:s.get(i.aliasOf);return r===void 0||!n(r.fileType)})}function Qn(t){let e=new Map;for(let n of[...t].sort((s,i)=>s.path.localeCompare(i.path))){let s=n.aliasOf??n.path,i=e.get(s);i?i.push(n):e.set(s,[n])}return[...e.values()]}function tp(t,e,n){let s=Qn(Yt(t,e??[],n)).map(i=>i[0]);return s.length===0?t:[...t,...s]}var _n=[{id:"no-verification-loop",title:"No verification loop instruction",summary:'No instruction found asking the agent to run lint, typecheck, or tests before marking work complete. Without this, agents commonly report "done" without validating that changes compile or pass tests.',patterns:[/run\s+(pnpm|npm|yarn)\s+(lint|test|build|typecheck)/i,/pnpm\s+(lint|test|build|typecheck)\b(?!\s+(?:outputs?|generates?|creates?|produces?|writes?|emits?|runs?)\b)/i,/\bnpm\s+(run\s+)?(lint|test|build)/i,/before\s+(you\s+)?(say|mark|call|consider|report)\s+(it\s+)?(done|complete|finished)/i,/before\s+(finishing|completing|submitting|pushing|closing)/i,/work\s+is\s+not\s+complete\s+until/i],recommendation:'Add an explicit rule such as: "Before saying done, run pnpm lint && pnpm typecheck && pnpm test && pnpm build. Work is not complete until all checks pass."',severity:"warning",confidence:.75,fixRecipe:"Before saying work is complete, run pnpm lint, pnpm typecheck, pnpm test, and pnpm build. If any command fails, report the failure and stop."},{id:"no-honesty-policy",title:'No "report failures honestly" instruction',summary:"No instruction found requiring the agent to report test failures, errors, or build breakage honestly. Without this, agents may claim success when commands actually fail.",patterns:[/report\s+(the\s+)?(fail|error|break)/i,/don.?t\s+(fake|claim|pretend)\s+success/i,/(?<!to\s+be\s+)\bhonestly?\b/i,/if\s+(a\s+)?(test|build|check)s?\s+(fail|break|error)/i,/never\s+skip\s+(failing\s+)?test/i,/never\s+hide\s+(error|fail)/i],recommendation:'Add a rule such as: "If tests fail, report the failure. Never claim success when commands error or tests are skipped."',severity:"warning",confidence:.75,fixRecipe:"If tests or commands fail, report the failure honestly. Never claim success when checks are skipped or error."},{id:"no-ask-when-unsure",title:'No "ask when unsure" instruction',summary:"No instruction found telling the agent to surface uncertainty \u2014 to ask or say so when it is unsure \u2014 instead of guessing. Without this, agents may proceed on assumptions and produce confidently wrong work.",patterns:[/\bif\s+(?:you(?:'|’)?re\s+|you\s+are\s+|ever\s+)?unsure\b/i,/\bif\s+in\s+(?:any\s+)?doubt\b/i,/\bwhen\s+(?:you(?:'|’)?re\s+|you\s+are\s+)?(?:unsure|uncertain)\b/i,/\bif\s+(?:you(?:'|’)?re\s+|you\s+are\s+|it(?:'|’)?s\s+)?uncertain\b/i,/\bif\s+you\s+(?:don(?:'|’)?t|do\s+not|dont)\s+know\b/i,/\bask\s+(?:before|first|for\s+clarification|the\s+user|a\s+question|questions)\b/i,/\bclarify\s+(?:before|first|with)\b/i,/\b(?:don(?:'|’)?t|do\s+not|dont)\s+guess\b/i,/\bsay\s+(?:you|that\s+you)\s+(?:don(?:'|’)?t|do\s+not|dont)\s+know\b/i,/\breport\s+uncertainty\b/i,/\backnowledge\s+(?:when|uncertainty|any\s+uncertainty)\b/i],recommendation:'Add a rule such as: "If you are uncertain about the correct approach, say so and ask before proceeding rather than guessing."',severity:"warning",confidence:.75,fixRecipe:"If you are uncertain about the correct approach, say so before proceeding rather than guessing."},{id:"no-read-before-edit",title:'No "read before edit" instruction',summary:"No instruction found requiring the agent to read a file before editing it. Agents that edit files they haven't read may clobber context or introduce inconsistencies.",patterns:[/read\s+(the\s+|a\s+|any\s+)?file\s+(fully\s+|first\s+)?before\s+(edit|modif|chang)/i,/read\s+(the\s+|a\s+)?file.*before\s+(edit|modif|chang)/i,/must\s+(first\s+)?read\s+(the\s+|a\s+|any\s+)?(file|source|code)/i,/always\s+read\s+(the\s+|a\s+)?(file|source|code)/i,/inspect\s+(the\s+|a\s+)?file\s+before/i,/read.*before.*edit/i,/before\s+(?:you\s+)?(?:edit|modif|chang)\w*\b[^.\n]{0,40}\bread(?:ing)?\b/i],recommendation:'Add a rule such as: "Always read a file fully before editing it."',severity:"warning",confidence:.75,fixRecipe:"Read a file before editing it. Preserve unrelated user changes."},{id:"no-scope-control",title:"No scope-control instruction",summary:"No instruction found telling the agent to avoid rewriting unrelated systems or making sweeping changes. Unconstrained agents often refactor things they were not asked to touch.",patterns:[/focused\s+(diff|change|edit|pr|commit)/i,/don.?t\s+rewrite\s+unrelated/i,/do\s+not\s+rewrite\s+unrelated/i,/avoid\s+unrelated\s+(change|edit|refactor)/i,/minimal\s+(change|diff|edit)/i,/small\s+(change|diff|edit|pr|commit)/i,/targeted\s+(change|edit|fix)/i,/prefer\s+(small|focused|minimal)\s+(diff|change|pr)/i],recommendation:'Add a rule such as: "Prefer focused, minimal diffs. Do not rewrite or refactor code unrelated to the current task."',severity:"warning",confidence:.7,fixRecipe:"Prefer focused, minimal diffs. Do not rewrite or refactor code unrelated to the current task."},{id:"no-preserve-scope",title:"No code-preservation instruction",summary:"No instruction found telling the agent to preserve existing code and only change what the task requires. Without this, agents may delete working code, drop tests, or overwrite unrelated edits to reach a passing state.",patterns:[/\bpreserve\s+(?:existing|unrelated|the\s+existing|current|working|any\s+existing)\b/i,/\bpreserve\s+(?:unrelated\s+changes|the\s+user(?:'|’)?s?\s+(?:changes|edits|work))\b/i,/\b(?:don(?:'|’)?t|do\s+not|dont|never)\s+(?:delete|remove|drop|strip)\s+(?:existing|working|unrelated|any)\b/i,/\bkeep\s+(?:existing|the\s+existing|current|working)\s+(?:code|behaviou?r|functionality|logic|tests?)\b/i,/\bonly\s+(?:change|modify|touch|edit|update)\s+(?:what|the\s+code\s+(?:that|you)|files?\s+(?:that|you)|lines?)\b/i,/\b(?:don(?:'|’)?t|do\s+not|dont)\s+(?:modify|change|touch)\s+code\s+outside\b/i,/\bleave\s+(?:unrelated|existing|working|other)\s+(?:code|files?|logic|behaviou?r)\s+(?:untouched|alone|intact|as[- ]is)\b/i],recommendation:'Add a rule such as: "Preserve existing code and only change what the task requires. Do not delete working code, tests, or unrelated edits."',severity:"warning",confidence:.7,fixRecipe:"Preserve existing code and only change what the task requires. Do not delete working code, tests, or unrelated edits."},{id:"no-plan-first",title:'No "plan before implementing" instruction',summary:"No instruction found asking the agent to outline an approach for complex tasks before writing code. Planning prompts significantly reduce wasted implementation effort on multi-file changes.",patterns:[/plan\s+(first|before|ahead)/i,/outline\s+(the\s+)?(approach|plan|design|steps)\s+before/i,/think\s+(?:through|it\s+through)\s+(?:the\s+)?(?:approach|plan|design|steps|task|problem)/i,/propose\s+(a\s+)?(plan|approach|design)/i,/before\s+implement\w+.*\b(plan|outline|design)\b/i,/design\s+before\s+(implement|cod)/i],recommendation:'Add a rule such as: "For complex or multi-file tasks, outline the approach and get confirmation before writing code."',severity:"info",confidence:.65,fixRecipe:"For complex or multi-file tasks, outline the approach and get confirmation before writing code."}],qx=/\bdo\s+not\s+(edit|modify|change)\b/im,Kx=/<!--\s*auto[- ]?generated|auto[- ]?generated|<!--\s*generated\s*(?:by\s+\w+)?|this\s+file\s+is\s+generated|generated\s+by\s+\w+/i,Yx=/<\/?claude:[\w-]+|<instructions-for-claude[\s>]/i,np=/(?:follow|use|see|refer\s+to|canonical\s+(?:source|instructions?)|pointer\s+to)\s+[`'"*]*(?:\.?\/)?(?:\.github\/)?(?:AGENTS|CLAUDE)\.md\b/i,Jx=/\b(AGENTS|CLAUDE)\.md\b[^\n]{0,60}?\b(?:single\s+source\s+of\s+truth|canonical)\b/i;function Xx(t){return`agent-practice-${jt.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Zx(t){return`do-not-edit-${jt.createHash("sha1").update(`do-not-edit:${t}`).digest("hex").slice(0,12)}`}function Qx(t){return`per-file-behavior-${jt.createHash("sha1").update(`per-file-behavior:${t}`).digest("hex").slice(0,12)}`}function es(t,e){return e.some(n=>n.test(t))}function eS(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
45
+ `&&n++;return n}function Ri(t){return t.split(`
46
46
  `).filter(e=>!/^\s*(?:[-*+]|\d+\.)\s+/.test(e)||!/\[[ x?]\]/.test(e)).join(`
47
- `)}function ki(t){return t.fileType==="copilot"||Ne.basename(t.path).toLowerCase()==="copilot-instructions.md"}function Jx(t){return t.fileType==="cursor"||Ne.basename(t.path).toLowerCase()===".cursorrules"}function Xx(t){return t.fileType==="windsurf"||Ne.basename(t.path).toLowerCase()===".windsurfrules"}function Zx(t){return t.fileType==="claude"||Ne.basename(t.path).toLowerCase()==="claude.md"}function Ri(t){if(Jx(t))return{label:"Cursor rules file",agent:"Cursor agents"};if(Xx(t))return{label:".windsurfrules",agent:"Windsurf agents"};if(Zx(t))return{label:"CLAUDE.md",agent:"Claude"};if(ki(t))return{label:".github/copilot-instructions.md",agent:"GitHub Copilot"};if(t.fileType==="gemini")return{label:"GEMINI.md",agent:"Gemini CLI"};if(t.fileType==="cline"&&Ne.basename(t.path)===".clinerules")return{label:".clinerules",agent:"Cline"}}function Zd(t){let e=t.content.split(/\r?\n/).slice(0,12).join(`
48
- `);if(Xd.test(e))return!0;let n=Vx.exec(e);return n&&`${n[1].toLowerCase()}.md`!==Ne.basename(t.path).toLowerCase()?!0:t.lineCount<20&&Xd.test(t.content)}function Qx(t,e){return e.filter(n=>{let s=Ri(n);if(!s)return!1;let i=t.find(r=>r.relativePath===n.aliasOf);return i===void 0||Ri(i)?.label!==s.label})}function ep(t){return t!=="claude"&&t!=="readme"}function Qd(t){let e=t[0];if(!ep(e.fileType))return;let n=Ke(e.content).replace(/`[^`\n]+`/g,"");if(!Ux.test(n))return;let s=Nt.createHash("sha1").update(`claude-xml-tag:${L(e)}`).digest("hex").slice(0,12),i=/<\/?claude:[\w-]+/i.exec(n)?.[0]??"<claude:...>";return{id:`claude-xml-tag-${s}`,severity:"warning",category:"structure",title:"Claude-specific XML tag in non-Claude instruction file",summary:`This file contains a Claude-specific XML tag (${i}) but is not a CLAUDE.md file. Claude XML tags are only interpreted by Claude; other AI tools (Cursor, Copilot, etc.) will treat them as literal text or ignore them.`,filePaths:t.map(r=>r.path),locations:t.map(r=>({filePath:r.path})),evidence:[`Found: ${i} in ${[...new Set(t.map(r=>r.fileType))].join(", ")} file`],recommendation:"Move Claude-specific directives to CLAUDE.md, or replace this tag with a plain-text instruction that all tools can understand.",confidence:.85}}function ma(t,e=[]){if(t.length===0)return[];let n=[...t,...Qx(t,e)],s=[],i=t.map(p=>p.content).join(`
49
- `),r=Ei(i),o=t.map(p=>p.path);for(let p of Sn){let h=p.id==="no-verification-loop"?r:i;es(h,p.patterns)||s.push({id:zx(p.id),severity:p.severity,category:"agent_practices",title:p.title,summary:p.summary,filePaths:o,locations:[],evidence:[`Pattern not found across ${t.length} instruction file(s).`],recommendation:p.recommendation,fixRecipe:p.fixRecipe,confidence:p.confidence})}let a=[...Sn.find(p=>p.id==="no-verification-loop").patterns,...Sn.find(p=>p.id==="no-honesty-policy").patterns,...Sn.find(p=>p.id==="no-scope-control").patterns,...Sn.find(p=>p.id==="no-read-before-edit").patterns],c=p=>es(Ei(p.content),a),l=new Set;for(let p of n){let h=Ri(p);if(!h||c(p)||Zd(p))continue;let m=t.find(g=>g!==p&&c(g));m&&(l.add(p.path),s.push({id:Kx(L(p)),severity:"warning",category:"agent_practices",title:`No behavioral guidance in ${h.label}`,summary:`The ${h.label} contains no agent behavioral rules (verification loop, honesty policy, scope control, read-before-edit). ${h.agent} may rely on this file, so they will have no behavioral guidance even though another instruction file in the repo contains related rules.`,filePaths:[p.path],locations:[{filePath:p.path}],evidence:[`No behavioral patterns found in ${Ne.basename(p.path)}.`,`Some behavioral guidance appears in ${Ne.basename(m.path)}.`],recommendation:`Add at minimum: a verification rule ("run tests before saying done"), a scope-control rule ("prefer focused diffs"), a read-before-edit rule, and an honesty policy directly to ${h.label} so behavioral guidance is available in the file this tool reads. Alternatively, use a forwarding pointer if the tool supports it (e.g., "Follow AGENTS.md").`,confidence:.8}))}for(let p of Sn){let h=t.find(m=>es(Ei(m.content),p.patterns));if(h)for(let m of n){if(m===h)continue;let g=Ri(m);if(!g||Zd(m)||l.has(m.path))continue;if(!es(Ei(m.content),p.patterns)){let w=p.title.toLowerCase().replace("no ","").replace(" instruction",""),y=Nt.createHash("sha1").update(`behavior-gap:${L(m)}:${p.id}`).digest("hex").slice(0,12);s.push({id:`per-file-behavioral-gap-${y}`,severity:"warning",category:"agent_practices",title:`Missing critical guidance "${p.title.replace("No ","").replace(" instruction","")}" in ${g.label}`,summary:`The ${g.label} lacks the critical behavioral guidance regarding "${w}" which is defined in ${Ne.basename(h.path)}. Since ${g.agent} reads ${g.label}, they will miss this rule.`,filePaths:[m.path,h.path],locations:[{filePath:m.path}],evidence:[`Guidance pattern not found in ${Ne.basename(m.path)}.`,`Guidance defined in ${Ne.basename(h.path)}.`],recommendation:`Add the missing guidance to ${g.label} (e.g., "${p.recommendation.replace("Add a rule such as: ","").replace(/"/g,"")}") or use a forwarding pointer (e.g., "Follow ${Ne.basename(h.path)}").`,fixRecipe:p.fixRecipe,confidence:.8})}}}let u=/^#{1,4}\s+(?:agent\s+behavior|ai\s+behavior|agent\s+rules|behavior\s+rules|agent\s+instructions)\b/im,f=p=>`copilot-agent-behavior-${Nt.createHash("sha1").update(`copilot-agent-behavior:${p}`).digest("hex").slice(0,12)}`;if((()=>{let p=t.filter(ki);return p.length===0||!p.some(c)?!1:!t.filter(g=>!ki(g)&&g.fileType!=="readme"&&g.fileType!=="docs").some(c)})()){let p=t.find(ki);s.push({id:f(L(p)),severity:"warning",category:"structure",title:"General behavioral guidance placed only in Copilot instructions",summary:"General agent behavioral rules (verification loop, honesty policy, etc.) appear only in Copilot-specific instruction files. Other agents (Claude, Cursor, etc.) will likely not see these rules.",filePaths:[p.path],locations:[{filePath:p.path}],evidence:["Behavioral directives found only in Copilot-specific files."],recommendation:"Move general agent behavior rules to AGENTS.md or CLAUDE.md so all agents benefit. Keep copilot-instructions.md focused on Copilot-specific context.",confidence:.7})}for(let p of t)p.fileType==="copilot"&&u.test(p.content)&&es(p.content,a)&&(s.some(h=>h.id===f(L(p)))||s.push({id:f(L(p)),severity:"warning",category:"structure",title:"Agent-behavior section in copilot-instructions.md",summary:'copilot-instructions.md contains an "Agent Behavior" (or similar) heading with agent-practice directives. This file is scoped to GitHub Copilot; agent behavioral rules are typically placed in AGENTS.md or CLAUDE.md where all agents can read them.',filePaths:[p.path],locations:[{filePath:p.path}],evidence:["Agent behavioral directives found inside a Copilot-specific instruction file."],recommendation:"Move agent behavior rules to AGENTS.md or CLAUDE.md, or copy them there so all agents benefit. Keep copilot-instructions.md focused on Copilot-specific context (repo structure, technology stack, Copilot feature preferences).",confidence:.65}));for(let p of t){let h=p.content.slice(0,500),m=Wx.exec(h),g=!!m,b=Gx.test(h),w=m?Yx(p.content,m.index):1;if(g&&!b)s.push({id:qx(L(p)),severity:"warning",category:"agent_practices",title:'"Do not edit" header in human-maintained instruction file',summary:'This instruction file starts with a "do not edit" directive but does not appear to be auto-generated. Humans and agents need to update instruction files regularly \u2014 this header may prevent necessary edits.',filePaths:[p.path],locations:[{filePath:p.path,startLine:w,endLine:w}],evidence:[m[0].trim()],recommendation:'Remove the "do not edit" header, or add a clear generator comment explaining which tool generates this file.',confidence:.8});else if(g&&b&&p.lineCount>5){let v=k=>`auto-gen-header-${Nt.createHash("sha1").update(`auto-gen-header:${k}`).digest("hex").slice(0,12)}`;s.push({id:v(L(p)),severity:"warning",category:"agent_practices",title:"Misleading auto-generated header on human-maintained instruction file",summary:`This instruction file has an "AUTO-GENERATED \u2014 DO NOT EDIT" header, but with ${p.lineCount} lines of hand-written content it is clearly human-maintained. The header may prevent agents and humans from updating the file when needed.`,filePaths:[p.path],locations:[{filePath:p.path,startLine:w,endLine:w}],evidence:[m[0].trim()],recommendation:"Remove the auto-generated header. If this file is genuinely generated, add a clear generator comment that names the tool and the source template so the origin is unambiguous.",confidence:.75})}let y=Qd([p]);y&&s.push(y)}for(let p of Qn(Yt(t,e,ep))){let h=Qd(p);h&&s.push(h)}return s}var ap=x(require("node:crypto"),1);var e_=["duplicate","conflict","context_bloat","missing_context","stale_instruction","vague_guidance","structure","command_validity","agent_practices","ai_config","security","custom"],tp=new Set([...e_,"all"]),np=/<!--\s*promptci-ignore:\s*(\S+)([\s\S]*?)-->/g,sp=/<!--\s*promptci-ignore-start:\s*(\S+)([\s\S]*?)-->/g,ip=/<!--\s*promptci-ignore-end\s*-->/g;function ts(t,e){return t.slice(0,e).split(`
50
- `).length}function t_(t,e,n,s,i){let r=i.split(/\r?\n/);for(let o=0;o<n.length;o++){let a=n[o];if(a.startLine<=t&&a.endLine>=t){let c=n[o+1],u=r.slice(e,Math.max(e,c?.startLine?c.startLine-1:e)).every(f=>f.trim()==="");return c&&c.startLine>e&&u?c.endLine:a.endLine}}for(let o of n)if(o.startLine>t)return o.endLine;return s}function rp(t){let e=/reason:\s*(.+?)(?:\r?\n|$)/i.exec(t);return e?e[1].trim():null}function op(t,e){return tp.has(t)?!e||!e.trim()?{valid:!1,message:'promptci-ignore annotation is missing a required "reason:" field. Add: reason: <explanation of why this is intentional>.'}:{valid:!0}:{valid:!1,message:`Unknown suppression category "${t}". Valid values: ${[...tp].join(", ")}.`}}function n_(t,e,n){let s=`suppression-invalid:${t}:${e}:${n}`;return`suppression-invalid-${ap.createHash("sha1").update(s).digest("hex").slice(0,12)}`}function s_(t){let{content:e,path:n,sections:s,lineCount:i}=t,r=[],o=td(e),a=new RegExp(np.source,np.flags),c;for(;(c=a.exec(o))!==null;){let m=c[1]?.trim()??"",g=c[2]??"",b=rp(g),w=ts(o,c.index),y=ts(o,c.index+c[0].length),v=t_(w,y,s,i,e),{valid:k,message:R}=op(m,b);r.push({filePath:n,category:k?m:"all",reason:b??"",startLine:w,endLine:v,valid:k,validationMessage:R})}let l=[],u=new RegExp(sp.source,sp.flags);for(;(c=u.exec(o))!==null;)l.push({kind:"start",offset:c.index,endOffset:c.index+c[0].length,category:c[1]?.trim()??"",reason:rp(c[2]??"")});let f=new RegExp(ip.source,ip.flags);for(;(c=f.exec(o))!==null;)l.push({kind:"end",offset:c.index,endOffset:c.index+c[0].length});l.sort((m,g)=>m.offset-g.offset);let d=m=>{r.push({filePath:n,category:"all",reason:"",startLine:ts(o,m.offset),endLine:i,valid:!1,validationMessage:"promptci-ignore-start has no matching promptci-ignore-end marker."})},p=null;for(let m of l){if(m.kind==="start"){p&&d(p),p=m;continue}if(!p)continue;let g=ts(o,p.offset),b=ts(o,m.endOffset),{valid:w,message:y}=op(p.category??"",p.reason??null);r.push({filePath:n,category:w?p.category:"all",reason:p.reason??"",startLine:g,endLine:b,valid:w,validationMessage:y}),p=null}p&&d(p);let{relativePath:h}=t;return h===void 0?r:r.map(m=>({...m,relativePath:h}))}function ga(t){return t.flatMap(s_)}function ya(t){return t.filter(e=>!e.valid).map(e=>({id:n_(e.relativePath??e.filePath,e.startLine,e.validationMessage??""),severity:"warning",category:"structure",title:"Invalid promptci-ignore annotation",summary:e.validationMessage??"This promptci-ignore annotation is malformed.",filePaths:[e.filePath],locations:[{filePath:e.filePath,startLine:e.startLine}],evidence:[],recommendation:`Ensure the annotation has a valid category and a non-empty reason field. Example: <!-- promptci-ignore: vague_guidance
51
- reason: This section documents examples. -->`,confidence:1}))}function Ci(t,e){let n=e.filter(r=>r.valid),s=[],i=[];for(let r of t)n.some(a=>{if(a.category!=="all"&&a.category!==r.category)return!1;if(r.locations.length>0){if(r.locations.some(f=>{if(f.filePath!==a.filePath)return!1;if(f.startLine===void 0)return!0;let d=f.endLine??f.startLine;return f.startLine<=a.endLine&&d>=a.startLine}))return!0;let l=new Set(r.filePaths);return!!(!r.locations.some(f=>l.has(f.filePath))&&r.filePaths.includes(a.filePath))}return r.filePaths.includes(a.filePath)})?i.push(r):s.push(r);return{active:s,suppressed:i}}var ba={critical:18,high:10,warning:4,info:1},i_={structure:30,stale_instruction:15,duplicate:20,vague_guidance:10,ai_config:25},r_={"supply-chain":8,"skill-supply-chain":15};function o_(t){for(let n of t.tags??[]){let s=r_[n];if(s!==void 0)return{key:`tag:${n}`,cap:s}}let e=i_[t.category];return e!==void 0?{key:t.category,cap:e}:void 0}function wa(t){let e=100,n=new Map;for(let s of t){let i=(ba[s.severity]??0)*s.confidence,r=o_(s);if(r!==void 0){let o=n.get(r.key)??0,a=Math.max(0,r.cap-o),c=Math.min(i,a);n.set(r.key,o+c),e-=c}else e-=i}return Math.round(Math.max(0,Math.min(100,e)))}var cp={high:3,medium:2,low:1};function lp(t){if(t.impact)return t.impact;let e=t.category,n=t.title.toLowerCase();return e==="security"||n.includes("secret")||n.includes("auth")||n.includes("supabase")||n.includes("service role")||n.includes("upload")||e==="command_validity"||n.includes("build")||n.includes("test")||n.includes("lint")||n.includes("run script")||n.includes("package manager")||n.includes("workflow")||n.includes("deploy")||n.includes("vercel")||n.includes("ci/cd")||n.includes("release")||n.includes("framework")||n.includes("router")||n.includes("database")||n.includes("version conflict")||n.includes("package manager mismatch")||e==="agent_practices"||n.includes("verification")||n.includes("scope")||n.includes("read-before-edit")||n.includes("honesty")||n.includes("plan-first")?"high":e==="vague_guidance"||e==="duplicate"||n.includes("duplicate")||n.includes("vague")?"low":"medium"}function va(t){let e=[...t].sort((i,r)=>{let o=(ba[r.severity]??0)-(ba[i.severity]??0);if(o!==0)return o;let a=r.confidence-i.confidence;if(a!==0)return a;let c=cp[lp(r)]-cp[lp(i)];if(c!==0)return c;let l=r.filePaths.length-i.filePaths.length;if(l!==0)return l;let u=i.category.localeCompare(r.category);return u!==0?u:i.id.localeCompare(r.id)}),n=[],s=new Set;for(let i of e){if(n.length>=3)break;s.has(i.category)||(s.add(i.category),n.push({title:i.title,reason:i.summary,suggestedAction:i.recommendation}))}return n}var ne=x(require("node:fs/promises"),1),ue=x(require("node:path"),1);var fp=x(require("node:crypto"),1),Xt=x(require("node:path"),1),a_={info:0,warning:1,high:2,critical:3};function up(t){return a_[t]??-1}function Jt(t){return t.replace(/\\/g,"/")}function dp(t,e){if(!e)return t;try{let i=Xt.relative(e,t);if(i&&!i.startsWith("..")&&!Xt.isAbsolute(i))return Jt(i)}catch{}let n=Jt(t),s=[Jt(e).replace(/\/+$/,""),Jt(Xt.resolve(e)).replace(/\/+$/,"")];for(let i of s){if(n===i)return".";if(n.startsWith(`${i}/`))return n.slice(i.length+1)}return n}function c_(t,e){if(!e)return t;let n=Jt(t);return[Jt(e).replace(/\/+$/,""),Jt(Xt.resolve(e)).replace(/\/+$/,"")].reduce((i,r)=>i.replaceAll(r,"<repo>"),n)}function ns(t,e){let n=t.filePaths.map(r=>dp(r,e)).sort(),s=t.evidence.map(r=>c_(r,e)).sort(),i=[t.category,t.title,...n,...s].join("|");return fp.createHash("sha256").update(i).digest("hex")}function En(t,e){return t.map(n=>({id:n.id,category:n.category,title:n.title,filePaths:n.filePaths.map(s=>dp(s,e)).sort(),severity:n.severity,fingerprint:ns(n,e)})).sort((n,s)=>n.fingerprint.localeCompare(s.fingerprint))}function xa(t){if(!Array.isArray(t))throw new Error("Baseline file must contain a JSON array.");for(let e=0;e<t.length;e++){let n=t[e];if(typeof n!="object"||n===null)throw new Error(`Baseline entry at index ${e} is not an object.`);let s=n;if(typeof s.fingerprint!="string")throw new Error(`Baseline entry at index ${e} is missing a "fingerprint" string field.`);if(typeof s.category!="string")throw new Error(`Baseline entry at index ${e} is missing a "category" string field.`)}}function kn(t,e,n){let s=new Map;for(let o of e)s.set(o.fingerprint,o.severity??"info");let i=[],r=[];for(let o of t){let a=ns(o,n),c=s.get(a);c===void 0||up(o.severity)>up(c)?i.push(o):r.push(o)}return{newIssues:i,baselinedIssues:r}}var l_={critical:"CRITICAL",high:"HIGH",warning:"WARNING",info:"INFO"},Sa={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},pp={critical:0,high:1,warning:2,info:3},u_={critical:"Critical",high:"High",warning:"Warning",info:"Info"},f_="ai-setup",d_={critical:"issues-critical",high:"issues-high",warning:"issues-warning",info:"issues-info"},p_=50;function h_(t){let e=[],n=mp(t.filter(r=>r.category==="ai_config"));n.length>0&&e.push({anchor:f_,heading:`\u{1F916} AI Setup (${n.length})`,issues:n});let s=t.filter(r=>r.category!=="ai_config"),i=yp(s);for(let r of["critical","high","warning","info"]){let o=mp(i.get(r));o.length!==0&&e.push({anchor:d_[r],heading:`${Sa[r]} ${u_[r]} (${o.length})`,issues:o})}return e}function gp(t,e){let n=ue.relative(e,t);return!n||n.startsWith("..")?t:n}function m_(t,e){return ns({category:t.category??"",title:t.title??"",filePaths:t.filePaths??[],evidence:t.evidence??[]},e)}function hp(t,e){return t.map(n=>m_(n,e))}function g_(t){let e=Math.round(t/10),n=10-e;return"\u2588".repeat(e)+"\u2591".repeat(n)}function Rn(t){return t>=90?"Healthy":t>=70?"Fair":t>=50?"Needs attention":"Critical issues found"}function yp(t){let e=new Map;for(let n of["critical","high","warning","info"])e.set(n,[]);for(let n of t)e.get(n.severity).push(n);return e}function mp(t){return[...t].sort((e,n)=>{let s=pp[e.severity]-pp[n.severity];if(s!==0)return s;let i=n.confidence-e.confidence;return i!==0?i:e.id.localeCompare(n.id)})}function _a(t){let e=gi(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),s="`".repeat(n+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${s}${i}${e}${i}${s}`}function y_(t,e,n){let s=Sa[t.severity],i=l_[t.severity],r=[];if(r.push(`#### ${e}. ${s} [${i}] ${t.title}`),r.push(""),r.push(`**ID:** \`${t.id}\``),r.push(""),r.push(`${t.summary}`),r.push(""),t.filePaths.length>0){for(let a of t.filePaths)r.push(`**File:** ${_a(n(a))}`);r.push("")}let o=t.locations.filter(a=>a.startLine!==void 0);if(o.length>0){for(let a of o){let c=a.endLine!==void 0?`L${a.startLine}\u2013L${a.endLine}`:`L${a.startLine}`;r.push(`**Location:** ${_a(n(a.filePath))} ${c}`)}r.push("")}if(t.evidence.length>0){r.push("**Evidence:**");let a=t.tags?.[0]==="skill-supply-chain";for(let c of t.evidence)r.push(`- ${a?_a(q(c,160)):q(c,100)}`);r.push("")}return r.push(`> **Recommendation:** ${t.recommendation}`),t.fixRecipe&&(r.push(""),r.push("**Suggested text to add:**"),r.push("```markdown"),r.push(t.fixRecipe),r.push("```")),r.join(`
52
- `)}function bp(t){let e=[],{healthScore:n,topFixes:s,issues:i,projectType:r,repoPath:o,generatedAt:a,filesScanned:c}=t,l=d=>gp(d,o);e.push("# PromptCI Health Report"),e.push(""),e.push(`**Generated:** ${a}`),e.push(`**Repo:** \`${o}\``),e.push(`**Project type:** ${r}`),e.push(`**Files scanned:** ${c.filter(d=>d.aliasOf===void 0).length}`),t.metrics&&(e.push(`**Estimated instruction tokens:** ${t.metrics.estimatedInstructionTokens} (always-loaded)`),t.metrics.estimatedOnDemandTokens&&e.push(`**On-demand skill/agent tokens:** ${t.metrics.estimatedOnDemandTokens} across ${t.metrics.onDemandFileCount} file(s) \u2014 loaded only when invoked, not counted above`)),e.push(""),e.push("## Health Score"),e.push(""),e.push("```"),e.push(`${g_(n)} ${n}/100 ${Rn(n)}`),e.push("```"),e.push("");let u=yp(i);if(i.length>0){let d=[];for(let p of["critical","high","warning","info"]){let h=u.get(p).length;h>0&&d.push(`${Sa[p]} ${h} ${p}`)}e.push(d.join(" \xB7 ")),e.push("")}if(e.push("## Trend"),e.push(""),t.trend){let d=t.trend;d.previousScanDate&&e.push(`- **Previous scan:** ${d.previousScanDate}`);let p=d.scoreDelta>0?`+${d.scoreDelta}`:`${d.scoreDelta}`;e.push(`- **Score change:** ${p}`),e.push(`- **New issues:** ${d.newIssuesCount}`),e.push(`- **Resolved issues:** ${d.resolvedIssuesCount}`);let h=Object.keys(d.categoryDeltas);if(h.length>0){e.push("- **Category changes:**");for(let m of h){let g=d.categoryDeltas[m],b=g>0?`+${g}`:`${g}`;e.push(` - ${m}: ${b}`)}}d.streak>0&&e.push(`- **Streak:** ${d.streak} scan(s) without high/critical issues`)}else e.push("First scan \u2014 no trend data available yet.");if(e.push(""),s.length>0&&(e.push("## Top Fixes"),e.push(""),s.forEach((d,p)=>{e.push(`**${p+1}. ${d.title}**`),e.push(""),e.push(`${d.reason}`),e.push(""),e.push(`*Action:* ${d.suggestedAction}`),e.push("")})),i.length===0)e.push("## Issues"),e.push(""),e.push("No issues found. Instruction files look good!"),e.push("");else{e.push("## Issues"),e.push("");let d=h_(i);e.push(`**Jump to:** ${d.map(p=>`[${p.heading}](#${p.anchor})`).join(" \xB7 ")}`),e.push("");for(let p of d)e.push(`<a id="${p.anchor}"></a>`),e.push(""),e.push(`### ${p.heading}`),e.push(""),p.issues.forEach((h,m)=>{e.push(y_(h,m+1,l)),e.push(""),e.push("---"),e.push("")})}let f=t.suppressedIssues;if(f&&f.length>0){e.push(`## Suppressed (${f.length})`),e.push(""),e.push(`The following ${f.length===1?"issue was":"issues were"} silenced by inline \`promptci-ignore\` annotations and do not affect the health score.`),e.push("");for(let d of f){let p=d.filePaths[0]?l(d.filePaths[0]):"(unknown)",h=d.locations.find(g=>g.startLine!==void 0),m=h?` L${h.startLine}${h.endLine?`\u2013${h.endLine}`:""}`:"";e.push(`- **${d.category}** in \`${p}\`${m}`)}e.push("")}if(c.length>0){e.push("## Files Scanned"),e.push("");let d=c.slice(0,p_);for(let h of d)e.push(h.aliasOf!==void 0?`- \`${l(h.path)}\` (symlink to \`${h.aliasOf}\`)`:`- \`${l(h.path)}\` (${h.fileType}, ${h.lineCount} lines, ~${h.estimatedTokens} tokens)`);let p=c.length-d.length;p>0&&e.push(`- \u2026and ${p} more`),e.push("")}return e.push("---"),e.push("> Findings are heuristic. Review each item before acting. Some can be applied automatically with `promptci fix`; others are advisory and must be edited by hand."),e.push(""),e.push("*Generated by [PromptCI](https://github.com/SeriousGeese/PromptCI)*"),e.join(`
53
- `)}function Ai(t,e=!0){let n=i=>gp(i,t.repoPath),s={schemaVersion:t.schemaVersion,generatedAt:t.generatedAt,repoPath:t.repoPath,projectType:t.projectType,healthScore:t.healthScore,topFixes:t.topFixes,...t.metrics?{metrics:t.metrics}:{},...t.trend?{trend:t.trend}:{},issues:t.issues.map(i=>({...i,filePaths:i.filePaths.map(n),locations:i.locations.map(r=>({...r,filePath:n(r.filePath)}))})),filesScanned:t.filesScanned.map(i=>({path:n(i.path).replace(/\\/g,"/"),fileType:i.fileType,lineCount:i.lineCount,charCount:i.charCount,estimatedTokens:i.estimatedTokens,...i.aliasOf!==void 0?{aliasOf:i.aliasOf}:{}})),...t.suppressedIssues&&t.suppressedIssues.length>0?{suppressedIssues:t.suppressedIssues.map(i=>({...i,filePaths:i.filePaths.map(n),locations:i.locations.map(r=>({...r,filePath:n(r.filePath)}))}))}:{}};return e?JSON.stringify(s,null,2):JSON.stringify(s)}function Ea(t){return ue.join(t,".promptci","history","index.json")}async function ka(t){let e=Ea(t);try{let n=await ne.readFile(e,"utf8"),s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return[]}async function wp(t,e,n){let s;try{s=await ne.readFile(n,"utf8")}catch{return null}let i;try{i=JSON.parse(s)}catch{return null}let r=typeof i.generatedAt=="string"?i.generatedAt:new Date().toISOString(),o=r.replace(/[:.]/g,"-").replace(/Z$/,"Z"),a=ue.join(t,".promptci","history",o);await ne.mkdir(a,{recursive:!0});let c=ue.join(".promptci","history",o,"report.md"),l=ue.join(".promptci","history",o,"report.json"),u=ue.join(t,c),f=ue.join(t,l);try{await ne.copyFile(e,u)}catch{await ne.writeFile(u,s,"utf8")}await ne.copyFile(n,f);let d=Array.isArray(i.issues)?i.issues:[],p={critical:0,high:0,warning:0,info:0};for(let w of d){let y=w.severity;y in p&&p[y]++}let h={generatedAt:r,healthScore:typeof i.healthScore=="number"?i.healthScore:0,issueCount:p,archiveMdPath:c,archiveJsonPath:l},m=await ka(t);m.push(h);let g=Ea(t);await ne.mkdir(ue.dirname(g),{recursive:!0});let b=`${g}.tmp`;return await ne.writeFile(b,JSON.stringify(m,null,2),"utf8"),await ne.rename(b,g),h}async function $i(t,e={}){let n=ue.join(t.repoPath,".promptci"),s=e.mdPath??ue.join(n,"latest.md"),i=e.jsonPath??ue.join(n,"report.json");for(let d of[n,s,i,ue.join(n,"history")])if(!zn(t.repoPath,d))throw new Error(`Refusing to write the report: ${d} resolves outside the repository through a symlink.`);await ne.mkdir(ue.dirname(s),{recursive:!0}),await ne.mkdir(ue.dirname(i),{recursive:!0});let r=await b_(i),o=await ka(t.repoPath),a=await w_(t,r,o);a&&(t.trend=a);let l=e.archive!==!1&&!e.mdPath&&!e.jsonPath?await wp(t.repoPath,s,i):null,u=bp(t),f=Ai(t);return await Promise.all([ne.writeFile(s,u,"utf8"),ne.writeFile(i,f,"utf8")]),{mdPath:s,jsonPath:i,archivedEntry:l}}async function b_(t){try{let e=await ne.readFile(t,"utf8");return JSON.parse(e)}catch{return null}}async function w_(t,e,n){if(!e)return null;try{let s=t.issues||[],i=Array.isArray(e.issues)?e.issues:[],r=new Set(hp(s,t.repoPath)),o=new Set(hp(i,t.repoPath)),a=[...r].filter(b=>!o.has(b)),c=[...o].filter(b=>!r.has(b)),l=new Set([...s.map(b=>b.category),...i.map(b=>b.category)].filter(b=>typeof b=="string")),u={};for(let b of l){if(!b)continue;let w=s.filter(v=>v.category===b).length,y=i.filter(v=>v.category===b).length;u[b]=w-y}let f=["critical","high","warning","info"],d={};for(let b of f){let w=s.filter(v=>v.severity===b).length,y=i.filter(v=>v.severity===b).length;d[b]=w-y}let p=s.filter(b=>b.severity==="high"||b.severity==="critical").length,h=0;if(p===0&&(h=1,i.filter(w=>w.severity==="high"||w.severity==="critical").length===0)){h++;for(let w=n.length-1;w>=0;w--){let y=n[w];if(y&&(y.issueCount.high??0)===0&&(y.issueCount.critical??0)===0)h++;else break}}let m=typeof e.generatedAt=="string"?e.generatedAt:void 0,g=typeof e.healthScore=="number"?e.healthScore:0;return{previousScanDate:m,scoreDelta:t.healthScore-g,newIssuesCount:a.length,resolvedIssuesCount:c.length,severityDeltas:d,categoryDeltas:u,newIssueIds:a,resolvedIssueIds:c,streak:h}}catch{return null}}var Np=x(require("node:crypto"),1),jp=x(require("node:fs"),1),Mp=x(require("node:path"),1);var yt=x(require("node:fs"),1),re=x(require("node:path"),1),Ip=x(require("node:crypto"),1);var ss=x(require("node:fs/promises"),1),Ep=x(require("node:path"),1),Ra=x(Et(),1);var vp=200,v_=["apps/*","packages/*","libs/*"],x_=["dependencies","devDependencies","peerDependencies","optionalDependencies"],__={tsc:["typescript"],tsserver:["typescript"],tsx:["tsx"],"ts-node":["ts-node"],tsup:["tsup"],"tsc-alias":["tsc-alias"],"vue-tsc":["vue-tsc"],esbuild:["esbuild"],rollup:["rollup"],webpack:["webpack-cli","webpack"],vite:["vite"],swc:["@swc/cli"],babel:["@babel/cli"],parcel:["parcel"],rspack:["@rspack/cli"],unbuild:["unbuild"],bunchee:["bunchee"],eslint:["eslint"],prettier:["prettier"],biome:["@biomejs/biome"],oxlint:["oxlint"],stylelint:["stylelint"],knip:["knip"],depcheck:["depcheck"],madge:["madge"],commitlint:["@commitlint/cli"],"svelte-check":["svelte-check"],typedoc:["typedoc"],"size-limit":["size-limit"],vitest:["vitest"],jest:["jest"],mocha:["mocha"],ava:["ava"],playwright:["@playwright/test","playwright"],cypress:["cypress"],storybook:["storybook","@storybook/cli"],msw:["msw"],turbo:["turbo"],nx:["nx"],lerna:["lerna"],changeset:["@changesets/cli"],"semantic-release":["semantic-release"],husky:["husky"],"lint-staged":["lint-staged"],next:["next"],nuxt:["nuxt"],nuxi:["nuxt","nuxi"],astro:["astro"],remix:["@remix-run/dev"],expo:["expo"],eas:["eas-cli"],"react-native":["react-native"],ng:["@angular/cli"],nest:["@nestjs/cli"],gatsby:["gatsby"],docusaurus:["@docusaurus/core"],vitepress:["vitepress"],tauri:["@tauri-apps/cli"],electron:["electron"],"electron-builder":["electron-builder"],sanity:["sanity","@sanity/cli"],strapi:["@strapi/strapi"],prisma:["prisma"],"drizzle-kit":["drizzle-kit"],knex:["knex"],typeorm:["typeorm"],sequelize:["sequelize-cli"],supabase:["supabase"],wrangler:["wrangler"],vercel:["vercel"],netlify:["netlify-cli"],firebase:["firebase-tools"],sst:["sst"],cdk:["aws-cdk"],serverless:["serverless"],nodemon:["nodemon"],concurrently:["concurrently"],"cross-env":["cross-env"],rimraf:["rimraf"],dotenv:["dotenv-cli","dotenv"],"npm-run-all":["npm-run-all","npm-run-all2"],"run-s":["npm-run-all","npm-run-all2"],"run-p":["npm-run-all","npm-run-all2"],tailwindcss:["tailwindcss","@tailwindcss/cli"],postcss:["postcss-cli"],"graphql-codegen":["@graphql-codegen/cli"],"openapi-typescript":["openapi-typescript"]};function S_(t){return typeof t!="object"||t===null||Array.isArray(t)?[]:Object.keys(t)}function xp(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e}function E_(t){let{bin:e,name:n}=t;return typeof e=="string"&&typeof n=="string"?[n.split("/").pop()]:S_(e)}function is(t,e){let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let s=n,i=new Set,r={};for(let o of x_){let a=xp(s[o]);for(let c of Object.keys(a))a[c].startsWith("workspace:")||(i.add(c),c in r||(r[c]=a[c]))}return{dir:t,name:typeof s.name=="string"?s.name:void 0,scripts:xp(s.scripts),dependencies:[...i].sort(),versions:r,bins:E_(s)}}function k_(t){if(!t)return[];try{let n=JSON.parse(t).workspaces;return(Array.isArray(n)?n:typeof n=="object"&&n!==null&&Array.isArray(n.packages)?n.packages:[]).filter(i=>typeof i=="string")}catch{return[]}}function _p(t){let e=t.trim(),n=/^(?:"([^"]*)"|'([^']*)')/.exec(e);return n?n[1]??n[2]??"":e.replace(/\s+#.*$/,"")}function R_(t){if(!t)return[];let e=t.split(/\r?\n/),n=[];for(let s=0;s<e.length;s++){let i=/^packages\s*:\s*(.*)$/.exec(e[s]);if(!i)continue;let r=i[1].trim();if(r.startsWith("[")){let o=r;for(let c=s+1;!o.includes("]")&&c<e.length;c++)o+=` ${e[c].trim()}`;let a=o.slice(1,o.includes("]")?o.indexOf("]"):void 0);for(let c of a.split(",")){let l=_p(c);l&&n.push(l)}break}for(let o=s+1;o<e.length;o++){let a=e[o],c=/^\s*-\s+(.*)$/.exec(a);if(c){let l=_p(c[1]);l&&n.push(l);continue}if(!(a.trim()===""||/^\s*#/.test(a)||/^\s/.test(a)))break}break}return n}function Sp(t){let e=t.replace(/\\/g,"/");return e.startsWith("/")||/^[a-zA-Z]:/.test(e)?!1:!e.split("/").includes("..")}function C_(t){return`${t.replace(/^\.\//,"").replace(/\/+$/,"")}/package.json`}async function kp(t,e,n=()=>!1){let s;try{let p=K(t,"pnpm-workspace.yaml");s=p?await ss.readFile(p,"utf-8"):void 0}catch{s=void 0}let i=[...k_(e),...R_(s)],r=i.filter(p=>!p.startsWith("!")&&Sp(p)),o=i.filter(p=>p.startsWith("!")).map(p=>p.slice(1)),a=r.length>0?r:v_,c=["**/node_modules/**","**/.git/**",...o.filter(Sp).map(p=>`${p.replace(/\/+$/,"")}/**`)],l=ct(t,a.map(C_),c).filter(p=>It(t,p)!==null&&!n(p)),u=l.length>vp,f=[],d=e?is(".",e):void 0;d&&f.push(d);for(let p of l.slice(0,vp))if(p!=="package.json")try{let h=K(t,p);if(!h)continue;let m=await ss.stat(h);if(!m.isFile()||m.size>ce)continue;let g=is(Ep.posix.dirname(p),await ss.readFile(h,"utf-8"));g&&f.push(g)}catch{}return{manifests:f,truncated:u}}function A_(t){let e=new Set((t.workspaces??[]).map(a=>a.name).filter(a=>!!a)),n=new Set,s=a=>{!a.startsWith("@types/")&&!e.has(a)&&n.add(a)},{dependencies:i,devDependencies:r,peerDependencies:o}=t.packageJson;for(let a of[i,r,o])for(let[c,l]of Object.entries(a))l.startsWith("workspace:")||s(c);for(let a of t.workspaces??[])a.dependencies.forEach(s);return n}function Cn(t,e){if((t.workspaces??[]).some(i=>i.bins.includes(e)))return!0;let n=A_(t);if(n.has(e))return!0;let s=__[e];return s?t.workspaces===void 0||t.workspacesTruncated?!0:s.some(i=>n.has(i)):!1}function Pi(t,e){return t.packageJson.scripts[e]?!0:(t.workspaces??[]).some(n=>!!n.scripts[e])}function Ca(t,e){let n=t.workspaces??[];if(e==="*"||e==="**"||e.startsWith("!")||e.startsWith("["))return n;let s=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),i={dot:!0};return n.filter(r=>r.name===e||r.dir===s||r.dir.endsWith(`/${s}`)||/[*?[{]/.test(e)&&(r.name!==void 0&&Ra.default.isMatch(r.name,e,i)||Ra.default.isMatch(r.dir,s,i)))}var An=x(require("node:fs"),1),Cp=x(require("node:path"),1);var $_=["GNUmakefile","makefile","Makefile"],Rp=/^[A-Za-z0-9_.%/+-]+$/;function P_(t){let e=[],n="";for(let s of t.split(/\r?\n/)){if(/\\$/.test(s)){n+=s.slice(0,-1)+" ";continue}e.push(n+s),n=""}return n&&e.push(n),e}function T_(t,e="Makefile"){let n=new Set,s=new Set,i=!1,r=!1;for(let o of P_(t)){if(o.startsWith(" "))continue;let c=o.replace(/(?<!\\)#.*$/,"").trimEnd().trim();if(!c)continue;if(/^define\b/.test(c)||/^(?:override\s+)?define\s/.test(c)){r=!0;continue}if(r){/^endef\b/.test(c)&&(r=!1);continue}if(/^(?:-include|sinclude|include)\s/.test(c)){i=!0;continue}if(/\$\((?:eval|call)\b/.test(c)){i=!0;continue}let l=c.indexOf(":"),u=c.indexOf("=");if(l===-1||u!==-1&&u<l)continue;let f=c.slice(l+1);if(/^:?=/.test(f)||/^::=/.test(f))continue;let d=c.slice(0,l).trim();if(d&&!/^(?:ifeq|ifneq|ifdef|ifndef|else|endif|export|unexport|override|private|vpath)\b/.test(d)){if(d.includes("$")){i=!0;continue}if(d===".DEFAULT"){i=!0;continue}if(d===".PHONY"){for(let p of f.replace(/^:/,"").trim().split(/\s+/))p&&!p.includes("$")&&Rp.test(p)?n.add(p):p.includes("$")&&(i=!0);continue}for(let p of d.split(/\s+/))!p||!Rp.test(p)||(p.includes("%")?s.add(p):n.add(p))}}return{file:e,targets:[...n].sort(),patterns:[...s].sort(),unverifiable:i}}function Ap(t,e){return t.targets.includes(e)?!0:t.patterns.some(n=>{let s=n.indexOf("%"),i=n.slice(0,s),r=n.slice(s+1);return e.length>i.length+r.length&&e.startsWith(i)&&e.endsWith(r)})}function Ti(t,e){for(let n of $_){let s=e==="."||e===""?n:`${e}/${n}`,i=K(t,s);if(i)try{let r=An.statSync(i);if(!r.isFile()||!An.readdirSync(Cp.dirname(i)).includes(n))continue;return r.size>ce?{file:s,targets:[],patterns:[],unverifiable:!0}:T_(An.readFileSync(i,"utf8"),s)}catch{continue}}}function I_(t,e){return`cmd-validity-${Ip.createHash("sha1").update(`${t}|${e}`).digest("hex").slice(0,12)}`}function rs(t,e){try{let n=re.resolve(t,e);return yt.existsSync(n)}catch{return!1}}function O_(t,e){try{return yt.statSync(re.resolve(t,e)).isDirectory()}catch{return!1}}function Op(t,e){if(!ae(t,e))return null;try{let n=yt.readFileSync(e,"utf8"),s=JSON.parse(n);if(typeof s!="object"||s===null||Array.isArray(s))return null;let i=typeof s.scripts=="object"&&s.scripts!==null&&!Array.isArray(s.scripts)?Object.fromEntries(Object.entries(s.scripts).filter(r=>typeof r[1]=="string")):{};return{name:typeof s.name=="string"?s.name:void 0,scripts:i}}catch{return null}}function L_(t){for(let e=1;e<t.length;e++){let n=t[e];if(n==="--filter"||n==="-F")return t[e+1];if(n.startsWith("--filter="))return n.slice(9);if(n.startsWith("-F="))return n.slice(3)}}function N_(t){if(t)return t.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").replace(/^!/,"").trim()}function j_(t,e){let n=new Set,s=e.replace(/\\/g,"/");(s.startsWith(".")||s.includes("/"))&&n.add(re.join(t,s,"package.json"));for(let i of["apps","packages","libs"]){let r=re.join(t,i);try{for(let o of yt.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&n.add(re.join(r,o.name,"package.json"))}catch{}}return[...n]}function M_(t,e,n){let s=N_(e);if(!s)return!1;if(t.workspaces)return Ca(t,s).some(i=>!!i.scripts[n]);for(let i of j_(t.repoRoot,s)){let r=Op(t.repoRoot,i);if(!r)continue;let o=re.dirname(i).replace(/\\/g,"/"),a=re.relative(t.repoRoot,o).replace(/\\/g,"/");if((r.name===s||a===s||a.endsWith(`/${s}`))&&r.scripts[n])return!0}return!1}function os(t){return!t||t.startsWith("-")?!1:t.includes("/")||t.includes("\\")||/\.[a-z]{1,5}$/i.test(t)}var D_=new Set(["install","i","add","remove","uninstall","test","it","init","create","publish","link","unlink","outdated","audit","update","up","exec","dlx","run","store","list","ls","why","pack","recursive","m","multi","prune","version","run-script","env","config","fetch","rebuild","rb","patch","patch-commit","deploy","import","licenses","root","bin","setup","self-update","dedupe","doctor","approve-builds","sbom","cache"]),F_=new Set(["install","i","ci","uninstall","remove","update","outdated","audit","start","stop","restart","test","it","init","create","publish","link","unlink","pack","exec","run","run-script","version"]),H_=new Set(["install","add","remove","upgrade","outdated","audit","init","create","publish","link","unlink","why","pack","run","version","run-script","workspaces","exec","dlx","up","info","config","cache","bin","set","node","global","dedupe","patch","rebuild","plugin","constraints","unplug","npm"]),$a=new Set(["install","i","add","a","remove","rm","update","test","build","init","create","c","x","bunx","pm","link","unlink","upgrade","repl","outdated","publish","patch","audit","info","why","completions","help","feedback","run","exec"]),$p=new Set(["run","run-script"]);function Ii(t,e){if(t===null)return null;let n=e.replace(/^['"]|['"]$/g,"").trim();if(!n||n.startsWith("/")||n.startsWith("~")||/^[a-zA-Z]:[\\/]/.test(n)||/^-|[$`%<>{}*?]/.test(n))return null;let s=t==="."?[]:t.split("/");for(let i of n.replace(/\\/g,"/").split("/"))if(!(i===""||i==="."))if(i===".."){if(s.length===0)return null;s.pop()}else s.push(i);return s.length===0?".":s.join("/")}function Pp(t){return t.split(/&&|\|\||;|\n/).map(e=>e.trim()).filter(Boolean)}function B_(t){let e=["npm","pnpm","yarn","bun","node","tsx","ts-node","bash","sh","python","python3","dotnet","docker","make","git","ls","cd","mkdir","rm","cp","mv","./","../"],n=t.trim().split(/\s+/)[0]??"";return!!(e.some(s=>n===s||n.startsWith("./"))||n.startsWith("./")||n.startsWith("../"))}var W_=new Set(["bash","sh","shell","powershell","pwsh","zsh","command-line","cmd"]);function G_(t){let e=[];for(let n of Vn(t)){let s=/^[a-zA-Z0-9_-]*/.exec(n.lang)[0];if(!(!(s===""||W_.has(s))||!n.closed))for(let r=0;r<n.lines.length;r++){let o=n.lines[r].trim();if(o.startsWith("#"))continue;let a=o.replace(/^\$\s*/,"");if(!a)continue;let c=".";for(let l of Pp(a)){let u=/^cd\s+(.+)$/.exec(l);u&&(c=Ii(c,u[1].trim())),e.push({text:l,line:n.contentStartLine+r,cwd:c,fenced:!0})}}}for(let n of xe(t)){if(n.inFence)continue;let s=n.lineNumber-1,i=n.text.replace(/\r$/,"");for(let r of i.matchAll(/`([^`]+)`/g)){let o=r[1].trim(),a=".";for(let c of Pp(o)){let l=/^cd\s+(.+)$/.exec(c);l&&(a=Ii(a,l[1].trim())),B_(c)&&e.push({text:c,line:s+1,cwd:a})}}for(let r of i.matchAll(/\brun\s+(pnpm|npm|yarn|bun|node|tsx|ts-node|bash|python|dotnet|docker)\s+(.+?)(?=[.!?](?:\s|$)|[,;!]|$)/gi)){let o=(r[2]??"").trim().replace(/[.!?]+$/,""),a=`${r[1]} ${o}`.trim();e.push({text:a,line:s+1})}}return e.sort((n,s)=>n.line-s.line)}var U_=/[<{]|\.{3,}|your-file|your-script|example|placeholder/i,V_=new Set(["--filter","-F","--cwd","-C","--dir","--loader","--require","-r","--workspace","--prefix"]);function z_(t,e){return t==="pnpm"&&e==="-r"?!1:e==="-w"?t==="npm":V_.has(e)}function Aa(t,e=1){let n=e,s=t[0]??"";for(;n<t.length;){let i=t[n];if(!i.startsWith("-"))break;n++,z_(s,i)&&t[n]&&!t[n].startsWith("-")&&n++}return n}function q_(t,e){let n=L_(e);if(n)return n;if(t==="npm")for(let s=1;s<e.length;s++){let i=e[s];if(i==="-w"||i==="--workspace")return e[s+1];if(i.startsWith("--workspace="))return i.slice(12)}}function K_(t,e){return t==="pnpm"?e.some(n=>n==="-r"||n==="--recursive"):t==="npm"?e.some(n=>n==="--workspaces"||n==="-ws"):!1}function Y_(t){for(let e=1;e<t.length;e++){let n=t[e];if(n==="--cwd"||n==="-C"||n==="--dir"||n==="--prefix")return t[e+1];let s=/^(?:--cwd|--dir|--prefix)=(.+)$/.exec(n);if(s)return s[1]}}function J_(t,e,n,s,i,r,o,a){let c=s.includes("/")?s.split("/").map(b=>b.trim()).filter(Boolean):[s];for(let b of c)a?.(b);if(e===null)return null;let l=Y_(n);if(l!==void 0){let b=Ii(e,l);if(b===null)return null;e=b}let u=o.workspaceName??q_(r,n),f=K_(r,n),d=b=>f?Pi(t,b):M_(t,u,b),p=u&&t.workspaces&&!f?Ca(t,u.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").trim()):void 0,h=e!=="."&&e!=="",m=h?Op(t.repoRoot,re.join(t.repoRoot,e,"package.json")):null;if(h&&!m)return null;let g=Object.keys(t.packageJson.scripts).length>0;if(!m&&!g)return null;for(let b of c)if(!i.has(b)&&!(o.allowBinary&&Cn(t,b))){if(p){if(p.length===0){if(t.workspacesTruncated)continue;return`no workspace matches "${u}" for ${r} script "${b}"`}if(p.some(y=>!!y.scripts[b]))continue;let w=p.length===1?`${p[0].name??p[0].dir} (${p[0].dir}/package.json)`:`the ${p.length} workspaces selected by "${u}"`;return`${r} script "${b}" does not appear in ${w} scripts`}if(m){if(m.scripts[b]||d(b))continue;return`${r} script "${b}" does not appear in ${e}/package.json scripts`}if(!d(b)&&!t.packageJson.scripts[b])return`${r} script "${b}" does not appear in package.json scripts`}return null}var X_={pnpm:D_,npm:F_,yarn:H_,bun:new Set};function Z_(t,e,n,s,i,r){let o=Aa(e),a=e[o];if(!a)return null;let c=!1,l=o,u;if($p.has(a))c=!0,l=Aa(e,o+1);else{if(t==="npm")return null;t==="yarn"&&a==="workspace"&&(u=e[o+1],l=o+2,$p.has(e[l]??"")&&(c=!0,l++))}let f=e[l];if(!f||f.startsWith("-"))return null;if(t==="bun"){if(!c&&$a.has(f))return null;if(os(f))return i&&/\.[cm]?[jt]sx?$/.test(f)&&!rs(i,f)?`File "${f}" referenced by "bun" does not appear to exist in the repository`:null}return J_(n,s,e,f,X_[t],t,{allowBinary:!(c&&(t==="npm"||t==="pnpm")),workspaceName:u},r)}var Q_=new Set(["-C","-f","-o","-W","-I","-E","--directory","--file","--makefile","--old-file","--what-if","--include-dir","--new-file","--assume-old","--assume-new","--eval"]),eS=new Set(["sure","it","this","that","them","these","those","certain","sense","changes","room","use","way"]),tS=new Set(["-j","-l","--jobs","--load-average","--max-load"]);function nS(t,e,n,s){let i=n,r=[];for(let l=1;l<t.length;l++){let u=t[l];if(/^(?:[|&<>#]|\d*>)/.test(u))break;if(u.startsWith("-")){let f=u.indexOf("="),d=f===-1?u:u.slice(0,f);if(d==="-f"||d==="--file"||d==="--makefile"||/^-f./.test(u))return null;let p;Q_.has(d)?p=f!==-1?u.slice(f+1):t[++l]:/^-C./.test(u)?p=u.slice(2):tS.has(u)&&/^\d+(?:\.\d+)?$/.test(t[l+1]??"")&&l++,(d==="-C"||d==="--directory"||/^-C./.test(u))&&p!==void 0&&(i=Ii(i,p));continue}u.includes("=")||r.push(u)}if(i===null||r.length===0)return null;let o=s(i);if(!o||o.unverifiable)return null;let a=i==="."?e.repoRoot:re.join(e.repoRoot,i),c;for(let l of r){let u=l.replace(/^['"]|['"]$/g,"");if(!(!u||os(u)||!/^[A-Za-z0-9_.+-]+$/.test(u))&&!Ap(o,u)){try{c??=yt.readdirSync(a)}catch{c=[]}if(!c.some(f=>f===u||f.startsWith(`${u}.`)))return`make target "${u}" does not appear in ${o.file}`}}return null}function sS(t,e,n=".",s,i={}){if(U_.test(t))return null;let r=t.trim().split(/\s+/);if(r.length===0)return null;let o=r[0],a=n===null?null:n!=="."&&n!==""?re.join(e.repoRoot,n):e.repoRoot;if(o==="pnpm"||o==="npm"||o==="yarn"||o==="bun")return Z_(o,r,e,n,a,s);if(a&&["node","tsx","ts-node","bash","sh","python","python3"].includes(o)&&r[1]){let l=r[Aa(r)];if(l&&os(l)&&!rs(a,l))return`File "${l}" referenced by "${o}" does not appear to exist in the repository`}if(o==="make"&&n!==null&&i.makefileFor){let l=i.fileDir??".",u=n==="."&&l!=="."&&i.makefileFor(l)?l:n;return!i.fenced&&r.length===2&&eS.has(r[1].toLowerCase())?null:nS(r,e,u,i.makefileFor)}if(a&&(o.startsWith("./")||o.startsWith("../"))){if(r.length===1&&re.extname(o.replace(/\/+$/,""))===""&&(O_(a,o)||!i.fenced||o.endsWith("/")))return null;if(!rs(a,o))return`Script "${o}" does not appear to exist in the repository`}if(a&&o==="docker"&&r[1]==="compose"&&r.includes("-f")){let l=r.indexOf("-f"),u=r[l+1];if(u&&os(u)&&!rs(a,u))return`Docker Compose file "${u}" does not appear to exist in the repository`}if(a&&o==="dotnet"&&r[1]==="test"&&r[2]){let l=r[2];if(os(l)){if(!rs(a,l))return`dotnet test target "${l}" does not appear to exist`;if(!/\.(sln|csproj|fsproj)$/.test(l))return`dotnet test target "${l}" should be a .sln, .csproj, or .fsproj file`}}return null}function Lp(t){return Pa(t).issues.map(e=>({...e}))}var Tp=new WeakMap;function Pa(t){let e=Tp.get(t);return e||(e=iS(t),Tp.set(t,e)),e}function iS(t){let e=[],n=new Map,s=new Set,i=new Map,r=o=>o==="."||o===""?t.makefile:(i.has(o)||i.set(o,Ti(t.repoRoot,o)),i.get(o));for(let o of t.files){let a=G_(o.content),c=new Set,l=re.relative(t.repoRoot,re.dirname(o.path)).replace(/\\/g,"/")||".";n.set(o.path,c);for(let u of a){let f=u.cwd===void 0?".":u.cwd,d=sS(u.text,t,f,h=>c.add(`${u.line}:${h}`),{fenced:u.fenced===!0,makefileFor:r,fileDir:l.startsWith("..")?".":l});if(!d)continue;let p=`${o.path}|${u.text}`;s.has(p)||(s.add(p),e.push({id:I_(L(o),u.text),severity:"warning",category:"command_validity",title:`Possible reference to missing command or file: \`${u.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:d,filePaths:[o.path],locations:[{filePath:o.path,startLine:u.line,endLine:u.line}],evidence:[`Command: \`${u.text}\``,`In file: ${o.path}`],recommendation:"Verify the command. If the script was renamed, update the instruction file. If it is an illustrative example, wrap it in a placeholder like <script-name> to suppress this finding.",confidence:.8}))}}return{issues:e,evaluatedScripts:n}}function Oi(t){return`manifest-${Np.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function rS(t,e,n){if(!(/\[tool\.poetry\]/.test(e)||/build-backend\s*=\s*["'][^"']*poetry[^"']*["']/i.test(e)))return null;let i=Mp.join(n,"requirements.txt");if(jp.existsSync(i))return null;let r=/pip\s+install\s+-r\s+requirements\.txt/i,o=t.filter(a=>r.test(a.content));return o.length===0?null:{id:Oi("pip-vs-poetry"),severity:"high",category:"conflict",title:"Tooling mismatch: instruction uses pip but project uses Poetry",summary:"Instruction files tell the agent to run `pip install -r requirements.txt`, but this project uses Poetry as its build system (pyproject.toml with [tool.poetry]) and has no requirements.txt. Running this command would fail immediately.",filePaths:o.map(a=>a.path),locations:o.map(a=>({filePath:a.path})),evidence:["`pip install -r requirements.txt` found in instruction file(s)","pyproject.toml declares Poetry as the build system","requirements.txt does not exist in the repo"],recommendation:"Update the instruction files to use Poetry commands instead: `poetry install` (or `uv sync` if the project has migrated to uv). Remove the `pip install -r requirements.txt` reference.",confidence:.9}}function oS(t,e){let n=/^python\s*=\s*["'][\^~>=<*]*(\d+)\.(\d+)/m.exec(e)||/^requires-python\s*=\s*["'][\^~>=<*]*(\d+)\.(\d+)/m.exec(e);if(!n)return[];let s=parseInt(n[1],10),i=parseInt(n[2],10),r=[],o=new Set,a=/\bPython\s+(\d+)\.(\d+)\b/gi;for(let c of t){let l,u=new RegExp(a.source,a.flags);for(;(l=u.exec(c.content))!==null;){let f=parseInt(l[1],10),d=parseInt(l[2],10);if(Oa(c.content,l.index)||!(f<s||f===s&&d<i))continue;let h=`${f}.${d}`,m=`${s}.${i}`,g=`${c.path}:${h}`;o.has(g)||(o.add(g),r.push({id:Oi(`python-version:${L(c)}:${h}`),severity:"high",category:"stale_instruction",title:`Python version mismatch: instruction says ${h}, pyproject.toml requires \u2265${m}`,summary:`An instruction file refers to Python ${h}, but pyproject.toml declares \`python = "^${m}"\` (or newer). An agent following this instruction would target an older interpreter and may avoid language features or APIs that are safe to use in this project.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`Instruction says "Python ${h}"; pyproject.toml requires \u2265${m}`],recommendation:`Update the instruction file to reference Python ${m} (or remove the version claim and rely on pyproject.toml as the authoritative source).`,confidence:.85}))}}return r}var aS=["pandas","numpy","sqlalchemy","fastapi","django","flask","pydantic"];function cS(t){return t==="sqlalchemy"?"SQLAlchemy":t==="fastapi"?"FastAPI":t[0].toUpperCase()+t.slice(1)}function Ia(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ta(t){let e=t.trim();if(/^<=?\s*\d+/.test(e))return null;let n=/^(?:\^|~=|==|>=|>|=)?\s*(\d+)(?:\.\d+)?/.exec(e);return n?parseInt(n[1],10):null}function lS(t){let e=new Map;for(let n of aS){let s=Ia(n),r=new RegExp(`^\\s*${s}\\s*=\\s*["']([^"']+)["']`,"im").exec(t);if(r){let c=Ta(r[1]);if(c!==null){e.set(n,c);continue}}let o=new RegExp(`["']${s}(?:\\[[^\\]]+\\])?\\s*([~^=<>!]{1,2}\\s*\\d+(?:\\.\\d+)?)`,"gim"),a;for(;(a=o.exec(t))!==null;){let c=Ta(a[1]);if(c!==null){e.set(n,c);break}}}return e}function uS(t,e){let n=Math.max(0,e-80),s=Math.min(t.length,e+120),i=t.slice(n,s);return/\b(target|support|supports|compatibility|compatible|avoid|maintain|maintains)\b/i.test(i)}function fS(t,e){let n=lS(e);if(n.size===0)return[];let s=[],i=new Set;for(let[r,o]of n){let a=cS(r),c=new RegExp(`\\b${Ia(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let u,f=new RegExp(c.source,c.flags);for(;(u=f.exec(l.content))!==null;){if(!uS(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=o)continue;let p=u[2]?`${d}.${u[2]}`:`${d}.x`,h=`${l.path}:${r}:${p}`;i.has(h)||(i.add(h),s.push({id:Oi(`library-version:${L(l)}:${r}:${p}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${p}, pyproject.toml uses ${o}.x`,summary:`An instruction file refers to ${a} ${p}, but pyproject.toml declares ${r} ${o}.x. An agent following this instruction may avoid APIs that are valid for the installed dependency or target compatibility behavior that no longer matches the project manifest.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Instruction says "${a} ${p}"; pyproject.toml uses ${r} ${o}.x`],recommendation:`Update the instruction file to match ${a} ${o}.x, or remove the version-specific guidance and rely on pyproject.toml as the authoritative source.`,confidence:.85}))}}}return s}var dS=["react","next","typescript","vite","vitest","jest"],pS={react:"React",next:"Next.js",typescript:"TypeScript",vite:"Vite",vitest:"Vitest",jest:"Jest"};function hS(t){let e;try{e=JSON.parse(t)}catch{return new Map}if(typeof e!="object"||e===null||Array.isArray(e))return new Map;let n=e,s=new Map,i=[n.dependencies,n.devDependencies,n.peerDependencies];for(let r of i){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;for(let a of dS){let c=o[a];if(typeof c!="string")continue;let l=Ta(c);l!==null&&s.set(a,l)}}return s}function mS(t,e){let n=hS(e);if(n.size===0)return[];let s=[],i=new Set;for(let[r,o]of n){let a=pS[r],c=new RegExp(`\\b${Ia(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let u,f=new RegExp(c.source,c.flags);for(;(u=f.exec(l.content))!==null;){if(!gS(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=o)continue;let p=u[2]?`${d}.${u[2]}`:`${d}.x`,h=`${l.path}:${r}:${p}`;i.has(h)||(i.add(h),s.push({id:Oi(`js-library-version:${L(l)}:${r}:${p}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${p}, package.json uses ${o}.x`,summary:`An instruction file refers to ${a} ${p}, but package.json declares ${r} ${o}.x. An agent following this instruction may target compatibility behavior or APIs that no longer match the installed dependency.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Instruction says "${a} ${p}"; package.json uses ${r} ${o}.x`],recommendation:`Update the instruction file to match ${a} ${o}.x, or remove the version-specific guidance and rely on package.json as the authoritative source.`,confidence:.85}))}}}return s}function gS(t,e){let n=Math.max(0,e-100),s=Math.min(t.length,e+140),i=t.slice(n,s);return/\b(use|using|target|support|supports|compatibility|compatible|avoid|maintain|migration|migrate|features?|apis?)\b/i.test(i)}function Oa(t,e){let n=t.lastIndexOf(`
47
+ `)}function Ci(t){return t.fileType==="copilot"||Ne.basename(t.path).toLowerCase()==="copilot-instructions.md"}function tS(t){return t.fileType==="cursor"||Ne.basename(t.path).toLowerCase()===".cursorrules"}function nS(t){return t.fileType==="windsurf"||Ne.basename(t.path).toLowerCase()===".windsurfrules"}function sS(t){return t.fileType==="claude"||Ne.basename(t.path).toLowerCase()==="claude.md"}function Ai(t){if(tS(t))return{label:"Cursor rules file",agent:"Cursor agents"};if(nS(t))return{label:".windsurfrules",agent:"Windsurf agents"};if(sS(t))return{label:"CLAUDE.md",agent:"Claude"};if(Ci(t))return{label:".github/copilot-instructions.md",agent:"GitHub Copilot"};if(t.fileType==="gemini")return{label:"GEMINI.md",agent:"Gemini CLI"};if(t.fileType==="cline"&&Ne.basename(t.path)===".clinerules")return{label:".clinerules",agent:"Cline"}}function sp(t){let e=t.content.split(/\r?\n/).slice(0,12).join(`
48
+ `);if(np.test(e))return!0;let n=Jx.exec(e);return n&&`${n[1].toLowerCase()}.md`!==Ne.basename(t.path).toLowerCase()?!0:t.lineCount<20&&np.test(t.content)}function iS(t,e){return e.filter(n=>{let s=Ai(n);if(!s)return!1;let i=t.find(r=>r.relativePath===n.aliasOf);return i===void 0||Ai(i)?.label!==s.label})}function rp(t){return t!=="claude"&&t!=="readme"}function ip(t){let e=t[0];if(!rp(e.fileType))return;let n=Ke(e.content).replace(/`[^`\n]+`/g,"");if(!Yx.test(n))return;let s=jt.createHash("sha1").update(`claude-xml-tag:${L(e)}`).digest("hex").slice(0,12),i=/<\/?claude:[\w-]+/i.exec(n)?.[0]??"<claude:...>";return{id:`claude-xml-tag-${s}`,severity:"warning",category:"structure",title:"Claude-specific XML tag in non-Claude instruction file",summary:`This file contains a Claude-specific XML tag (${i}) but is not a CLAUDE.md file. Claude XML tags are only interpreted by Claude; other AI tools (Cursor, Copilot, etc.) will treat them as literal text or ignore them.`,filePaths:t.map(r=>r.path),locations:t.map(r=>({filePath:r.path})),evidence:[`Found: ${i} in ${[...new Set(t.map(r=>r.fileType))].join(", ")} file`],recommendation:"Move Claude-specific directives to CLAUDE.md, or replace this tag with a plain-text instruction that all tools can understand.",confidence:.85}}function ba(t,e=[]){if(t.length===0)return[];let n=[...t,...iS(t,e)],s=[],i=t.map(p=>p.content).join(`
49
+ `),r=Ri(i),o=t.map(p=>p.path);for(let p of _n){let h=p.id==="no-verification-loop"?r:i;es(h,p.patterns)||s.push({id:Xx(p.id),severity:p.severity,category:"agent_practices",title:p.title,summary:p.summary,filePaths:o,locations:[],evidence:[`Pattern not found across ${t.length} instruction file(s).`],recommendation:p.recommendation,fixRecipe:p.fixRecipe,confidence:p.confidence})}let a=[..._n.find(p=>p.id==="no-verification-loop").patterns,..._n.find(p=>p.id==="no-honesty-policy").patterns,..._n.find(p=>p.id==="no-scope-control").patterns,..._n.find(p=>p.id==="no-read-before-edit").patterns],c=p=>es(Ri(p.content),a),l=new Set;for(let p of n){let h=Ai(p);if(!h||c(p)||sp(p))continue;let m=t.find(g=>g!==p&&c(g));m&&(l.add(p.path),s.push({id:Qx(L(p)),severity:"warning",category:"agent_practices",title:`No behavioral guidance in ${h.label}`,summary:`The ${h.label} contains no agent behavioral rules (verification loop, honesty policy, scope control, read-before-edit). ${h.agent} may rely on this file, so they will have no behavioral guidance even though another instruction file in the repo contains related rules.`,filePaths:[p.path],locations:[{filePath:p.path}],evidence:[`No behavioral patterns found in ${Ne.basename(p.path)}.`,`Some behavioral guidance appears in ${Ne.basename(m.path)}.`],recommendation:`Add at minimum: a verification rule ("run tests before saying done"), a scope-control rule ("prefer focused diffs"), a read-before-edit rule, and an honesty policy directly to ${h.label} so behavioral guidance is available in the file this tool reads. Alternatively, use a forwarding pointer if the tool supports it (e.g., "Follow AGENTS.md").`,confidence:.8}))}for(let p of _n){let h=t.find(m=>es(Ri(m.content),p.patterns));if(h)for(let m of n){if(m===h)continue;let g=Ai(m);if(!g||sp(m)||l.has(m.path))continue;if(!es(Ri(m.content),p.patterns)){let w=p.title.toLowerCase().replace("no ","").replace(" instruction",""),y=jt.createHash("sha1").update(`behavior-gap:${L(m)}:${p.id}`).digest("hex").slice(0,12);s.push({id:`per-file-behavioral-gap-${y}`,severity:"warning",category:"agent_practices",title:`Missing critical guidance "${p.title.replace("No ","").replace(" instruction","")}" in ${g.label}`,summary:`The ${g.label} lacks the critical behavioral guidance regarding "${w}" which is defined in ${Ne.basename(h.path)}. Since ${g.agent} reads ${g.label}, they will miss this rule.`,filePaths:[m.path,h.path],locations:[{filePath:m.path}],evidence:[`Guidance pattern not found in ${Ne.basename(m.path)}.`,`Guidance defined in ${Ne.basename(h.path)}.`],recommendation:`Add the missing guidance to ${g.label} (e.g., "${p.recommendation.replace("Add a rule such as: ","").replace(/"/g,"")}") or use a forwarding pointer (e.g., "Follow ${Ne.basename(h.path)}").`,fixRecipe:p.fixRecipe,confidence:.8})}}}let u=/^#{1,4}\s+(?:agent\s+behavior|ai\s+behavior|agent\s+rules|behavior\s+rules|agent\s+instructions)\b/im,f=p=>`copilot-agent-behavior-${jt.createHash("sha1").update(`copilot-agent-behavior:${p}`).digest("hex").slice(0,12)}`;if((()=>{let p=t.filter(Ci);return p.length===0||!p.some(c)?!1:!t.filter(g=>!Ci(g)&&g.fileType!=="readme"&&g.fileType!=="docs").some(c)})()){let p=t.find(Ci);s.push({id:f(L(p)),severity:"warning",category:"structure",title:"General behavioral guidance placed only in Copilot instructions",summary:"General agent behavioral rules (verification loop, honesty policy, etc.) appear only in Copilot-specific instruction files. Other agents (Claude, Cursor, etc.) will likely not see these rules.",filePaths:[p.path],locations:[{filePath:p.path}],evidence:["Behavioral directives found only in Copilot-specific files."],recommendation:"Move general agent behavior rules to AGENTS.md or CLAUDE.md so all agents benefit. Keep copilot-instructions.md focused on Copilot-specific context.",confidence:.7})}for(let p of t)p.fileType==="copilot"&&u.test(p.content)&&es(p.content,a)&&(s.some(h=>h.id===f(L(p)))||s.push({id:f(L(p)),severity:"warning",category:"structure",title:"Agent-behavior section in copilot-instructions.md",summary:'copilot-instructions.md contains an "Agent Behavior" (or similar) heading with agent-practice directives. This file is scoped to GitHub Copilot; agent behavioral rules are typically placed in AGENTS.md or CLAUDE.md where all agents can read them.',filePaths:[p.path],locations:[{filePath:p.path}],evidence:["Agent behavioral directives found inside a Copilot-specific instruction file."],recommendation:"Move agent behavior rules to AGENTS.md or CLAUDE.md, or copy them there so all agents benefit. Keep copilot-instructions.md focused on Copilot-specific context (repo structure, technology stack, Copilot feature preferences).",confidence:.65}));for(let p of t){let h=p.content.slice(0,500),m=qx.exec(h),g=!!m,b=Kx.test(h),w=m?eS(p.content,m.index):1;if(g&&!b)s.push({id:Zx(L(p)),severity:"warning",category:"agent_practices",title:'"Do not edit" header in human-maintained instruction file',summary:'This instruction file starts with a "do not edit" directive but does not appear to be auto-generated. Humans and agents need to update instruction files regularly \u2014 this header may prevent necessary edits.',filePaths:[p.path],locations:[{filePath:p.path,startLine:w,endLine:w}],evidence:[m[0].trim()],recommendation:'Remove the "do not edit" header, or add a clear generator comment explaining which tool generates this file.',confidence:.8});else if(g&&b&&p.lineCount>5){let v=R=>`auto-gen-header-${jt.createHash("sha1").update(`auto-gen-header:${R}`).digest("hex").slice(0,12)}`;s.push({id:v(L(p)),severity:"warning",category:"agent_practices",title:"Misleading auto-generated header on human-maintained instruction file",summary:`This instruction file has an "AUTO-GENERATED \u2014 DO NOT EDIT" header, but with ${p.lineCount} lines of hand-written content it is clearly human-maintained. The header may prevent agents and humans from updating the file when needed.`,filePaths:[p.path],locations:[{filePath:p.path,startLine:w,endLine:w}],evidence:[m[0].trim()],recommendation:"Remove the auto-generated header. If this file is genuinely generated, add a clear generator comment that names the tool and the source template so the origin is unambiguous.",confidence:.75})}let y=ip([p]);y&&s.push(y)}for(let p of Qn(Yt(t,e,rp))){let h=ip(p);h&&s.push(h)}return s}var dp=x(require("node:crypto"),1);var rS=["duplicate","conflict","context_bloat","missing_context","stale_instruction","vague_guidance","structure","command_validity","agent_practices","ai_config","security","custom"],op=new Set([...rS,"all"]),ap=/<!--\s*promptci-ignore:\s*(\S+)([\s\S]*?)-->/g,cp=/<!--\s*promptci-ignore-start:\s*(\S+)([\s\S]*?)-->/g,lp=/<!--\s*promptci-ignore-end\s*-->/g;function ts(t,e){return t.slice(0,e).split(`
50
+ `).length}function oS(t,e,n,s,i){let r=i.split(/\r?\n/);for(let o=0;o<n.length;o++){let a=n[o];if(a.startLine<=t&&a.endLine>=t){let c=n[o+1],u=r.slice(e,Math.max(e,c?.startLine?c.startLine-1:e)).every(f=>f.trim()==="");return c&&c.startLine>e&&u?c.endLine:a.endLine}}for(let o of n)if(o.startLine>t)return o.endLine;return s}function up(t){let e=/reason:\s*(.+?)(?:\r?\n|$)/i.exec(t);return e?e[1].trim():null}function fp(t,e){return op.has(t)?!e||!e.trim()?{valid:!1,message:'promptci-ignore annotation is missing a required "reason:" field. Add: reason: <explanation of why this is intentional>.'}:{valid:!0}:{valid:!1,message:`Unknown suppression category "${t}". Valid values: ${[...op].join(", ")}.`}}function aS(t,e,n){let s=`suppression-invalid:${t}:${e}:${n}`;return`suppression-invalid-${dp.createHash("sha1").update(s).digest("hex").slice(0,12)}`}function cS(t){let{content:e,path:n,sections:s,lineCount:i}=t,r=[],o=id(e),a=new RegExp(ap.source,ap.flags),c;for(;(c=a.exec(o))!==null;){let m=c[1]?.trim()??"",g=c[2]??"",b=up(g),w=ts(o,c.index),y=ts(o,c.index+c[0].length),v=oS(w,y,s,i,e),{valid:R,message:k}=fp(m,b);r.push({filePath:n,category:R?m:"all",reason:b??"",startLine:w,endLine:v,valid:R,validationMessage:k})}let l=[],u=new RegExp(cp.source,cp.flags);for(;(c=u.exec(o))!==null;)l.push({kind:"start",offset:c.index,endOffset:c.index+c[0].length,category:c[1]?.trim()??"",reason:up(c[2]??"")});let f=new RegExp(lp.source,lp.flags);for(;(c=f.exec(o))!==null;)l.push({kind:"end",offset:c.index,endOffset:c.index+c[0].length});l.sort((m,g)=>m.offset-g.offset);let d=m=>{r.push({filePath:n,category:"all",reason:"",startLine:ts(o,m.offset),endLine:i,valid:!1,validationMessage:"promptci-ignore-start has no matching promptci-ignore-end marker."})},p=null;for(let m of l){if(m.kind==="start"){p&&d(p),p=m;continue}if(!p)continue;let g=ts(o,p.offset),b=ts(o,m.endOffset),{valid:w,message:y}=fp(p.category??"",p.reason??null);r.push({filePath:n,category:w?p.category:"all",reason:p.reason??"",startLine:g,endLine:b,valid:w,validationMessage:y}),p=null}p&&d(p);let{relativePath:h}=t;return h===void 0?r:r.map(m=>({...m,relativePath:h}))}function wa(t){return t.flatMap(cS)}function va(t){return t.filter(e=>!e.valid).map(e=>({id:aS(e.relativePath??e.filePath,e.startLine,e.validationMessage??""),severity:"warning",category:"structure",title:"Invalid promptci-ignore annotation",summary:e.validationMessage??"This promptci-ignore annotation is malformed.",filePaths:[e.filePath],locations:[{filePath:e.filePath,startLine:e.startLine}],evidence:[],recommendation:`Ensure the annotation has a valid category and a non-empty reason field. Example: <!-- promptci-ignore: vague_guidance
51
+ reason: This section documents examples. -->`,confidence:1}))}function $i(t,e){let n=e.filter(r=>r.valid),s=[],i=[];for(let r of t)n.some(a=>{if(a.category!=="all"&&a.category!==r.category)return!1;if(r.locations.length>0){if(r.locations.some(f=>{if(f.filePath!==a.filePath)return!1;if(f.startLine===void 0)return!0;let d=f.endLine??f.startLine;return f.startLine<=a.endLine&&d>=a.startLine}))return!0;let l=new Set(r.filePaths);return!!(!r.locations.some(f=>l.has(f.filePath))&&r.filePaths.includes(a.filePath))}return r.filePaths.includes(a.filePath)})?i.push(r):s.push(r);return{active:s,suppressed:i}}var xa={critical:18,high:10,warning:4,info:1},lS={structure:30,stale_instruction:15,duplicate:20,vague_guidance:10,ai_config:25},uS={"supply-chain":8,"skill-supply-chain":15};function fS(t){for(let n of t.tags??[]){let s=uS[n];if(s!==void 0)return{key:`tag:${n}`,cap:s}}let e=lS[t.category];return e!==void 0?{key:t.category,cap:e}:void 0}function Sa(t){let e=100,n=new Map;for(let s of t){let i=(xa[s.severity]??0)*s.confidence,r=fS(s);if(r!==void 0){let o=n.get(r.key)??0,a=Math.max(0,r.cap-o),c=Math.min(i,a);n.set(r.key,o+c),e-=c}else e-=i}return Math.round(Math.max(0,Math.min(100,e)))}var pp={high:3,medium:2,low:1};function hp(t){if(t.impact)return t.impact;let e=t.category,n=t.title.toLowerCase();return e==="security"||n.includes("secret")||n.includes("auth")||n.includes("supabase")||n.includes("service role")||n.includes("upload")||e==="command_validity"||n.includes("build")||n.includes("test")||n.includes("lint")||n.includes("run script")||n.includes("package manager")||n.includes("workflow")||n.includes("deploy")||n.includes("vercel")||n.includes("ci/cd")||n.includes("release")||n.includes("framework")||n.includes("router")||n.includes("database")||n.includes("version conflict")||n.includes("package manager mismatch")||e==="agent_practices"||n.includes("verification")||n.includes("scope")||n.includes("read-before-edit")||n.includes("honesty")||n.includes("plan-first")?"high":e==="vague_guidance"||e==="duplicate"||n.includes("duplicate")||n.includes("vague")?"low":"medium"}function _a(t){let e=[...t].sort((i,r)=>{let o=(xa[r.severity]??0)-(xa[i.severity]??0);if(o!==0)return o;let a=r.confidence-i.confidence;if(a!==0)return a;let c=pp[hp(r)]-pp[hp(i)];if(c!==0)return c;let l=r.filePaths.length-i.filePaths.length;if(l!==0)return l;let u=i.category.localeCompare(r.category);return u!==0?u:i.id.localeCompare(r.id)}),n=[],s=new Set;for(let i of e){if(n.length>=3)break;s.has(i.category)||(s.add(i.category),n.push({title:i.title,reason:i.summary,suggestedAction:i.recommendation}))}return n}var se=x(require("node:fs/promises"),1),ue=x(require("node:path"),1);var gp=x(require("node:crypto"),1),Xt=x(require("node:path"),1),dS={info:0,warning:1,high:2,critical:3};function mp(t){return dS[t]??-1}function Jt(t){return t.replace(/\\/g,"/")}function yp(t,e){if(!e)return t;try{let i=Xt.relative(e,t);if(i&&!i.startsWith("..")&&!Xt.isAbsolute(i))return Jt(i)}catch{}let n=Jt(t),s=[Jt(e).replace(/\/+$/,""),Jt(Xt.resolve(e)).replace(/\/+$/,"")];for(let i of s){if(n===i)return".";if(n.startsWith(`${i}/`))return n.slice(i.length+1)}return n}function pS(t,e){if(!e)return t;let n=Jt(t);return[Jt(e).replace(/\/+$/,""),Jt(Xt.resolve(e)).replace(/\/+$/,"")].reduce((i,r)=>i.replaceAll(r,"<repo>"),n)}function ns(t,e){let n=t.filePaths.map(r=>yp(r,e)).sort(),s=t.evidence.map(r=>pS(r,e)).sort(),i=[t.category,t.title,...n,...s].join("|");return gp.createHash("sha256").update(i).digest("hex")}function En(t,e){return t.map(n=>({id:n.id,category:n.category,title:n.title,filePaths:n.filePaths.map(s=>yp(s,e)).sort(),severity:n.severity,fingerprint:ns(n,e)})).sort((n,s)=>n.fingerprint.localeCompare(s.fingerprint))}function Ea(t){if(!Array.isArray(t))throw new Error("Baseline file must contain a JSON array.");for(let e=0;e<t.length;e++){let n=t[e];if(typeof n!="object"||n===null)throw new Error(`Baseline entry at index ${e} is not an object.`);let s=n;if(typeof s.fingerprint!="string")throw new Error(`Baseline entry at index ${e} is missing a "fingerprint" string field.`);if(typeof s.category!="string")throw new Error(`Baseline entry at index ${e} is missing a "category" string field.`)}}function kn(t,e,n){let s=new Map;for(let o of e)s.set(o.fingerprint,o.severity??"info");let i=[],r=[];for(let o of t){let a=ns(o,n),c=s.get(a);c===void 0||mp(o.severity)>mp(c)?i.push(o):r.push(o)}return{newIssues:i,baselinedIssues:r}}var hS={critical:"CRITICAL",high:"HIGH",warning:"WARNING",info:"INFO"},Ra={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},bp={critical:0,high:1,warning:2,info:3},mS={critical:"Critical",high:"High",warning:"Warning",info:"Info"},gS="ai-setup",yS={critical:"issues-critical",high:"issues-high",warning:"issues-warning",info:"issues-info"},bS=50;function wS(t){let e=[],n=vp(t.filter(r=>r.category==="ai_config"));n.length>0&&e.push({anchor:gS,heading:`\u{1F916} AI Setup (${n.length})`,issues:n});let s=t.filter(r=>r.category!=="ai_config"),i=Sp(s);for(let r of["critical","high","warning","info"]){let o=vp(i.get(r));o.length!==0&&e.push({anchor:yS[r],heading:`${Ra[r]} ${mS[r]} (${o.length})`,issues:o})}return e}function xp(t,e){let n=ue.relative(e,t);return!n||n.startsWith("..")?t:n}function vS(t,e){return ns({category:t.category??"",title:t.title??"",filePaths:t.filePaths??[],evidence:t.evidence??[]},e)}function wp(t,e){return t.map(n=>vS(n,e))}function xS(t){let e=Math.round(t/10),n=10-e;return"\u2588".repeat(e)+"\u2591".repeat(n)}function Rn(t){return t>=90?"Healthy":t>=70?"Fair":t>=50?"Needs attention":"Critical issues found"}function Sp(t){let e=new Map;for(let n of["critical","high","warning","info"])e.set(n,[]);for(let n of t)e.get(n.severity).push(n);return e}function vp(t){return[...t].sort((e,n)=>{let s=bp[e.severity]-bp[n.severity];if(s!==0)return s;let i=n.confidence-e.confidence;return i!==0?i:e.id.localeCompare(n.id)})}function ka(t){let e=gi(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),s="`".repeat(n+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${s}${i}${e}${i}${s}`}function SS(t,e,n){let s=Ra[t.severity],i=hS[t.severity],r=[];if(r.push(`#### ${e}. ${s} [${i}] ${t.title}`),r.push(""),r.push(`**ID:** \`${t.id}\``),r.push(""),r.push(`${t.summary}`),r.push(""),t.filePaths.length>0){for(let a of t.filePaths)r.push(`**File:** ${ka(n(a))}`);r.push("")}let o=t.locations.filter(a=>a.startLine!==void 0);if(o.length>0){for(let a of o){let c=a.endLine!==void 0?`L${a.startLine}\u2013L${a.endLine}`:`L${a.startLine}`;r.push(`**Location:** ${ka(n(a.filePath))} ${c}`)}r.push("")}if(t.evidence.length>0){r.push("**Evidence:**");let a=t.tags?.[0]==="skill-supply-chain";for(let c of t.evidence)r.push(`- ${a?ka(Y(c,160)):Y(c,100)}`);r.push("")}return r.push(`> **Recommendation:** ${t.recommendation}`),t.fixRecipe&&(r.push(""),r.push("**Suggested text to add:**"),r.push("```markdown"),r.push(t.fixRecipe),r.push("```")),r.join(`
52
+ `)}function _p(t){let e=[],{healthScore:n,topFixes:s,issues:i,projectType:r,repoPath:o,generatedAt:a,filesScanned:c}=t,l=d=>xp(d,o);e.push("# PromptCI Health Report"),e.push(""),e.push(`**Generated:** ${a}`),e.push(`**Repo:** \`${o}\``),e.push(`**Project type:** ${r}`),e.push(`**Files scanned:** ${c.filter(d=>d.aliasOf===void 0).length}`),t.metrics&&(e.push(`**Estimated instruction tokens:** ${t.metrics.estimatedInstructionTokens} (always-loaded)`),t.metrics.estimatedOnDemandTokens&&e.push(`**On-demand skill/agent tokens:** ${t.metrics.estimatedOnDemandTokens} across ${t.metrics.onDemandFileCount} file(s) \u2014 loaded only when invoked, not counted above`)),e.push(""),e.push("## Health Score"),e.push(""),e.push("```"),e.push(`${xS(n)} ${n}/100 ${Rn(n)}`),e.push("```"),e.push("");let u=Sp(i);if(i.length>0){let d=[];for(let p of["critical","high","warning","info"]){let h=u.get(p).length;h>0&&d.push(`${Ra[p]} ${h} ${p}`)}e.push(d.join(" \xB7 ")),e.push("")}if(e.push("## Trend"),e.push(""),t.trend){let d=t.trend;d.previousScanDate&&e.push(`- **Previous scan:** ${d.previousScanDate}`);let p=d.scoreDelta>0?`+${d.scoreDelta}`:`${d.scoreDelta}`;e.push(`- **Score change:** ${p}`),e.push(`- **New issues:** ${d.newIssuesCount}`),e.push(`- **Resolved issues:** ${d.resolvedIssuesCount}`);let h=Object.keys(d.categoryDeltas);if(h.length>0){e.push("- **Category changes:**");for(let m of h){let g=d.categoryDeltas[m],b=g>0?`+${g}`:`${g}`;e.push(` - ${m}: ${b}`)}}d.streak>0&&e.push(`- **Streak:** ${d.streak} scan(s) without high/critical issues`)}else e.push("First scan \u2014 no trend data available yet.");if(e.push(""),s.length>0&&(e.push("## Top Fixes"),e.push(""),s.forEach((d,p)=>{e.push(`**${p+1}. ${d.title}**`),e.push(""),e.push(`${d.reason}`),e.push(""),e.push(`*Action:* ${d.suggestedAction}`),e.push("")})),i.length===0)e.push("## Issues"),e.push(""),e.push("No issues found. Instruction files look good!"),e.push("");else{e.push("## Issues"),e.push("");let d=wS(i);e.push(`**Jump to:** ${d.map(p=>`[${p.heading}](#${p.anchor})`).join(" \xB7 ")}`),e.push("");for(let p of d)e.push(`<a id="${p.anchor}"></a>`),e.push(""),e.push(`### ${p.heading}`),e.push(""),p.issues.forEach((h,m)=>{e.push(SS(h,m+1,l)),e.push(""),e.push("---"),e.push("")})}let f=t.suppressedIssues;if(f&&f.length>0){e.push(`## Suppressed (${f.length})`),e.push(""),e.push(`The following ${f.length===1?"issue was":"issues were"} silenced by inline \`promptci-ignore\` annotations and do not affect the health score.`),e.push("");for(let d of f){let p=d.filePaths[0]?l(d.filePaths[0]):"(unknown)",h=d.locations.find(g=>g.startLine!==void 0),m=h?` L${h.startLine}${h.endLine?`\u2013${h.endLine}`:""}`:"";e.push(`- **${d.category}** in \`${p}\`${m}`)}e.push("")}if(c.length>0){e.push("## Files Scanned"),e.push("");let d=c.slice(0,bS);for(let h of d)e.push(h.aliasOf!==void 0?`- \`${l(h.path)}\` (symlink to \`${h.aliasOf}\`)`:`- \`${l(h.path)}\` (${h.fileType}, ${h.lineCount} lines, ~${h.estimatedTokens} tokens)`);let p=c.length-d.length;p>0&&e.push(`- \u2026and ${p} more`),e.push("")}return e.push("---"),e.push("> Findings are heuristic. Review each item before acting. Some can be applied automatically with `promptci fix`; others are advisory and must be edited by hand."),e.push(""),e.push("*Generated by [PromptCI](https://github.com/SeriousGeese/PromptCI)*"),e.join(`
53
+ `)}function Pi(t,e=!0){let n=i=>xp(i,t.repoPath),s={schemaVersion:t.schemaVersion,generatedAt:t.generatedAt,repoPath:t.repoPath,projectType:t.projectType,healthScore:t.healthScore,topFixes:t.topFixes,...t.metrics?{metrics:t.metrics}:{},...t.trend?{trend:t.trend}:{},issues:t.issues.map(i=>({...i,filePaths:i.filePaths.map(n),locations:i.locations.map(r=>({...r,filePath:n(r.filePath)}))})),filesScanned:t.filesScanned.map(i=>({path:n(i.path).replace(/\\/g,"/"),fileType:i.fileType,lineCount:i.lineCount,charCount:i.charCount,estimatedTokens:i.estimatedTokens,...i.aliasOf!==void 0?{aliasOf:i.aliasOf}:{}})),...t.suppressedIssues&&t.suppressedIssues.length>0?{suppressedIssues:t.suppressedIssues.map(i=>({...i,filePaths:i.filePaths.map(n),locations:i.locations.map(r=>({...r,filePath:n(r.filePath)}))}))}:{}};return e?JSON.stringify(s,null,2):JSON.stringify(s)}function Ca(t){return ue.join(t,".promptci","history","index.json")}async function Aa(t){let e=Ca(t);try{let n=await se.readFile(e,"utf8"),s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return[]}async function Ep(t,e,n){let s;try{s=await se.readFile(n,"utf8")}catch{return null}let i;try{i=JSON.parse(s)}catch{return null}let r=typeof i.generatedAt=="string"?i.generatedAt:new Date().toISOString(),o=r.replace(/[:.]/g,"-").replace(/Z$/,"Z"),a=ue.join(t,".promptci","history",o);await se.mkdir(a,{recursive:!0});let c=ue.join(".promptci","history",o,"report.md"),l=ue.join(".promptci","history",o,"report.json"),u=ue.join(t,c),f=ue.join(t,l);try{await se.copyFile(e,u)}catch{await se.writeFile(u,s,"utf8")}await se.copyFile(n,f);let d=Array.isArray(i.issues)?i.issues:[],p={critical:0,high:0,warning:0,info:0};for(let w of d){let y=w.severity;y in p&&p[y]++}let h={generatedAt:r,healthScore:typeof i.healthScore=="number"?i.healthScore:0,issueCount:p,archiveMdPath:c,archiveJsonPath:l},m=await Aa(t);m.push(h);let g=Ca(t);await se.mkdir(ue.dirname(g),{recursive:!0});let b=`${g}.tmp`;return await se.writeFile(b,JSON.stringify(m,null,2),"utf8"),await se.rename(b,g),h}async function Ti(t,e={}){let n=ue.join(t.repoPath,".promptci"),s=e.mdPath??ue.join(n,"latest.md"),i=e.jsonPath??ue.join(n,"report.json");for(let d of[n,s,i,ue.join(n,"history")])if(!zn(t.repoPath,d))throw new Error(`Refusing to write the report: ${d} resolves outside the repository through a symlink.`);await se.mkdir(ue.dirname(s),{recursive:!0}),await se.mkdir(ue.dirname(i),{recursive:!0});let r=await _S(i),o=await Aa(t.repoPath),a=await ES(t,r,o);a&&(t.trend=a);let l=e.archive!==!1&&!e.mdPath&&!e.jsonPath?await Ep(t.repoPath,s,i):null,u=_p(t),f=Pi(t);return await Promise.all([se.writeFile(s,u,"utf8"),se.writeFile(i,f,"utf8")]),{mdPath:s,jsonPath:i,archivedEntry:l}}async function _S(t){try{let e=await se.readFile(t,"utf8");return JSON.parse(e)}catch{return null}}async function ES(t,e,n){if(!e)return null;try{let s=t.issues||[],i=Array.isArray(e.issues)?e.issues:[],r=new Set(wp(s,t.repoPath)),o=new Set(wp(i,t.repoPath)),a=[...r].filter(b=>!o.has(b)),c=[...o].filter(b=>!r.has(b)),l=new Set([...s.map(b=>b.category),...i.map(b=>b.category)].filter(b=>typeof b=="string")),u={};for(let b of l){if(!b)continue;let w=s.filter(v=>v.category===b).length,y=i.filter(v=>v.category===b).length;u[b]=w-y}let f=["critical","high","warning","info"],d={};for(let b of f){let w=s.filter(v=>v.severity===b).length,y=i.filter(v=>v.severity===b).length;d[b]=w-y}let p=s.filter(b=>b.severity==="high"||b.severity==="critical").length,h=0;if(p===0&&(h=1,i.filter(w=>w.severity==="high"||w.severity==="critical").length===0)){h++;for(let w=n.length-1;w>=0;w--){let y=n[w];if(y&&(y.issueCount.high??0)===0&&(y.issueCount.critical??0)===0)h++;else break}}let m=typeof e.generatedAt=="string"?e.generatedAt:void 0,g=typeof e.healthScore=="number"?e.healthScore:0;return{previousScanDate:m,scoreDelta:t.healthScore-g,newIssuesCount:a.length,resolvedIssuesCount:c.length,severityDeltas:d,categoryDeltas:u,newIssueIds:a,resolvedIssueIds:c,streak:h}}catch{return null}}var Hp=x(require("node:crypto"),1),Bp=x(require("node:fs"),1),Wp=x(require("node:path"),1);var yt=x(require("node:fs"),1),re=x(require("node:path"),1),Mp=x(require("node:crypto"),1);var ss=x(require("node:fs/promises"),1),$p=x(require("node:path"),1),$a=x(Et(),1);var kp=200,kS=["apps/*","packages/*","libs/*"],RS=["dependencies","devDependencies","peerDependencies","optionalDependencies"],CS={tsc:["typescript"],tsserver:["typescript"],tsx:["tsx"],"ts-node":["ts-node"],tsup:["tsup"],"tsc-alias":["tsc-alias"],"vue-tsc":["vue-tsc"],esbuild:["esbuild"],rollup:["rollup"],webpack:["webpack-cli","webpack"],vite:["vite"],swc:["@swc/cli"],babel:["@babel/cli"],parcel:["parcel"],rspack:["@rspack/cli"],unbuild:["unbuild"],bunchee:["bunchee"],eslint:["eslint"],prettier:["prettier"],biome:["@biomejs/biome"],oxlint:["oxlint"],stylelint:["stylelint"],knip:["knip"],depcheck:["depcheck"],madge:["madge"],commitlint:["@commitlint/cli"],"svelte-check":["svelte-check"],typedoc:["typedoc"],"size-limit":["size-limit"],vitest:["vitest"],jest:["jest"],mocha:["mocha"],ava:["ava"],playwright:["@playwright/test","playwright"],cypress:["cypress"],storybook:["storybook","@storybook/cli"],msw:["msw"],turbo:["turbo"],nx:["nx"],lerna:["lerna"],changeset:["@changesets/cli"],"semantic-release":["semantic-release"],husky:["husky"],"lint-staged":["lint-staged"],next:["next"],nuxt:["nuxt"],nuxi:["nuxt","nuxi"],astro:["astro"],remix:["@remix-run/dev"],expo:["expo"],eas:["eas-cli"],"react-native":["react-native"],ng:["@angular/cli"],nest:["@nestjs/cli"],gatsby:["gatsby"],docusaurus:["@docusaurus/core"],vitepress:["vitepress"],tauri:["@tauri-apps/cli"],electron:["electron"],"electron-builder":["electron-builder"],sanity:["sanity","@sanity/cli"],strapi:["@strapi/strapi"],prisma:["prisma"],"drizzle-kit":["drizzle-kit"],knex:["knex"],typeorm:["typeorm"],sequelize:["sequelize-cli"],supabase:["supabase"],wrangler:["wrangler"],vercel:["vercel"],netlify:["netlify-cli"],firebase:["firebase-tools"],sst:["sst"],cdk:["aws-cdk"],serverless:["serverless"],nodemon:["nodemon"],concurrently:["concurrently"],"cross-env":["cross-env"],rimraf:["rimraf"],dotenv:["dotenv-cli","dotenv"],"npm-run-all":["npm-run-all","npm-run-all2"],"run-s":["npm-run-all","npm-run-all2"],"run-p":["npm-run-all","npm-run-all2"],tailwindcss:["tailwindcss","@tailwindcss/cli"],postcss:["postcss-cli"],"graphql-codegen":["@graphql-codegen/cli"],"openapi-typescript":["openapi-typescript"]};function AS(t){return typeof t!="object"||t===null||Array.isArray(t)?[]:Object.keys(t)}function Rp(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e}function $S(t){let{bin:e,name:n}=t;return typeof e=="string"&&typeof n=="string"?[n.split("/").pop()]:AS(e)}function is(t,e){let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let s=n,i=new Set,r={};for(let o of RS){let a=Rp(s[o]);for(let c of Object.keys(a))a[c].startsWith("workspace:")||(i.add(c),c in r||(r[c]=a[c]))}return{dir:t,name:typeof s.name=="string"?s.name:void 0,scripts:Rp(s.scripts),dependencies:[...i].sort(),versions:r,bins:$S(s)}}function PS(t){if(!t)return[];try{let n=JSON.parse(t).workspaces;return(Array.isArray(n)?n:typeof n=="object"&&n!==null&&Array.isArray(n.packages)?n.packages:[]).filter(i=>typeof i=="string")}catch{return[]}}function Cp(t){let e=t.trim(),n=/^(?:"([^"]*)"|'([^']*)')/.exec(e);return n?n[1]??n[2]??"":e.replace(/\s+#.*$/,"")}function TS(t){if(!t)return[];let e=t.split(/\r?\n/),n=[];for(let s=0;s<e.length;s++){let i=/^packages\s*:\s*(.*)$/.exec(e[s]);if(!i)continue;let r=i[1].trim();if(r.startsWith("[")){let o=r;for(let c=s+1;!o.includes("]")&&c<e.length;c++)o+=` ${e[c].trim()}`;let a=o.slice(1,o.includes("]")?o.indexOf("]"):void 0);for(let c of a.split(",")){let l=Cp(c);l&&n.push(l)}break}for(let o=s+1;o<e.length;o++){let a=e[o],c=/^\s*-\s+(.*)$/.exec(a);if(c){let l=Cp(c[1]);l&&n.push(l);continue}if(!(a.trim()===""||/^\s*#/.test(a)||/^\s/.test(a)))break}break}return n}function Ap(t){let e=t.replace(/\\/g,"/");return e.startsWith("/")||/^[a-zA-Z]:/.test(e)?!1:!e.split("/").includes("..")}function IS(t){return`${t.replace(/^\.\//,"").replace(/\/+$/,"")}/package.json`}async function Pp(t,e,n=()=>!1){let s;try{let p=J(t,"pnpm-workspace.yaml");s=p?await ss.readFile(p,"utf-8"):void 0}catch{s=void 0}let i=[...PS(e),...TS(s)],r=i.filter(p=>!p.startsWith("!")&&Ap(p)),o=i.filter(p=>p.startsWith("!")).map(p=>p.slice(1)),a=r.length>0?r:kS,c=["**/node_modules/**","**/.git/**",...o.filter(Ap).map(p=>`${p.replace(/\/+$/,"")}/**`)],l=ct(t,a.map(IS),c).filter(p=>Ot(t,p)!==null&&!n(p)),u=l.length>kp,f=[],d=e?is(".",e):void 0;d&&f.push(d);for(let p of l.slice(0,kp))if(p!=="package.json")try{let h=J(t,p);if(!h)continue;let m=await ss.stat(h);if(!m.isFile()||m.size>ce)continue;let g=is($p.posix.dirname(p),await ss.readFile(h,"utf-8"));g&&f.push(g)}catch{}return{manifests:f,truncated:u}}function OS(t){let e=new Set((t.workspaces??[]).map(a=>a.name).filter(a=>!!a)),n=new Set,s=a=>{!a.startsWith("@types/")&&!e.has(a)&&n.add(a)},{dependencies:i,devDependencies:r,peerDependencies:o}=t.packageJson;for(let a of[i,r,o])for(let[c,l]of Object.entries(a))l.startsWith("workspace:")||s(c);for(let a of t.workspaces??[])a.dependencies.forEach(s);return n}function Cn(t,e){if((t.workspaces??[]).some(i=>i.bins.includes(e)))return!0;let n=OS(t);if(n.has(e))return!0;let s=CS[e];return s?t.workspaces===void 0||t.workspacesTruncated?!0:s.some(i=>n.has(i)):!1}function Ii(t,e){return t.packageJson.scripts[e]?!0:(t.workspaces??[]).some(n=>!!n.scripts[e])}function Pa(t,e){let n=t.workspaces??[];if(e==="*"||e==="**"||e.startsWith("!")||e.startsWith("["))return n;let s=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),i={dot:!0};return n.filter(r=>r.name===e||r.dir===s||r.dir.endsWith(`/${s}`)||/[*?[{]/.test(e)&&(r.name!==void 0&&$a.default.isMatch(r.name,e,i)||$a.default.isMatch(r.dir,s,i)))}var An=x(require("node:fs"),1),Ip=x(require("node:path"),1);var LS=["GNUmakefile","makefile","Makefile"],Tp=/^[A-Za-z0-9_.%/+-]+$/;function NS(t){let e=[],n="";for(let s of t.split(/\r?\n/)){if(/\\$/.test(s)){n+=s.slice(0,-1)+" ";continue}e.push(n+s),n=""}return n&&e.push(n),e}function jS(t,e="Makefile"){let n=new Set,s=new Set,i=!1,r=!1;for(let o of NS(t)){if(o.startsWith(" "))continue;let c=o.replace(/(?<!\\)#.*$/,"").trimEnd().trim();if(!c)continue;if(/^define\b/.test(c)||/^(?:override\s+)?define\s/.test(c)){r=!0;continue}if(r){/^endef\b/.test(c)&&(r=!1);continue}if(/^(?:-include|sinclude|include)\s/.test(c)){i=!0;continue}if(/\$\((?:eval|call)\b/.test(c)){i=!0;continue}let l=c.indexOf(":"),u=c.indexOf("=");if(l===-1||u!==-1&&u<l)continue;let f=c.slice(l+1);if(/^:?=/.test(f)||/^::=/.test(f))continue;let d=c.slice(0,l).trim();if(d&&!/^(?:ifeq|ifneq|ifdef|ifndef|else|endif|export|unexport|override|private|vpath)\b/.test(d)){if(d.includes("$")){i=!0;continue}if(d===".DEFAULT"){i=!0;continue}if(d===".PHONY"){for(let p of f.replace(/^:/,"").trim().split(/\s+/))p&&!p.includes("$")&&Tp.test(p)?n.add(p):p.includes("$")&&(i=!0);continue}for(let p of d.split(/\s+/))!p||!Tp.test(p)||(p.includes("%")?s.add(p):n.add(p))}}return{file:e,targets:[...n].sort(),patterns:[...s].sort(),unverifiable:i}}function Op(t,e){return t.targets.includes(e)?!0:t.patterns.some(n=>{let s=n.indexOf("%"),i=n.slice(0,s),r=n.slice(s+1);return e.length>i.length+r.length&&e.startsWith(i)&&e.endsWith(r)})}function Oi(t,e){for(let n of LS){let s=e==="."||e===""?n:`${e}/${n}`,i=J(t,s);if(i)try{let r=An.statSync(i);if(!r.isFile()||!An.readdirSync(Ip.dirname(i)).includes(n))continue;return r.size>ce?{file:s,targets:[],patterns:[],unverifiable:!0}:jS(An.readFileSync(i,"utf8"),s)}catch{continue}}}function MS(t,e){return`cmd-validity-${Mp.createHash("sha1").update(`${t}|${e}`).digest("hex").slice(0,12)}`}function rs(t,e){try{let n=re.resolve(t,e);return yt.existsSync(n)}catch{return!1}}function DS(t,e){try{return yt.statSync(re.resolve(t,e)).isDirectory()}catch{return!1}}function Dp(t,e){if(!ae(t,e))return null;try{let n=yt.readFileSync(e,"utf8"),s=JSON.parse(n);if(typeof s!="object"||s===null||Array.isArray(s))return null;let i=typeof s.scripts=="object"&&s.scripts!==null&&!Array.isArray(s.scripts)?Object.fromEntries(Object.entries(s.scripts).filter(r=>typeof r[1]=="string")):{};return{name:typeof s.name=="string"?s.name:void 0,scripts:i}}catch{return null}}function FS(t){for(let e=1;e<t.length;e++){let n=t[e];if(n==="--filter"||n==="-F")return t[e+1];if(n.startsWith("--filter="))return n.slice(9);if(n.startsWith("-F="))return n.slice(3)}}function HS(t){if(t)return t.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").replace(/^!/,"").trim()}function BS(t,e){let n=new Set,s=e.replace(/\\/g,"/");(s.startsWith(".")||s.includes("/"))&&n.add(re.join(t,s,"package.json"));for(let i of["apps","packages","libs"]){let r=re.join(t,i);try{for(let o of yt.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&n.add(re.join(r,o.name,"package.json"))}catch{}}return[...n]}function WS(t,e,n){let s=HS(e);if(!s)return!1;if(t.workspaces)return Pa(t,s).some(i=>!!i.scripts[n]);for(let i of BS(t.repoRoot,s)){let r=Dp(t.repoRoot,i);if(!r)continue;let o=re.dirname(i).replace(/\\/g,"/"),a=re.relative(t.repoRoot,o).replace(/\\/g,"/");if((r.name===s||a===s||a.endsWith(`/${s}`))&&r.scripts[n])return!0}return!1}function os(t){return!t||t.startsWith("-")?!1:t.includes("/")||t.includes("\\")||/\.[a-z]{1,5}$/i.test(t)}var GS=new Set(["install","i","add","remove","uninstall","test","it","init","create","publish","link","unlink","outdated","audit","update","up","exec","dlx","run","store","list","ls","why","pack","recursive","m","multi","prune","version","run-script","env","config","fetch","rebuild","rb","patch","patch-commit","deploy","import","licenses","root","bin","setup","self-update","dedupe","doctor","approve-builds","sbom","cache"]),US=new Set(["install","i","ci","uninstall","remove","update","outdated","audit","start","stop","restart","test","it","init","create","publish","link","unlink","pack","exec","run","run-script","version"]),VS=new Set(["install","add","remove","upgrade","outdated","audit","init","create","publish","link","unlink","why","pack","run","version","run-script","workspaces","exec","dlx","up","info","config","cache","bin","set","node","global","dedupe","patch","rebuild","plugin","constraints","unplug","npm"]),Ia=new Set(["install","i","add","a","remove","rm","update","test","build","init","create","c","x","bunx","pm","link","unlink","upgrade","repl","outdated","publish","patch","audit","info","why","completions","help","feedback","run","exec"]),Lp=new Set(["run","run-script"]);function Li(t,e){if(t===null)return null;let n=e.replace(/^['"]|['"]$/g,"").trim();if(!n||n.startsWith("/")||n.startsWith("~")||/^[a-zA-Z]:[\\/]/.test(n)||/^-|[$`%<>{}*?]/.test(n))return null;let s=t==="."?[]:t.split("/");for(let i of n.replace(/\\/g,"/").split("/"))if(!(i===""||i==="."))if(i===".."){if(s.length===0)return null;s.pop()}else s.push(i);return s.length===0?".":s.join("/")}function Np(t){return t.split(/&&|\|\||;|\n/).map(e=>e.trim()).filter(Boolean)}function zS(t){let e=["npm","pnpm","yarn","bun","node","tsx","ts-node","bash","sh","python","python3","dotnet","docker","make","git","ls","cd","mkdir","rm","cp","mv","./","../"],n=t.trim().split(/\s+/)[0]??"";return!!(e.some(s=>n===s||n.startsWith("./"))||n.startsWith("./")||n.startsWith("../"))}var qS=new Set(["bash","sh","shell","powershell","pwsh","zsh","command-line","cmd"]);function KS(t){let e=[];for(let n of Vn(t)){let s=/^[a-zA-Z0-9_-]*/.exec(n.lang)[0];if(!(!(s===""||qS.has(s))||!n.closed))for(let r=0;r<n.lines.length;r++){let o=n.lines[r].trim();if(o.startsWith("#"))continue;let a=o.replace(/^\$\s*/,"");if(!a)continue;let c=".";for(let l of Np(a)){let u=/^cd\s+(.+)$/.exec(l);u&&(c=Li(c,u[1].trim())),e.push({text:l,line:n.contentStartLine+r,cwd:c,fenced:!0})}}}for(let n of xe(t)){if(n.inFence)continue;let s=n.lineNumber-1,i=n.text.replace(/\r$/,"");for(let r of i.matchAll(/`([^`]+)`/g)){let o=r[1].trim(),a=".";for(let c of Np(o)){let l=/^cd\s+(.+)$/.exec(c);l&&(a=Li(a,l[1].trim())),zS(c)&&e.push({text:c,line:s+1,cwd:a})}}for(let r of i.matchAll(/\brun\s+(pnpm|npm|yarn|bun|node|tsx|ts-node|bash|python|dotnet|docker)\s+(.+?)(?=[.!?](?:\s|$)|[,;!]|$)/gi)){let o=(r[2]??"").trim().replace(/[.!?]+$/,""),a=`${r[1]} ${o}`.trim();e.push({text:a,line:s+1})}}return e.sort((n,s)=>n.line-s.line)}var YS=/[<{]|\.{3,}|your-file|your-script|example|placeholder/i,JS=new Set(["--filter","-F","--cwd","-C","--dir","--loader","--require","-r","--workspace","--prefix"]);function XS(t,e){return t==="pnpm"&&e==="-r"?!1:e==="-w"?t==="npm":JS.has(e)}function Ta(t,e=1){let n=e,s=t[0]??"";for(;n<t.length;){let i=t[n];if(!i.startsWith("-"))break;n++,XS(s,i)&&t[n]&&!t[n].startsWith("-")&&n++}return n}function ZS(t,e){let n=FS(e);if(n)return n;if(t==="npm")for(let s=1;s<e.length;s++){let i=e[s];if(i==="-w"||i==="--workspace")return e[s+1];if(i.startsWith("--workspace="))return i.slice(12)}}function QS(t,e){return t==="pnpm"?e.some(n=>n==="-r"||n==="--recursive"):t==="npm"?e.some(n=>n==="--workspaces"||n==="-ws"):!1}function e_(t){for(let e=1;e<t.length;e++){let n=t[e];if(n==="--cwd"||n==="-C"||n==="--dir"||n==="--prefix")return t[e+1];let s=/^(?:--cwd|--dir|--prefix)=(.+)$/.exec(n);if(s)return s[1]}}function t_(t,e,n,s,i,r,o,a){let c=s.includes("/")?s.split("/").map(b=>b.trim()).filter(Boolean):[s];for(let b of c)a?.(b);if(e===null)return null;let l=e_(n);if(l!==void 0){let b=Li(e,l);if(b===null)return null;e=b}let u=o.workspaceName??ZS(r,n),f=QS(r,n),d=b=>f?Ii(t,b):WS(t,u,b),p=u&&t.workspaces&&!f?Pa(t,u.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").trim()):void 0,h=e!=="."&&e!=="",m=h?Dp(t.repoRoot,re.join(t.repoRoot,e,"package.json")):null;if(h&&!m)return null;let g=Object.keys(t.packageJson.scripts).length>0;if(!m&&!g)return null;for(let b of c)if(!i.has(b)&&!(o.allowBinary&&Cn(t,b))){if(p){if(p.length===0){if(t.workspacesTruncated)continue;return`no workspace matches "${u}" for ${r} script "${b}"`}if(p.some(y=>!!y.scripts[b]))continue;let w=p.length===1?`${p[0].name??p[0].dir} (${p[0].dir}/package.json)`:`the ${p.length} workspaces selected by "${u}"`;return`${r} script "${b}" does not appear in ${w} scripts`}if(m){if(m.scripts[b]||d(b))continue;return`${r} script "${b}" does not appear in ${e}/package.json scripts`}if(!d(b)&&!t.packageJson.scripts[b])return`${r} script "${b}" does not appear in package.json scripts`}return null}var n_={pnpm:GS,npm:US,yarn:VS,bun:new Set};function s_(t,e,n,s,i,r){let o=Ta(e),a=e[o];if(!a)return null;let c=!1,l=o,u;if(Lp.has(a))c=!0,l=Ta(e,o+1);else{if(t==="npm")return null;t==="yarn"&&a==="workspace"&&(u=e[o+1],l=o+2,Lp.has(e[l]??"")&&(c=!0,l++))}let f=e[l];if(!f||f.startsWith("-"))return null;if(t==="bun"){if(!c&&Ia.has(f))return null;if(os(f))return i&&/\.[cm]?[jt]sx?$/.test(f)&&!rs(i,f)?`File "${f}" referenced by "bun" does not appear to exist in the repository`:null}return t_(n,s,e,f,n_[t],t,{allowBinary:!(c&&(t==="npm"||t==="pnpm")),workspaceName:u},r)}var i_=new Set(["-C","-f","-o","-W","-I","-E","--directory","--file","--makefile","--old-file","--what-if","--include-dir","--new-file","--assume-old","--assume-new","--eval"]),r_=new Set(["sure","it","this","that","them","these","those","certain","sense","changes","room","use","way"]),o_=new Set(["-j","-l","--jobs","--load-average","--max-load"]);function a_(t,e,n,s){let i=n,r=[];for(let l=1;l<t.length;l++){let u=t[l];if(/^(?:[|&<>#]|\d*>)/.test(u))break;if(u.startsWith("-")){let f=u.indexOf("="),d=f===-1?u:u.slice(0,f);if(d==="-f"||d==="--file"||d==="--makefile"||/^-f./.test(u))return null;let p;i_.has(d)?p=f!==-1?u.slice(f+1):t[++l]:/^-C./.test(u)?p=u.slice(2):o_.has(u)&&/^\d+(?:\.\d+)?$/.test(t[l+1]??"")&&l++,(d==="-C"||d==="--directory"||/^-C./.test(u))&&p!==void 0&&(i=Li(i,p));continue}u.includes("=")||r.push(u)}if(i===null||r.length===0)return null;let o=s(i);if(!o||o.unverifiable)return null;let a=i==="."?e.repoRoot:re.join(e.repoRoot,i),c;for(let l of r){let u=l.replace(/^['"]|['"]$/g,"");if(!(!u||os(u)||!/^[A-Za-z0-9_.+-]+$/.test(u))&&!Op(o,u)){try{c??=yt.readdirSync(a)}catch{c=[]}if(!c.some(f=>f===u||f.startsWith(`${u}.`)))return`make target "${u}" does not appear in ${o.file}`}}return null}function c_(t,e,n=".",s,i={}){if(YS.test(t))return null;let r=t.trim().split(/\s+/);if(r.length===0)return null;let o=r[0],a=n===null?null:n!=="."&&n!==""?re.join(e.repoRoot,n):e.repoRoot;if(o==="pnpm"||o==="npm"||o==="yarn"||o==="bun")return s_(o,r,e,n,a,s);if(a&&["node","tsx","ts-node","bash","sh","python","python3"].includes(o)&&r[1]){let l=r[Ta(r)];if(l&&os(l)&&!rs(a,l))return`File "${l}" referenced by "${o}" does not appear to exist in the repository`}if(o==="make"&&n!==null&&i.makefileFor){let l=i.fileDir??".",u=n==="."&&l!=="."&&i.makefileFor(l)?l:n;return!i.fenced&&r.length===2&&r_.has(r[1].toLowerCase())?null:a_(r,e,u,i.makefileFor)}if(a&&(o.startsWith("./")||o.startsWith("../"))){if(r.length===1&&re.extname(o.replace(/\/+$/,""))===""&&(DS(a,o)||!i.fenced||o.endsWith("/")))return null;if(!rs(a,o))return`Script "${o}" does not appear to exist in the repository`}if(a&&o==="docker"&&r[1]==="compose"&&r.includes("-f")){let l=r.indexOf("-f"),u=r[l+1];if(u&&os(u)&&!rs(a,u))return`Docker Compose file "${u}" does not appear to exist in the repository`}if(a&&o==="dotnet"&&r[1]==="test"&&r[2]){let l=r[2];if(os(l)){if(!rs(a,l))return`dotnet test target "${l}" does not appear to exist`;if(!/\.(sln|csproj|fsproj)$/.test(l))return`dotnet test target "${l}" should be a .sln, .csproj, or .fsproj file`}}return null}function Fp(t){return Oa(t).issues.map(e=>({...e}))}var jp=new WeakMap;function Oa(t){let e=jp.get(t);return e||(e=l_(t),jp.set(t,e)),e}function l_(t){let e=[],n=new Map,s=new Set,i=new Map,r=o=>o==="."||o===""?t.makefile:(i.has(o)||i.set(o,Oi(t.repoRoot,o)),i.get(o));for(let o of t.files){let a=KS(o.content),c=new Set,l=re.relative(t.repoRoot,re.dirname(o.path)).replace(/\\/g,"/")||".";n.set(o.path,c);for(let u of a){let f=u.cwd===void 0?".":u.cwd,d=c_(u.text,t,f,h=>c.add(`${u.line}:${h}`),{fenced:u.fenced===!0,makefileFor:r,fileDir:l.startsWith("..")?".":l});if(!d)continue;let p=`${o.path}|${u.text}`;s.has(p)||(s.add(p),e.push({id:MS(L(o),u.text),severity:"warning",category:"command_validity",title:`Possible reference to missing command or file: \`${u.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:d,filePaths:[o.path],locations:[{filePath:o.path,startLine:u.line,endLine:u.line}],evidence:[`Command: \`${u.text}\``,`In file: ${o.path}`],recommendation:"Verify the command. If the script was renamed, update the instruction file. If it is an illustrative example, wrap it in a placeholder like <script-name> to suppress this finding.",confidence:.8}))}}return{issues:e,evaluatedScripts:n}}function Ni(t){return`manifest-${Hp.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function u_(t,e,n){if(!(/\[tool\.poetry\]/.test(e)||/build-backend\s*=\s*["'][^"']*poetry[^"']*["']/i.test(e)))return null;let i=Wp.join(n,"requirements.txt");if(Bp.existsSync(i))return null;let r=/pip\s+install\s+-r\s+requirements\.txt/i,o=t.filter(a=>r.test(a.content));return o.length===0?null:{id:Ni("pip-vs-poetry"),severity:"high",category:"conflict",title:"Tooling mismatch: instruction uses pip but project uses Poetry",summary:"Instruction files tell the agent to run `pip install -r requirements.txt`, but this project uses Poetry as its build system (pyproject.toml with [tool.poetry]) and has no requirements.txt. Running this command would fail immediately.",filePaths:o.map(a=>a.path),locations:o.map(a=>({filePath:a.path})),evidence:["`pip install -r requirements.txt` found in instruction file(s)","pyproject.toml declares Poetry as the build system","requirements.txt does not exist in the repo"],recommendation:"Update the instruction files to use Poetry commands instead: `poetry install` (or `uv sync` if the project has migrated to uv). Remove the `pip install -r requirements.txt` reference.",confidence:.9}}function f_(t,e){let n=/^python\s*=\s*["'][\^~>=<*]*(\d+)\.(\d+)/m.exec(e)||/^requires-python\s*=\s*["'][\^~>=<*]*(\d+)\.(\d+)/m.exec(e);if(!n)return[];let s=parseInt(n[1],10),i=parseInt(n[2],10),r=[],o=new Set,a=/\bPython\s+(\d+)\.(\d+)\b/gi;for(let c of t){let l,u=new RegExp(a.source,a.flags);for(;(l=u.exec(c.content))!==null;){let f=parseInt(l[1],10),d=parseInt(l[2],10);if(ja(c.content,l.index)||!(f<s||f===s&&d<i))continue;let h=`${f}.${d}`,m=`${s}.${i}`,g=`${c.path}:${h}`;o.has(g)||(o.add(g),r.push({id:Ni(`python-version:${L(c)}:${h}`),severity:"high",category:"stale_instruction",title:`Python version mismatch: instruction says ${h}, pyproject.toml requires \u2265${m}`,summary:`An instruction file refers to Python ${h}, but pyproject.toml declares \`python = "^${m}"\` (or newer). An agent following this instruction would target an older interpreter and may avoid language features or APIs that are safe to use in this project.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`Instruction says "Python ${h}"; pyproject.toml requires \u2265${m}`],recommendation:`Update the instruction file to reference Python ${m} (or remove the version claim and rely on pyproject.toml as the authoritative source).`,confidence:.85}))}}return r}var d_=["pandas","numpy","sqlalchemy","fastapi","django","flask","pydantic"];function p_(t){return t==="sqlalchemy"?"SQLAlchemy":t==="fastapi"?"FastAPI":t[0].toUpperCase()+t.slice(1)}function Na(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function La(t){let e=t.trim();if(/^<=?\s*\d+/.test(e))return null;let n=/^(?:\^|~=|==|>=|>|=)?\s*(\d+)(?:\.\d+)?/.exec(e);return n?parseInt(n[1],10):null}function h_(t){let e=new Map;for(let n of d_){let s=Na(n),r=new RegExp(`^\\s*${s}\\s*=\\s*["']([^"']+)["']`,"im").exec(t);if(r){let c=La(r[1]);if(c!==null){e.set(n,c);continue}}let o=new RegExp(`["']${s}(?:\\[[^\\]]+\\])?\\s*([~^=<>!]{1,2}\\s*\\d+(?:\\.\\d+)?)`,"gim"),a;for(;(a=o.exec(t))!==null;){let c=La(a[1]);if(c!==null){e.set(n,c);break}}}return e}function m_(t,e){let n=Math.max(0,e-80),s=Math.min(t.length,e+120),i=t.slice(n,s);return/\b(target|support|supports|compatibility|compatible|avoid|maintain|maintains)\b/i.test(i)}function g_(t,e){let n=h_(e);if(n.size===0)return[];let s=[],i=new Set;for(let[r,o]of n){let a=p_(r),c=new RegExp(`\\b${Na(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let u,f=new RegExp(c.source,c.flags);for(;(u=f.exec(l.content))!==null;){if(!m_(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=o)continue;let p=u[2]?`${d}.${u[2]}`:`${d}.x`,h=`${l.path}:${r}:${p}`;i.has(h)||(i.add(h),s.push({id:Ni(`library-version:${L(l)}:${r}:${p}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${p}, pyproject.toml uses ${o}.x`,summary:`An instruction file refers to ${a} ${p}, but pyproject.toml declares ${r} ${o}.x. An agent following this instruction may avoid APIs that are valid for the installed dependency or target compatibility behavior that no longer matches the project manifest.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Instruction says "${a} ${p}"; pyproject.toml uses ${r} ${o}.x`],recommendation:`Update the instruction file to match ${a} ${o}.x, or remove the version-specific guidance and rely on pyproject.toml as the authoritative source.`,confidence:.85}))}}}return s}var y_=["react","next","typescript","vite","vitest","jest"],b_={react:"React",next:"Next.js",typescript:"TypeScript",vite:"Vite",vitest:"Vitest",jest:"Jest"};function w_(t){let e;try{e=JSON.parse(t)}catch{return new Map}if(typeof e!="object"||e===null||Array.isArray(e))return new Map;let n=e,s=new Map,i=[n.dependencies,n.devDependencies,n.peerDependencies];for(let r of i){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;for(let a of y_){let c=o[a];if(typeof c!="string")continue;let l=La(c);l!==null&&s.set(a,l)}}return s}function v_(t,e){let n=w_(e);if(n.size===0)return[];let s=[],i=new Set;for(let[r,o]of n){let a=b_[r],c=new RegExp(`\\b${Na(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let u,f=new RegExp(c.source,c.flags);for(;(u=f.exec(l.content))!==null;){if(!x_(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=o)continue;let p=u[2]?`${d}.${u[2]}`:`${d}.x`,h=`${l.path}:${r}:${p}`;i.has(h)||(i.add(h),s.push({id:Ni(`js-library-version:${L(l)}:${r}:${p}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${p}, package.json uses ${o}.x`,summary:`An instruction file refers to ${a} ${p}, but package.json declares ${r} ${o}.x. An agent following this instruction may target compatibility behavior or APIs that no longer match the installed dependency.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Instruction says "${a} ${p}"; package.json uses ${r} ${o}.x`],recommendation:`Update the instruction file to match ${a} ${o}.x, or remove the version-specific guidance and rely on package.json as the authoritative source.`,confidence:.85}))}}}return s}function x_(t,e){let n=Math.max(0,e-100),s=Math.min(t.length,e+140),i=t.slice(n,s);return/\b(use|using|target|support|supports|compatibility|compatible|avoid|maintain|migration|migrate|features?|apis?)\b/i.test(i)}function ja(t,e){let n=t.lastIndexOf(`
54
54
  `,e-1)+1,s=t.indexOf(`
55
- `,e),i=t.slice(n,s===-1?void 0:s);return/\b(?:do\s+not|don'?t|avoid|never|instead\s+of|not\s+use|refrain\s+from)\b/i.test(i)}function yS(t){let{packageJson:e,files:n}=t,s=e.packageManagerName;if(s==="unknown")return null;let i=[{name:"npm",label:"npm"},{name:"pnpm",label:"pnpm"},{name:"yarn",label:"Yarn"},{name:"bun",label:"Bun"}].filter(o=>o.name!==s),r=[];for(let o of n)for(let a of i){let c=new RegExp(`\\b${a.name}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),l,u=!1;for(;(l=c.exec(o.content))!==null;){let f=o.content.lastIndexOf(`
55
+ `,e),i=t.slice(n,s===-1?void 0:s);return/\b(?:do\s+not|don'?t|avoid|never|instead\s+of|not\s+use|refrain\s+from)\b/i.test(i)}function S_(t){let{packageJson:e,files:n}=t,s=e.packageManagerName;if(s==="unknown")return null;let i=[{name:"npm",label:"npm"},{name:"pnpm",label:"pnpm"},{name:"yarn",label:"Yarn"},{name:"bun",label:"Bun"}].filter(o=>o.name!==s),r=[];for(let o of n)for(let a of i){let c=new RegExp(`\\b${a.name}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),l,u=!1;for(;(l=c.exec(o.content))!==null;){let f=o.content.lastIndexOf(`
56
56
  `,l.index-1)+1,d=o.content.indexOf(`
57
- `,l.index),p=o.content.slice(f,d===-1?void 0:d);if(!(s==="pnpm"&&/\bnpm\s+(?:install|i)\s+-g\s+pnpm\b/i.test(p))&&!Oa(o.content,l.index)){u=!0;break}}if(u){r.push(o);break}}return r.length===0?null:{id:"manifest-package-manager-mismatch",severity:"warning",category:"conflict",title:`Possible package manager mismatch: instructions use alternatives to ${s}`,summary:`Instruction files refer to other package managers, but this project appears to use ${s} (based on ${e.lockfiles.join(", ")||"package.json"}). Mixing package managers can lead to inconsistent lockfiles and installation errors.`,filePaths:r.map(o=>o.path),locations:r.map(o=>({filePath:o.path})),evidence:[`Project appears to use ${s}`,"Instruction files mention other package managers in command-like contexts"],recommendation:`Update instruction files to consistently use ${s} commands.`,fixRecipe:`This repo uses ${s}. Use \`${s} install\`, \`${s} test\`, and \`${s} build\`; do not substitute npm/yarn commands.`,confidence:.8}}function bS(t){let{packageJson:e,files:n}=t,s=new Set(Object.keys(e.scripts));if(s.size===0)return[];let i=[],r=/\b(npm|yarn|pnpm|bun)\s+(run(?:-script)?\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,o=/\bcd\s+\S+\s*&&\s*(?:[^&;|\n]*&&\s*)*$/,a=/(?:^|\s)(?:--filter\b|-F\b|--cwd\b|-C\b|--prefix\b|--dir\b|-w\b|--workspaces?\b|-ws\b|-r\b|--recursive\b)/,c=(p,h,m)=>{let g=p.lastIndexOf(`
57
+ `,l.index),p=o.content.slice(f,d===-1?void 0:d);if(!(s==="pnpm"&&/\bnpm\s+(?:install|i)\s+-g\s+pnpm\b/i.test(p))&&!ja(o.content,l.index)){u=!0;break}}if(u){r.push(o);break}}return r.length===0?null:{id:"manifest-package-manager-mismatch",severity:"warning",category:"conflict",title:`Possible package manager mismatch: instructions use alternatives to ${s}`,summary:`Instruction files refer to other package managers, but this project appears to use ${s} (based on ${e.lockfiles.join(", ")||"package.json"}). Mixing package managers can lead to inconsistent lockfiles and installation errors.`,filePaths:r.map(o=>o.path),locations:r.map(o=>({filePath:o.path})),evidence:[`Project appears to use ${s}`,"Instruction files mention other package managers in command-like contexts"],recommendation:`Update instruction files to consistently use ${s} commands.`,fixRecipe:`This repo uses ${s}. Use \`${s} install\`, \`${s} test\`, and \`${s} build\`; do not substitute npm/yarn commands.`,confidence:.8}}function __(t){let{packageJson:e,files:n}=t,s=new Set(Object.keys(e.scripts));if(s.size===0)return[];let i=[],r=/\b(npm|yarn|pnpm|bun)\s+(run(?:-script)?\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,o=/\bcd\s+\S+\s*&&\s*(?:[^&;|\n]*&&\s*)*$/,a=/(?:^|\s)(?:--filter\b|-F\b|--cwd\b|-C\b|--prefix\b|--dir\b|-w\b|--workspaces?\b|-ws\b|-r\b|--recursive\b)/,c=(p,h,m)=>{let g=p.lastIndexOf(`
58
58
  `,h-1)+1;if(o.test(p.slice(g,h)))return!0;let b=p.indexOf(`
59
- `,m),w=p.slice(m,b===-1?void 0:b);return a.test(w.split(/&&|\|\||;|\||`|,\s|\.\s|\bthen\b/)[0])},l=new Set,u=new Set(["install","add","remove","init","test","start","stop","restart","exec","dlx","i","help","run","run-script","ci","audit","update","outdated","publish","create","link","why","workspace","workspaces","store","ls","list","pack","unlink","uninstall","up","prune","package","packages","project","repo","repository","version"]),f=new Set(["instead","of","packages","package","scripts","script","ecosystem","are","is","the","a","an","that","this","for","to","and","or","not","with","without","via","because","since","before","after","than","as","like","but","so","any","all","each","every","either","both","one","it","them","these","those","my","our","your","their","its"]),d=Pa(t);for(let p of n){let h=sd(p.content),m=d.evaluatedScripts.get(p.path),g,b=new RegExp(r.source,r.flags);for(;(g=b.exec(p.content))!==null;){let w=g[1].toLowerCase(),y=g[2]!==void 0,v=g[3];if(!v.startsWith("-")&&!/^[0-9]/.test(v)&&!(!y&&!h[g.index])&&!u.has(v)&&!f.has(v.toLowerCase())&&!(w==="bun"&&!y&&$a.has(v))&&!s.has(v)){if(m?.size){let I=p.content.slice(0,g.index).split(`
60
- `).length;if(m.has(`${I}:${v}`))continue}if(Pi(t,v)||!(y&&(w==="npm"||w==="pnpm"))&&Cn(t,v)||c(p.content,g.index,g.index+g[0].length))continue;let R=`${p.path}:${v}`;if(l.has(R))continue;l.add(R),i.push({id:`manifest-missing-script:${L(p)}:${v}`,severity:"warning",category:"stale_instruction",title:`Reference to missing script: "${v}"`,summary:`Instructions tell the agent to run \`${v}\`, but this script is not defined in package.json. The agent might attempt to run a command that fails.`,filePaths:[p.path],locations:[{filePath:p.path}],evidence:[`Found reference to \`${v}\` in ${p.path}`],recommendation:"Verify if the script name is correct or add the missing script to package.json.",confidence:.7})}}}return i}function wS(t){let{packageJson:e,files:n}=t;if(!e.enginesNode)return[];let s=/>=\s*(\d+)/.exec(e.enginesNode)||/\^\s*(\d+)/.exec(e.enginesNode);if(!s)return[];let i=parseInt(s[1],10),r=[],o=new Set,a=/\bNode(?:\.js)?\s*(?:v)?(\d+)\b/gi;for(let c of n){let l,u=new RegExp(a.source,a.flags);for(;(l=u.exec(c.content))!==null;){let f=parseInt(l[1],10);if(!Oa(c.content,l.index)&&f<i){let d=`${c.path}:${f}`;if(o.has(d))continue;o.add(d),r.push({id:`manifest-node-version-mismatch:${L(c)}:${f}`,severity:"warning",category:"stale_instruction",title:`Node.js version mismatch: instruction says ${f}, project requires \u2265${i}`,summary:`Instructions mention Node.js ${f}, but package.json specifies a minimum version of ${i} in \`engines.node\`.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`Instruction says Node ${f}; engines.node says ${e.enginesNode}`],recommendation:`Update instructions to reflect the minimum supported Node.js version (${i}).`,confidence:.8})}}}return r}function vS(t,e,n){let s=t.lastIndexOf(`
59
+ `,m),w=p.slice(m,b===-1?void 0:b);return a.test(w.split(/&&|\|\||;|\||`|,\s|\.\s|\bthen\b/)[0])},l=new Set,u=new Set(["install","add","remove","init","test","start","stop","restart","exec","dlx","i","help","run","run-script","ci","audit","update","outdated","publish","create","link","why","workspace","workspaces","store","ls","list","pack","unlink","uninstall","up","prune","package","packages","project","repo","repository","version"]),f=new Set(["instead","of","packages","package","scripts","script","ecosystem","are","is","the","a","an","that","this","for","to","and","or","not","with","without","via","because","since","before","after","than","as","like","but","so","any","all","each","every","either","both","one","it","them","these","those","my","our","your","their","its"]),d=Oa(t);for(let p of n){let h=od(p.content),m=d.evaluatedScripts.get(p.path),g,b=new RegExp(r.source,r.flags);for(;(g=b.exec(p.content))!==null;){let w=g[1].toLowerCase(),y=g[2]!==void 0,v=g[3];if(!v.startsWith("-")&&!/^[0-9]/.test(v)&&!(!y&&!h[g.index])&&!u.has(v)&&!f.has(v.toLowerCase())&&!(w==="bun"&&!y&&Ia.has(v))&&!s.has(v)){if(m?.size){let T=p.content.slice(0,g.index).split(`
60
+ `).length;if(m.has(`${T}:${v}`))continue}if(Ii(t,v)||!(y&&(w==="npm"||w==="pnpm"))&&Cn(t,v)||c(p.content,g.index,g.index+g[0].length))continue;let k=`${p.path}:${v}`;if(l.has(k))continue;l.add(k),i.push({id:`manifest-missing-script:${L(p)}:${v}`,severity:"warning",category:"stale_instruction",title:`Reference to missing script: "${v}"`,summary:`Instructions tell the agent to run \`${v}\`, but this script is not defined in package.json. The agent might attempt to run a command that fails.`,filePaths:[p.path],locations:[{filePath:p.path}],evidence:[`Found reference to \`${v}\` in ${p.path}`],recommendation:"Verify if the script name is correct or add the missing script to package.json.",confidence:.7})}}}return i}function E_(t){let{packageJson:e,files:n}=t;if(!e.enginesNode)return[];let s=/>=\s*(\d+)/.exec(e.enginesNode)||/\^\s*(\d+)/.exec(e.enginesNode);if(!s)return[];let i=parseInt(s[1],10),r=[],o=new Set,a=/\bNode(?:\.js)?\s*(?:v)?(\d+)\b/gi;for(let c of n){let l,u=new RegExp(a.source,a.flags);for(;(l=u.exec(c.content))!==null;){let f=parseInt(l[1],10);if(!ja(c.content,l.index)&&f<i){let d=`${c.path}:${f}`;if(o.has(d))continue;o.add(d),r.push({id:`manifest-node-version-mismatch:${L(c)}:${f}`,severity:"warning",category:"stale_instruction",title:`Node.js version mismatch: instruction says ${f}, project requires \u2265${i}`,summary:`Instructions mention Node.js ${f}, but package.json specifies a minimum version of ${i} in \`engines.node\`.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`Instruction says Node ${f}; engines.node says ${e.enginesNode}`],recommendation:`Update instructions to reflect the minimum supported Node.js version (${i}).`,confidence:.8})}}}return r}function k_(t,e,n){let s=t.lastIndexOf(`
61
61
  `,e-1)+1,i=t.indexOf(`
62
- `,e),r=t.slice(s,i===-1?void 0:i);return!!(/\b(?:do\s+not|don'?t|avoid|never|refrain\s+from|not\s+use)\b/i.test(r.slice(0,e-s+n.length+5))||/\b(?:migrat(?:ed?|ing)|replaced?|switched?\s+(?:from|away)|moved?\s+(?:from|away)|no\s+longer\s+use|previously\s+used?)\b/i.test(r))}function xS(t){let{packageJson:e,files:n}=t,s={...e.dependencies,...e.devDependencies},i=[],r=[{name:"Jest",package:"jest",alternatives:["vitest"]},{name:"Vitest",package:"vitest",alternatives:["jest"]},{name:"Playwright",package:"@playwright/test",alternatives:["cypress"]},{name:"Cypress",package:"cypress",alternatives:["@playwright/test"]}];for(let o of r)if(!s[o.package]){let a=o.alternatives.find(c=>s[c]);if(a){let c=new RegExp(`\\b${o.name}\\b`,"gi"),l=n.filter(u=>{let f,d=new RegExp(c.source,c.flags);for(;(f=d.exec(u.content))!==null;)if(!vS(u.content,f.index,o.name))return!0;return!1});l.length>0&&i.push({id:`manifest-js-tooling-mismatch:${o.package}`,severity:"warning",category:"conflict",title:`Possible tooling mismatch: instructions mention ${o.name} but project uses ${a}`,summary:`Instructions appear to reference ${o.name}, but this package is not in dependencies. ${a} is present instead. Consider reviewing whether the instructions are current.`,filePaths:l.map(u=>u.path),locations:l.map(u=>({filePath:u.path})),evidence:[`Instructions mention ${o.name}`,`${a} found in dependencies`,`${o.package} not found in dependencies`],recommendation:`Update instructions to reference ${a} instead of ${o.name}, or confirm migration is complete.`,confidence:.75})}}return i}function La(t){let{files:e,manifests:n,repoRoot:s}=t,i=[];n.packageJson&&(i.push(...mS(e,n.packageJson)),i.push(...bS(t)),i.push(...wS(t)),i.push(...xS(t)));let r=yS(t);if(r&&i.push(r),n.pyproject){let o=rS(e,n.pyproject,s);o&&i.push(o),i.push(...oS(e,n.pyproject)),i.push(...fS(e,n.pyproject))}return i}var rh=x(require("node:crypto"),1),wt=x(require("node:fs"),1),Qt=x(require("node:path"),1),Ka=x(wn(),1);var Je=x(require("node:fs/promises"),1),bt=x(require("node:path"),1);var Jp=x(Et(),1);var Na={"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-sonnet-5":1e6,"claude-sonnet-4-6":1e6,"claude-haiku-4-5":2e5,"claude-fable-5":1e6,"gpt-5":4e5,"gpt-5-mini":4e5,"gemini-2.5-pro":1e6,"gemini-2.5-flash":1e6},as=Object.keys(Na),Dp={claude:"claude-opus-5","claude-opus":"claude-opus-5","claude-sonnet":"claude-sonnet-5","claude-haiku":"claude-haiku-4-5",gpt:"gpt-5",openai:"gpt-5",copilot:"gpt-5",gemini:"gemini-2.5-pro"},_S=4,SS=.03,ES=.35;function Fp(t){return Math.round(t/1e3)*1e3}function $n(t){let e=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(Na,e))return e;if(Object.prototype.hasOwnProperty.call(Dp,e))return Dp[e]}function Hp(t){let e=Na[t],n=Fp(e*SS*_S),s=Fp(n*ES);return{contextWindowTokens:e,contextBudget:n,fileContextBudget:s}}function ja(t){let e=$n(t);return e?Hp(e):void 0}var Gp=x(require("node:crypto"),1),Up=x(require("node:fs/promises"),1),Zt=x(require("node:path"),1),Vp=x(Et(),1);var Da=Zt.join(".promptci","custom-rules.json"),Ma=["forbiddenPattern","absentPattern","requiredSection","crossFileConflict"],Bp=["info","warning","high","critical"],kS=/^[gimsuy]*$/,_e=class extends Error{constructor(e){super(`Invalid ${Da}: ${e}`),this.name="CustomRulesError"}};function cs(t,e,n){let s=t[e];if(typeof s!="string"||s.trim()==="")throw new _e(`${n} is missing a non-empty string "${e}".`);return s}function RS(t,e,n){if(!Array.isArray(t)||!t.every(s=>typeof s=="string"))throw new _e(`${n}: "${e}" must be an array of strings.`);return t}function CS(t,e,n){if(e!==void 0&&!kS.test(e))throw new _e(`${n}: "flags" may only contain regex flags (gimsuy).`);try{new RegExp(t,e)}catch(s){throw new _e(`${n}: "pattern" is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`)}}function zp(t){let e;if(Array.isArray(t))e=t;else if(t&&typeof t=="object"&&"rules"in t)e=t.rules;else throw new _e('top level must be an object with a "rules" array (or a bare array of rules).');if(!Array.isArray(e))throw new _e('"rules" must be an array.');let n=[],s=new Set;for(let i=0;i<e.length;i++){let r=e[i],o=`rule at index ${i}`;if(typeof r!="object"||r===null||Array.isArray(r))throw new _e(`${o} must be an object.`);let a=r,c=cs(a,"id",o),l=`rule "${c}"`;if(s.has(c))throw new _e(`${l}: duplicate rule id (ids must be unique).`);s.add(c);let u=cs(a,"type",l);if(!Ma.includes(u))throw new _e(`${l}: "type" must be one of ${Ma.join(", ")} (got "${u}").`);let f=cs(a,"message",l),d="warning";if("severity"in a){if(typeof a.severity!="string"||!Bp.includes(a.severity))throw new _e(`${l}: "severity" must be one of ${Bp.join(", ")}.`);d=a.severity}let p={id:c,type:u,message:f,severity:d};if("files"in a&&(p.files=RS(a.files,"files",l)),"flags"in a){if(typeof a.flags!="string")throw new _e(`${l}: "flags" must be a string.`);p.flags=a.flags}u==="requiredSection"?p.heading=cs(a,"heading",l):(p.pattern=cs(a,"pattern",l),CS(p.pattern,p.flags,l)),n.push(p)}return n}async function Fa(t){let e=Zt.join(t,Da);if(!ae(t,e))return[];let n;try{n=await Up.readFile(e,"utf-8")}catch(i){if(i.code==="ENOENT")return[];throw i}let s;try{s=JSON.parse(n)}catch{throw new _e("file is not valid JSON.")}return zp(s)}function AS(t){return Gp.createHash("sha1").update(t).digest("hex").slice(0,12)}function qp(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
63
- `&&n++;return n}function $S(t,e,n){return!e.files||e.files.length===0?t:t.filter(s=>{let i=Zt.relative(n,s.path).replace(/\\/g,"/");return Vp.default.isMatch(i,e.files,{dot:!0})})}function Ha(t){return new RegExp(t.pattern,t.flags)}function Li(t){return{severity:t.severity,category:"custom",confidence:1,tags:["custom-rule"]}}function PS(t,e){let n=[];for(let s of t){let i=Ha(e).exec(s.content);if(!i)continue;let r=qp(s.content,i.index);n.push({id:`custom:${e.id}:${AS(L(s))}`,...Li(e),title:e.message,summary:`Custom rule "${e.id}": a forbidden pattern was found in this file.`,filePaths:[s.path],locations:[{filePath:s.path,startLine:r,endLine:r}],evidence:[`Matched text: "${q(i[0],120)}" (line ${r})`],recommendation:`Remove or revise the flagged content to satisfy custom rule "${e.id}".`})}return n}function TS(t,e){return t.some(s=>Ha(e).test(s.content))?[]:[{id:`custom:${e.id}`,...Li(e),title:e.message,summary:`Custom rule "${e.id}": a required pattern is absent from all checked instruction files.`,filePaths:t.map(s=>s.path),locations:t.map(s=>({filePath:s.path})),evidence:[`Required pattern was not found in any of ${t.length} checked file(s).`],recommendation:`Add content matching custom rule "${e.id}" to one of the instruction files.`}]}function Wp(t){return t.toLowerCase().replace(/^#+\s*/,"").replace(/\s+/g," ").trim()}function IS(t,e){let n=Wp(e.heading);return t.some(i=>i.sections.some(r=>r.heading!==void 0&&Wp(r.heading).includes(n)))?[]:[{id:`custom:${e.id}`,...Li(e),title:e.message,summary:`Custom rule "${e.id}": a required section heading ("${e.heading}") is missing from all checked files.`,filePaths:t.map(i=>i.path),locations:t.map(i=>({filePath:i.path})),evidence:[`No section heading matching "${e.heading}" was found in ${t.length} checked file(s).`],recommendation:`Add a "${e.heading}" section to one of the instruction files to satisfy custom rule "${e.id}".`}]}function OS(t,e){let n=new Map;for(let o of t){let a=Ha(e).exec(o.content);if(!a)continue;let c=(a[1]??a[0]).trim(),l=qp(o.content,a.index),u=n.get(c)??[];u.push({filePath:o.path,line:l}),n.set(c,u)}if(n.size<2)return[];let s=[...new Set([...n.values()].flat().map(o=>o.filePath))],i=[...n.values()].flat().map(o=>({filePath:o.filePath,startLine:o.line,endLine:o.line})),r=[...n.entries()].map(([o,a])=>`"${q(o,60)}" in ${a.map(c=>Zt.basename(c.filePath)).join(", ")}`);return[{id:`custom:${e.id}`,...Li(e),title:e.message,summary:`Custom rule "${e.id}": the tracked value differs across files (${n.size} distinct values).`,filePaths:s,locations:i,evidence:r,recommendation:`Reconcile the conflicting values so custom rule "${e.id}" sees a single consistent value.`}]}function Ba(t,e,n){let s=[];for(let i of e){let r=$S(t,i,n);switch(i.type){case"forbiddenPattern":s.push(...PS(r,i));break;case"absentPattern":s.push(...TS(r,i));break;case"requiredSection":s.push(...IS(r,i));break;case"crossFileConflict":s.push(...OS(r,i));break}}return s}var LS=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock"];function NS(){return{packageManagerName:"unknown",scripts:{},dependencies:{},devDependencies:{},peerDependencies:{},lockfiles:[]}}function ls(t,e){let n=K(t,e);if(n===null)throw new Error(`Path escapes repo root: ${e}`);return n}async function Wa(t,e){try{return await Je.readFile(ls(t,e),"utf-8")}catch{return}}async function jS(t,e){let n=[];for(let s of e)try{(await Je.stat(ls(t,s))).isFile()&&n.push(s)}catch{}return n}function Kp(t){return t?t.startsWith("pnpm@")?"pnpm":t.startsWith("npm@")?"npm":t.startsWith("yarn@")?"yarn":t.startsWith("bun@")?"bun":"unknown":"unknown"}function Ni(t){return t.includes("pnpm-lock.yaml")?"pnpm":t.includes("package-lock.json")?"npm":t.includes("yarn.lock")?"yarn":t.some(e=>e.startsWith("bun.lock"))?"bun":"unknown"}function ji(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e}function Xp(t,e){let n=NS();if(n.raw=t,n.lockfiles=e,!t)return n.packageManagerName=Ni(e),n;let s;try{s=JSON.parse(t)}catch{return n.packageManagerName=Ni(e),n}if(typeof s!="object"||s===null||Array.isArray(s))return n.packageManagerName=Ni(e),n;let i=s;if(n.packageManager=typeof i.packageManager=="string"?i.packageManager:void 0,n.packageManagerName=Kp(n.packageManager)!=="unknown"?Kp(n.packageManager):Ni(e),n.scripts=ji(i.scripts),n.dependencies=ji(i.dependencies),n.devDependencies=ji(i.devDependencies),n.peerDependencies=ji(i.peerDependencies),typeof i.engines=="object"&&i.engines!==null&&!Array.isArray(i.engines)){let r=i.engines;n.enginesNode=typeof r.node=="string"?r.node:void 0}return n}function MS(t,e){let n=e.split(/\r?\n/),s=[];for(let i=0;i<n.length;i++){let r=n[i],o=/^(\s*)(?:-\s*)?run:\s*(.*)$/.exec(r);if(!o)continue;let a=o[1].length,c=o[2].trim();if(c&&!/^[|>][+-]?$/.test(c)){s.push({filePath:t,command:c,line:i+1});continue}let l=[];for(let f=i+1;f<n.length;f++){let d=n[f];if(d.trim()===""){l.push("");continue}if((d.match(/^\s*/)?.[0].length??0)<=a)break;l.push(d.trim())}let u=l.filter(Boolean).join(`
64
- `).trim();u&&s.push({filePath:t,command:u,line:i+1})}return s}async function DS(t,e=[]){let n,s;try{n=ls(t,bt.join(".github","workflows")),s=await Je.readdir(n,{withFileTypes:!0})}catch{return{files:[],commands:[],sources:await Yp(t,e)}}let i=s.filter(a=>a.isFile()&&/\.(ya?ml)$/i.test(a.name)).map(a=>bt.join(n,a.name)).sort(),r=[],o=[];for(let a of i){let c=bt.relative(t,a);if(!ae(t,a))continue;let l;try{l=await Je.readFile(a,"utf-8")}catch{continue}r.push(...MS(c,l));let u=c.replace(/\\/g,"/");l.length<=ce&&!us(u,e)&&o.push({filePath:u,content:l})}return o.push(...await Yp(t,e)),{files:i.map(a=>bt.relative(t,a)),commands:r,sources:o}}var FS=["action.yml","action.yaml",".github/actions/**/action.yml",".github/actions/**/action.yaml"];async function Yp(t,e){let n=[];for(let s of ct(t,FS)){if(us(s,e))continue;let i=K(t,s);if(i)try{let r=await Je.stat(i);if(!r.isFile()||r.size>ce)continue;n.push({filePath:s,content:await Je.readFile(i,"utf-8")})}catch{}}return n}function us(t,e){if(e.length===0)return!1;let n=[t],s=t.split("/");for(let i=1;i<s.length;i++){let r=s.slice(0,i).join("/");n.push(r,`${r}/`)}return n.some(i=>Jp.default.isMatch(i,e,{dot:!0}))}async function HS(t,e,n){let s;try{let o=await Je.stat(ls(t,e));if(!o.isFile()||o.size>ce)return;s=await Je.readFile(ls(t,e))}catch{return}if(Vt(s))return;let i=s.toString("utf-8"),r=i.split(`
62
+ `,e),r=t.slice(s,i===-1?void 0:i);return!!(/\b(?:do\s+not|don'?t|avoid|never|refrain\s+from|not\s+use)\b/i.test(r.slice(0,e-s+n.length+5))||/\b(?:migrat(?:ed?|ing)|replaced?|switched?\s+(?:from|away)|moved?\s+(?:from|away)|no\s+longer\s+use|previously\s+used?)\b/i.test(r))}function R_(t){let{packageJson:e,files:n}=t,s={...e.dependencies,...e.devDependencies},i=[],r=[{name:"Jest",package:"jest",alternatives:["vitest"]},{name:"Vitest",package:"vitest",alternatives:["jest"]},{name:"Playwright",package:"@playwright/test",alternatives:["cypress"]},{name:"Cypress",package:"cypress",alternatives:["@playwright/test"]}];for(let o of r)if(!s[o.package]){let a=o.alternatives.find(c=>s[c]);if(a){let c=new RegExp(`\\b${o.name}\\b`,"gi"),l=n.filter(u=>{let f,d=new RegExp(c.source,c.flags);for(;(f=d.exec(u.content))!==null;)if(!k_(u.content,f.index,o.name))return!0;return!1});l.length>0&&i.push({id:`manifest-js-tooling-mismatch:${o.package}`,severity:"warning",category:"conflict",title:`Possible tooling mismatch: instructions mention ${o.name} but project uses ${a}`,summary:`Instructions appear to reference ${o.name}, but this package is not in dependencies. ${a} is present instead. Consider reviewing whether the instructions are current.`,filePaths:l.map(u=>u.path),locations:l.map(u=>({filePath:u.path})),evidence:[`Instructions mention ${o.name}`,`${a} found in dependencies`,`${o.package} not found in dependencies`],recommendation:`Update instructions to reference ${a} instead of ${o.name}, or confirm migration is complete.`,confidence:.75})}}return i}function Ma(t){let{files:e,manifests:n,repoRoot:s}=t,i=[];n.packageJson&&(i.push(...v_(e,n.packageJson)),i.push(...__(t)),i.push(...E_(t)),i.push(...R_(t)));let r=S_(t);if(r&&i.push(r),n.pyproject){let o=u_(e,n.pyproject,s);o&&i.push(o),i.push(...f_(e,n.pyproject)),i.push(...g_(e,n.pyproject))}return i}var uh=x(require("node:crypto"),1),wt=x(require("node:fs"),1),Qt=x(require("node:path"),1),Xa=x(wn(),1);var Je=x(require("node:fs/promises"),1),bt=x(require("node:path"),1);var th=x(Et(),1);var Da={"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-sonnet-5":1e6,"claude-sonnet-4-6":1e6,"claude-haiku-4-5":2e5,"claude-fable-5":1e6,"gpt-5":4e5,"gpt-5-mini":4e5,"gemini-2.5-pro":1e6,"gemini-2.5-flash":1e6},as=Object.keys(Da),Gp={claude:"claude-opus-5","claude-opus":"claude-opus-5","claude-sonnet":"claude-sonnet-5","claude-haiku":"claude-haiku-4-5",gpt:"gpt-5",openai:"gpt-5",copilot:"gpt-5",gemini:"gemini-2.5-pro"},C_=4,A_=.03,$_=.35;function Up(t){return Math.round(t/1e3)*1e3}function $n(t){let e=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(Da,e))return e;if(Object.prototype.hasOwnProperty.call(Gp,e))return Gp[e]}function Vp(t){let e=Da[t],n=Up(e*A_*C_),s=Up(n*$_);return{contextWindowTokens:e,contextBudget:n,fileContextBudget:s}}function Fa(t){let e=$n(t);return e?Vp(e):void 0}var Kp=x(require("node:crypto"),1),Yp=x(require("node:fs/promises"),1),Zt=x(require("node:path"),1),Jp=x(Et(),1);var Ba=Zt.join(".promptci","custom-rules.json"),Ha=["forbiddenPattern","absentPattern","requiredSection","crossFileConflict"],zp=["info","warning","high","critical"],P_=/^[gimsuy]*$/,Se=class extends Error{constructor(e){super(`Invalid ${Ba}: ${e}`),this.name="CustomRulesError"}};function cs(t,e,n){let s=t[e];if(typeof s!="string"||s.trim()==="")throw new Se(`${n} is missing a non-empty string "${e}".`);return s}function T_(t,e,n){if(!Array.isArray(t)||!t.every(s=>typeof s=="string"))throw new Se(`${n}: "${e}" must be an array of strings.`);return t}function I_(t,e,n){if(e!==void 0&&!P_.test(e))throw new Se(`${n}: "flags" may only contain regex flags (gimsuy).`);try{new RegExp(t,e)}catch(s){throw new Se(`${n}: "pattern" is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`)}}function Xp(t){let e;if(Array.isArray(t))e=t;else if(t&&typeof t=="object"&&"rules"in t)e=t.rules;else throw new Se('top level must be an object with a "rules" array (or a bare array of rules).');if(!Array.isArray(e))throw new Se('"rules" must be an array.');let n=[],s=new Set;for(let i=0;i<e.length;i++){let r=e[i],o=`rule at index ${i}`;if(typeof r!="object"||r===null||Array.isArray(r))throw new Se(`${o} must be an object.`);let a=r,c=cs(a,"id",o),l=`rule "${c}"`;if(s.has(c))throw new Se(`${l}: duplicate rule id (ids must be unique).`);s.add(c);let u=cs(a,"type",l);if(!Ha.includes(u))throw new Se(`${l}: "type" must be one of ${Ha.join(", ")} (got "${u}").`);let f=cs(a,"message",l),d="warning";if("severity"in a){if(typeof a.severity!="string"||!zp.includes(a.severity))throw new Se(`${l}: "severity" must be one of ${zp.join(", ")}.`);d=a.severity}let p={id:c,type:u,message:f,severity:d};if("files"in a&&(p.files=T_(a.files,"files",l)),"flags"in a){if(typeof a.flags!="string")throw new Se(`${l}: "flags" must be a string.`);p.flags=a.flags}u==="requiredSection"?p.heading=cs(a,"heading",l):(p.pattern=cs(a,"pattern",l),I_(p.pattern,p.flags,l)),n.push(p)}return n}async function Wa(t){let e=Zt.join(t,Ba);if(!ae(t,e))return[];let n;try{n=await Yp.readFile(e,"utf-8")}catch(i){if(i.code==="ENOENT")return[];throw i}let s;try{s=JSON.parse(n)}catch{throw new Se("file is not valid JSON.")}return Xp(s)}function O_(t){return Kp.createHash("sha1").update(t).digest("hex").slice(0,12)}function Zp(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
63
+ `&&n++;return n}function L_(t,e,n){return!e.files||e.files.length===0?t:t.filter(s=>{let i=Zt.relative(n,s.path).replace(/\\/g,"/");return Jp.default.isMatch(i,e.files,{dot:!0})})}function Ga(t){return new RegExp(t.pattern,t.flags)}function ji(t){return{severity:t.severity,category:"custom",confidence:1,tags:["custom-rule"]}}function N_(t,e){let n=[];for(let s of t){let i=Ga(e).exec(s.content);if(!i)continue;let r=Zp(s.content,i.index);n.push({id:`custom:${e.id}:${O_(L(s))}`,...ji(e),title:e.message,summary:`Custom rule "${e.id}": a forbidden pattern was found in this file.`,filePaths:[s.path],locations:[{filePath:s.path,startLine:r,endLine:r}],evidence:[`Matched text: "${Y(i[0],120)}" (line ${r})`],recommendation:`Remove or revise the flagged content to satisfy custom rule "${e.id}".`})}return n}function j_(t,e){return t.some(s=>Ga(e).test(s.content))?[]:[{id:`custom:${e.id}`,...ji(e),title:e.message,summary:`Custom rule "${e.id}": a required pattern is absent from all checked instruction files.`,filePaths:t.map(s=>s.path),locations:t.map(s=>({filePath:s.path})),evidence:[`Required pattern was not found in any of ${t.length} checked file(s).`],recommendation:`Add content matching custom rule "${e.id}" to one of the instruction files.`}]}function qp(t){return t.toLowerCase().replace(/^#+\s*/,"").replace(/\s+/g," ").trim()}function M_(t,e){let n=qp(e.heading);return t.some(i=>i.sections.some(r=>r.heading!==void 0&&qp(r.heading).includes(n)))?[]:[{id:`custom:${e.id}`,...ji(e),title:e.message,summary:`Custom rule "${e.id}": a required section heading ("${e.heading}") is missing from all checked files.`,filePaths:t.map(i=>i.path),locations:t.map(i=>({filePath:i.path})),evidence:[`No section heading matching "${e.heading}" was found in ${t.length} checked file(s).`],recommendation:`Add a "${e.heading}" section to one of the instruction files to satisfy custom rule "${e.id}".`}]}function D_(t,e){let n=new Map;for(let o of t){let a=Ga(e).exec(o.content);if(!a)continue;let c=(a[1]??a[0]).trim(),l=Zp(o.content,a.index),u=n.get(c)??[];u.push({filePath:o.path,line:l}),n.set(c,u)}if(n.size<2)return[];let s=[...new Set([...n.values()].flat().map(o=>o.filePath))],i=[...n.values()].flat().map(o=>({filePath:o.filePath,startLine:o.line,endLine:o.line})),r=[...n.entries()].map(([o,a])=>`"${Y(o,60)}" in ${a.map(c=>Zt.basename(c.filePath)).join(", ")}`);return[{id:`custom:${e.id}`,...ji(e),title:e.message,summary:`Custom rule "${e.id}": the tracked value differs across files (${n.size} distinct values).`,filePaths:s,locations:i,evidence:r,recommendation:`Reconcile the conflicting values so custom rule "${e.id}" sees a single consistent value.`}]}function Ua(t,e,n){let s=[];for(let i of e){let r=L_(t,i,n);switch(i.type){case"forbiddenPattern":s.push(...N_(r,i));break;case"absentPattern":s.push(...j_(r,i));break;case"requiredSection":s.push(...M_(r,i));break;case"crossFileConflict":s.push(...D_(r,i));break}}return s}var F_=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock"];function H_(){return{packageManagerName:"unknown",scripts:{},dependencies:{},devDependencies:{},peerDependencies:{},lockfiles:[]}}function ls(t,e){let n=J(t,e);if(n===null)throw new Error(`Path escapes repo root: ${e}`);return n}async function Va(t,e){try{return await Je.readFile(ls(t,e),"utf-8")}catch{return}}async function B_(t,e){let n=[];for(let s of e)try{(await Je.stat(ls(t,s))).isFile()&&n.push(s)}catch{}return n}function Qp(t){return t?t.startsWith("pnpm@")?"pnpm":t.startsWith("npm@")?"npm":t.startsWith("yarn@")?"yarn":t.startsWith("bun@")?"bun":"unknown":"unknown"}function Mi(t){return t.includes("pnpm-lock.yaml")?"pnpm":t.includes("package-lock.json")?"npm":t.includes("yarn.lock")?"yarn":t.some(e=>e.startsWith("bun.lock"))?"bun":"unknown"}function Di(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,s]of Object.entries(t))typeof s=="string"&&(e[n]=s);return e}function nh(t,e){let n=H_();if(n.raw=t,n.lockfiles=e,!t)return n.packageManagerName=Mi(e),n;let s;try{s=JSON.parse(t)}catch{return n.packageManagerName=Mi(e),n}if(typeof s!="object"||s===null||Array.isArray(s))return n.packageManagerName=Mi(e),n;let i=s;if(n.packageManager=typeof i.packageManager=="string"?i.packageManager:void 0,n.packageManagerName=Qp(n.packageManager)!=="unknown"?Qp(n.packageManager):Mi(e),n.scripts=Di(i.scripts),n.dependencies=Di(i.dependencies),n.devDependencies=Di(i.devDependencies),n.peerDependencies=Di(i.peerDependencies),typeof i.engines=="object"&&i.engines!==null&&!Array.isArray(i.engines)){let r=i.engines;n.enginesNode=typeof r.node=="string"?r.node:void 0}return n}function W_(t,e){let n=e.split(/\r?\n/),s=[];for(let i=0;i<n.length;i++){let r=n[i],o=/^(\s*)(?:-\s*)?run:\s*(.*)$/.exec(r);if(!o)continue;let a=o[1].length,c=o[2].trim();if(c&&!/^[|>][+-]?$/.test(c)){s.push({filePath:t,command:c,line:i+1});continue}let l=[];for(let f=i+1;f<n.length;f++){let d=n[f];if(d.trim()===""){l.push("");continue}if((d.match(/^\s*/)?.[0].length??0)<=a)break;l.push(d.trim())}let u=l.filter(Boolean).join(`
64
+ `).trim();u&&s.push({filePath:t,command:u,line:i+1})}return s}async function G_(t,e=[]){let n,s;try{n=ls(t,bt.join(".github","workflows")),s=await Je.readdir(n,{withFileTypes:!0})}catch{return{files:[],commands:[],sources:await eh(t,e)}}let i=s.filter(a=>a.isFile()&&/\.(ya?ml)$/i.test(a.name)).map(a=>bt.join(n,a.name)).sort(),r=[],o=[];for(let a of i){let c=bt.relative(t,a);if(!ae(t,a))continue;let l;try{l=await Je.readFile(a,"utf-8")}catch{continue}r.push(...W_(c,l));let u=c.replace(/\\/g,"/");l.length<=ce&&!us(u,e)&&o.push({filePath:u,content:l})}return o.push(...await eh(t,e)),{files:i.map(a=>bt.relative(t,a)),commands:r,sources:o}}var U_=["action.yml","action.yaml",".github/actions/**/action.yml",".github/actions/**/action.yaml"];async function eh(t,e){let n=[];for(let s of ct(t,U_)){if(us(s,e))continue;let i=J(t,s);if(i)try{let r=await Je.stat(i);if(!r.isFile()||r.size>ce)continue;n.push({filePath:s,content:await Je.readFile(i,"utf-8")})}catch{}}return n}function us(t,e){if(e.length===0)return!1;let n=[t],s=t.split("/");for(let i=1;i<s.length;i++){let r=s.slice(0,i).join("/");n.push(r,`${r}/`)}return n.some(i=>th.default.isMatch(i,e,{dot:!0}))}async function V_(t,e,n){let s;try{let o=await Je.stat(ls(t,e));if(!o.isFile()||o.size>ce)return;s=await Je.readFile(ls(t,e))}catch{return}if(zt(s))return;let i=s.toString("utf-8"),r=i.split(`
65
65
  `);return i.endsWith(`
66
- `)&&r.pop(),{path:n,relativePath:e,fileType:"skill",content:i,sections:Ut(i,n,e),lineCount:r.length,charCount:i.length,estimatedTokens:Math.round(i.length/4)}}function BS(t,e){let n={estimatedInstructionTokens:t.reduce((s,i)=>s+i.estimatedTokens,0),instructionFileCount:t.length,largestInstructionFiles:[...t].sort((s,i)=>i.estimatedTokens-s.estimatedTokens).slice(0,5).map(s=>({path:s.path,estimatedTokens:s.estimatedTokens}))};return e.length>0&&(n.onDemandFileCount=e.length,n.estimatedOnDemandTokens=e.reduce((s,i)=>s+i.estimatedTokens,0)),n}async function fs(t){let e=bt.resolve(t.repoPath),{files:n,aliases:s}=await pi({...t,repoPath:e}),i=[],r=[];for(let y of n)(cl(y.fileType)?r:i).push(y);let o=ca(e,t),a=new Set(n.map(y=>y.path));for(let y of o.allSkills??[]){let v=bt.resolve(e,y);if(a.has(v))continue;let k=await HS(e,y,v);k&&r.push(k)}r.sort((y,v)=>y.path.localeCompare(v.path));let c=t.projectType&&t.projectType!=="auto"?t.projectType:await Yn(e);c==="unknown"&&(c=Yo(i));let[l,u,f,d,p,h]=await Promise.all([Wa(e,"package.json"),Wa(e,"pyproject.toml"),Wa(e,"requirements.txt"),jS(e,LS),DS(e,t.exclude),Fa(e)]),m=await kp(e,l,y=>us(y,t.exclude??[])),g=Ti(e,"."),b={};l&&(b.packageJson=l),u&&(b.pyproject=u),f!==void 0&&(b.requirements=f);let w=t.targetModel?ja(t.targetModel):void 0;return{repoRoot:e,files:i,projectType:c,manifests:b,packageJson:Xp(l,d),workflows:p,workspaces:m.manifests,workspacesTruncated:m.truncated,...g?{makefile:g}:{},aiConfig:o,...t.exclude&&t.exclude.length>0?{exclude:t.exclude}:{},metrics:BS(i,r),contextBudget:t.contextBudget??w?.contextBudget,fileContextBudget:t.fileContextBudget??w?.fileContextBudget,vagueGuidanceSeverity:t.vagueGuidanceSeverity,onDemandFiles:r,...s.length>0?{aliasFiles:s}:{},customRules:h}}var WS=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib","test","sqlite"]),GS=new Set(["npm","pnpm","yarn","npx","bun","bunx","deno","node","corepack","nvm","fnm","volta","git"]),US=new Set(["package","package-name","pkg","name","module","module-name","lib","library","dependency","dep","foo","bar","baz","example","sample","x","y","z","a","b","c","my-package","my-lib","my-app","some-package","some-lib","your-package","package-a","package-b","new-package","new-dependency"]),VS=/^(?:your|my|some|example|sample|foo|bar|baz|pkg|package)(?:-|$)/,zS=new Set(["scope","your-scope","my-scope","org","your-org","my-org","yourorg","myorg","company","your-company","acme","example","project","repo","workspace","name","user","username","namespace","team","monorepo","scope-name","org-name","your-username"]),qS=new Set(["src","app","lib","libs","components","component","utils","util","hooks","types","config","styles","assets","public","test","tests","shared","common","core","store","stores","services","service","pages","features","modules","server","client","api","db","models","helpers","constants","context","contexts","layouts","routes","views","data","mocks","fixtures","schemas","icons","images","ui","actions","reducers","providers","middleware","controllers","entities","domain","dev","prod","optional","peer","build","lint","main","default","latest","local","root","runtime","required","direct","transitive","external","internal","vendor"]),Ua=/\b(?:not|never|don'?t|do\s+not|doesn'?t|avoid|instead\s+of|rather\s+than|no\s+longer|replace[sd]?|replacing|migrat\w+|deprecated|removed|legacy|without|except|unlike|vs\.?|versus|older|previously|formerly|used\s+to|drop(?:ped)?|stop\s+using|forbidden|banned|prohibited|phas(?:e[sd]?|ing)\s+out|being\s+replaced|sunset\w*)\b/i,Va={moment:{status:"is a legacy project in maintenance mode",replacement:"date-fns, Luxon, Day.js, or the Temporal API",distinctive:!0,command:!1},request:{status:"was deprecated by its maintainers in 2020",replacement:"the built-in fetch, undici, got, or axios",distinctive:!1,command:!1},tslint:{status:"was deprecated in favor of ESLint",replacement:"ESLint with typescript-eslint",distinctive:!0,command:!0},"node-sass":{status:"is deprecated (LibSass is no longer maintained)",replacement:"sass (Dart Sass)",distinctive:!0,command:!0},"react-scripts":{status:"belongs to Create React App, which the React team has deprecated",replacement:"Vite, Next.js, or another maintained React toolchain",distinctive:!0,command:!0},enzyme:{status:"is unmaintained and has no official adapter for current React versions",replacement:"@testing-library/react",distinctive:!0,command:!1}},KS=/(?:^|[\s;&|(])(?:cd|pushd)\s+\S/,YS=new Set(["","sh","bash","shell","zsh","console","shellsession","terminal","powershell","ps1","pwsh","cmd"]),JS=new Set(["","js","jsx","ts","tsx","javascript","typescript","mjs","cjs","mts","cts","vue","svelte","astro"]),Zp=/(`+)([^`\n]+)\1/g;function XS(t){let e=[],n=[],s=!1;for(let i of xe(t.content)){let r=i.text.replace(/\r$/,"");if(i.kind==="open"&&(s=!1),i.kind==="content")e.push({text:r,line:i.lineNumber,fenced:!0,lang:i.lang,lineText:r,afterCd:s}),KS.test(r)&&(s=!0);else if(i.kind==="text"){n.push({line:i.lineNumber,text:r});let o=new RegExp(Zp.source,Zp.flags),a;for(;(a=o.exec(r))!==null;)e.push({text:a[2].trim(),line:i.lineNumber,fenced:!1,lang:"",lineText:r,afterCd:!1})}}return{segments:e,prose:n}}var oh=/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/,ah=/\.(?:json|jsonc|ts|tsx|mts|cts|jsx|mjs|cjs|md|mdx|ya?ml|toml|lock|css|scss|sass|less|styl|html|sh|txt|env|config|dart|go|py|rs|rb|java|kt|swift|vue|svelte|astro|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|mp[34]|wasm|graphql|gql|sql)$/i,ZS=/^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|org|net|io|dev|co|app|ai|me|sh|xyz|gg|tv|cc|us|uk|de|fr|ru|cn|jp|to|in|so|cloud)\//i;function ch(t){let e=t.replace(/^['"]|['"]$/g,""),n=/^(@[^/@\s]+\/[^/@\s]+|[^/@\s][^@/\s]*)(?:@\S*)?$/.exec(e);if(!n)return;let s=n[1];return oh.test(s)&&!ah.test(s)?s:void 0}function QS(t){if(/^[./~#$]|^@\/|:|\s|\*|<|\{/.test(t)||ZS.test(t))return;let e=/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._-]*)(?:\/.*)?$/.exec(t);if(e)return ah.test(e[1])?void 0:e[1]}var lh=new Set(["-C","--cwd","--prefix","--dir"]),Qp=new Set(["--filter","-F","--workspace",...lh]),eE=new Set(["-D","--save-dev","-S","--save","-E","--save-exact","-O","--save-optional","-P","--save-prod","--dev","--exact","--optional","--peer","--no-save","--force","--legacy-peer-deps","--ignore-scripts","--silent","--no-audit","--no-fund","--prefer-offline","--workspace-root","-W"]),tE={npm:new Set(["install","i","add"]),pnpm:new Set(["add","install","i"]),yarn:new Set(["add"]),bun:new Set(["add","install","i"])};function nE(t,e){if(e)return[];let n=[];for(let s of t.split(/&&|\|\||[;|]/)){let i=s.replace(/^\s*(?:[$>%]\s+|[({]\s*)+/,"").trim().split(/\s+/),r=i[0];if(r==="cd"||r==="pushd")break;let o=r?tE[r]:void 0;if(!o||i.some(f=>lh.has(f)||/^--(?:prefix|cwd|dir)=/.test(f)))continue;let a=1,c=!1;for(;a<i.length;a++){let f=i[a];if(o.has(f)){c=!0,a++;break}if(Qp.has(f)||r==="npm"&&f==="-w"||r==="yarn"&&f==="workspace"){a++;continue}if(!f.startsWith("-"))break}if(!c)continue;let l=[],u=!1;for(;a<i.length;a++){let f=i[a];if(f.startsWith("#"))break;if(f==="-g"||f==="--global"||f==="--location=global"){u=!0;break}if(f.startsWith("-")){if(eE.has(f)||r==="pnpm"&&f==="-w"||f.includes("="))continue;if(Qp.has(f)||r==="npm"&&f==="-w"){a++;continue}u=!0;break}let d=ch(f);if(d===void 0){u=!0;break}l.push(d)}u||n.push(...l)}return n}var eh=[/\bimport\s+(?:type\s+)?[^'"`;]*?\sfrom\s+['"]([^'"]+)['"]/g,/\bimport\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,/^\s*\}?\s*from\s+['"]([^'"]+)['"]/g],sE=/\bimport\s+['"]([^'"]+)['"]/g;function iE(t,e){let n=[],s=e?eh:[...eh,sE];for(let i of s){let r=new RegExp(i.source,i.flags),o;for(;(o=r.exec(t))!==null;){let a=QS(o[1]);a!==void 0&&n.push(a)}}return n}var rE=[/\b(?:package|library|dependency)\s+`([^`\s]+)`/gi,/`([^`\s]+)`\s+(?:npm\s+)?(?:package|library|dependency)\b/gi];function oE(t){let e=[];for(let n of rE){let s=new RegExp(n.source,n.flags),i;for(;(i=s.exec(t))!==null;){let r=ch(i[1]);r!==void 0&&e.push(r)}}return e}var aE=/(?:^|[\s;&|(])(?:(?:npx|bunx|yarn|pnpm\s+(?:exec|dlx)|npm\s+exec)\s+)?(react-scripts|tslint|node-sass)(?=\s|$)/g;function cE(t){let e=/(?:^|\s)(?:#|\/\/|\/\*|--)\s*(.*)$/.exec(t);return e?e[1]:""}function lE(t){let e=[],{segments:n,prose:s}=XS(t),i=(r,o,a,c)=>{e.push({pkg:r,kind:o,file:t,line:a,text:c})};for(let r of n){if(Ua.test(r.fenced?cE(r.lineText):r.lineText))continue;let o=r.text;if(!r.fenced||YS.has(r.lang)){for(let l of nE(o,r.afterCd))i(l,"install",r.line,r.lineText);let a=new RegExp(aE.source,"g"),c;for(;(c=a.exec(o))!==null;)Va[c[1]]?.command&&i(c[1],"command",r.line,r.lineText)}if(!r.fenced||JS.has(r.lang)){let a=!r.fenced||r.lang==="";for(let c of iE(o,a))i(c,"import",r.line,r.lineText)}!r.fenced&&oh.test(o)&&Va[o]?.distinctive&&i(o,"span",r.line,r.lineText)}for(let{line:r,text:o}of s)if(!Ua.test(o))for(let a of oE(o))i(a,"qualified",r,o);return e}var th=200,uh=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/worktrees/**","**/.worktrees/**","**/vendor/**","**/target/**","**/.turbo/**","**/coverage/**","**/Library/**","**/Temp/**"],uE=new Set(["vscode","k6"]),fE={jest:["vitest"],vitest:["jest"],"@playwright/test":["cypress"],cypress:["@playwright/test"]};function za(t,e){t.any=!0,e.name&&t.declared.add(e.name);for(let n of e.dependencies)t.declared.add(n);for(let[n,s]of Object.entries(e.versions??{}))t.specs.set(n,[...t.specs.get(n)??[],s]);e.dependencies.includes("next")&&t.nextDirs.push(e.dir),t.dirs.add(e.dir),e.dir!=="."&&t.localNames.add(Qt.posix.basename(e.dir)),e.name&&t.localNames.add(e.name.replace(/^@[^/]+\//,""))}function dE(t){let e={declared:new Set,specs:new Map,any:!1,dirs:new Set,nextDirs:[],localNames:new Set,aliasNames:new Set,aliasScopes:new Set,catalogs:{default:{},named:{}},truncated:t.workspacesTruncated===!0,lazyLoaded:!1},n=t.manifests.packageJson,s=(t.workspaces??[]).find(i=>i.dir===".");if(n!==void 0&&s===void 0){let{dependencies:i,devDependencies:r,peerDependencies:o}=t.packageJson,a=is(".",JSON.stringify({dependencies:i,devDependencies:r,peerDependencies:o}));a&&za(e,a)}for(let i of t.workspaces??[])za(e,i);return e}function Mi(t,e){try{let n=K(t,e);if(!n)return;let s=wt.statSync(n);return!s.isFile()||s.size>ce?void 0:wt.readFileSync(n,"utf-8")}catch{return}}function nh(t){let e="",n=!1;for(let s=0;s<t.length;s++){let i=t[s];if(n)e+=i,i==="\\"?e+=t[++s]??"":i==='"'&&(n=!1);else if(i==='"')n=!0,e+=i;else if(i==="/"&&t[s+1]==="/"){for(;s<t.length&&t[s]!==`
66
+ `)&&r.pop(),{path:n,relativePath:e,fileType:"skill",content:i,sections:Vt(i,n,e),lineCount:r.length,charCount:i.length,estimatedTokens:Math.round(i.length/4)}}function z_(t,e){let n={estimatedInstructionTokens:t.reduce((s,i)=>s+i.estimatedTokens,0),instructionFileCount:t.length,largestInstructionFiles:[...t].sort((s,i)=>i.estimatedTokens-s.estimatedTokens).slice(0,5).map(s=>({path:s.path,estimatedTokens:s.estimatedTokens}))};return e.length>0&&(n.onDemandFileCount=e.length,n.estimatedOnDemandTokens=e.reduce((s,i)=>s+i.estimatedTokens,0)),n}async function fs(t){let e=bt.resolve(t.repoPath),{files:n,aliases:s}=await pi({...t,repoPath:e}),i=[],r=[];for(let y of n)(fl(y.fileType)?r:i).push(y);let o=ua(e,t),a=new Set(n.map(y=>y.path));for(let y of o.allSkills??[]){let v=bt.resolve(e,y);if(a.has(v))continue;let R=await V_(e,y,v);R&&r.push(R)}r.sort((y,v)=>y.path.localeCompare(v.path));let c=t.projectType&&t.projectType!=="auto"?t.projectType:await Yn(e);c==="unknown"&&(c=Xo(i));let[l,u,f,d,p,h]=await Promise.all([Va(e,"package.json"),Va(e,"pyproject.toml"),Va(e,"requirements.txt"),B_(e,F_),G_(e,t.exclude),Wa(e)]),m=await Pp(e,l,y=>us(y,t.exclude??[])),g=Oi(e,"."),b={};l&&(b.packageJson=l),u&&(b.pyproject=u),f!==void 0&&(b.requirements=f);let w=t.targetModel?Fa(t.targetModel):void 0;return{repoRoot:e,files:i,projectType:c,manifests:b,packageJson:nh(l,d),workflows:p,workspaces:m.manifests,workspacesTruncated:m.truncated,...g?{makefile:g}:{},aiConfig:o,...t.exclude&&t.exclude.length>0?{exclude:t.exclude}:{},metrics:z_(i,r),contextBudget:t.contextBudget??w?.contextBudget,fileContextBudget:t.fileContextBudget??w?.fileContextBudget,vagueGuidanceSeverity:t.vagueGuidanceSeverity,onDemandFiles:r,...s.length>0?{aliasFiles:s}:{},customRules:h}}var q_=new Set(["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib","test","sqlite"]),K_=new Set(["npm","pnpm","yarn","npx","bun","bunx","deno","node","corepack","nvm","fnm","volta","git"]),Y_=new Set(["package","package-name","pkg","name","module","module-name","lib","library","dependency","dep","foo","bar","baz","example","sample","x","y","z","a","b","c","my-package","my-lib","my-app","some-package","some-lib","your-package","package-a","package-b","new-package","new-dependency"]),J_=/^(?:your|my|some|example|sample|foo|bar|baz|pkg|package)(?:-|$)/,X_=new Set(["scope","your-scope","my-scope","org","your-org","my-org","yourorg","myorg","company","your-company","acme","example","project","repo","workspace","name","user","username","namespace","team","monorepo","scope-name","org-name","your-username"]),Z_=new Set(["src","app","lib","libs","components","component","utils","util","hooks","types","config","styles","assets","public","test","tests","shared","common","core","store","stores","services","service","pages","features","modules","server","client","api","db","models","helpers","constants","context","contexts","layouts","routes","views","data","mocks","fixtures","schemas","icons","images","ui","actions","reducers","providers","middleware","controllers","entities","domain","dev","prod","optional","peer","build","lint","main","default","latest","local","root","runtime","required","direct","transitive","external","internal","vendor"]),qa=/\b(?:not|never|don'?t|do\s+not|doesn'?t|avoid|instead\s+of|rather\s+than|no\s+longer|replace[sd]?|replacing|migrat\w+|deprecated|removed|legacy|without|except|unlike|vs\.?|versus|older|previously|formerly|used\s+to|drop(?:ped)?|stop\s+using|forbidden|banned|prohibited|phas(?:e[sd]?|ing)\s+out|being\s+replaced|sunset\w*)\b/i,Ka={moment:{status:"is a legacy project in maintenance mode",replacement:"date-fns, Luxon, Day.js, or the Temporal API",distinctive:!0,command:!1},request:{status:"was deprecated by its maintainers in 2020",replacement:"the built-in fetch, undici, got, or axios",distinctive:!1,command:!1},tslint:{status:"was deprecated in favor of ESLint",replacement:"ESLint with typescript-eslint",distinctive:!0,command:!0},"node-sass":{status:"is deprecated (LibSass is no longer maintained)",replacement:"sass (Dart Sass)",distinctive:!0,command:!0},"react-scripts":{status:"belongs to Create React App, which the React team has deprecated",replacement:"Vite, Next.js, or another maintained React toolchain",distinctive:!0,command:!0},enzyme:{status:"is unmaintained and has no official adapter for current React versions",replacement:"@testing-library/react",distinctive:!0,command:!1}},Q_=/(?:^|[\s;&|(])(?:cd|pushd)\s+\S/,eE=new Set(["","sh","bash","shell","zsh","console","shellsession","terminal","powershell","ps1","pwsh","cmd"]),tE=new Set(["","js","jsx","ts","tsx","javascript","typescript","mjs","cjs","mts","cts","vue","svelte","astro"]),sh=/(`+)([^`\n]+)\1/g;function nE(t){let e=[],n=[],s=!1;for(let i of xe(t.content)){let r=i.text.replace(/\r$/,"");if(i.kind==="open"&&(s=!1),i.kind==="content")e.push({text:r,line:i.lineNumber,fenced:!0,lang:i.lang,lineText:r,afterCd:s}),Q_.test(r)&&(s=!0);else if(i.kind==="text"){n.push({line:i.lineNumber,text:r});let o=new RegExp(sh.source,sh.flags),a;for(;(a=o.exec(r))!==null;)e.push({text:a[2].trim(),line:i.lineNumber,fenced:!1,lang:"",lineText:r,afterCd:!1})}}return{segments:e,prose:n}}var fh=/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/,dh=/\.(?:json|jsonc|ts|tsx|mts|cts|jsx|mjs|cjs|md|mdx|ya?ml|toml|lock|css|scss|sass|less|styl|html|sh|txt|env|config|dart|go|py|rs|rb|java|kt|swift|vue|svelte|astro|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|mp[34]|wasm|graphql|gql|sql)$/i,sE=/^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:com|org|net|io|dev|co|app|ai|me|sh|xyz|gg|tv|cc|us|uk|de|fr|ru|cn|jp|to|in|so|cloud)\//i;function ph(t){let e=t.replace(/^['"]|['"]$/g,""),n=/^(@[^/@\s]+\/[^/@\s]+|[^/@\s][^@/\s]*)(?:@\S*)?$/.exec(e);if(!n)return;let s=n[1];return fh.test(s)&&!dh.test(s)?s:void 0}function iE(t){if(/^[./~#$]|^@\/|:|\s|\*|<|\{/.test(t)||sE.test(t))return;let e=/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._-]*)(?:\/.*)?$/.exec(t);if(e)return dh.test(e[1])?void 0:e[1]}var hh=new Set(["-C","--cwd","--prefix","--dir"]),ih=new Set(["--filter","-F","--workspace",...hh]),rE=new Set(["-D","--save-dev","-S","--save","-E","--save-exact","-O","--save-optional","-P","--save-prod","--dev","--exact","--optional","--peer","--no-save","--force","--legacy-peer-deps","--ignore-scripts","--silent","--no-audit","--no-fund","--prefer-offline","--workspace-root","-W"]),oE={npm:new Set(["install","i","add"]),pnpm:new Set(["add","install","i"]),yarn:new Set(["add"]),bun:new Set(["add","install","i"])};function aE(t,e){if(e)return[];let n=[];for(let s of t.split(/&&|\|\||[;|]/)){let i=s.replace(/^\s*(?:[$>%]\s+|[({]\s*)+/,"").trim().split(/\s+/),r=i[0];if(r==="cd"||r==="pushd")break;let o=r?oE[r]:void 0;if(!o||i.some(f=>hh.has(f)||/^--(?:prefix|cwd|dir)=/.test(f)))continue;let a=1,c=!1;for(;a<i.length;a++){let f=i[a];if(o.has(f)){c=!0,a++;break}if(ih.has(f)||r==="npm"&&f==="-w"||r==="yarn"&&f==="workspace"){a++;continue}if(!f.startsWith("-"))break}if(!c)continue;let l=[],u=!1;for(;a<i.length;a++){let f=i[a];if(f.startsWith("#"))break;if(f==="-g"||f==="--global"||f==="--location=global"){u=!0;break}if(f.startsWith("-")){if(rE.has(f)||r==="pnpm"&&f==="-w"||f.includes("="))continue;if(ih.has(f)||r==="npm"&&f==="-w"){a++;continue}u=!0;break}let d=ph(f);if(d===void 0){u=!0;break}l.push(d)}u||n.push(...l)}return n}var rh=[/\bimport\s+(?:type\s+)?[^'"`;]*?\sfrom\s+['"]([^'"]+)['"]/g,/\bimport\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,/^\s*\}?\s*from\s+['"]([^'"]+)['"]/g],cE=/\bimport\s+['"]([^'"]+)['"]/g;function lE(t,e){let n=[],s=e?rh:[...rh,cE];for(let i of s){let r=new RegExp(i.source,i.flags),o;for(;(o=r.exec(t))!==null;){let a=iE(o[1]);a!==void 0&&n.push(a)}}return n}var uE=[/\b(?:package|library|dependency)\s+`([^`\s]+)`/gi,/`([^`\s]+)`\s+(?:npm\s+)?(?:package|library|dependency)\b/gi];function fE(t){let e=[];for(let n of uE){let s=new RegExp(n.source,n.flags),i;for(;(i=s.exec(t))!==null;){let r=ph(i[1]);r!==void 0&&e.push(r)}}return e}var dE=/(?:^|[\s;&|(])(?:(?:npx|bunx|yarn|pnpm\s+(?:exec|dlx)|npm\s+exec)\s+)?(react-scripts|tslint|node-sass)(?=\s|$)/g;function pE(t){let e=/(?:^|\s)(?:#|\/\/|\/\*|--)\s*(.*)$/.exec(t);return e?e[1]:""}function hE(t){let e=[],{segments:n,prose:s}=nE(t),i=(r,o,a,c)=>{e.push({pkg:r,kind:o,file:t,line:a,text:c})};for(let r of n){if(qa.test(r.fenced?pE(r.lineText):r.lineText))continue;let o=r.text;if(!r.fenced||eE.has(r.lang)){for(let l of aE(o,r.afterCd))i(l,"install",r.line,r.lineText);let a=new RegExp(dE.source,"g"),c;for(;(c=a.exec(o))!==null;)Ka[c[1]]?.command&&i(c[1],"command",r.line,r.lineText)}if(!r.fenced||tE.has(r.lang)){let a=!r.fenced||r.lang==="";for(let c of lE(o,a))i(c,"import",r.line,r.lineText)}!r.fenced&&fh.test(o)&&Ka[o]?.distinctive&&i(o,"span",r.line,r.lineText)}for(let{line:r,text:o}of s)if(!qa.test(o))for(let a of fE(o))i(a,"qualified",r,o);return e}var oh=200,mh=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/worktrees/**","**/.worktrees/**","**/vendor/**","**/target/**","**/.turbo/**","**/coverage/**","**/Library/**","**/Temp/**"],mE=new Set(["vscode","k6"]),gE={jest:["vitest"],vitest:["jest"],"@playwright/test":["cypress"],cypress:["@playwright/test"]};function Ya(t,e){t.any=!0,e.name&&t.declared.add(e.name);for(let n of e.dependencies)t.declared.add(n);for(let[n,s]of Object.entries(e.versions??{}))t.specs.set(n,[...t.specs.get(n)??[],s]);e.dependencies.includes("next")&&t.nextDirs.push(e.dir),t.dirs.add(e.dir),e.dir!=="."&&t.localNames.add(Qt.posix.basename(e.dir)),e.name&&t.localNames.add(e.name.replace(/^@[^/]+\//,""))}function yE(t){let e={declared:new Set,specs:new Map,any:!1,dirs:new Set,nextDirs:[],localNames:new Set,aliasNames:new Set,aliasScopes:new Set,catalogs:{default:{},named:{}},truncated:t.workspacesTruncated===!0,lazyLoaded:!1},n=t.manifests.packageJson,s=(t.workspaces??[]).find(i=>i.dir===".");if(n!==void 0&&s===void 0){let{dependencies:i,devDependencies:r,peerDependencies:o}=t.packageJson,a=is(".",JSON.stringify({dependencies:i,devDependencies:r,peerDependencies:o}));a&&Ya(e,a)}for(let i of t.workspaces??[])Ya(e,i);return e}function Fi(t,e){try{let n=J(t,e);if(!n)return;let s=wt.statSync(n);return!s.isFile()||s.size>ce?void 0:wt.readFileSync(n,"utf-8")}catch{return}}function ah(t){let e="",n=!1;for(let s=0;s<t.length;s++){let i=t[s];if(n)e+=i,i==="\\"?e+=t[++s]??"":i==='"'&&(n=!1);else if(i==='"')n=!0,e+=i;else if(i==="/"&&t[s+1]==="/"){for(;s<t.length&&t[s]!==`
67
67
  `;)s++;e+=`
68
- `}else if(i==="/"&&t[s+1]==="*"){for(s+=2;s<t.length&&!(t[s]==="*"&&t[s+1]==="/");)s++;s++}else e+=i}try{return JSON.parse(e.replace(/,(\s*[}\]])/g,"$1"))}catch{return}}function pE(t,e){if(e.startsWith("@/")||e.startsWith("~")||e.startsWith("#")||e==="*")return;let n=e.replace(/\/?\*.*$/,"");n&&(n.startsWith("@")?n.includes("/")?t.aliasNames.add(n):t.aliasScopes.add(n):t.aliasNames.add(n.split("/")[0]))}function hE(t,e){for(let n of[...new Set([".",...e.dirs])]){let s=i=>n==="."?i:`${n}/${i}`;for(let i of["tsconfig.json","jsconfig.json"]){let r=Mi(t.repoRoot,s(i)),o=r===void 0?void 0:nh(r);for(let a of Object.keys(o?.compilerOptions?.paths??{}))pE(e,a)}for(let i of["deno.json","deno.jsonc"]){let r=Mi(t.repoRoot,s(i)),o=r===void 0?void 0:nh(r);for(let a of Object.keys(o?.imports??{}))e.declared.add(a.replace(/\/$/,""))}}}var sh=/^\s+(['"]?)(@?[^'":\s]+(?:\/[^'":\s]+)?)\1\s*:\s*['"]?([^'"#\s]+)['"]?/;function mE(t){let e={default:{},named:{}},n=null,s=null;for(let i of t.split(/\r?\n/))if(!/^\s*(?:#.*)?$/.test(i)){if(/^catalog:\s*(?:#.*)?$/.test(i)){n="catalog";continue}if(/^catalogs:\s*(?:#.*)?$/.test(i)){n="catalogs",s=null;continue}if(/^\S/.test(i)){n=null;continue}if(n==="catalog"){let r=sh.exec(i);r&&(e.default[r[2]]=r[3])}else if(n==="catalogs"){let r=/^ {1,3}(['"]?)([^'":\s]+)\1\s*:\s*(?:#.*)?$/.exec(i);if(r){s=r[2],e.named[s]??={};continue}let o=sh.exec(i);o&&s&&(e.named[s][o[2]]=o[3])}}return e}function gE(t,e,n){if(!n.startsWith("catalog:"))return n;let s=n.slice(8).trim();return s===""||s==="default"?t.catalogs.default[e]:t.catalogs.named[s]?.[e]}function Di(t,e){if(e.lazyLoaded)return;e.lazyLoaded=!0;let n=t.exclude??[],s=[];try{s=Ka.default.sync(["**/package.json"],{cwd:t.repoRoot,ignore:uh,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{e.truncated=!0}s=s.filter(r=>!us(r,n)&&!e.dirs.has(Qt.posix.dirname(r))).sort(),s.length>th&&(e.truncated=!0);for(let r of s.slice(0,th)){let o=Mi(t.repoRoot,r),a=o===void 0?void 0:is(Qt.posix.dirname(r),o);a&&za(e,a)}hE(t,e);let i=Mi(t.repoRoot,"pnpm-workspace.yaml");i!==void 0&&(e.catalogs=mE(i))}function qa(t){return t.startsWith("@")?t.slice(0,t.indexOf("/")):void 0}function yE(t){let e=t.trim();if(/^(?:workspace|catalog|link|file|git|github|http|https|npm):/.test(e)||e.startsWith("<"))return null;let n=/^(?:\^|~|>=|>|=)?\s*v?(\d+)(?:[.x*]|\b)/.exec(e);return n?parseInt(n[1],10):null}function fh(t,e){let n=null;for(let s of e)for(let i of t.specs.get(s)??[]){let r=gE(t,s,i),o=r===void 0?null:yE(r);if(r===void 0||o===null)return null;(n===null||o<n.major)&&(n={major:o,spec:r})}return n}function ds(t,e){let n=rh.createHash("sha1").update(`dep-staleness:${t}:${e}`).digest("hex").slice(0,12);return`dep-staleness-${t}-${n}`}function ps(t){let e=new Set,n=[];for(let s of t)e.has(s.file.path)||(e.add(s.file.path),n.push(s));return n}function hs(t){return t.map(e=>({filePath:e.file.path,startLine:e.line,endLine:e.line}))}function ms(t){return`${t.file.relativePath??Qt.basename(t.file.path)}:${t.line}: "${q(t.text,100)}"`}function bE(t){let e=qa(t);return e!==void 0?zS.has(e.slice(1)):US.has(t)||VS.test(t)}function Ya(t,...e){return K(t,Qt.posix.join(...e))}function wE(t,...e){let n=Ya(t,...e);if(n===null)return!1;try{return wt.existsSync(n)}catch{return!1}}function vE(t,e,n){for(let s of new Set([".",...e.dirs]))for(let i of[".","src"])if(wE(t,s,i,n))return!0;return!1}function xE(t){return t.startsWith("@")?`@types/${t.slice(1).replace("/","__")}`:`@types/${t}`}function _E(t,e,n){let s=new Map;for(let o of e)for(let a of lE(o))s.set(a.pkg,[...s.get(a.pkg)??[],a]);if(s.size===0)return[];let i=[],r=o=>{let a=c=>n.declared.has(c)||n.declared.has(xE(c));return a(o)?!0:(Di(t,n),a(o)||Cn(t,o))};for(let[o,a]of[...s].sort(([c],[l])=>c.localeCompare(l))){let c=o.startsWith("@")?o:o.split("/")[0];if(WS.has(c)||GS.has(c)||uE.has(c)||bE(o))continue;let l=Va[o];if(l){let h=r(o),m=h||n.truncated?"info":"warning",g=ps(a);i.push({id:ds("deprecated",o),severity:m,category:"stale_instruction",title:`Instructions point at a deprecated package: ${o}`,summary:`Instruction files mention \`${o}\`, which ${l.status}. `+(h?"A package.json in this repo still declares it, so an agent will keep extending the old dependency. ":"No package.json in this repo declares it, so an agent following the instructions would add a deprecated dependency. ")+`Consider ${l.replacement} instead, or confirm the repo intends to keep using it.`,filePaths:g.map(b=>b.file.path),locations:hs(g),evidence:[...g.slice(0,3).map(ms),h?`${o} is declared in a package.json`:`${o} is not declared in any package.json`],recommendation:`Update the instructions to recommend ${l.replacement}${h?", and plan the dependency migration":""}; if the repo deliberately keeps ${o}, note why.`,confidence:.7});continue}let u=a.filter(h=>h.kind==="install"||h.kind==="import");if(u.length===0||r(o)||n.truncated||fE[o]?.some(h=>r(h)))continue;let f=qa(o),d=u.some(h=>h.kind==="install");if(!d&&(f===void 0&&(qS.has(o)||vE(t.repoRoot,n,o))||n.aliasNames.has(o)||f!==void 0&&n.aliasScopes.has(f)||n.localNames.has(o)||f!==void 0&&![...n.declared].some(h=>qa(h)===f)))continue;let p=ps(u);i.push({id:ds("missing-package",o),severity:d?"warning":"info",category:"stale_instruction",title:`Package named in instructions is not in any package.json: ${o}`,summary:`Instruction files refer to the npm package \`${o}\`, but no package.json in this repo declares it. It may have been removed or renamed since the instructions were written. Treat this as a prompt to check, not a certainty: it may be an optional or external tool.`,filePaths:p.map(h=>h.file.path),locations:hs(p),evidence:[...p.slice(0,3).map(ms),`${o} is not declared in any package.json`],recommendation:`Remove or update the mention of ${o}, or add it to package.json if the repo really depends on it.`,confidence:.5})}return i}var Ga=/\b(?:before|old(?:er)?|previously|legacy|prior|outdated|anti-?patterns?|bad|wrong)\b|❌/i,SE=/^\s{0,3}#{1,6}\s/;function Ja(t,e,n,s){let i=[];for(let r of t){let o=xe(r.content),a=[],c=[""],l=[""],u=[],f=0,d=-1;o.forEach((h,m)=>{h.kind==="text"&&SE.test(h.text)&&(f++,c[f]="",l[f]=h.text),h.kind==="open"&&(d=m),u[m]=h.inFence?d:-1,a[m]=f,c[f]+=`${h.text}
69
- `});let p=h=>{for(let m=(u[h]>=0?u[h]:h)-1;m>=0;m--)if(o[m].text.trim()!=="")return o[m].text;return""};o.forEach((h,m)=>{if(h.kind==="open"||h.kind==="close"||h.inFence&&(h.lang==="diff"||h.lang==="patch"))return;let g=h.text.replace(/\r$/,"");!e.test(g)||Ua.test(g)||n.test(g)||s.test(c[a[m]])||Ga.test(g)||Ga.test(l[a[m]])||Ga.test(p(m))||i.push({file:r,line:h.lineNumber,text:g})})}return i}var EE=/\bReactDOM\.render\b/,kE=/\bReact\s*(?:v\.?\s*)?(?:0|1[0-7])\b/i,RE=/\b(?:createRoot|hydrateRoot)\b/;function CE(t,e,n){let s=ps(Ja(e,EE,kE,RE));if(s.length===0)return[];Di(t,n);let i=fh(n,["react","react-dom"]);if(i===null||i.major<18)return[];let r=i.major>=19;return[{id:ds("react-dom-render","ReactDOM.render"),severity:r?"high":"warning",category:"stale_instruction",title:r?"Instructions use ReactDOM.render, which React 19 removed":"Instructions use ReactDOM.render, which is the legacy React 17 root API",summary:`Instruction files mention \`ReactDOM.render\`, but package.json declares React ${i.spec}. `+(r?"`ReactDOM.render` was removed in React 19, so code an agent writes from this guidance will fail.":"In React 18 it still runs but only in legacy mode (with a console warning) and without concurrent features.")+" Use `createRoot` from `react-dom/client` instead.",filePaths:s.map(o=>o.file.path),locations:hs(s),evidence:[...s.slice(0,3).map(ms),`package.json declares react ${i.spec}`],recommendation:"Replace the `ReactDOM.render(...)` guidance with `createRoot(container).render(...)` from `react-dom/client`.",confidence:.8}]}var AE=/\bgetInitialProps\b/,$E=/\bpages\s*(?:router|dir(?:ectory)?)\b|\bpages\//i,PE=/\bServer Components?\b|\broute handlers?\b|\bapp\s+router\b/i,TE=/^(?:layout|page)\.(?:tsx|ts|jsx|js|mdx)$/;function IE(t,e){for(let n of["app","src/app"])try{let s=Ya(t,e,n);if(s!==null&&wt.readdirSync(s).some(i=>TE.test(i)))return!0}catch{}return!1}function OE(t,e){for(let n of["pages","src/pages"])try{let s=Ya(t,e,n);if(s!==null&&wt.statSync(s).isDirectory())return!0}catch{}return!1}function LE(t,e,n){let s=ps(Ja(e,AE,$E,PE));if(s.length===0)return[];Di(t,n);let i=n.nextDirs;return i.length===0?[]:i.some(r=>OE(t.repoRoot,r))?[]:i.some(r=>IE(t.repoRoot,r))?[{id:ds("get-initial-props","getInitialProps"),severity:"warning",category:"stale_instruction",title:"Instructions use getInitialProps in a Next.js app-router project",summary:"Instruction files mention `getInitialProps`, but this project uses the Next.js `app/` router (and has no `pages/` directory). `getInitialProps` only applies to the pages router, so an agent following this guidance would write data fetching that never runs.",filePaths:s.map(r=>r.file.path),locations:hs(s),evidence:[...s.slice(0,3).map(ms),"an app/ directory with layout/page files exists; no pages/ directory"],recommendation:"Describe data fetching with Server Components (async components, `fetch`) or route handlers instead, or scope the `getInitialProps` note to the pages router.",confidence:.65}]:[]}var NE=/\bNgModules?\b/,ih=/\bstandalone\b/i;function jE(t){try{return Ka.default.sync(["**/*.module.ts"],{cwd:t,ignore:uh,deep:8,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0}).some(n=>K(t,n)!==null)}catch{return!0}}function ME(t,e,n){let s=ps(Ja(e,NE,ih,ih));if(s.length===0)return[];Di(t,n);let i=fh(n,["@angular/core"]);return i===null||i.major<17?[]:jE(t.repoRoot)?[]:[{id:ds("ngmodule","NgModule"),severity:"info",category:"stale_instruction",title:"Instructions are NgModule-centric in an Angular 17+ project with no modules",summary:`Instruction files describe NgModules, but package.json declares @angular/core ${i.spec} and the repo has no \`*.module.ts\` files. New Angular projects use standalone components, so an agent following this guidance may scaffold NgModules the project does not use.`,filePaths:s.map(r=>r.file.path),locations:hs(s),evidence:[...s.slice(0,3).map(ms),`package.json declares @angular/core ${i.spec}; no *.module.ts files`],recommendation:"Describe standalone components (`standalone: true`, `bootstrapApplication`) instead of NgModules.",confidence:.6}]}function Xa(t){let e=t.files.filter(s=>Ce.has(s.fileType));if(e.length===0)return[];let n=dE(t);return n.any?[..._E(t,e,n),...CE(t,e,n),...LE(t,e,n),...ME(t,e,n)].sort((s,i)=>s.id.localeCompare(i.id)):[]}var ph=x(require("node:crypto"),1),hh=x(require("node:path"),1),DE=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,FE=/^[\w.-]+\/[\w.-]+(?:\/[\w./-]+)?$/,HE=/^[\w./+-]+$/,BE=new Set(["actions","github"]),WE=/^(\s*)(-\s+)?([\w.-]+)\s*:(?:\s+(.*))?$/,GE=/^\s*-\s+(\{.*)$/,UE=/^[|>][+-]?\d*\s*(?:#.*)?$/,VE=new Set(["with","env","secrets","inputs","outputs"]);function mh(t){let e=t.trim(),n=e[0];if(n==='"'||n==="'"){let i=e.indexOf(n,1);return i>0?e.slice(1,i):e.slice(1)}let s=e.search(/(?:^|\s)#/);return s>=0&&(e=e.slice(0,s)),e.trim()}function zE(t){let e=[],n=0,s="",i="";for(let r of t){if(s){r===s&&(s=""),n===1&&(i+=r);continue}if(r==='"'||r==="'"){s=r,n===1&&(i+=r);continue}if(r==="{"||r==="["){n++,n>1&&(i+=r);continue}if(r==="}"||r==="]"){if(n--,n===0)break;i+=r;continue}if(r===","&&n===1){e.push(i),i="";continue}n>=1&&(i+=r)}e.push(i);for(let r of e){let o=/^\s*uses\s*:\s*(.*)$/.exec(r);if(o)return mh(o[1])}}function gh(t){let e=t.split(/\r?\n/),n=[],s=-1;for(let i=0;i<e.length;i++){let r=e[i];if(r.trim()==="")continue;let o=/^\s*/.exec(r)[0].length;if(s>=0){if(o>s)continue;s=-1}if(/^\s*#/.test(r))continue;let a=GE.exec(r);if(a){let p=zE(a[1]);p&&n.push({ref:p,line:i+1});continue}let c=WE.exec(r);if(!c)continue;let l=c[1].length+(c[2]?.length??0),u=c[3],f=c[4]??"",d=f.trim();if(u==="uses"){let p=mh(f);p&&n.push({ref:p,line:i+1});continue}if(UE.test(d)){s=l;continue}(d===""||d.startsWith("#"))&&VE.has(u)&&(s=l)}return n}function qE(t){let{ref:e}=t;if(e.startsWith("./")||e.startsWith(".\\")||e.startsWith("docker://")||e.includes("${{"))return;let n=e.lastIndexOf("@");if(n<=0||!e.slice(0,n).includes("/"))return;let s=e.slice(0,n),i=e.slice(n+1);if(DE.test(i))return;let r=FE.test(s)&&HE.test(i);return{...t,displayable:r,action:s,version:i,owner:r?s.split("/")[0].toLowerCase():""}}function dh(t){return ph.createHash("sha1").update(t).digest("hex").slice(0,12)}function gs(t){return t.replace(/`/g,"'")}function KE(t,e){let{filePath:n,lines:s,use:i}=e,r=hh.resolve(t.repoRoot,n),o={id:`action-pin-${dh(`action-pin:${n}:${i.ref}`)}`,category:"security",filePaths:[r],locations:s.map(d=>({filePath:r,startLine:d,endLine:d})),confidence:.8,tags:["supply-chain","github-actions"]},a="A tag or branch is a mutable pointer: whoever can push to the action's repository can move it, and the next run executes the new code with this repository's token and secrets.";if(!i.displayable)return{...o,severity:"warning",title:"GitHub Action reference is not pinned to a commit SHA",summary:`${n} has a \`uses:\` reference (line ${s.join(", ")}) that is not pinned to a full commit SHA and does not look like a plain \`owner/repo@ref\` value. ${a}`,evidence:[`${n}: unrecognised uses: value (sha1 ${dh(i.ref)})`],recommendation:"Review this `uses:` line by hand. Pin the action to the full 40-character commit SHA of a release you trust (resolved from the action's own repository), keep the version in a trailing comment, and let Dependabot or Renovate update both. PromptCI reports this but does not rewrite workflow files."};let c=BE.has(i.owner),[l,u]=i.action.split("/"),f=gs(i.ref);return{...o,severity:c?"info":"warning",title:`GitHub Action \`${f}\` is not pinned to a commit SHA`,summary:`${n} references \`${gs(i.action)}\` at \`${gs(i.version)}\`, which appears to be a tag or branch rather than a full commit SHA. ${a} `+(c?"This action is maintained by GitHub, which lowers but does not remove the risk.":"Consider pinning third-party actions to a reviewed commit."),evidence:[`${n}: uses: ${f}`],recommendation:`Pin the action to the full commit SHA of the release you trust and keep the version in a trailing comment, e.g. \`uses: ${gs(i.action)}@<40-char-sha> # ${gs(i.version)}\`. Resolve the SHA from the action's own repository (\`gh api repos/${l}/${u}/commits/${i.version} --jq .sha\`), and let Dependabot or Renovate update the SHA and comment together. PromptCI reports this but does not rewrite workflow files.`}}function Za(t){let e=t.workflows.sources??[],n=new Map;for(let s of e)for(let i of gh(s.content)){let r=qE(i);if(!r)continue;let o=`${s.filePath}\0${r.ref}`,a=n.get(o)??{filePath:s.filePath,lines:[],use:r};a.lines.push(r.line),n.set(o,a)}return[...n.keys()].sort().map(s=>KE(t,n.get(s)))}var Qa=x(require("node:crypto"),1),en=x(require("node:path"),1);var YE=[/canonical\s+(?:source\s+of\s+truth|instruction|guidance)/i,/authoritative\s+(?:source|instruction|guidance)/i,/primary\s+(?:source\s+of\s+truth|instruction|guidance)/i,/source\s+of\s+truth\s+for\s+all\s+agents/i,/master\s+instruction\s+file/i],JE=/\b(AGENTS|CLAUDE)\.md\b/gi;function XE(t){let e=en.basename(t.path).toLowerCase();for(let n of YE)for(let s of t.content.matchAll(new RegExp(n.source,"gi"))){let i=t.content.lastIndexOf(`
68
+ `}else if(i==="/"&&t[s+1]==="*"){for(s+=2;s<t.length&&!(t[s]==="*"&&t[s+1]==="/");)s++;s++}else e+=i}try{return JSON.parse(e.replace(/,(\s*[}\]])/g,"$1"))}catch{return}}function bE(t,e){if(e.startsWith("@/")||e.startsWith("~")||e.startsWith("#")||e==="*")return;let n=e.replace(/\/?\*.*$/,"");n&&(n.startsWith("@")?n.includes("/")?t.aliasNames.add(n):t.aliasScopes.add(n):t.aliasNames.add(n.split("/")[0]))}function wE(t,e){for(let n of[...new Set([".",...e.dirs])]){let s=i=>n==="."?i:`${n}/${i}`;for(let i of["tsconfig.json","jsconfig.json"]){let r=Fi(t.repoRoot,s(i)),o=r===void 0?void 0:ah(r);for(let a of Object.keys(o?.compilerOptions?.paths??{}))bE(e,a)}for(let i of["deno.json","deno.jsonc"]){let r=Fi(t.repoRoot,s(i)),o=r===void 0?void 0:ah(r);for(let a of Object.keys(o?.imports??{}))e.declared.add(a.replace(/\/$/,""))}}}var ch=/^\s+(['"]?)(@?[^'":\s]+(?:\/[^'":\s]+)?)\1\s*:\s*['"]?([^'"#\s]+)['"]?/;function vE(t){let e={default:{},named:{}},n=null,s=null;for(let i of t.split(/\r?\n/))if(!/^\s*(?:#.*)?$/.test(i)){if(/^catalog:\s*(?:#.*)?$/.test(i)){n="catalog";continue}if(/^catalogs:\s*(?:#.*)?$/.test(i)){n="catalogs",s=null;continue}if(/^\S/.test(i)){n=null;continue}if(n==="catalog"){let r=ch.exec(i);r&&(e.default[r[2]]=r[3])}else if(n==="catalogs"){let r=/^ {1,3}(['"]?)([^'":\s]+)\1\s*:\s*(?:#.*)?$/.exec(i);if(r){s=r[2],e.named[s]??={};continue}let o=ch.exec(i);o&&s&&(e.named[s][o[2]]=o[3])}}return e}function xE(t,e,n){if(!n.startsWith("catalog:"))return n;let s=n.slice(8).trim();return s===""||s==="default"?t.catalogs.default[e]:t.catalogs.named[s]?.[e]}function Hi(t,e){if(e.lazyLoaded)return;e.lazyLoaded=!0;let n=t.exclude??[],s=[];try{s=Xa.default.sync(["**/package.json"],{cwd:t.repoRoot,ignore:mh,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{e.truncated=!0}s=s.filter(r=>!us(r,n)&&!e.dirs.has(Qt.posix.dirname(r))).sort(),s.length>oh&&(e.truncated=!0);for(let r of s.slice(0,oh)){let o=Fi(t.repoRoot,r),a=o===void 0?void 0:is(Qt.posix.dirname(r),o);a&&Ya(e,a)}wE(t,e);let i=Fi(t.repoRoot,"pnpm-workspace.yaml");i!==void 0&&(e.catalogs=vE(i))}function Ja(t){return t.startsWith("@")?t.slice(0,t.indexOf("/")):void 0}function SE(t){let e=t.trim();if(/^(?:workspace|catalog|link|file|git|github|http|https|npm):/.test(e)||e.startsWith("<"))return null;let n=/^(?:\^|~|>=|>|=)?\s*v?(\d+)(?:[.x*]|\b)/.exec(e);return n?parseInt(n[1],10):null}function gh(t,e){let n=null;for(let s of e)for(let i of t.specs.get(s)??[]){let r=xE(t,s,i),o=r===void 0?null:SE(r);if(r===void 0||o===null)return null;(n===null||o<n.major)&&(n={major:o,spec:r})}return n}function ds(t,e){let n=uh.createHash("sha1").update(`dep-staleness:${t}:${e}`).digest("hex").slice(0,12);return`dep-staleness-${t}-${n}`}function ps(t){let e=new Set,n=[];for(let s of t)e.has(s.file.path)||(e.add(s.file.path),n.push(s));return n}function hs(t){return t.map(e=>({filePath:e.file.path,startLine:e.line,endLine:e.line}))}function ms(t){return`${t.file.relativePath??Qt.basename(t.file.path)}:${t.line}: "${Y(t.text,100)}"`}function _E(t){let e=Ja(t);return e!==void 0?X_.has(e.slice(1)):Y_.has(t)||J_.test(t)}function Za(t,...e){return J(t,Qt.posix.join(...e))}function EE(t,...e){let n=Za(t,...e);if(n===null)return!1;try{return wt.existsSync(n)}catch{return!1}}function kE(t,e,n){for(let s of new Set([".",...e.dirs]))for(let i of[".","src"])if(EE(t,s,i,n))return!0;return!1}function RE(t){return t.startsWith("@")?`@types/${t.slice(1).replace("/","__")}`:`@types/${t}`}function CE(t,e,n){let s=new Map;for(let o of e)for(let a of hE(o))s.set(a.pkg,[...s.get(a.pkg)??[],a]);if(s.size===0)return[];let i=[],r=o=>{let a=c=>n.declared.has(c)||n.declared.has(RE(c));return a(o)?!0:(Hi(t,n),a(o)||Cn(t,o))};for(let[o,a]of[...s].sort(([c],[l])=>c.localeCompare(l))){let c=o.startsWith("@")?o:o.split("/")[0];if(q_.has(c)||K_.has(c)||mE.has(c)||_E(o))continue;let l=Ka[o];if(l){let h=r(o),m=h||n.truncated?"info":"warning",g=ps(a);i.push({id:ds("deprecated",o),severity:m,category:"stale_instruction",title:`Instructions point at a deprecated package: ${o}`,summary:`Instruction files mention \`${o}\`, which ${l.status}. `+(h?"A package.json in this repo still declares it, so an agent will keep extending the old dependency. ":"No package.json in this repo declares it, so an agent following the instructions would add a deprecated dependency. ")+`Consider ${l.replacement} instead, or confirm the repo intends to keep using it.`,filePaths:g.map(b=>b.file.path),locations:hs(g),evidence:[...g.slice(0,3).map(ms),h?`${o} is declared in a package.json`:`${o} is not declared in any package.json`],recommendation:`Update the instructions to recommend ${l.replacement}${h?", and plan the dependency migration":""}; if the repo deliberately keeps ${o}, note why.`,confidence:.7});continue}let u=a.filter(h=>h.kind==="install"||h.kind==="import");if(u.length===0||r(o)||n.truncated||gE[o]?.some(h=>r(h)))continue;let f=Ja(o),d=u.some(h=>h.kind==="install");if(!d&&(f===void 0&&(Z_.has(o)||kE(t.repoRoot,n,o))||n.aliasNames.has(o)||f!==void 0&&n.aliasScopes.has(f)||n.localNames.has(o)||f!==void 0&&![...n.declared].some(h=>Ja(h)===f)))continue;let p=ps(u);i.push({id:ds("missing-package",o),severity:d?"warning":"info",category:"stale_instruction",title:`Package named in instructions is not in any package.json: ${o}`,summary:`Instruction files refer to the npm package \`${o}\`, but no package.json in this repo declares it. It may have been removed or renamed since the instructions were written. Treat this as a prompt to check, not a certainty: it may be an optional or external tool.`,filePaths:p.map(h=>h.file.path),locations:hs(p),evidence:[...p.slice(0,3).map(ms),`${o} is not declared in any package.json`],recommendation:`Remove or update the mention of ${o}, or add it to package.json if the repo really depends on it.`,confidence:.5})}return i}var za=/\b(?:before|old(?:er)?|previously|legacy|prior|outdated|anti-?patterns?|bad|wrong)\b|❌/i,AE=/^\s{0,3}#{1,6}\s/;function Qa(t,e,n,s){let i=[];for(let r of t){let o=xe(r.content),a=[],c=[""],l=[""],u=[],f=0,d=-1;o.forEach((h,m)=>{h.kind==="text"&&AE.test(h.text)&&(f++,c[f]="",l[f]=h.text),h.kind==="open"&&(d=m),u[m]=h.inFence?d:-1,a[m]=f,c[f]+=`${h.text}
69
+ `});let p=h=>{for(let m=(u[h]>=0?u[h]:h)-1;m>=0;m--)if(o[m].text.trim()!=="")return o[m].text;return""};o.forEach((h,m)=>{if(h.kind==="open"||h.kind==="close"||h.inFence&&(h.lang==="diff"||h.lang==="patch"))return;let g=h.text.replace(/\r$/,"");!e.test(g)||qa.test(g)||n.test(g)||s.test(c[a[m]])||za.test(g)||za.test(l[a[m]])||za.test(p(m))||i.push({file:r,line:h.lineNumber,text:g})})}return i}var $E=/\bReactDOM\.render\b/,PE=/\bReact\s*(?:v\.?\s*)?(?:0|1[0-7])\b/i,TE=/\b(?:createRoot|hydrateRoot)\b/;function IE(t,e,n){let s=ps(Qa(e,$E,PE,TE));if(s.length===0)return[];Hi(t,n);let i=gh(n,["react","react-dom"]);if(i===null||i.major<18)return[];let r=i.major>=19;return[{id:ds("react-dom-render","ReactDOM.render"),severity:r?"high":"warning",category:"stale_instruction",title:r?"Instructions use ReactDOM.render, which React 19 removed":"Instructions use ReactDOM.render, which is the legacy React 17 root API",summary:`Instruction files mention \`ReactDOM.render\`, but package.json declares React ${i.spec}. `+(r?"`ReactDOM.render` was removed in React 19, so code an agent writes from this guidance will fail.":"In React 18 it still runs but only in legacy mode (with a console warning) and without concurrent features.")+" Use `createRoot` from `react-dom/client` instead.",filePaths:s.map(o=>o.file.path),locations:hs(s),evidence:[...s.slice(0,3).map(ms),`package.json declares react ${i.spec}`],recommendation:"Replace the `ReactDOM.render(...)` guidance with `createRoot(container).render(...)` from `react-dom/client`.",confidence:.8}]}var OE=/\bgetInitialProps\b/,LE=/\bpages\s*(?:router|dir(?:ectory)?)\b|\bpages\//i,NE=/\bServer Components?\b|\broute handlers?\b|\bapp\s+router\b/i,jE=/^(?:layout|page)\.(?:tsx|ts|jsx|js|mdx)$/;function ME(t,e){for(let n of["app","src/app"])try{let s=Za(t,e,n);if(s!==null&&wt.readdirSync(s).some(i=>jE.test(i)))return!0}catch{}return!1}function DE(t,e){for(let n of["pages","src/pages"])try{let s=Za(t,e,n);if(s!==null&&wt.statSync(s).isDirectory())return!0}catch{}return!1}function FE(t,e,n){let s=ps(Qa(e,OE,LE,NE));if(s.length===0)return[];Hi(t,n);let i=n.nextDirs;return i.length===0?[]:i.some(r=>DE(t.repoRoot,r))?[]:i.some(r=>ME(t.repoRoot,r))?[{id:ds("get-initial-props","getInitialProps"),severity:"warning",category:"stale_instruction",title:"Instructions use getInitialProps in a Next.js app-router project",summary:"Instruction files mention `getInitialProps`, but this project uses the Next.js `app/` router (and has no `pages/` directory). `getInitialProps` only applies to the pages router, so an agent following this guidance would write data fetching that never runs.",filePaths:s.map(r=>r.file.path),locations:hs(s),evidence:[...s.slice(0,3).map(ms),"an app/ directory with layout/page files exists; no pages/ directory"],recommendation:"Describe data fetching with Server Components (async components, `fetch`) or route handlers instead, or scope the `getInitialProps` note to the pages router.",confidence:.65}]:[]}var HE=/\bNgModules?\b/,lh=/\bstandalone\b/i;function BE(t){try{return Xa.default.sync(["**/*.module.ts"],{cwd:t,ignore:mh,deep:8,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0}).some(n=>J(t,n)!==null)}catch{return!0}}function WE(t,e,n){let s=ps(Qa(e,HE,lh,lh));if(s.length===0)return[];Hi(t,n);let i=gh(n,["@angular/core"]);return i===null||i.major<17?[]:BE(t.repoRoot)?[]:[{id:ds("ngmodule","NgModule"),severity:"info",category:"stale_instruction",title:"Instructions are NgModule-centric in an Angular 17+ project with no modules",summary:`Instruction files describe NgModules, but package.json declares @angular/core ${i.spec} and the repo has no \`*.module.ts\` files. New Angular projects use standalone components, so an agent following this guidance may scaffold NgModules the project does not use.`,filePaths:s.map(r=>r.file.path),locations:hs(s),evidence:[...s.slice(0,3).map(ms),`package.json declares @angular/core ${i.spec}; no *.module.ts files`],recommendation:"Describe standalone components (`standalone: true`, `bootstrapApplication`) instead of NgModules.",confidence:.6}]}function ec(t){let e=t.files.filter(s=>Ce.has(s.fileType));if(e.length===0)return[];let n=yE(t);return n.any?[...CE(t,e,n),...IE(t,e,n),...FE(t,e,n),...WE(t,e,n)].sort((s,i)=>s.id.localeCompare(i.id)):[]}var bh=x(require("node:crypto"),1),wh=x(require("node:path"),1),GE=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,UE=/^[\w.-]+\/[\w.-]+(?:\/[\w./-]+)?$/,VE=/^[\w./+-]+$/,zE=new Set(["actions","github"]),qE=/^(\s*)(-\s+)?([\w.-]+)\s*:(?:\s+(.*))?$/,KE=/^\s*-\s+(\{.*)$/,YE=/^[|>][+-]?\d*\s*(?:#.*)?$/,JE=new Set(["with","env","secrets","inputs","outputs"]);function vh(t){let e=t.trim(),n=e[0];if(n==='"'||n==="'"){let i=e.indexOf(n,1);return i>0?e.slice(1,i):e.slice(1)}let s=e.search(/(?:^|\s)#/);return s>=0&&(e=e.slice(0,s)),e.trim()}function XE(t){let e=[],n=0,s="",i="";for(let r of t){if(s){r===s&&(s=""),n===1&&(i+=r);continue}if(r==='"'||r==="'"){s=r,n===1&&(i+=r);continue}if(r==="{"||r==="["){n++,n>1&&(i+=r);continue}if(r==="}"||r==="]"){if(n--,n===0)break;i+=r;continue}if(r===","&&n===1){e.push(i),i="";continue}n>=1&&(i+=r)}e.push(i);for(let r of e){let o=/^\s*uses\s*:\s*(.*)$/.exec(r);if(o)return vh(o[1])}}function xh(t){let e=t.split(/\r?\n/),n=[],s=-1;for(let i=0;i<e.length;i++){let r=e[i];if(r.trim()==="")continue;let o=/^\s*/.exec(r)[0].length;if(s>=0){if(o>s)continue;s=-1}if(/^\s*#/.test(r))continue;let a=KE.exec(r);if(a){let p=XE(a[1]);p&&n.push({ref:p,line:i+1});continue}let c=qE.exec(r);if(!c)continue;let l=c[1].length+(c[2]?.length??0),u=c[3],f=c[4]??"",d=f.trim();if(u==="uses"){let p=vh(f);p&&n.push({ref:p,line:i+1});continue}if(YE.test(d)){s=l;continue}(d===""||d.startsWith("#"))&&JE.has(u)&&(s=l)}return n}function ZE(t){let{ref:e}=t;if(e.startsWith("./")||e.startsWith(".\\")||e.startsWith("docker://")||e.includes("${{"))return;let n=e.lastIndexOf("@");if(n<=0||!e.slice(0,n).includes("/"))return;let s=e.slice(0,n),i=e.slice(n+1);if(GE.test(i))return;let r=UE.test(s)&&VE.test(i);return{...t,displayable:r,action:s,version:i,owner:r?s.split("/")[0].toLowerCase():""}}function yh(t){return bh.createHash("sha1").update(t).digest("hex").slice(0,12)}function gs(t){return t.replace(/`/g,"'")}function QE(t,e){let{filePath:n,lines:s,use:i}=e,r=wh.resolve(t.repoRoot,n),o={id:`action-pin-${yh(`action-pin:${n}:${i.ref}`)}`,category:"security",filePaths:[r],locations:s.map(d=>({filePath:r,startLine:d,endLine:d})),confidence:.8,tags:["supply-chain","github-actions"]},a="A tag or branch is a mutable pointer: whoever can push to the action's repository can move it, and the next run executes the new code with this repository's token and secrets.";if(!i.displayable)return{...o,severity:"warning",title:"GitHub Action reference is not pinned to a commit SHA",summary:`${n} has a \`uses:\` reference (line ${s.join(", ")}) that is not pinned to a full commit SHA and does not look like a plain \`owner/repo@ref\` value. ${a}`,evidence:[`${n}: unrecognised uses: value (sha1 ${yh(i.ref)})`],recommendation:"Review this `uses:` line by hand. Pin the action to the full 40-character commit SHA of a release you trust (resolved from the action's own repository), keep the version in a trailing comment, and let Dependabot or Renovate update both. PromptCI reports this but does not rewrite workflow files."};let c=zE.has(i.owner),[l,u]=i.action.split("/"),f=gs(i.ref);return{...o,severity:c?"info":"warning",title:`GitHub Action \`${f}\` is not pinned to a commit SHA`,summary:`${n} references \`${gs(i.action)}\` at \`${gs(i.version)}\`, which appears to be a tag or branch rather than a full commit SHA. ${a} `+(c?"This action is maintained by GitHub, which lowers but does not remove the risk.":"Consider pinning third-party actions to a reviewed commit."),evidence:[`${n}: uses: ${f}`],recommendation:`Pin the action to the full commit SHA of the release you trust and keep the version in a trailing comment, e.g. \`uses: ${gs(i.action)}@<40-char-sha> # ${gs(i.version)}\`. Resolve the SHA from the action's own repository (\`gh api repos/${l}/${u}/commits/${i.version} --jq .sha\`), and let Dependabot or Renovate update the SHA and comment together. PromptCI reports this but does not rewrite workflow files.`}}function tc(t){let e=t.workflows.sources??[],n=new Map;for(let s of e)for(let i of xh(s.content)){let r=ZE(i);if(!r)continue;let o=`${s.filePath}\0${r.ref}`,a=n.get(o)??{filePath:s.filePath,lines:[],use:r};a.lines.push(r.line),n.set(o,a)}return[...n.keys()].sort().map(s=>QE(t,n.get(s)))}var nc=x(require("node:crypto"),1),en=x(require("node:path"),1);var ek=[/canonical\s+(?:source\s+of\s+truth|instruction|guidance)/i,/authoritative\s+(?:source|instruction|guidance)/i,/primary\s+(?:source\s+of\s+truth|instruction|guidance)/i,/source\s+of\s+truth\s+for\s+all\s+agents/i,/master\s+instruction\s+file/i],tk=/\b(AGENTS|CLAUDE)\.md\b/gi;function nk(t){let e=en.basename(t.path).toLowerCase();for(let n of ek)for(let s of t.content.matchAll(new RegExp(n.source,"gi"))){let i=t.content.lastIndexOf(`
70
70
  `,s.index)+1,r=t.content.indexOf(`
71
- `,s.index+s[0].length),a=[...t.content.slice(i,r===-1?void 0:r).matchAll(JE)].map(l=>`${l[1].toLowerCase()}.md`);if(!(a.length>0&&a.every(l=>l!==e)))return s[0]}}function yh(t){if(t.length===0)return[];let e=[],n=new Map;for(let a of t){let c=XE(a);c!==void 0&&n.set(a,c)}let s=[...n.keys()];function i(a){let c=Qa.createHash("sha1").update(a).digest("hex").slice(0,12);return`canonical-${a}-${c}`}s.length>1&&e.push({id:i("ambiguous-authority"),severity:"warning",category:"structure",title:"Ambiguous authority: multiple files claim to be canonical",summary:`Multiple files (${s.map(a=>en.basename(a.path)).join(", ")}) claim to be the "canonical" or "authoritative" source of truth. This leads to confusion about which instructions take precedence.`,filePaths:s.map(a=>a.path),locations:s.map(a=>({filePath:a.path})),evidence:s.map(a=>`${en.basename(a.path)}: "${q(n.get(a))}"`),recommendation:"Designate ONE file (usually AGENTS.md) as the canonical source. Other files should use forwarding pointers and only contain tool-specific reminders.",confidence:.9});let o=t.find(a=>en.basename(a.path).toLowerCase()==="agents.md")||s[0];if(o){let a=c=>{let l=c.split(`
71
+ `,s.index+s[0].length),a=[...t.content.slice(i,r===-1?void 0:r).matchAll(tk)].map(l=>`${l[1].toLowerCase()}.md`);if(!(a.length>0&&a.every(l=>l!==e)))return s[0]}}function Sh(t){if(t.length===0)return[];let e=[],n=new Map;for(let a of t){let c=nk(a);c!==void 0&&n.set(a,c)}let s=[...n.keys()];function i(a){let c=nc.createHash("sha1").update(a).digest("hex").slice(0,12);return`canonical-${a}-${c}`}s.length>1&&e.push({id:i("ambiguous-authority"),severity:"warning",category:"structure",title:"Ambiguous authority: multiple files claim to be canonical",summary:`Multiple files (${s.map(a=>en.basename(a.path)).join(", ")}) claim to be the "canonical" or "authoritative" source of truth. This leads to confusion about which instructions take precedence.`,filePaths:s.map(a=>a.path),locations:s.map(a=>({filePath:a.path})),evidence:s.map(a=>`${en.basename(a.path)}: "${Y(n.get(a))}"`),recommendation:"Designate ONE file (usually AGENTS.md) as the canonical source. Other files should use forwarding pointers and only contain tool-specific reminders.",confidence:.9});let o=t.find(a=>en.basename(a.path).toLowerCase()==="agents.md")||s[0];if(o){let a=c=>{let l=c.split(`
72
72
  `);return l.length>0&&l[0].trim().startsWith("#")?l.slice(1).join(`
73
- `).trim():c.trim()};for(let c of t){if(c===o)continue;let l=en.basename(c.path).toLowerCase();if((c.fileType==="claude"||c.fileType==="cursor"||c.fileType==="windsurf"||c.fileType==="copilot"||c.fileType==="gemini"||c.fileType==="cline"||l==="claude.md"||l===".cursorrules"||l===".windsurfrules")&&c.lineCount>50){for(let f of c.sections)if(f.endLine-f.startLine>50&&o.sections.some(p=>{let h=a(p.text).toLowerCase().replace(/\s+/g," ").trim(),m=a(f.text).toLowerCase().replace(/\s+/g," ").trim();return h===m||h.length>500&&h.slice(0,500)===m.slice(0,500)})){let p=Qa.createHash("sha1").update(`canonical-owner:behavior-duplication:${L(c)}`).digest("hex").slice(0,12),h=en.basename(o.path),m=Math.round(f.text.length/4);e.push({id:`behavior-duplication-${p}`,severity:"info",category:"duplicate",title:"Large duplicated behavior in tool-specific file",summary:`The ${l} contains a large section (> 50 lines) that appears to be duplicated from ${h}. This can lead to instruction drift.`,filePaths:[c.path,o.path],locations:[{filePath:c.path,startLine:f.startLine,endLine:f.endLine}],evidence:[`Section "${f.heading??"Untitled"}" is near-identical to one in ${h}`,`Duplicate size: ~${m} tokens`],recommendation:`Consider moving shared rules to ${h} and using a forwarding pointer (e.g., "Follow ${h}") to save ~${m} tokens per session.`,confidence:.8});break}}}}return e}var bh=x(require("node:crypto"),1);function ec(t){return`ci-align-${bh.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function tc(t){return t.split(/&&|\n/).map(e=>e.trim()).filter(Boolean)}function ZE(t){let e=t.toLowerCase(),n=/\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?(test|lint|build|typecheck|format)\b/.exec(e);return n?n[1]:/\bjest\b|\bvitest\b|\bmocha\b|\bplaywright\s+test\b/.test(e)?"test":/\beslint\b|\bprettier\s+--check\b/.test(e)?"lint":/\btsc\b/.test(e)&&/--noemit\b/i.test(e)?"typecheck":/\btsc\b/.test(e)&&!/--noemit\b/i.test(e)?"build":/\bprettier\s+--write\b/.test(e)?"format":null}function QE(t){let e=[];for(let n of tc(t)){let s=ZE(n);s&&!e.includes(s)&&e.push(s)}return e}var ek={lint:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?lint|eslint\b|run\s+lint|lint\s+the\s+code|linting)\b/i,typecheck:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?typecheck|tsc\b|type.?check|run\s+typecheck)\b/i,test:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?test|vitest\b|jest\b|run\s+(?:the\s+)?tests?|pnpm\s+test)\b/i,build:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?build|tsc\b(?!\s+--noemit)|run\s+(?:the\s+)?build)\b/i,format:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?format|prettier\b|run\s+format)\b/i};function tk(t,e){let n=ek[t];return e.some(s=>n.test(s.content))}function nk(t){let e=/\b(pnpm|npm|yarn|bun)\b/.exec(t.toLowerCase());return e?e[1]:null}function sk(t){let e=new Set;for(let n of t)for(let s of tc(n.command)){let i=nk(s);i&&e.add(i)}return e}var wh=new Set(["install","i","add","remove","uninstall","init","help","test","start","stop","restart","exec","dlx","run","workspace","workspaces"]),vh=new Set(["instead","of","packages","package","are","is","the","a","an","that","this","for","to","and","or","not","with","without","via","because","since","before","after","than","as","like","but","so"]);function ik(t){let e=/\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?([a-z0-9][a-z0-9:_-]*)\b/i.exec(t);if(!e)return null;let n=e[1].toLowerCase();return wh.has(n)||vh.has(n)?null:n}function rk(t){let{workflows:e,files:n}=t;if(e.files.length===0)return[];let s=new Map;for(let r of e.commands)for(let o of QE(r.command))s.has(o)||s.set(o,[]),s.get(o).push(r);let i=[];for(let[r,o]of s.entries()){if(tk(r,n))continue;let a=[...new Set(o.map(c=>c.filePath))];i.push({id:ec(`missing-ci-task:${r}`),severity:"warning",category:"missing_context",title:`CI runs \`${r}\` but no instruction file appears to include it`,summary:`The GitHub workflow${a.length>1?"s":""} (${a.join(", ")}) run \`${r}\`, but no instruction file appears to direct the agent to run this step locally. Agents that follow only the instruction files may skip \`${r}\` and miss failures before declaring work complete.`,filePaths:n.map(c=>c.path),locations:o.map(c=>({filePath:c.filePath,startLine:c.line})),evidence:o.map(c=>`CI command: \`${c.command}\` in ${c.filePath} (line ${c.line})`),recommendation:`Consider adding \`${r}\` to the verification loop in the relevant instruction file (e.g., AGENTS.md or CLAUDE.md) so agents run the same checks as CI.`,confidence:.8})}return i}function ok(t){let{workflows:e,files:n,packageJson:s}=t;if(e.files.length===0)return[];let i=sk(e.commands);if(i.size===0)return[];let r=s.packageManagerName!=="unknown"?s.packageManagerName:Array.from(i)[0];if(!i.has(r))return[];let o=[];for(let a of n)for(let c of["npm","pnpm","yarn","bun"]){if(c===r)continue;let l=new RegExp(`\\b${c}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),u,f=!1;for(;(u=l.exec(a.content))!==null;){let d=a.content.lastIndexOf(`
73
+ `).trim():c.trim()};for(let c of t){if(c===o)continue;let l=en.basename(c.path).toLowerCase();if((c.fileType==="claude"||c.fileType==="cursor"||c.fileType==="windsurf"||c.fileType==="copilot"||c.fileType==="gemini"||c.fileType==="cline"||l==="claude.md"||l===".cursorrules"||l===".windsurfrules")&&c.lineCount>50){for(let f of c.sections)if(f.endLine-f.startLine>50&&o.sections.some(p=>{let h=a(p.text).toLowerCase().replace(/\s+/g," ").trim(),m=a(f.text).toLowerCase().replace(/\s+/g," ").trim();return h===m||h.length>500&&h.slice(0,500)===m.slice(0,500)})){let p=nc.createHash("sha1").update(`canonical-owner:behavior-duplication:${L(c)}`).digest("hex").slice(0,12),h=en.basename(o.path),m=Math.round(f.text.length/4);e.push({id:`behavior-duplication-${p}`,severity:"info",category:"duplicate",title:"Large duplicated behavior in tool-specific file",summary:`The ${l} contains a large section (> 50 lines) that appears to be duplicated from ${h}. This can lead to instruction drift.`,filePaths:[c.path,o.path],locations:[{filePath:c.path,startLine:f.startLine,endLine:f.endLine}],evidence:[`Section "${f.heading??"Untitled"}" is near-identical to one in ${h}`,`Duplicate size: ~${m} tokens`],recommendation:`Consider moving shared rules to ${h} and using a forwarding pointer (e.g., "Follow ${h}") to save ~${m} tokens per session.`,confidence:.8});break}}}}return e}var _h=x(require("node:crypto"),1);function sc(t){return`ci-align-${_h.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function ic(t){return t.split(/&&|\n/).map(e=>e.trim()).filter(Boolean)}function sk(t){let e=t.toLowerCase(),n=/\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?(test|lint|build|typecheck|format)\b/.exec(e);return n?n[1]:/\bjest\b|\bvitest\b|\bmocha\b|\bplaywright\s+test\b/.test(e)?"test":/\beslint\b|\bprettier\s+--check\b/.test(e)?"lint":/\btsc\b/.test(e)&&/--noemit\b/i.test(e)?"typecheck":/\btsc\b/.test(e)&&!/--noemit\b/i.test(e)?"build":/\bprettier\s+--write\b/.test(e)?"format":null}function ik(t){let e=[];for(let n of ic(t)){let s=sk(n);s&&!e.includes(s)&&e.push(s)}return e}var rk={lint:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?lint|eslint\b|run\s+lint|lint\s+the\s+code|linting)\b/i,typecheck:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?typecheck|tsc\b|type.?check|run\s+typecheck)\b/i,test:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?test|vitest\b|jest\b|run\s+(?:the\s+)?tests?|pnpm\s+test)\b/i,build:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?build|tsc\b(?!\s+--noemit)|run\s+(?:the\s+)?build)\b/i,format:/\b(?:(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?format|prettier\b|run\s+format)\b/i};function ok(t,e){let n=rk[t];return e.some(s=>n.test(s.content))}function ak(t){let e=/\b(pnpm|npm|yarn|bun)\b/.exec(t.toLowerCase());return e?e[1]:null}function ck(t){let e=new Set;for(let n of t)for(let s of ic(n.command)){let i=ak(s);i&&e.add(i)}return e}var Eh=new Set(["install","i","add","remove","uninstall","init","help","test","start","stop","restart","exec","dlx","run","workspace","workspaces"]),kh=new Set(["instead","of","packages","package","are","is","the","a","an","that","this","for","to","and","or","not","with","without","via","because","since","before","after","than","as","like","but","so"]);function lk(t){let e=/\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?([a-z0-9][a-z0-9:_-]*)\b/i.exec(t);if(!e)return null;let n=e[1].toLowerCase();return Eh.has(n)||kh.has(n)?null:n}function uk(t){let{workflows:e,files:n}=t;if(e.files.length===0)return[];let s=new Map;for(let r of e.commands)for(let o of ik(r.command))s.has(o)||s.set(o,[]),s.get(o).push(r);let i=[];for(let[r,o]of s.entries()){if(ok(r,n))continue;let a=[...new Set(o.map(c=>c.filePath))];i.push({id:sc(`missing-ci-task:${r}`),severity:"warning",category:"missing_context",title:`CI runs \`${r}\` but no instruction file appears to include it`,summary:`The GitHub workflow${a.length>1?"s":""} (${a.join(", ")}) run \`${r}\`, but no instruction file appears to direct the agent to run this step locally. Agents that follow only the instruction files may skip \`${r}\` and miss failures before declaring work complete.`,filePaths:n.map(c=>c.path),locations:o.map(c=>({filePath:c.filePath,startLine:c.line})),evidence:o.map(c=>`CI command: \`${c.command}\` in ${c.filePath} (line ${c.line})`),recommendation:`Consider adding \`${r}\` to the verification loop in the relevant instruction file (e.g., AGENTS.md or CLAUDE.md) so agents run the same checks as CI.`,confidence:.8})}return i}function fk(t){let{workflows:e,files:n,packageJson:s}=t;if(e.files.length===0)return[];let i=ck(e.commands);if(i.size===0)return[];let r=s.packageManagerName!=="unknown"?s.packageManagerName:Array.from(i)[0];if(!i.has(r))return[];let o=[];for(let a of n)for(let c of["npm","pnpm","yarn","bun"]){if(c===r)continue;let l=new RegExp(`\\b${c}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),u,f=!1;for(;(u=l.exec(a.content))!==null;){let d=a.content.lastIndexOf(`
74
74
  `,u.index-1)+1,p=a.content.indexOf(`
75
- `,u.index),h=a.content.slice(d,p===-1?void 0:p);if(!/\b(?:do\s+not|don'?t|avoid|never|not\s+use|refrain)\b/i.test(h)){f=!0;break}}f&&o.push({id:ec(`pm-mismatch-ci:${L(a)}:${c}`),severity:"warning",category:"conflict",title:`Possible package manager mismatch: instructions use \`${c}\` but CI uses \`${r}\``,summary:`The instruction file appears to direct the agent to use \`${c}\`, but the CI workflows use \`${r}\`. This may lead to lockfile conflicts or unexpected installation behaviour. Consider reviewing whether the instructions match the CI setup.`,filePaths:[a.path],locations:[{filePath:a.path}],evidence:[`CI workflows use: ${Array.from(i).join(", ")}`,`Instruction file appears to use \`${c}\``],recommendation:`Update the instruction file to use \`${r}\` commands to align with CI.`,confidence:.85})}return o}function ak(t){let{workflows:e,files:n,packageJson:s,manifests:i}=t;if(e.files.length===0)return[];if(i.packageJson)return[];let r=new Set(Object.keys(s.scripts)),o=new Set;for(let l of e.commands)for(let u of tc(l.command)){let f=ik(u);f&&o.add(f)}let a=new Set,c=[];for(let l of n){let u=/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,f;for(;(f=u.exec(l.content))!==null;){let d=f[1].toLowerCase();if(!(wh.has(d)||vh.has(d))&&!r.has(d)&&!o.has(d)){let p=`${l.path}:${d}`;if(a.has(p))continue;a.add(p),c.push({id:ec(`orphan-script:${L(l)}:${d}`),severity:"warning",category:"stale_instruction",title:`Possible reference to missing script: \`${d}\` (not in CI or package.json)`,summary:`The instruction file appears to tell the agent to run \`${d}\`, but this script does not appear in package.json and is not used in any CI workflow. This command may fail if executed. Consider reviewing whether the script name is current.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Found reference to \`${d}\` in ${l.path}`,"Script not found in package.json scripts","Script not found in .github/workflows/*.yml"],recommendation:"Verify the script name. If it was renamed, update the instruction file. If it is a new script, add it to package.json.",confidence:.8})}}}return c}function xh(t){return t.workflows.files.length===0?[]:[...rk(t),...ok(t),...ak(t)]}var Eh=x(require("node:crypto"),1);var ck={fileWarning:8e3,fileHigh:2e4,totalWarning:3e4,totalHigh:6e4,copilotLineWarning:1e3,readmeFileWarning:15e3,readmeFileHigh:3e4,windsurfFileWarning:6e3,windsurfFileHigh:12e3};function Fi(t){return`context-bloat-file-${Eh.createHash("sha1").update(t).digest("hex").slice(0,12)}`}var _h="context-bloat-total",lk=.5,uk=1e3,ys=["cost","context"];function fk(t,e){if(!e)return t;let n={...t};for(let s of Object.keys(e)){let i=e[s];i!==void 0&&(n[s]=i)}return n}function Sh(t,e,n){return Yt(t,e,s=>s===n)}function kh(t,e,n=[]){let s=fk(ck,e),i=[];for(let l of[...t,...Sh(t,n,"windsurf")]){let{charCount:u,estimatedTokens:f,path:d,fileType:p}=l,h=s.fileWarning,m=s.fileHigh;p==="readme"?(h=s.readmeFileWarning,m=s.readmeFileHigh):p==="windsurf"&&(h=s.windsurfFileWarning,m=s.windsurfFileHigh);let g=p==="windsurf",b=`Trim the file under ~${s.windsurfFileWarning.toLocaleString()} characters, or split it into scoped \`.windsurf/rules/*.md\` files so each loads only when relevant \u2014 Windsurf silently truncates rules past its limit, so later rules never reach the model.`;u>=m?i.push({id:Fi(L(l)),severity:"high",category:"context_bloat",title:g?".windsurfrules is past the Windsurf size limit":"Instruction file is very large",summary:g?`File is ${u.toLocaleString()} chars, past Windsurf's ~${s.windsurfFileHigh.toLocaleString()}-char combined budget \u2014 rules beyond the ~${s.windsurfFileWarning.toLocaleString()}-char limit are silently truncated.`:`File is ${u.toLocaleString()} chars, above high threshold (${m.toLocaleString()}).`,filePaths:[d],locations:[{filePath:d}],evidence:[`charCount: ${u.toLocaleString()}`,`estimatedTokens: ~${f.toLocaleString()}`],recommendation:g?b:"Consider splitting this file.",confidence:1,tags:ys}):u>=h&&i.push({id:Fi(L(l)),severity:"warning",category:"context_bloat",title:g?".windsurfrules may exceed the Windsurf size limit":"Instruction file may be too large",summary:g?`File is ${u.toLocaleString()} chars, past Windsurf's ~${s.windsurfFileWarning.toLocaleString()}-char truncation limit \u2014 rules beyond it may be silently dropped.`:`File is ${u.toLocaleString()} chars, above warning threshold (${h.toLocaleString()}).`,filePaths:[d],locations:[{filePath:d}],evidence:[`charCount: ${u.toLocaleString()}`,`estimatedTokens: ~${f.toLocaleString()}`],recommendation:g?b:"Consider trimming this file.",confidence:1,tags:ys})}for(let l of[...t,...Sh(t,n,"copilot")])l.fileType==="copilot"&&l.lineCount>s.copilotLineWarning&&i.push({id:Fi(L(l)+":copilot-lines"),severity:"warning",category:"context_bloat",title:"Copilot instructions file exceeds recommended line limit",summary:`File is ${l.lineCount.toLocaleString()} lines. GitHub recommends keeping Copilot instruction files under ${s.copilotLineWarning.toLocaleString()} lines \u2014 longer files may be truncated, degrading response quality.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`lineCount: ${l.lineCount.toLocaleString()}`,`threshold: ${s.copilotLineWarning.toLocaleString()} lines`],recommendation:"Split into multiple focused instruction files, or move rarely-needed context to separate docs that are linked rather than inlined.",confidence:1});let r=t.reduce((l,u)=>l+u.charCount,0),o=t.reduce((l,u)=>l+u.estimatedTokens,0),a=t.map(l=>l.path);r>=s.totalHigh?i.push({id:_h,severity:"high",category:"context_bloat",title:"Total instruction context is very large",summary:`Total is ${r.toLocaleString()} chars, above high threshold (${s.totalHigh.toLocaleString()}).`,filePaths:a,locations:a.map(l=>({filePath:l})),evidence:[`totalCharCount: ${r.toLocaleString()}`,`totalEstimatedTokens: ~${o.toLocaleString()}`],recommendation:"Aim to keep total context under 30k characters.",confidence:1,tags:ys}):r>=s.totalWarning&&i.push({id:_h,severity:"warning",category:"context_bloat",title:"Total instruction context may be too large",summary:`Total is ${r.toLocaleString()} chars, above warning threshold (${s.totalWarning.toLocaleString()}).`,filePaths:a,locations:a.map(l=>({filePath:l})),evidence:[`totalCharCount: ${r.toLocaleString()}`,`totalEstimatedTokens: ~${o.toLocaleString()}`],recommendation:"Consider trimming instruction files.",confidence:1,tags:ys});let c=t.find(l=>l.fileType==="readme");if(o>0&&c&&c.estimatedTokens>=uk&&c.estimatedTokens/o>=lk){let l=Math.round(c.estimatedTokens/o*100);i.push({id:Fi(`${L(c)}:readme-dominates`),severity:"info",category:"context_bloat",title:"README dominates scanned instruction context",summary:`README content accounts for about ${l}% of scanned instruction tokens. That may be appropriate, but AI-specific guidance is usually cheaper in a smaller canonical file.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`README: ~${c.estimatedTokens} of ~${o} scanned tokens`],recommendation:"Consider keeping AI rules in AGENTS.md and leaving README as project documentation linked only when relevant.",confidence:.65,tags:ys})}return i}var Ch=x(require("node:crypto"),1);var dk={unity:{keywords:["unity","monobehaviour","gameobject","c#","unity editor","prefab"],label:"Unity",minimumPresent:1},typescript:{keywords:["npm run build","pnpm run build","yarn run build","pnpm build","npm run test","npm test","pnpm test","yarn test","vitest","jest","typescript","tsconfig","tsc ","ts-node"],label:"TypeScript",minimumPresent:1},dotnet:{keywords:["dotnet",".sln",".csproj","xunit","nunit","mstest","dotnet test","dotnet build"],label:".NET",minimumPresent:1},nextjs:{keywords:["next.js","nextjs","next build","next dev","app router","pages router","vercel"],label:"Next.js",minimumPresent:1},python:{keywords:["python","pip","poetry","venv","pytest","pyproject.toml"],label:"Python",minimumPresent:1},go:{keywords:["golang","go.mod","go test","go build"],label:"Go",minimumPresent:1},rust:{keywords:["rust","cargo","cargo build","cargo test","rustc"],label:"Rust",minimumPresent:1}};function tn(t){return`missing-context-${Ch.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function pk(t,e){let n=e.toLowerCase();return/[^a-z0-9]/.test(n)?t.includes(n):new RegExp(`\\b${n}\\b`).test(t)}var hk=[/(npm|pnpm|yarn|uv)\s+(install|ci|run|sync|test|build|lint|add)/,/dotnet\s+(build|test|restore)/,/make\s+(build|test|install)/,/cargo\s+(build|test)/,/go\s+(build|test)/,/uv\s+(run|sync|install|add)\b/,/pip\s+(install|sync|download)\b/,/python\s+-m\s+(venv|pytest|pip|build)\b/,/python\s+setup\.py\b/,/\bpytest\b/],mk=[/`(npm|pnpm|yarn)\s+(run\s+)?(build|test|lint|install)/,/`(uv|dotnet)\s+(run|sync|install|test|build)/,/`pip\s+(install|sync)/,/`python\s+-m\s+(venv|pytest|pip)/,/`pytest\b/,/`go\s+(build|test|run|install)\b/,/(npm|pnpm|yarn)\s+run\s+(build|test|lint)/i,/pnpm\s+(build|test|install|lint)/i,/\buv\s+(run|sync|install|add)\b/i,/\b(install|build|test)\s+(command|step|instruction)/i,/how\s+to\s+(install|build|run|test)/i,/getting\s+started/i,/\bpip\s+install\b/i,/\bpython\s+-m\s+(venv|pytest|pip|build)\b/i,/\bpytest\b/i,/\bpython\s+setup\.py\b/i,/\bgo\s+(test|build|run)\s/i],gk=[/\b(auth(entication|orization)?|rls|row.?level.?security)\b/i,/\bsecrets?\b/i,/\bcredentials?\b/i,/\bpasswords?\b/i,/\bapi.?keys?\b/i,/\btokens?\b/i,/\b(sanitize|sanitises?|injection)\b/i,/\bvalidate\b.{0,50}\b(input|param)s?\b/i,/\b(never\s+commit|do\s+not\s+commit|don.?t\s+commit).{0,50}\b(secret|key|credential)s?\b/i,/\b(env(ironment)?\s+var|\.env)\b/i,/\b(ssm|parameter\s+store|vault|keychain)\b/i];function yk(t){let e=t.map(i=>i.content).join(`
76
- `),n=nd(e);return hk.some(i=>i.test(n))||mk.some(i=>i.test(e))?null:{id:tn("missing-setup-commands"),severity:"warning",category:"missing_context",title:"No setup or validation commands found",summary:"No instruction file appears to document how to install dependencies, build, or run tests. Agents cannot reliably set up or validate the project without this.",filePaths:t.map(i=>i.path),locations:[],evidence:["No install/build/test commands found in any instruction file."],recommendation:'Add a "Setup" or "Getting Started" section with the exact commands to install, build, and test: e.g. "pnpm install && pnpm build && pnpm test".',confidence:.75}}var bk=[/\b(?:oauth|api\s*key|access\s*token|bearer\s*token|personal\s*access\s*token|github\s+token|gitlab\s+token)/i,/\bPAT\b/,/\b(?:store[sd]?\s+(?:in|to)\s+(?:keychain|config|file)|credential\s+storage|token\s+storage)/i],wk=[/\b(?:scope[sd]?|permission[sd]?|required\s+scope|token\s+scope)/i,/\b(?:validat(?:e[sd]?|ion|ing)|verif(?:y|ied|ies|ication|ying))\b/i,/\btoken\s+(?:expir[yi]|refresh|rotat)/i,/\b(?:expir(?:y|ation|e[sd]?|ing)|refresh\s+token|token\s+rotation)\b/i];function vk(t){let e=t.map(i=>i.content).join(`
77
- `);return!bk.some(i=>i.test(e))||wk.some(i=>i.test(e))?null:{id:tn("missing-credential-surface"),severity:"warning",category:"missing_context",title:"Credential section missing scope/validation/expiry documentation",summary:"Instruction files describe credential or token storage but do not document required token scopes, how tokens are validated on first use, or how token expiry and rotation are handled. Agents cannot safely handle auth edge cases without this information.",filePaths:t.map(i=>i.path),locations:[],evidence:["Credential/token handling found, but no mention of scopes, validation, or expiry."],recommendation:"Add documentation covering: (1) which OAuth scopes or API permissions are required, (2) how tokens are validated on first use or after rotation, (3) what happens when a token expires (error message, re-auth flow).",confidence:.65}}function xk(t){let e=t.map(s=>s.content).join(`
78
- `);return gk.some(s=>s.test(e))?null:{id:tn("missing-security-rules"),severity:"info",category:"missing_context",title:"No security or secret-handling rules found",summary:"No instruction file mentions authentication, secrets, API keys, RLS policies, or input validation. Agents that handle user data or credentials benefit from explicit security guidelines.",filePaths:t.map(s=>s.path),locations:[],evidence:["No auth, secrets, RLS, or input validation keywords found."],recommendation:"Add a security section covering: how auth is handled, where secrets live (.env, vault), RLS/data-isolation requirements, and what agents must never commit or log.",confidence:.65}}var _k=[/\b(?:jwt|jwks|json\s+web\s+token)\b/i,/\b(?:tls|ssl)\s+(?:cert(?:ificate)?|key)\b/i,/\bsigning\s+key\b/i,/\b(?:private|secret)\s+key\b/i,/\bapi\s+(?:secret|signing)\b/i,/\b(?:redis|kafka|broker)\s+(?:credential|password|secret|auth)\b/i,/\bkey\s+(?:store|vault|ring)\b/i],Sk=[/\b(?:rotat(?:e[sd]?|ion|ing)|key\s+rotation|secret\s+rotation|credential\s+rotation)\b/i,/\b(?:compromis(?:e[sd]?|ing)|key\s+compromise|breach)\b/i,/\b(?:incident\s+response|security\s+incident)\b/i,/\b(?:revo(?:ke[sd]?|cation)|invalidat(?:e[sd]?|ion))\b/i,/\bwhat\s+to\s+do\s+(?:if|when)\s+.{0,40}(?:key|secret|credential|token)\b/i,/\b(?:key|secret|token|cert(?:ificate)?)\s+expir(?:y|ation|es?|ing)\b/i,/\brenew(?:ing|al|ed)?\s+(?:cert(?:ificate)?|key|token)\b/i];function Ek(t){let e=t.map(i=>i.content).join(`
79
- `);return!_k.some(i=>i.test(e))||Sk.some(i=>i.test(e))?null:{id:tn("missing-secret-rotation"),severity:"warning",category:"missing_context",title:"Security-sensitive project missing secret rotation / incident response guidance",summary:"Instruction files reference security-sensitive credentials or cryptographic keys (JWT, TLS, signing keys, etc.) but do not document how to rotate them, what to do on suspected compromise, or how to handle expiry. Agents cannot safely manage security events without this information.",filePaths:t.map(i=>i.path),locations:[],evidence:["Security-sensitive key/credential references found, but no rotation, compromise, or incident-response procedure documented."],recommendation:"Add a section covering: (1) how to rotate secrets or API keys, (2) what to do if a key is suspected compromised (revoke, re-issue, notify), (3) how certificate/token expiry is handled.",confidence:.65}}var Rh=/\b([A-Z][A-Z0-9_]{3,})\b/g,kk=[/\b(?:environment\s+variables?|env\s+vars?|required\s+(?:env(?:ironment)?\s+)?variables?)\b/i,/\.env\.example\b/i,/\benv(?:ironment)?\s+(?:setup|configuration|config)\b/i,/\bconfigure\s+(?:your\s+)?environment\b/i],Rk=new Set(["API","URL","HTTP","HTML","JSON","SQL","JWT","TLS","SSL","RLS","CRUD","REST","CORS","UUID","AUTH","NOTE","TODO","HACK","FIXME","WARN","INFO","NULL","TRUE","FALSE","NONE","VOID","ENUM","TYPE","TEST","PROD","DEV","DOCS","SKIP","PASS","FAIL","DONE","STOP"]);function Ck(t){let e=t.map(a=>a.content).join(`
80
- `);if(kk.some(a=>a.test(e)))return null;let s=new Set,i,r=new RegExp(Rh.source,Rh.flags);for(;(i=r.exec(e))!==null;){let a=i[1];!Rk.has(a)&&a.includes("_")&&s.add(a)}if(s.size<3)return null;let o=[...s].slice(0,4).join(", ");return{id:tn("missing-env-var-list"),severity:"info",category:"missing_context",title:"Environment variables referenced but no comprehensive list documented",summary:`Instruction files mention ${s.size} environment variable name(s) (e.g. ${o}) but do not have a dedicated section listing all required variables. Agents and new developers cannot reliably set up the project without a complete env var reference.`,filePaths:t.map(a=>a.path),locations:[],evidence:[`${s.size} env-var-like names found: ${o}\u2026`],recommendation:'Add an "Environment Variables" or "Required Environment" section listing every required variable, its purpose, and a safe example value. A .env.example file reference also satisfies this check.',confidence:.6}}var Ak=[{label:"file naming convention",patterns:[/\b(?:kebab-case|camelCase|camelcase|PascalCase|pascalcase|snake_case|naming\s+convention)\b/i],recommendation:'Add a file naming rule to copilot-instructions.md (e.g. "Use kebab-case for all files") so Copilot agents apply the same convention as the rest of the codebase.'}];function $k(t){let e=c=>c.path.replace(/\\/g,"/").toLowerCase(),n=c=>{let l=e(c);return l===".github/copilot-instructions.md"||l.endsWith("/.github/copilot-instructions.md")},s=c=>c.fileType==="copilot"||e(c).includes("/.github/instructions/"),i=t.find(n);if(!i)return[];let r=t.filter(s),o=t.filter(c=>!r.includes(c));if(o.length===0)return[];let a=[];for(let{label:c,patterns:l,recommendation:u}of Ak)!o.some(p=>l.some(h=>h.test(p.content)))||r.some(p=>l.some(h=>h.test(p.content)))||a.push({id:tn(`copilot-topic-silence:${c}`),severity:"info",category:"missing_context",title:`copilot-instructions.md is silent on: ${c}`,summary:`Other instruction files document the ${c}, but Copilot instruction files do not mention it. Copilot agents will have no guidance on this topic.`,filePaths:[i.path],locations:[{filePath:i.path}],evidence:[`"${c}" is documented in other instruction files but absent from Copilot instruction files.`],recommendation:u,confidence:.6});return a}function Ah(t,e){let n=[],s=yk(t);s&&n.push(s);let i=xk(t);i&&n.push(i);let r=vk(t);r&&n.push(r);let o=Ek(t);o&&n.push(o);let a=Ck(t);if(a&&n.push(a),n.push(...$k(t)),e==="auto"||e==="unknown")return n;let c=dk[e];if(!c)return n;let l=t.map(f=>f.content.toLowerCase()).join(`
81
- `);if(c.keywords.filter(f=>pk(l,f)).length<c.minimumPresent){let f=c.keywords.slice(0,3).join(", ");n.push({id:tn(e),severity:"warning",category:"missing_context",title:`Missing ${c.label}-specific context`,summary:`This appears to be a ${c.label} project, but the instruction files do not mention any ${c.label}-specific context (e.g. build commands, test runner, tooling).`,filePaths:t.map(d=>d.path),locations:[],evidence:[`No keywords found matching: ${f}\u2026`],recommendation:`Add a section covering ${c.label}-specific build commands, testing conventions, and common project patterns so AI assistants have enough context to help effectively.`,confidence:.75})}return n}var Th=x(require("node:crypto"),1);var Pk=7;function Ih(t=new Date){return t.getFullYear()}var $h=0,Hi=null;function Tk(){let t=Ih();if(Hi&&$h===t)return Hi;let e=[];for(let n=t-Pk;n<=t-1;n++)e.push(String(n));return $h=t,Hi=new RegExp(`(?<![/-])\\b(${e.join("|")})\\b(?![/-])`,"g"),Hi}var Ik=/\b(?:history|changelog|change\s*log|release\s+notes?|releases?|versions?|what.?s\s+new|for\s+reference)\b/i,Ok=/\b(TODO\s*:?\s*remove|remove\s+later|temporary\s+fix|workaround)\b/gi,Ph=/<!--(?:(?!-->)[\s\S])*?\b(TODO|FIXME|WORKAROUND|HACK|NOTE)\b(?:(?!-->)[\s\S])*?\(\s*(\d{4})[-–\d]/gi,Lk=/deprecated[\w\s,.()\\\-:`]{0,60}(v?\d+[\w.]+|react|next\.?js|angular|vue|webpack|babel|unity|jest|mocha)/gi,Nk=[{re:/\breact\s+v?1[0-6]\b/gi,label:"React 16 or earlier"},{re:/\bnext\.?js\s+v?[1-9]\b/gi,label:"Next.js 9 or earlier"},{re:/\bunity\s+v?201[0-9]\b/gi,label:"Unity 2019 or earlier"},{re:/\bangular\s+v?[1-9]\b/gi,label:"Angular 9 or earlier"},{re:/\bvue\s+v?[12]\b/gi,label:"Vue 2 or earlier"},{re:/\bwebpack\s+v?[1-3]\b/gi,label:"Webpack 3 or earlier"},{re:/\bbabel\s+v?[1-6]\b/gi,label:"Babel 6 or earlier"},{re:/\bnode(?:\.js?)?\s+v?(1[0-6]|[1-9])\b/gi,label:"Node.js 16 or earlier"},{re:/\btypescript\s+v?[1-3]\b/gi,label:"TypeScript 3 or earlier"},{re:/\bgo\s+v?1\.(1[0-7]|[0-9])\b/gi,label:"Go 1.17 or earlier"},{re:/\bpython\s+v?2\./gi,label:"Python 2"},{re:/\bpython\s+v?3\.[0-9]\b/gi,label:"Python 3.9 or earlier"},{re:/\.NET\s+v?[1-5]\b/gi,label:".NET 5 or earlier"}];function jk(t,e){let n=`${Be(t)}:${t.startLine}:${e}`;return`stale-${Th.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function nc(t,e){let n=[],s,i=new RegExp(e.source,e.flags);for(;(s=i.exec(t))!==null;)n.push(s[0]);return n}function Mk(t,e){let n=[],s,i=new RegExp(e.source,e.flags);for(;(s=i.exec(t))!==null;)n.push({match:s[0],index:s.index});return n}function Dk(t){let e=[],n,s=new RegExp(Ph.source,Ph.flags);for(;(n=s.exec(t))!==null;)Number(n[2])<Ih()&&e.push(n[0]);return e}function Fk(t,e){let n=t.slice(Math.max(0,e-80),e).toLowerCase();return/\b(?:do\s+not|don['']?t|avoid|never|no\s+longer|drop(?:ped|ping)?|remov(?:ed?|ing)|deprecat(?:ed?|ing)|stop(?:ped|ping)?\s+(?:using|support(?:ing)?))\b(?:(?!\n[ \t]*\n)[^.!?])*$/.test(n)}function Oh(t){let e=[],n=new Set;for(let s of t)for(let i of s.sections){if(i.heading&&Ik.test(i.heading))continue;let r=i.text,o=Ke(r,{stripInlineCode:!0}),a=Ke(r),c=[],l=0,u=`${s.path}:${i.startLine}`,f=nc(o,Tk());f.length>0&&(c.push(`Year reference(s) that may be outdated: ${[...new Set(f)].join(", ")}`),l=Math.max(l,.6));let d=nc(a,Ok);d.length>0&&(c.push(`Cleanup keyword(s): ${[...new Set(d.map(m=>m.trim()))].join(", ")}`),l=Math.max(l,.6));let p=nc(a,Lk);p.length>0&&(c.push(`"deprecated" near version/tool: ${q(p[0]??"",80)}`),l=Math.max(l,.7));for(let{re:m,label:g}of Nk){let w=Mk(o,m).filter(({index:y})=>!Fk(o,y));w.length>0&&(c.push(`Old version reference: ${g} ("${w[0].match}")`),l=Math.max(l,.7))}let h=Dk(a);h.length>0&&(c.push(`Dated ${h[0].match(/TODO|FIXME|WORKAROUND|HACK|NOTE/i)?.[0]??"TODO"} marker in HTML comment: ${q(h[0]??"",80)}`),l=Math.max(l,.65)),c.length!==0&&(n.has(u)||(n.add(u),e.push({id:jk(i,"stale"),severity:"warning",category:"stale_instruction",title:"Instruction may reference outdated content",summary:"This instruction may reference outdated content. Review and update or remove it.",filePaths:[s.path],locations:[{filePath:s.path,startLine:i.startLine,endLine:i.endLine}],evidence:[`Section: "${q(r,100)}"`,...c],recommendation:"Review this section for accuracy. Update any outdated version numbers, tool references, or remove temporary notes that are no longer relevant.",fixRecipe:"Edit each flagged reference by hand: replace outdated version pins and tool names with current ones, and delete temporary notes that no longer apply. Leave copyright lines, release dates, and historical references as they are.",confidence:l})))}return e}var Nh=x(require("node:crypto"),1);var Hk=["write clean code","write clean","use best practices","make it production ready","production ready","production-ready","be careful","do the right thing","follow good patterns","write good tests","keep it simple","keep things simple","best practices","production-quality","production quality","follow best practices","idiomatic code","make sure everything works","ensure quality","write quality code","industry standards","generally accepted","solid principles","follow solid","self-documenting","make it maintainable","clean maintainable","good engineering","clean architecture","maintainable code","readable code","high-quality code","high quality code","follow industry standards","functional programming principles","write idiomatic","polished and professional","looks polished","feel smooth and native","smooth and native","feels native","feel native","feel smooth","accessible and usable","provide good defaults","great user experience","good user experience","seamless experience","intuitive interface","user-friendly","easy to use","delightful","looks good","visually appealing","native feel","follow go best practices","follow rust best practices","follow python best practices","idiomatic go","idiomatic rust","idiomatic python","idiomatic elixir","idiomatic typescript"],Lh=120;function Bk(t){let e=new Set;for(let n of t)e.add(n),n.includes("-")&&e.add(n.replace(/-/g," "));return[...e]}var jh=Bk(Hk),Wk=new Set(["write clean code","write clean","use best practices","best practices","follow best practices","make it production ready","production ready","production-ready","production quality","production-quality","be careful","solid principles","follow solid","clean architecture","make it maintainable"]);function Gk(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Uk=new Map(jh.map(t=>[t,new RegExp(`\\b${Gk(t)}\\b`)]));function Vk(t,e){let n=t.split(`
82
- `).map(i=>i.trim()),s=[];for(let i=0;i<n.length;i++){let r=n[i];r&&e.test(r.toLowerCase())&&r.length<=Lh&&s.push(r);let o=n[i+1];if(r&&o){let a=`${r} ${o}`;e.test(a.toLowerCase())&&a.length<=Lh&&s.push(a)}}return s}function zk(t){let e=`${Be(t)}:${t.startLine}:vague`;return`vague-${Nh.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Mh(t,e={}){let n=[],s=new Set;for(let i of t)for(let r of i.sections){let o=`${i.path}:${r.startLine}`;if(s.has(o))continue;let a=Ke(r.text,{stripInlineCode:!0}),c=a.toLowerCase().replace(/\n/g," "),l=[],u=[];for(let g of jh){let b=Uk.get(g);if(b.test(c))for(let w of Vk(a,b))l.includes(g)||l.push(g),u.includes(w)||u.push(w)}if(l.length===0)continue;s.add(o);let f=l.map(g=>`"${g}"`).join(", "),d=l.some(g=>Wk.has(g)),p=d?"warning":"info",h=e.severityOverride??p,m=d?.8:.75;n.push({id:zk(r),severity:h,category:"vague_guidance",title:"Vague guidance detected",summary:`This section contains guidance that may be too vague to be actionable: ${f}.`,filePaths:[i.path],locations:[{filePath:i.path,startLine:r.startLine,endLine:r.endLine}],evidence:u.slice(0,3).map(g=>`Line: "${g}"`),recommendation:'Replace vague guidance with concrete constraints \u2014 specific commands, forbidden patterns, or measurable criteria. For example, replace "write clean code" with "functions must be \u2264 50 lines; no unused variables".',confidence:m})}return n}var Ui=x(require("node:crypto"),1),je=x(require("node:path"),1),We=x(require("node:fs"),1);var bs=["# PromptCI: ignore generated reports, keep the shared baseline, config, and custom rules","**/.promptci/*","!**/.promptci/baseline.json","!**/.promptci/config.json","!**/.promptci/custom-rules.json"],sc=`${bs.join(`
75
+ `,u.index),h=a.content.slice(d,p===-1?void 0:p);if(!/\b(?:do\s+not|don'?t|avoid|never|not\s+use|refrain)\b/i.test(h)){f=!0;break}}f&&o.push({id:sc(`pm-mismatch-ci:${L(a)}:${c}`),severity:"warning",category:"conflict",title:`Possible package manager mismatch: instructions use \`${c}\` but CI uses \`${r}\``,summary:`The instruction file appears to direct the agent to use \`${c}\`, but the CI workflows use \`${r}\`. This may lead to lockfile conflicts or unexpected installation behaviour. Consider reviewing whether the instructions match the CI setup.`,filePaths:[a.path],locations:[{filePath:a.path}],evidence:[`CI workflows use: ${Array.from(i).join(", ")}`,`Instruction file appears to use \`${c}\``],recommendation:`Update the instruction file to use \`${r}\` commands to align with CI.`,confidence:.85})}return o}function dk(t){let{workflows:e,files:n,packageJson:s,manifests:i}=t;if(e.files.length===0)return[];if(i.packageJson)return[];let r=new Set(Object.keys(s.scripts)),o=new Set;for(let l of e.commands)for(let u of ic(l.command)){let f=lk(u);f&&o.add(f)}let a=new Set,c=[];for(let l of n){let u=/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,f;for(;(f=u.exec(l.content))!==null;){let d=f[1].toLowerCase();if(!(Eh.has(d)||kh.has(d))&&!r.has(d)&&!o.has(d)){let p=`${l.path}:${d}`;if(a.has(p))continue;a.add(p),c.push({id:sc(`orphan-script:${L(l)}:${d}`),severity:"warning",category:"stale_instruction",title:`Possible reference to missing script: \`${d}\` (not in CI or package.json)`,summary:`The instruction file appears to tell the agent to run \`${d}\`, but this script does not appear in package.json and is not used in any CI workflow. This command may fail if executed. Consider reviewing whether the script name is current.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Found reference to \`${d}\` in ${l.path}`,"Script not found in package.json scripts","Script not found in .github/workflows/*.yml"],recommendation:"Verify the script name. If it was renamed, update the instruction file. If it is a new script, add it to package.json.",confidence:.8})}}}return c}function Rh(t){return t.workflows.files.length===0?[]:[...uk(t),...fk(t),...dk(t)]}var $h=x(require("node:crypto"),1);var pk={fileWarning:8e3,fileHigh:2e4,totalWarning:3e4,totalHigh:6e4,copilotLineWarning:1e3,readmeFileWarning:15e3,readmeFileHigh:3e4,windsurfFileWarning:6e3,windsurfFileHigh:12e3};function Bi(t){return`context-bloat-file-${$h.createHash("sha1").update(t).digest("hex").slice(0,12)}`}var Ch="context-bloat-total",hk=.5,mk=1e3,ys=["cost","context"];function gk(t,e){if(!e)return t;let n={...t};for(let s of Object.keys(e)){let i=e[s];i!==void 0&&(n[s]=i)}return n}function Ah(t,e,n){return Yt(t,e,s=>s===n)}function Ph(t,e,n=[]){let s=gk(pk,e),i=[];for(let l of[...t,...Ah(t,n,"windsurf")]){let{charCount:u,estimatedTokens:f,path:d,fileType:p}=l,h=s.fileWarning,m=s.fileHigh;p==="readme"?(h=s.readmeFileWarning,m=s.readmeFileHigh):p==="windsurf"&&(h=s.windsurfFileWarning,m=s.windsurfFileHigh);let g=p==="windsurf",b=`Trim the file under ~${s.windsurfFileWarning.toLocaleString()} characters, or split it into scoped \`.windsurf/rules/*.md\` files so each loads only when relevant \u2014 Windsurf silently truncates rules past its limit, so later rules never reach the model.`;u>=m?i.push({id:Bi(L(l)),severity:"high",category:"context_bloat",title:g?".windsurfrules is past the Windsurf size limit":"Instruction file is very large",summary:g?`File is ${u.toLocaleString()} chars, past Windsurf's ~${s.windsurfFileHigh.toLocaleString()}-char combined budget \u2014 rules beyond the ~${s.windsurfFileWarning.toLocaleString()}-char limit are silently truncated.`:`File is ${u.toLocaleString()} chars, above high threshold (${m.toLocaleString()}).`,filePaths:[d],locations:[{filePath:d}],evidence:[`charCount: ${u.toLocaleString()}`,`estimatedTokens: ~${f.toLocaleString()}`],recommendation:g?b:"Consider splitting this file.",confidence:1,tags:ys}):u>=h&&i.push({id:Bi(L(l)),severity:"warning",category:"context_bloat",title:g?".windsurfrules may exceed the Windsurf size limit":"Instruction file may be too large",summary:g?`File is ${u.toLocaleString()} chars, past Windsurf's ~${s.windsurfFileWarning.toLocaleString()}-char truncation limit \u2014 rules beyond it may be silently dropped.`:`File is ${u.toLocaleString()} chars, above warning threshold (${h.toLocaleString()}).`,filePaths:[d],locations:[{filePath:d}],evidence:[`charCount: ${u.toLocaleString()}`,`estimatedTokens: ~${f.toLocaleString()}`],recommendation:g?b:"Consider trimming this file.",confidence:1,tags:ys})}for(let l of[...t,...Ah(t,n,"copilot")])l.fileType==="copilot"&&l.lineCount>s.copilotLineWarning&&i.push({id:Bi(L(l)+":copilot-lines"),severity:"warning",category:"context_bloat",title:"Copilot instructions file exceeds recommended line limit",summary:`File is ${l.lineCount.toLocaleString()} lines. GitHub recommends keeping Copilot instruction files under ${s.copilotLineWarning.toLocaleString()} lines \u2014 longer files may be truncated, degrading response quality.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`lineCount: ${l.lineCount.toLocaleString()}`,`threshold: ${s.copilotLineWarning.toLocaleString()} lines`],recommendation:"Split into multiple focused instruction files, or move rarely-needed context to separate docs that are linked rather than inlined.",confidence:1});let r=t.reduce((l,u)=>l+u.charCount,0),o=t.reduce((l,u)=>l+u.estimatedTokens,0),a=t.map(l=>l.path);r>=s.totalHigh?i.push({id:Ch,severity:"high",category:"context_bloat",title:"Total instruction context is very large",summary:`Total is ${r.toLocaleString()} chars, above high threshold (${s.totalHigh.toLocaleString()}).`,filePaths:a,locations:a.map(l=>({filePath:l})),evidence:[`totalCharCount: ${r.toLocaleString()}`,`totalEstimatedTokens: ~${o.toLocaleString()}`],recommendation:"Aim to keep total context under 30k characters.",confidence:1,tags:ys}):r>=s.totalWarning&&i.push({id:Ch,severity:"warning",category:"context_bloat",title:"Total instruction context may be too large",summary:`Total is ${r.toLocaleString()} chars, above warning threshold (${s.totalWarning.toLocaleString()}).`,filePaths:a,locations:a.map(l=>({filePath:l})),evidence:[`totalCharCount: ${r.toLocaleString()}`,`totalEstimatedTokens: ~${o.toLocaleString()}`],recommendation:"Consider trimming instruction files.",confidence:1,tags:ys});let c=t.find(l=>l.fileType==="readme");if(o>0&&c&&c.estimatedTokens>=mk&&c.estimatedTokens/o>=hk){let l=Math.round(c.estimatedTokens/o*100);i.push({id:Bi(`${L(c)}:readme-dominates`),severity:"info",category:"context_bloat",title:"README dominates scanned instruction context",summary:`README content accounts for about ${l}% of scanned instruction tokens. That may be appropriate, but AI-specific guidance is usually cheaper in a smaller canonical file.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`README: ~${c.estimatedTokens} of ~${o} scanned tokens`],recommendation:"Consider keeping AI rules in AGENTS.md and leaving README as project documentation linked only when relevant.",confidence:.65,tags:ys})}return i}var Ih=x(require("node:crypto"),1);var yk={unity:{keywords:["unity","monobehaviour","gameobject","c#","unity editor","prefab"],label:"Unity",minimumPresent:1},typescript:{keywords:["npm run build","pnpm run build","yarn run build","pnpm build","npm run test","npm test","pnpm test","yarn test","vitest","jest","typescript","tsconfig","tsc ","ts-node"],label:"TypeScript",minimumPresent:1},dotnet:{keywords:["dotnet",".sln",".csproj","xunit","nunit","mstest","dotnet test","dotnet build"],label:".NET",minimumPresent:1},nextjs:{keywords:["next.js","nextjs","next build","next dev","app router","pages router","vercel"],label:"Next.js",minimumPresent:1},python:{keywords:["python","pip","poetry","venv","pytest","pyproject.toml"],label:"Python",minimumPresent:1},go:{keywords:["golang","go.mod","go test","go build"],label:"Go",minimumPresent:1},rust:{keywords:["rust","cargo","cargo build","cargo test","rustc"],label:"Rust",minimumPresent:1}};function tn(t){return`missing-context-${Ih.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function bk(t,e){let n=e.toLowerCase();return/[^a-z0-9]/.test(n)?t.includes(n):new RegExp(`\\b${n}\\b`).test(t)}var wk=[/(npm|pnpm|yarn|uv)\s+(install|ci|run|sync|test|build|lint|add)/,/dotnet\s+(build|test|restore)/,/make\s+(build|test|install)/,/cargo\s+(build|test)/,/go\s+(build|test)/,/uv\s+(run|sync|install|add)\b/,/pip\s+(install|sync|download)\b/,/python\s+-m\s+(venv|pytest|pip|build)\b/,/python\s+setup\.py\b/,/\bpytest\b/],vk=[/`(npm|pnpm|yarn)\s+(run\s+)?(build|test|lint|install)/,/`(uv|dotnet)\s+(run|sync|install|test|build)/,/`pip\s+(install|sync)/,/`python\s+-m\s+(venv|pytest|pip)/,/`pytest\b/,/`go\s+(build|test|run|install)\b/,/(npm|pnpm|yarn)\s+run\s+(build|test|lint)/i,/pnpm\s+(build|test|install|lint)/i,/\buv\s+(run|sync|install|add)\b/i,/\b(install|build|test)\s+(command|step|instruction)/i,/how\s+to\s+(install|build|run|test)/i,/getting\s+started/i,/\bpip\s+install\b/i,/\bpython\s+-m\s+(venv|pytest|pip|build)\b/i,/\bpytest\b/i,/\bpython\s+setup\.py\b/i,/\bgo\s+(test|build|run)\s/i],xk=[/\b(auth(entication|orization)?|rls|row.?level.?security)\b/i,/\bsecrets?\b/i,/\bcredentials?\b/i,/\bpasswords?\b/i,/\bapi.?keys?\b/i,/\btokens?\b/i,/\b(sanitize|sanitises?|injection)\b/i,/\bvalidate\b.{0,50}\b(input|param)s?\b/i,/\b(never\s+commit|do\s+not\s+commit|don.?t\s+commit).{0,50}\b(secret|key|credential)s?\b/i,/\b(env(ironment)?\s+var|\.env)\b/i,/\b(ssm|parameter\s+store|vault|keychain)\b/i];function Sk(t){let e=t.map(i=>i.content).join(`
76
+ `),n=rd(e);return wk.some(i=>i.test(n))||vk.some(i=>i.test(e))?null:{id:tn("missing-setup-commands"),severity:"warning",category:"missing_context",title:"No setup or validation commands found",summary:"No instruction file appears to document how to install dependencies, build, or run tests. Agents cannot reliably set up or validate the project without this.",filePaths:t.map(i=>i.path),locations:[],evidence:["No install/build/test commands found in any instruction file."],recommendation:'Add a "Setup" or "Getting Started" section with the exact commands to install, build, and test: e.g. "pnpm install && pnpm build && pnpm test".',confidence:.75}}var _k=[/\b(?:oauth|api\s*key|access\s*token|bearer\s*token|personal\s*access\s*token|github\s+token|gitlab\s+token)/i,/\bPAT\b/,/\b(?:store[sd]?\s+(?:in|to)\s+(?:keychain|config|file)|credential\s+storage|token\s+storage)/i],Ek=[/\b(?:scope[sd]?|permission[sd]?|required\s+scope|token\s+scope)/i,/\b(?:validat(?:e[sd]?|ion|ing)|verif(?:y|ied|ies|ication|ying))\b/i,/\btoken\s+(?:expir[yi]|refresh|rotat)/i,/\b(?:expir(?:y|ation|e[sd]?|ing)|refresh\s+token|token\s+rotation)\b/i];function kk(t){let e=t.map(i=>i.content).join(`
77
+ `);return!_k.some(i=>i.test(e))||Ek.some(i=>i.test(e))?null:{id:tn("missing-credential-surface"),severity:"warning",category:"missing_context",title:"Credential section missing scope/validation/expiry documentation",summary:"Instruction files describe credential or token storage but do not document required token scopes, how tokens are validated on first use, or how token expiry and rotation are handled. Agents cannot safely handle auth edge cases without this information.",filePaths:t.map(i=>i.path),locations:[],evidence:["Credential/token handling found, but no mention of scopes, validation, or expiry."],recommendation:"Add documentation covering: (1) which OAuth scopes or API permissions are required, (2) how tokens are validated on first use or after rotation, (3) what happens when a token expires (error message, re-auth flow).",confidence:.65}}function Rk(t){let e=t.map(s=>s.content).join(`
78
+ `);return xk.some(s=>s.test(e))?null:{id:tn("missing-security-rules"),severity:"info",category:"missing_context",title:"No security or secret-handling rules found",summary:"No instruction file mentions authentication, secrets, API keys, RLS policies, or input validation. Agents that handle user data or credentials benefit from explicit security guidelines.",filePaths:t.map(s=>s.path),locations:[],evidence:["No auth, secrets, RLS, or input validation keywords found."],recommendation:"Add a security section covering: how auth is handled, where secrets live (.env, vault), RLS/data-isolation requirements, and what agents must never commit or log.",confidence:.65}}var Ck=[/\b(?:jwt|jwks|json\s+web\s+token)\b/i,/\b(?:tls|ssl)\s+(?:cert(?:ificate)?|key)\b/i,/\bsigning\s+key\b/i,/\b(?:private|secret)\s+key\b/i,/\bapi\s+(?:secret|signing)\b/i,/\b(?:redis|kafka|broker)\s+(?:credential|password|secret|auth)\b/i,/\bkey\s+(?:store|vault|ring)\b/i],Ak=[/\b(?:rotat(?:e[sd]?|ion|ing)|key\s+rotation|secret\s+rotation|credential\s+rotation)\b/i,/\b(?:compromis(?:e[sd]?|ing)|key\s+compromise|breach)\b/i,/\b(?:incident\s+response|security\s+incident)\b/i,/\b(?:revo(?:ke[sd]?|cation)|invalidat(?:e[sd]?|ion))\b/i,/\bwhat\s+to\s+do\s+(?:if|when)\s+.{0,40}(?:key|secret|credential|token)\b/i,/\b(?:key|secret|token|cert(?:ificate)?)\s+expir(?:y|ation|es?|ing)\b/i,/\brenew(?:ing|al|ed)?\s+(?:cert(?:ificate)?|key|token)\b/i];function $k(t){let e=t.map(i=>i.content).join(`
79
+ `);return!Ck.some(i=>i.test(e))||Ak.some(i=>i.test(e))?null:{id:tn("missing-secret-rotation"),severity:"warning",category:"missing_context",title:"Security-sensitive project missing secret rotation / incident response guidance",summary:"Instruction files reference security-sensitive credentials or cryptographic keys (JWT, TLS, signing keys, etc.) but do not document how to rotate them, what to do on suspected compromise, or how to handle expiry. Agents cannot safely manage security events without this information.",filePaths:t.map(i=>i.path),locations:[],evidence:["Security-sensitive key/credential references found, but no rotation, compromise, or incident-response procedure documented."],recommendation:"Add a section covering: (1) how to rotate secrets or API keys, (2) what to do if a key is suspected compromised (revoke, re-issue, notify), (3) how certificate/token expiry is handled.",confidence:.65}}var Th=/\b([A-Z][A-Z0-9_]{3,})\b/g,Pk=[/\b(?:environment\s+variables?|env\s+vars?|required\s+(?:env(?:ironment)?\s+)?variables?)\b/i,/\.env\.example\b/i,/\benv(?:ironment)?\s+(?:setup|configuration|config)\b/i,/\bconfigure\s+(?:your\s+)?environment\b/i],Tk=new Set(["API","URL","HTTP","HTML","JSON","SQL","JWT","TLS","SSL","RLS","CRUD","REST","CORS","UUID","AUTH","NOTE","TODO","HACK","FIXME","WARN","INFO","NULL","TRUE","FALSE","NONE","VOID","ENUM","TYPE","TEST","PROD","DEV","DOCS","SKIP","PASS","FAIL","DONE","STOP"]);function Ik(t){let e=t.map(a=>a.content).join(`
80
+ `);if(Pk.some(a=>a.test(e)))return null;let s=new Set,i,r=new RegExp(Th.source,Th.flags);for(;(i=r.exec(e))!==null;){let a=i[1];!Tk.has(a)&&a.includes("_")&&s.add(a)}if(s.size<3)return null;let o=[...s].slice(0,4).join(", ");return{id:tn("missing-env-var-list"),severity:"info",category:"missing_context",title:"Environment variables referenced but no comprehensive list documented",summary:`Instruction files mention ${s.size} environment variable name(s) (e.g. ${o}) but do not have a dedicated section listing all required variables. Agents and new developers cannot reliably set up the project without a complete env var reference.`,filePaths:t.map(a=>a.path),locations:[],evidence:[`${s.size} env-var-like names found: ${o}\u2026`],recommendation:'Add an "Environment Variables" or "Required Environment" section listing every required variable, its purpose, and a safe example value. A .env.example file reference also satisfies this check.',confidence:.6}}var Ok=[{label:"file naming convention",patterns:[/\b(?:kebab-case|camelCase|camelcase|PascalCase|pascalcase|snake_case|naming\s+convention)\b/i],recommendation:'Add a file naming rule to copilot-instructions.md (e.g. "Use kebab-case for all files") so Copilot agents apply the same convention as the rest of the codebase.'}];function Lk(t){let e=c=>c.path.replace(/\\/g,"/").toLowerCase(),n=c=>{let l=e(c);return l===".github/copilot-instructions.md"||l.endsWith("/.github/copilot-instructions.md")},s=c=>c.fileType==="copilot"||e(c).includes("/.github/instructions/"),i=t.find(n);if(!i)return[];let r=t.filter(s),o=t.filter(c=>!r.includes(c));if(o.length===0)return[];let a=[];for(let{label:c,patterns:l,recommendation:u}of Ok)!o.some(p=>l.some(h=>h.test(p.content)))||r.some(p=>l.some(h=>h.test(p.content)))||a.push({id:tn(`copilot-topic-silence:${c}`),severity:"info",category:"missing_context",title:`copilot-instructions.md is silent on: ${c}`,summary:`Other instruction files document the ${c}, but Copilot instruction files do not mention it. Copilot agents will have no guidance on this topic.`,filePaths:[i.path],locations:[{filePath:i.path}],evidence:[`"${c}" is documented in other instruction files but absent from Copilot instruction files.`],recommendation:u,confidence:.6});return a}function Oh(t,e){let n=[],s=Sk(t);s&&n.push(s);let i=Rk(t);i&&n.push(i);let r=kk(t);r&&n.push(r);let o=$k(t);o&&n.push(o);let a=Ik(t);if(a&&n.push(a),n.push(...Lk(t)),e==="auto"||e==="unknown")return n;let c=yk[e];if(!c)return n;let l=t.map(f=>f.content.toLowerCase()).join(`
81
+ `);if(c.keywords.filter(f=>bk(l,f)).length<c.minimumPresent){let f=c.keywords.slice(0,3).join(", ");n.push({id:tn(e),severity:"warning",category:"missing_context",title:`Missing ${c.label}-specific context`,summary:`This appears to be a ${c.label} project, but the instruction files do not mention any ${c.label}-specific context (e.g. build commands, test runner, tooling).`,filePaths:t.map(d=>d.path),locations:[],evidence:[`No keywords found matching: ${f}\u2026`],recommendation:`Add a section covering ${c.label}-specific build commands, testing conventions, and common project patterns so AI assistants have enough context to help effectively.`,confidence:.75})}return n}var jh=x(require("node:crypto"),1);var Nk=7;function Mh(t=new Date){return t.getFullYear()}var Lh=0,Wi=null;function jk(){let t=Mh();if(Wi&&Lh===t)return Wi;let e=[];for(let n=t-Nk;n<=t-1;n++)e.push(String(n));return Lh=t,Wi=new RegExp(`(?<![/-])\\b(${e.join("|")})\\b(?![/-])`,"g"),Wi}var Mk=/\b(?:history|changelog|change\s*log|release\s+notes?|releases?|versions?|what.?s\s+new|for\s+reference)\b/i,Dk=/\b(TODO\s*:?\s*remove|remove\s+later|temporary\s+fix|workaround)\b/gi,Nh=/<!--(?:(?!-->)[\s\S])*?\b(TODO|FIXME|WORKAROUND|HACK|NOTE)\b(?:(?!-->)[\s\S])*?\(\s*(\d{4})[-–\d]/gi,Fk=/deprecated[\w\s,.()\\\-:`]{0,60}(v?\d+[\w.]+|react|next\.?js|angular|vue|webpack|babel|unity|jest|mocha)/gi,Hk=[{re:/\breact\s+v?1[0-6]\b/gi,label:"React 16 or earlier"},{re:/\bnext\.?js\s+v?[1-9]\b/gi,label:"Next.js 9 or earlier"},{re:/\bunity\s+v?201[0-9]\b/gi,label:"Unity 2019 or earlier"},{re:/\bangular\s+v?[1-9]\b/gi,label:"Angular 9 or earlier"},{re:/\bvue\s+v?[12]\b/gi,label:"Vue 2 or earlier"},{re:/\bwebpack\s+v?[1-3]\b/gi,label:"Webpack 3 or earlier"},{re:/\bbabel\s+v?[1-6]\b/gi,label:"Babel 6 or earlier"},{re:/\bnode(?:\.js?)?\s+v?(1[0-6]|[1-9])\b/gi,label:"Node.js 16 or earlier"},{re:/\btypescript\s+v?[1-3]\b/gi,label:"TypeScript 3 or earlier"},{re:/\bgo\s+v?1\.(1[0-7]|[0-9])\b/gi,label:"Go 1.17 or earlier"},{re:/\bpython\s+v?2\./gi,label:"Python 2"},{re:/\bpython\s+v?3\.[0-9]\b/gi,label:"Python 3.9 or earlier"},{re:/\.NET\s+v?[1-5]\b/gi,label:".NET 5 or earlier"}];function Bk(t,e){let n=`${Be(t)}:${t.startLine}:${e}`;return`stale-${jh.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function rc(t,e){let n=[],s,i=new RegExp(e.source,e.flags);for(;(s=i.exec(t))!==null;)n.push(s[0]);return n}function Wk(t,e){let n=[],s,i=new RegExp(e.source,e.flags);for(;(s=i.exec(t))!==null;)n.push({match:s[0],index:s.index});return n}function Gk(t){let e=[],n,s=new RegExp(Nh.source,Nh.flags);for(;(n=s.exec(t))!==null;)Number(n[2])<Mh()&&e.push(n[0]);return e}function Uk(t,e){let n=t.slice(Math.max(0,e-80),e).toLowerCase();return/\b(?:do\s+not|don['']?t|avoid|never|no\s+longer|drop(?:ped|ping)?|remov(?:ed?|ing)|deprecat(?:ed?|ing)|stop(?:ped|ping)?\s+(?:using|support(?:ing)?))\b(?:(?!\n[ \t]*\n)[^.!?])*$/.test(n)}function Dh(t){let e=[],n=new Set;for(let s of t)for(let i of s.sections){if(i.heading&&Mk.test(i.heading))continue;let r=i.text,o=Ke(r,{stripInlineCode:!0}),a=Ke(r),c=[],l=0,u=`${s.path}:${i.startLine}`,f=rc(o,jk());f.length>0&&(c.push(`Year reference(s) that may be outdated: ${[...new Set(f)].join(", ")}`),l=Math.max(l,.6));let d=rc(a,Dk);d.length>0&&(c.push(`Cleanup keyword(s): ${[...new Set(d.map(m=>m.trim()))].join(", ")}`),l=Math.max(l,.6));let p=rc(a,Fk);p.length>0&&(c.push(`"deprecated" near version/tool: ${Y(p[0]??"",80)}`),l=Math.max(l,.7));for(let{re:m,label:g}of Hk){let w=Wk(o,m).filter(({index:y})=>!Uk(o,y));w.length>0&&(c.push(`Old version reference: ${g} ("${w[0].match}")`),l=Math.max(l,.7))}let h=Gk(a);h.length>0&&(c.push(`Dated ${h[0].match(/TODO|FIXME|WORKAROUND|HACK|NOTE/i)?.[0]??"TODO"} marker in HTML comment: ${Y(h[0]??"",80)}`),l=Math.max(l,.65)),c.length!==0&&(n.has(u)||(n.add(u),e.push({id:Bk(i,"stale"),severity:"warning",category:"stale_instruction",title:"Instruction may reference outdated content",summary:"This instruction may reference outdated content. Review and update or remove it.",filePaths:[s.path],locations:[{filePath:s.path,startLine:i.startLine,endLine:i.endLine}],evidence:[`Section: "${Y(r,100)}"`,...c],recommendation:"Review this section for accuracy. Update any outdated version numbers, tool references, or remove temporary notes that are no longer relevant.",fixRecipe:"Edit each flagged reference by hand: replace outdated version pins and tool names with current ones, and delete temporary notes that no longer apply. Leave copyright lines, release dates, and historical references as they are.",confidence:l})))}return e}var Hh=x(require("node:crypto"),1);var Vk=["write clean code","write clean","use best practices","make it production ready","production ready","production-ready","be careful","do the right thing","follow good patterns","write good tests","keep it simple","keep things simple","best practices","production-quality","production quality","follow best practices","idiomatic code","make sure everything works","ensure quality","write quality code","industry standards","generally accepted","solid principles","follow solid","self-documenting","make it maintainable","clean maintainable","good engineering","clean architecture","maintainable code","readable code","high-quality code","high quality code","follow industry standards","functional programming principles","write idiomatic","polished and professional","looks polished","feel smooth and native","smooth and native","feels native","feel native","feel smooth","accessible and usable","provide good defaults","great user experience","good user experience","seamless experience","intuitive interface","user-friendly","easy to use","delightful","looks good","visually appealing","native feel","follow go best practices","follow rust best practices","follow python best practices","idiomatic go","idiomatic rust","idiomatic python","idiomatic elixir","idiomatic typescript"],Fh=120;function zk(t){let e=new Set;for(let n of t)e.add(n),n.includes("-")&&e.add(n.replace(/-/g," "));return[...e]}var Bh=zk(Vk),qk=new Set(["write clean code","write clean","use best practices","best practices","follow best practices","make it production ready","production ready","production-ready","production quality","production-quality","be careful","solid principles","follow solid","clean architecture","make it maintainable"]);function Kk(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Yk=new Map(Bh.map(t=>[t,new RegExp(`\\b${Kk(t)}\\b`)]));function Jk(t,e){let n=t.split(`
82
+ `).map(i=>i.trim()),s=[];for(let i=0;i<n.length;i++){let r=n[i];r&&e.test(r.toLowerCase())&&r.length<=Fh&&s.push(r);let o=n[i+1];if(r&&o){let a=`${r} ${o}`;e.test(a.toLowerCase())&&a.length<=Fh&&s.push(a)}}return s}function Xk(t){let e=`${Be(t)}:${t.startLine}:vague`;return`vague-${Hh.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Wh(t,e={}){let n=[],s=new Set;for(let i of t)for(let r of i.sections){let o=`${i.path}:${r.startLine}`;if(s.has(o))continue;let a=Ke(r.text,{stripInlineCode:!0}),c=a.toLowerCase().replace(/\n/g," "),l=[],u=[];for(let g of Bh){let b=Yk.get(g);if(b.test(c))for(let w of Jk(a,b))l.includes(g)||l.push(g),u.includes(w)||u.push(w)}if(l.length===0)continue;s.add(o);let f=l.map(g=>`"${g}"`).join(", "),d=l.some(g=>qk.has(g)),p=d?"warning":"info",h=e.severityOverride??p,m=d?.8:.75;n.push({id:Xk(r),severity:h,category:"vague_guidance",title:"Vague guidance detected",summary:`This section contains guidance that may be too vague to be actionable: ${f}.`,filePaths:[i.path],locations:[{filePath:i.path,startLine:r.startLine,endLine:r.endLine}],evidence:u.slice(0,3).map(g=>`Line: "${g}"`),recommendation:'Replace vague guidance with concrete constraints \u2014 specific commands, forbidden patterns, or measurable criteria. For example, replace "write clean code" with "functions must be \u2264 50 lines; no unused variables".',confidence:m})}return n}var zi=x(require("node:crypto"),1),je=x(require("node:path"),1),We=x(require("node:fs"),1);var bs=["# PromptCI: ignore generated reports, keep the shared baseline, config, and custom rules","**/.promptci/*","!**/.promptci/baseline.json","!**/.promptci/config.json","!**/.promptci/custom-rules.json"],oc=`${bs.join(`
83
83
  `)}
84
- `;function ws(t){return`${bs.join(t)}${t}`}var Bi=[{id:"no-secret-safeguard",title:"Missing secret safeguard instruction",summary:"Environment variables are used in this repository, but no instruction found warning the agent never to print or commit secrets.",patterns:[/never\s+.*(print|commit|log|expose)\s+.*(secret|password|token|key|credential)/i,/do\s+not\s+.*(print|commit|log|expose)\s+.*(secret|password|token|key|credential)/i,/secrets?\s+must\s+never\s+be/i,/keep\s+secrets?\s+secure/i],recommendation:'Add a rule such as: "Never print or commit secrets, API keys, or credentials. If you need to use an environment variable, use it silently without echoing its value."',severity:"warning",confidence:.8,fixRecipe:"Never print or commit secrets, API keys, or credentials. If you need to use an environment variable, use it silently without echoing its value."},{id:"no-supabase-service-role-rule",title:"Missing Supabase service role safeguard",summary:"Supabase is used in this repository, but no instruction found warning that the service role key must only be used server-side.",patterns:[/service\s+role\s+key\s+must\s+(stay|only\s+be\s+used)\s+server-side/i,/never\s+expose\s+supabase\s+service\s+role/i,/supabase\s+service\s+role\s+key.*server-side/i],recommendation:'Add a rule such as: "The Supabase service role key must stay server-side and never be exposed to the client."',severity:"warning",confidence:.85,fixRecipe:"Keep SUPABASE_SERVICE_ROLE_KEY server-side only. Never expose it in browser code, logs, or committed files."},{id:"no-upload-boundary-docs",title:"Missing data boundary documentation for uploads",summary:"Upload features detected, but no instruction found defining data boundaries or validation requirements for user-provided files.",patterns:[/validate\s+user\s+(provided|uploaded)\s+files/i,/data\s+boundary\s+for\s+uploads/i,/upload\s+validation/i,/limit\s+upload\s+size/i],recommendation:"Add guidance on how to safely handle and validate user uploads to prevent security risks.",severity:"info",confidence:.7,fixRecipe:"Before handling user uploads, document what file types are allowed, the max file size, and the sanitization steps required."},{id:"no-promptci-report-safeguard",title:"Missing safeguard for .promptci/ reports",summary:".promptci/ folder exists, but no instruction found warning the agent not to commit generated reports to the repository.",patterns:[/do\s+not\s+commit\s+\.promptci/i,/never\s+commit\s+\.promptci/i,/\.promptci\/\s+reports\s+should\s+not\s+be\s+committed/i],recommendation:'Add a rule such as: "Do not commit .promptci/ reports to the repository."',severity:"info",confidence:.8,fixRecipe:"Do not commit .promptci/ reports to the repository."}],qk=[{pattern:/\brm\s+-(?:rf|fr)\b/i,name:"rm -rf"},{pattern:/drop\s+table/i,name:"drop table"},{pattern:/git\s+push\s+--force/i,name:"git push --force"}];function Wi(t){return`security-pack-${Ui.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Kk(t,e){return`destructive-command-${Ui.createHash("sha1").update(`destructive-command:${t}:${e}`).digest("hex").slice(0,12)}`}function Yk(t){return`security-pack-inspect-reports-first-${Ui.createHash("sha1").update(`inspect-reports-first:${t}`).digest("hex").slice(0,12)}`}function vs(t,e){return e.some(n=>n.test(t))}function Gi(t,e){return t.startsWith("!")?!1:t.replace(/^\/+|\/+$/g,"").split("/").includes(e)}function Dh(t){let{files:e,repoRoot:n}=t;if(e.length===0)return[];let s=[],i=e.map(y=>y.content).join(`
85
- `),r=e.map(y=>y.path);if([".env",".env.example",".env.local",".env.development",".env.production"].some(y=>We.existsSync(je.join(n,y)))||t.files.some(y=>/env\s+vars|environment\s+variables/i.test(y.content))){let y=Bi.find(v=>v.id==="no-secret-safeguard");vs(i,y.patterns)||s.push({id:Wi(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:["Environment variables detected but no safeguard instruction found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}let c={...t.packageJson.dependencies,...t.packageJson.devDependencies,...t.packageJson.peerDependencies};if(We.existsSync(je.join(n,"supabase/migrations"))||Object.keys(c).some(y=>y==="@supabase/supabase-js"||y.startsWith("@supabase/"))){let y=Bi.find(v=>v.id==="no-supabase-service-role-rule");vs(i,y.patterns)||s.push({id:Wi(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:["Supabase detected but no service role safeguard instruction found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}if(t.files.some(y=>{let v=y.path.replace(/\\/g,"/");return v.includes("/api/upload")||v.includes("/uploads/")||/multer|busboy|formidable/i.test(y.content)})){let y=Bi.find(v=>v.id==="no-upload-boundary-docs");vs(i,y.patterns)||s.push({id:Wi(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:["Upload features detected but no data boundary documentation found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}if(We.existsSync(je.join(n,".promptci"))){let y=Bi.find(v=>v.id==="no-promptci-report-safeguard");vs(i,y.patterns)||s.push({id:Wi(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:[".promptci/ folder detected but no report safeguard instruction found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}for(let y of e)for(let v of qk)if(v.pattern.test(y.content)){let k=[/ask\s+(before|for\s+approval)/i,/confirm\s+before/i,/be\s+careful\s+with/i,/destructive\s+operation/i,/\bdanger(?:ous)?\b/i];vs(y.content,k)||s.push({id:Kk(L(y),v.name),severity:"warning",category:"security",title:`Destructive command "${v.name}" without safety language`,summary:`Instruction file contains a destructive command "${v.name}" but lacks safety language (e.g., "Ask before running").`,filePaths:[y.path],locations:[],evidence:[`Destructive command "${v.name}" found in ${je.basename(y.path)} without safety language.`],recommendation:`Add safety language such as "Ask for confirmation before running ${v.name}" to ensure destructive operations are not performed accidentally.`,confidence:.7})}let d=je.join(n,".gitignore"),p="";try{We.existsSync(d)&&ae(n,d)&&(p=We.readFileSync(d,"utf8"))}catch{}let h=p.split(/\r?\n/).map(y=>y.trim()).filter(y=>y&&!y.startsWith("#"));h.some(y=>Gi(y,".promptci"))||s.push({id:"security-pack-no-promptci-gitignore",severity:"info",category:"security",title:"Missing .promptci/ ignore in .gitignore",summary:"The .promptci/ directory is not ignored in .gitignore, which may lead to committing large generated scan reports to the repository.",filePaths:[".gitignore"],locations:[],evidence:[".promptci/ entry not found in .gitignore"],recommendation:"Add the following to `.gitignore` so generated reports stay out of git while the shared baseline and config remain committed:\n"+bs.map(y=>` ${y}`).join(`
86
- `)+"\n\nUse `.promptci/*` rather than `.promptci/` \u2014 git does not descend into an ignored directory, so the `!` negations only work against the directory's contents.",fixRecipe:sc,autoApplySafe:!0,confidence:.9});let b=["coverage","dist","build",".next","bin","obj","temp","tmp","logs"].filter(y=>{let v=je.join(n,y);try{if(We.existsSync(v)&&We.statSync(v).isDirectory())return!h.some(I=>Gi(I,y))}catch{}return!1});b.length>0&&s.push({id:"security-pack-unignored-dirs",severity:"warning",category:"context_bloat",title:"Unignored build, output, or coverage directories",summary:`The repository contains directory/directories (${b.join(", ")}) that are commonly generated but not ignored in .gitignore. AI tools may ingest these, inflating token costs.`,filePaths:[".gitignore"],locations:[],evidence:b.map(y=>`Directory "${y}" exists but is not ignored in .gitignore.`),recommendation:`Add generated directories to .gitignore. For example: "${b.map(y=>`${y}/`).join(", ")}"`,fixRecipe:b.map(y=>`echo "${y}/" >> .gitignore`).join(`
87
- `),autoApplySafe:!0,confidence:.8});let w=!1;try{let y=je.join(n,".promptci","config.json");if(We.existsSync(y)&&ae(n,y)){let v=JSON.parse(We.readFileSync(y,"utf8"));if(Array.isArray(v.include)){let k=["**/*","**/*.md","*","*.*","**"];w=v.include.some(R=>k.includes(R.trim()))}}}catch{}if(w){let y=e.filter(v=>{let k=je.relative(n,v.path).replace(/\\/g,"/");return k.includes(".promptci/")||k.includes("coverage/")||k.includes(".next/")});y.length>0&&s.push({id:"security-pack-broad-include",severity:"warning",category:"context_bloat",title:"Broad include pattern scanning generated directories",summary:"PromptCI configuration has a broad include pattern that matches generated directories such as .promptci/ or coverage/, causing them to be unnecessarily scanned.",filePaths:[".promptci/config.json"],locations:[],evidence:y.map(v=>`Scanned generated file: ${je.relative(n,v.path).replace(/\\/g,"/")}`),recommendation:"Refine the include patterns in .promptci/config.json or add exclusions to avoid scanning generated/temporary documents.",fixRecipe:'Modify .promptci/config.json to restrict "include" to specific instruction files, or add exclusions to "exclude".',confidence:.95})}for(let y of e){let v=[{re:/read\s+.*\.promptci\s+before/i,label:"Instruction to read .promptci reports first"},{re:/inspect\s+.*\.promptci\s+before/i,label:"Instruction to inspect .promptci reports first"},{re:/check\s+.*\.promptci\s+before/i,label:"Instruction to check .promptci reports first"},{re:/read\s+.*report.*\s+before\s+.*(source|docs|code)/i,label:"Instruction to read generated reports before source"},{re:/inspect\s+.*report.*\s+before\s+.*(source|docs|code)/i,label:"Instruction to inspect generated reports before source"}];for(let k of v)if(k.re.test(y.content)){s.push({id:Yk(L(y)),severity:"info",category:"context_bloat",title:"Instruction prioritizing generated reports over source docs",summary:`Instruction file "${je.basename(y.path)}" tells the agent to inspect generated reports before source files, which can cause circular or outdated guidance ingestion.`,filePaths:[y.path],locations:[],evidence:[xn(y.content,k.re,k.label)],recommendation:"Recommend linking to latest reports or directing the agent to read source documents first instead of generated reports.",fixRecipe:"Update the instruction to prioritize reading source files and configuration rather than relying on generated reports.",confidence:.7});break}}return s}var Se=x(require("node:path"),1),Ee=x(require("node:fs"),1);function Fh(t){let e=[],{packageJson:n,repoRoot:s,files:i}=t,r=!!(n.dependencies.next||n.devDependencies.next),o=Ee.existsSync(Se.join(s,"next.config.js"))||Ee.existsSync(Se.join(s,"next.config.mjs"))||Ee.existsSync(Se.join(s,"next.config.ts"))||Ee.existsSync(Se.join(s,"apps","web","next.config.js"))||Ee.existsSync(Se.join(s,"apps","web","next.config.mjs"))||Ee.existsSync(Se.join(s,"apps","web","next.config.ts"));if(!r&&!o)return[];let a=Ee.existsSync(Se.join(s,"app"))||Ee.existsSync(Se.join(s,"src","app"))||Ee.existsSync(Se.join(s,"apps","web","app"))||Ee.existsSync(Se.join(s,"apps","web","src","app")),c=Ee.existsSync(Se.join(s,"pages"))||Ee.existsSync(Se.join(s,"src","pages"))||Ee.existsSync(Se.join(s,"apps","web","pages"))||Ee.existsSync(Se.join(s,"apps","web","src","pages"));if(a&&(i.some(u=>u.content.toLowerCase().includes("app router")||u.content.toLowerCase().includes("server component")||u.content.toLowerCase().includes("client component"))||e.push({id:"nextjs-missing-app-router-guidance",severity:"warning",category:"structure",title:"Missing Next.js App Router Guidance",summary:"The project uses the App Router, but the instructions do not mention App Router specific rules like Server vs Client components.",filePaths:i.map(u=>u.path),locations:[],evidence:['App directory detected, but no "App Router" or "Server/Client Component" mention in instructions.'],recommendation:"Add guidance for Next.js App Router, specifically regarding Server and Client Component usage.",confidence:.9})),a&&!c){let l=i.filter(u=>u.content.toLowerCase().includes("pages router")||u.content.toLowerCase().includes("getstaticprops")||u.content.toLowerCase().includes("getserversideprops"));l.length>0&&e.push({id:"nextjs-stale-pages-router-guidance",severity:"warning",category:"stale_instruction",title:"Stale Pages Router Guidance",summary:"The project uses the App Router exclusively, but instructions still reference Pages Router concepts like getStaticProps.",filePaths:l.map(u=>u.path),locations:l.map(u=>({filePath:u.path})),evidence:["Pages Router specific terms found in an App Router project."],recommendation:"Remove or update Pages Router specific instructions to align with App Router.",confidence:.8})}return e}var Pn=x(require("node:path"),1),ic=x(require("node:fs"),1);function Hh(t){let e=[],{manifests:n,repoRoot:s,files:i}=t,r=!!n.pyproject,o=n.requirements!==void 0,a=ic.existsSync(Pn.join(s,"Pipfile")),c=ic.existsSync(Pn.join(s,"environment.yml"));if(!r&&!o&&!a&&!c)return[];(n.pyproject?.includes("pytest")||n.requirements?.includes("pytest"))&&(i.some(p=>p.content.toLowerCase().includes("pytest")||p.content.toLowerCase().includes("test guidance"))||e.push({id:"python-missing-pytest-guidance",severity:"info",category:"structure",title:"Missing Pytest Guidance",summary:"The project uses pytest, but no testing guidance was found in the instructions.",filePaths:i.map(p=>p.path),locations:[],evidence:["pytest detected in dependencies, but no mention in instructions."],recommendation:"Add guidance on how to run and write tests using pytest.",confidence:.8}));let u=[],f=[];return a&&u.push("Pipenv (Pipfile)"),a&&f.push(Pn.join(s,"Pipfile")),c&&u.push("Conda (environment.yml)"),c&&f.push(Pn.join(s,"environment.yml")),r&&n.pyproject?.includes("[tool.poetry]")&&u.push("Poetry (pyproject.toml)"),r&&n.pyproject?.includes("[tool.poetry]")&&f.push(Pn.join(s,"pyproject.toml")),u.length>1&&e.push({id:"python-multiple-env-managers",severity:"warning",category:"conflict",title:"Multiple Python Environment Managers",summary:`Multiple environment managers detected: ${u.join(", ")}. This can lead to conflicting instructions.`,filePaths:f.length>0?f:i.map(d=>d.path),locations:[],evidence:[`Detected: ${u.join(", ")}`],recommendation:"Decide on a single environment manager and remove the others, or clearly document when to use each.",confidence:.9}),e}var rc=x(require("node:path"),1),oc=x(require("node:fs"),1);function Bh(t){let e=[],{repoRoot:n,files:s}=t,i=oc.existsSync(rc.join(n,"Assets")),r=oc.existsSync(rc.join(n,"ProjectSettings","ProjectVersion.txt")),o=s.map(d=>d.content).join(`
88
- `),a=/\bunity\b.*\b(lts|editor|hub|engine)\b|\bmonobehaviour\b|\bunityengine\b|\bgameobject\b|\bprefab\b|\bscriptableobject\b/i.test(o);if(!(i&&r)&&!a)return[];let c=s.map(d=>d.path);return/monobehaviour\s+(?:lifecycle|guidance|rules?)|\blifecycle\s+(?:method|methods|guidance|rules?)|instantiate\b.*monobehaviour|avoid\b.*update|new\s+monobehaviour|awake\(\)|start\(\)|update\(\)/i.test(o)||e.push({id:"unity-missing-monobehaviour-guidance",severity:"warning",category:"structure",title:"Missing Unity MonoBehaviour Lifecycle Guidance",summary:'Unity project detected, but instructions lack guidelines on MonoBehaviour lifecycle (e.g. not calling "new" on MonoBehaviours, avoiding empty Update methods).',filePaths:c,locations:[],evidence:["Unity detected, but no MonoBehaviour lifecycle rules found in instructions."],recommendation:'Add guidance warning never to use "new" to instantiate MonoBehaviours, and advising on efficient Update() / Awake() / Start() usage.',fixRecipe:'Do not instantiate MonoBehaviours using the "new" keyword; always use GameObject.AddComponent or Object.Instantiate. Avoid leaving empty Awake, Start, or Update methods in scripts as they still incur Unity lifecycle overhead.',confidence:.8}),/\[serializefield\]|serializefield\b|prefab\s+(?:safety|workflow|guidance|rules?)|meta\s+file/i.test(o)||e.push({id:"unity-missing-serialization-guidance",severity:"warning",category:"structure",title:"Missing Unity Serialization and Prefab Safety Guidance",summary:"Unity project detected, but instructions lack safety rules for Prefabs and [SerializeField] parameters.",filePaths:c,locations:[],evidence:["Unity detected, but no SerializeField or prefab rules found in instructions."],recommendation:"Add rules for using [SerializeField] for private variables to expose them in the inspector, and avoiding editing .meta files manually.",fixRecipe:"Use [SerializeField] to expose private fields in the Unity Inspector instead of making them public. Never manually edit or delete .meta files; let the Unity Editor manage them to prevent serialization breakages.",confidence:.8}),/play\s+mode|test\s+runner|unity\s+test/i.test(o)||e.push({id:"unity-missing-test-guidance",severity:"info",category:"structure",title:"Missing Unity Play Mode and Test Runner Guidance",summary:"Unity project detected, but instructions do not guide agents to test changes in Play Mode or Unity Test Runner.",filePaths:c,locations:[],evidence:["Unity detected, but no Play Mode/Test Runner verification found in instructions."],recommendation:"Add instructions telling agents to run tests using Unity Test Runner or test changes in Play Mode.",fixRecipe:"Verify gameplay and UI changes by testing in the Unity Editor Play Mode or running Unity Test Runner (Window > General > Test Runner).",confidence:.75}),e}var ac=x(require("node:fs"),1);function Wh(t){let e=[],{repoRoot:n,files:s}=t,i=t.projectType==="dotnet";if(!i)try{i=ac.readdirSync(n).some(u=>u.endsWith(".sln")||u.endsWith(".csproj"))}catch{}let r=s.map(u=>u.content).join(`
89
- `),o=/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(r);if(!i&&!o)return[];let a=s.map(u=>u.path);/dotnet\s+(build|test|restore|run)/i.test(r)||e.push({id:"dotnet-missing-validation-commands",severity:"warning",category:"structure",title:"Missing .NET Validation Commands",summary:'The project uses .NET, but instructions do not mention dotnet validation commands like "dotnet build" or "dotnet test".',filePaths:a,locations:[],evidence:[".NET detected, but no dotnet build/test commands found in instructions."],recommendation:'Add instructions telling the agent to run "dotnet build" and "dotnet test" to verify changes.',fixRecipe:"Before saying work is complete, run dotnet build && dotnet test to verify changes.",confidence:.85});let l;try{let f=ac.readdirSync(n).find(d=>d.endsWith(".csproj"));if(f){let d=ie(n,f)??"",p=/<TargetFramework>(.*?)<\/TargetFramework>/.exec(d);p&&(l=p[1]?.trim())}}catch{}if(l){let u=/\b(netcoreapp\d+\.\d+|net5\.0|netcore)\b/i.test(r);/^net(?:[6-9]|[1-9]\d+)\.0/.test(l)&&u&&e.push({id:"dotnet-obsolete-framework-reference",severity:"warning",category:"stale_instruction",title:".NET Obsolete Framework Reference",summary:`The project targets modern .NET (${l}), but instructions still reference obsolete versions like .NET Core 3.1 or .NET 5.0.`,filePaths:a,locations:[],evidence:[`Project targets ${l}; obsolete framework references found in instructions.`],recommendation:`Update instructions to reference the current target framework version (${l}).`,fixRecipe:`Target .NET ${l} as the framework for this project. Do not use legacy .NET Core 3.1 or .NET 5.0 APIs.`,confidence:.8})}return e}var Gh=x(require("node:path"),1),Uh=x(require("node:fs"),1);function Vh(t){let e=[],{repoRoot:n,files:s}=t,i=Uh.existsSync(Gh.join(n,"go.mod")),r=s.map(l=>l.content).join(`
90
- `),o=/\bgo\.mod\b/i.test(r)||/`[^`\n]*\bgo\s+(?:build|test|run|get|mod)\b[^`\n]*`/i.test(r);if(!i&&!o)return[];let a=s.map(l=>l.path);return/\bgo\s+test\b/i.test(r)||e.push({id:"go-missing-testing-commands",severity:"warning",category:"structure",title:"Missing Go Testing Commands",summary:'Go project detected, but instructions do not mention Go testing commands like "go test ./...".',filePaths:a,locations:[],evidence:['Go detected, but no "go test" command found in instructions.'],recommendation:'Add instructions telling the agent to run "go test ./..." to verify changes.',fixRecipe:"Before saying work is complete, run go test ./... to verify all tests pass.",confidence:.85}),e}var zh=x(require("node:path"),1),qh=x(require("node:fs"),1);function Kh(t){let e=[],{repoRoot:n,files:s}=t,i=qh.existsSync(zh.join(n,"Cargo.toml")),r=s.map(u=>u.content).join(`
91
- `),o=/\bcargo\.toml\b|\bcargo\s+(build|test|run|clippy|fmt)\b/i.test(r);if(!i&&!o)return[];let a=s.map(u=>u.path);/cargo\s+(test|clippy|fmt)/i.test(r)||e.push({id:"rust-missing-verification-commands",severity:"warning",category:"structure",title:"Missing Rust Verification Commands",summary:'Rust project detected, but instructions do not mention Cargo verification commands like "cargo test" or "cargo clippy".',filePaths:a,locations:[],evidence:["Rust detected, but no cargo test/clippy/fmt commands found in instructions."],recommendation:"Add instructions telling the agent to run cargo test, cargo clippy, and cargo fmt to verify changes.",fixRecipe:"Before saying work is complete, verify changes by running cargo fmt, cargo clippy, and cargo test.",confidence:.85});let l;if(i)try{let u=ie(n,"Cargo.toml")??"",f=/^rust-version\s*=\s*["'](.*?)["']/m.exec(u);f&&(l=f[1]?.trim())}catch{}if(l){let u=p=>{let h=/^(\d+)\.(\d+)/.exec(p);return h?`${h[1]}.${h[2]}`:void 0},d=/\bRust\s+(\d+\.\d+(?:\.\d+)?)\b/i.exec(r);if(d){let p=d[1];u(p)!==u(l)&&e.push({id:"rust-version-mismatch",severity:"warning",category:"stale_instruction",title:"Rust Version Mismatch",summary:`Instructions mention Rust version ${p}, but Cargo.toml specifies rust-version = "${l}".`,filePaths:a,locations:[],evidence:[`Cargo.toml requires rust-version = ${l}; instructions mention Rust ${p}`],recommendation:`Update instructions to match the Rust version specified in Cargo.toml (${l}).`,fixRecipe:`Target Rust ${l} as the Minimum Supported Rust Version (MSRV) for this project.`,confidence:.8})}}return e}function Yh(t){let e=[];return e.push(...Fh(t)),e.push(...Hh(t)),e.push(...Bh(t)),e.push(...Wh(t)),e.push(...Vh(t)),e.push(...Kh(t)),e}var Xh=x(require("node:path"),1),Zh=x(require("node:crypto"),1);function xs(t,e){let n=Zh.createHash("sha1").update(`prompt-cache-${t}:${e}`).digest("hex").slice(0,12);return`prompt-cache-${t}-${n}`}var Jk=[{re:/\b(?:last\s+updated|last\s+modified|updated\s+at|modified\s+at|date)\b\s*:\s*\b\d{4}-\d{2}-\d{2}\b/i,label:'Dated "last updated"/"modified" line'},{re:/\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}\b/i,label:"ISO 8601 timestamp"},{re:/\b(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b/i,label:"Long-form calendar date"}],Xk=[{re:/health\s+score\s*:\s*\d+/i,label:"Health-score line from a scan report"},{re:/files\s+scanned\s*:\s*\d+/i,label:"File-count line from a scan report"},{re:/promptci\s+report/i,label:"PromptCI report heading"},{re:/\bgenerated\s+by\s+promptci\b/i,label:"PromptCI generated-by marker"},{re:/latest\s+scan\s+results/i,label:'Pasted "latest scan results" section'},{re:/scan\s+history/i,label:'Pasted "scan history" section'}],Zk=[{re:/current\s+branch\s*:\s*\S+/i,label:"Current-branch line"},{re:/git\s+branch\s*:\s*\S+/i,label:"Git-branch line"},{re:/current\s+task\s*:\s*\S+/i,label:"Current-task line"}],Jh=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i;function Qh(t){let e=[],n=t.filter(s=>Ce.has(s.fileType));for(let s of n){let i=Xh.basename(s.path);for(let c of Jk)if(c.re.test(s.content)){e.push({id:xs("volatile-timestamp",L(s)),severity:"warning",category:"context_bloat",title:"Volatile timestamp in instruction file",summary:`The instruction file "${i}" contains a volatile date or timestamp. Frequently changing dates in persistent instruction files invalidate prompt caches.`,filePaths:[s.path],locations:[],evidence:[xn(s.content,c.re,c.label)],recommendation:"Move volatile dates to a separate task-specific prompt or scratch file, or remove them from canonical instructions.",fixRecipe:'Remove the "Last updated: <date>" or timestamp line from the file.',confidence:.85});break}for(let c of Xk)if(c.re.test(s.content)){e.push({id:xs("pasted-report",L(s)),severity:"warning",category:"context_bloat",title:"Pasted scan report or summary in instructions",summary:`The instruction file "${i}" contains pasted scan results or reports. Committing generated reports into canonical instruction files breaks prompt caching and bloats context.`,filePaths:[s.path],locations:[],evidence:[xn(s.content,c.re,c.label)],recommendation:"Link to the generated report file or read it on-demand instead of pasting its contents into canonical instructions.",fixRecipe:"Delete the pasted report summary block and reference the report file path instead.",confidence:.9});break}for(let c of Zk)if(c.re.test(s.content)){e.push({id:xs("volatile-branch-task",L(s)),severity:"warning",category:"context_bloat",title:"Volatile branch or task status in instructions",summary:`The instruction file "${i}" contains active git branch or task details. Frequently updated task status or branch names break prompt caching.`,filePaths:[s.path],locations:[],evidence:[xn(s.content,c.re,c.label)],recommendation:"Move branch-specific notes and active task details to git commit messages, PR descriptions, or a temporary scratch file.",fixRecipe:"Remove active branch and task notes from the persistent instructions.",confidence:.85});break}if(Jh.test(s.content)){let c=s.content.match(Jh)?.[0]??"";e.push({id:xs("local-paths",L(s)),severity:"warning",category:"context_bloat",title:"Local machine paths in instructions",summary:`The instruction file "${i}" contains absolute local machine paths ("${c}"). These paths change per environment, preventing prompt caching and causing instruction drift.`,filePaths:[s.path],locations:[],evidence:[`Found absolute local path: ${c}`],recommendation:"Use repository-relative paths instead of absolute local machine paths.",fixRecipe:"Replace absolute local paths with repository-relative paths.",confidence:.8})}let r=s.content.split(/\r?\n/),o=0,a=0;for(let c of r){let l=c.trim();if(l.startsWith("|")&&l.endsWith("|")){if(/^\|[-\s:|]+\|$/.test(l))continue;a++}else a>o&&(o=a),a=0}a>o&&(o=a),o>15&&e.push({id:xs("large-table",L(s)),severity:"warning",category:"context_bloat",title:"Large table in instruction file",summary:`The instruction file "${i}" contains a large Markdown table (${o} rows). Large tables bloat prompt context and reduce caching friendliness.`,filePaths:[s.path],locations:[],evidence:[`Markdown table with ${o} rows found in ${i}.`],recommendation:"Move large tables to separate documentation files (e.g. under docs/) or load them on-demand via tools instead of keeping them in always-loaded instructions.",fixRecipe:"Extract the table to a separate document and link to it.",confidence:.9})}return e}var cc=x(require("node:path"),1);var em=12,Qk={idPrefix:"skill",noun:"Skill",why:"Claude Code treats frontmatter as optional, but strict Agent Skills loaders (for example Codex) skip a skill without `name` and `description`.",recommendation:"Add a frontmatter block with `name` and `description` at the top of the SKILL.md file.",noFrontmatterSeverity:"warning"};function Tn(t,e,n=""){return`ai-config-skill-${t}-${le(`${e}|${n}`)}`}function eR(t){return t.toLowerCase().replace(/[`*_~]/g,"").replace(/[^a-z0-9]+/g," ").trim()}function tR(t){if(!t)return!1;let e=t.trim();if(/^(https?:|mailto:|#|\/\/)/i.test(e)||/^[a-zA-Z]:[\\/]/.test(e)||/[<>{}*?|"\s]/.test(e)||e.includes(".."))return!1;let n=e.split("#")[0],s=n.includes("/"),i=/\.[a-z0-9]{1,6}$/i.test(n);return s&&i}function lc(t){let e=[],n=new Set,s=(r,o)=>{if(!tR(r))return;let a=r.split("#")[0];n.has(a)||(n.add(a),e.push({ref:a,line:o}))},i=t.split(/\r?\n/);for(let r=0;r<i.length;r++){let o=i[r];for(let a of o.matchAll(/\[[^\]]*\]\(([^)]+)\)/g))s(a[1].split(/\s+/)[0].replace(/^<|>$/g,""),r+1);for(let a of o.matchAll(/`([^`]+)`/g))s(a[1].trim(),r+1)}return e}function nR(t,e){if(e.startsWith("/")){let r=e.slice(1);return sR.has(r.split("/")[0])?void 0:[r]}let n=/^(.*?)\/?skills\/[^/]+$/.exec(t)?.[1],i=[t,...n&&n!==".claude"&&n!==".agents"?[n]:[],"."];return[...new Set(i.map(r=>r==="."||r===""?e:`${r}/${e}`))]}var sR=new Set(["usr","var","etc","opt","tmp","home","Users","Library","bin","sbin","dev","proc","mnt","private","System"]);function iR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rR(t,e){let s="[^`;\\n]{0,40}";return new RegExp(`\\b(?:do\\s+not|don'?t|never|must\\s+not|should\\s+not|shouldn'?t)\\s+(?:\\w+\\s+)?(?:commit|stage|check\\s+in|add|push|track)\\b(?:${s}\`[^\`\\n]{1,100}\`){0,4}${s}\`?${iR(e)}`,"i").test(t)}function uc(t){let e=[],n=[],s;for(let i of t.aiConfig.skills){let r=ie(t.repoRoot,i);if(r===void 0)continue;let o=qt(cc.dirname(i)).split("/").pop()??"",a=gt(r);if(e.push(...Ot(i,r,a,Qk)),!a.present)continue;let c=typeof a.data.name=="string"?a.data.name.trim():void 0,l=typeof a.data.description=="string"?a.data.description.trim():void 0;c?c!==o&&o&&e.push(F({id:Tn("name-dir-mismatch",i),title:"Skill `name` does not match its directory",summary:`${i}: frontmatter \`name: ${c}\` does not match the skill directory \`${o}/\`. Claude resolves skills by directory name.`,filePaths:[i],locations:[{filePath:i,startLine:a.keyLines.name??1,endLine:a.keyLines.name??1}],evidence:[`name: ${c}`,`directory: ${o}`],recommendation:"Rename the directory or the `name` field so they match.",confidence:.6})):e.push(F({id:Tn("missing-name",i),title:"Skill frontmatter is missing `name`",summary:`${i} has no \`name\` field. Claude uses \`name\` to identify and invoke the skill.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:a.fenceEndLine>0?a.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(a.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter matching the skill directory name.",confidence:.85})),l?l.length<em&&e.push(F({id:Tn("empty-description",i),title:"Skill `description` is too short to trigger reliably",summary:`${i}: \`description\` is only ${l.length} characters. Claude matches the description against the user's request to decide when to invoke the skill.`,filePaths:[i],locations:[{filePath:i,startLine:a.keyLines.description??1,endLine:a.keyLines.description??1}],evidence:[`description: ${l}`],recommendation:"Expand the description to describe the task and its trigger conditions.",confidence:.7})):e.push(F({id:Tn("missing-description",i),title:"Skill frontmatter is missing `description`",summary:`${i} has no \`description\`. The description is the trigger text Claude matches against \u2014 without it the skill rarely activates.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:a.fenceEndLine>0?a.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(a.data).join(", ")||"(none)"}`],recommendation:"Add a `description` that says what the skill does and when to use it.",confidence:.85}));let u=qt(cc.dirname(i)),f=r.split(/\r?\n/);for(let{ref:d,line:p}of lc(r)){if(pa(d)||/^\/?\.git\//.test(d))continue;let h=nR(u,d);if(!h||h.some(g=>at(t.repoRoot,g))||(s??=_i(t.repoRoot),h.some(g=>s(g)))||rR(f[p-1]??"",d))continue;let m=d.startsWith("/");e.push(F({id:Tn("dead-ref",i,d),title:"Skill references a bundled file that does not exist",summary:m?`${i} references \`${d}\`, but no such file exists at that path from the repository root.`:`${i} references \`${d}\`, but no such file exists relative to the skill directory or the repository root.`,filePaths:[i],locations:[{filePath:i,startLine:p,endLine:p}],evidence:[`Reference: ${d}`,`Looked in: ${h.join(", ")}`],recommendation:"Add the referenced file, fix the path, or remove the reference.",confidence:.75}))}l&&n.push({filePath:i,description:l})}return e.push(...oR(n)),Te(t.repoRoot,e)}function oR(t){let e=[],n=new Map;for(let s of t){if(s.description.length<em)continue;let i=eR(s.description);if(!i)continue;let r=n.get(i)??[];r.push(s),n.set(i,r)}for(let s of n.values()){if(s.length<2)continue;let i=[...s].sort((o,a)=>o.filePath.localeCompare(a.filePath)),r=i.map(o=>o.filePath);e.push(F({id:Tn("overlap",r.join("|")),title:"Multiple skills share the same trigger description",summary:`${r.length} skills have effectively identical \`description\` text, so Claude cannot tell which to invoke for a given request.`,filePaths:r,locations:i.map(o=>({filePath:o.filePath,startLine:1,endLine:1})),evidence:[`Shared description: ${i[0].description}`,`Skills: ${r.join(", ")}`],recommendation:"Give each skill a distinct description that states its unique trigger conditions.",confidence:.75}))}return e}var ut=x(require("node:fs"),1),Ue=x(require("node:path"),1);var bc="skill-supply-chain",aR=20*1024*1024,cR=2e3,lR={"remote-exec":{title:"Skill may download and execute remote code",category:"security",summary:"content fetched from the network appears to be executed \u2014 piped or substituted into an interpreter, or downloaded and run without verification. Whatever the server returns at run time runs with the user's permissions, and it can change after the skill was reviewed.",recommendation:"Consider vendoring the script into the skill directory (so it is reviewed with the skill), or download it to a file, verify a pinned checksum, and only then run it."},"encoded-exec":{title:"Skill may decode and execute an encoded payload",category:"security",summary:"an encoded string appears to be decoded and executed. Encoding hides what actually runs from anyone reviewing the skill.",recommendation:"Replace the encoded payload with the plain-text commands it runs, so the behavior can be reviewed."},"remote-eval":{title:"Skill may evaluate code fetched from the network",category:"security",summary:"code appears to be evaluated dynamically (eval/exec, `new Function`, a dynamic import, or deserialization) alongside network calls \u2014 the shape of a remote-code loader.",recommendation:"Review what the evaluated code is built from. If it comes from the network, replace the loader with code bundled in the skill."},"dynamic-eval":{title:"Skill script evaluates dynamically built code",category:"security",summary:"a bundled script uses eval/exec, `new Function`, or Invoke-Expression. What it runs cannot be read from the script itself.",recommendation:"Consider replacing dynamic evaluation with direct code so the script's behavior is reviewable."},"credential-exfil":{title:"Skill script reads credentials and makes network calls",category:"security",summary:"a bundled file reads a credential store (SSH keys, cloud credentials, wallets, the keychain) or dumps the whole environment, and the same file makes network calls \u2014 a possible credential-exfiltration path.",recommendation:"Confirm the script needs this access. A skill should read only the specific variable it needs and send it only to the service that requires it; remove bulk environment dumps and credential-file reads."},"exfil-instruction":{title:"Skill instructions may direct sending secrets off-machine",category:"security",summary:"the instructions appear to tell the agent to send, upload or post secrets, credentials or environment variables to a destination.",recommendation:"Remove the instruction. Skills should never direct an agent to transmit credentials anywhere; if an API call needs a key, reference the environment variable by name only."},"instruction-override":{title:"Skill contains prompt-injection style override text",category:"security",summary:`the text appears to try to override the agent's existing instructions (e.g. "ignore previous instructions") or embeds chat-template role tokens. A skill has no legitimate reason to do this.`,recommendation:"Remove the override text. If the skill documents injection strings as examples, quote them so they read as data."},"conceal-from-user":{title:"Skill instructions may hide actions from the user",category:"security",summary:"the instructions appear to tell the agent to act silently or keep something from the user.",recommendation:"Remove the concealment. Every action a skill takes should be visible to the person running it."},"permission-bypass":{title:"Skill may disable agent permission or safety prompts",category:"security",summary:"the skill appears to turn off permission prompts, approvals or sandboxing (for example `--dangerously-skip-permissions`), so later actions would run without the user confirming them.",recommendation:"Remove the bypass and let the agent's normal permission prompts apply; grant narrowly scoped `allowed-tools` instead if needed."},"hidden-unicode":{title:"Skill contains invisible or bidirectional Unicode characters",category:"security",summary:"the file contains characters that do not render \u2014 Unicode tag characters and bidi controls can smuggle instructions or reorder text so what a reviewer sees differs from what the agent reads.",recommendation:"Remove the invisible characters (the evidence shows them as <U+XXXX>, and decodes tag-character payloads) and re-review the affected lines."},"hidden-html-comment":{title:"Skill hides agent-directed text in an HTML comment",category:"security",summary:"an HTML comment contains agent-directed or sensitive text. Rendered previews hide comments, but the agent reads them.",recommendation:"Move the text into visible prose (or delete it) so reviewers see everything the agent is told."},"hidden-html-element":{title:"Skill hides text from rendered view with HTML/CSS",category:"security",summary:"an HTML element hides its content from rendered previews (`display:none`, `visibility:hidden`, `hidden`), but the agent still reads it.",recommendation:"Remove the hiding markup so the content is visible to reviewers, or delete the hidden content."},"encoded-blob":{title:"Skill instructions contain a large encoded blob",category:"security",summary:"the instruction text contains a long base64-like string whose content cannot be reviewed by reading the skill.",recommendation:"Replace the blob with the plain content it encodes, or move binary assets into bundled files."},"unpinned-remote-dep":{title:"Skill pulls a remote dependency without a pinned version",category:"security",summary:"the skill installs or fetches remote code by a mutable reference (a git URL without a commit or tag, `@latest`, or a script on a branch), so what runs can change after the skill was reviewed.",recommendation:"Pin the dependency to an exact version, tag or commit SHA (and prefer a checksum for downloaded scripts)."},"missing-script":{title:"Skill invokes a script that is not bundled with it",category:"ai_config",summary:"the skill tells the agent to run a script that exists neither in the skill directory nor at that path in the repo, so what actually runs cannot be reviewed with the skill.",recommendation:"Bundle the script in the skill directory, fix the path, or remove the instruction."},"unscanned-files":{title:"Some skill content was not fully scanned",category:"security",summary:"part of this skill could not be checked by the supply-chain scan \u2014 binaries, archives or compiled-language sources it cannot analyze, files beyond the per-skill cap or the per-scan budget, the middle of very large files, or directories it does not walk. Anything in those parts was not checked.",recommendation:"Review the listed content by hand. A skill that ships binaries or very large files deserves extra scrutiny before installing."}},uR=new Set(["md","mdx","markdown","txt"]),fR=new Set(["yml","yaml","json","jsonc","json5","toml","ini","cfg","conf","html","htm","xhtml","xml","svg"]),tm={sh:"sh",bash:"sh",zsh:"sh",ksh:"sh",fish:"sh",command:"sh",js:"js",mjs:"js",cjs:"js",ts:"js",mts:"js",cts:"js",jsx:"js",tsx:"js",py:"py",pyw:"py",rb:"rb",ps1:"ps",psm1:"ps",pl:"other",php:"other",lua:"other",bat:"other",cmd:"other"},dR=new Set(["go","rs","java","c","cc","cpp","cxx","h","hpp","cs","swift","kt","kts","groovy","gradle","scala","tf","hcl","sql","service","desktop"]),pR=new Set(["vbs","vba","vbe","hta","applescript","wsf","jse","reg"]),hR=new Set(["exe","dll","so","dylib","wasm","jar","war","class","zip","tar","gz","tgz","bz2","xz","7z","rar","msi","dmg","pkg","deb","rpm","appimage","apk","bin","o","a","lnk","scr","com","pif","scpt","node"]),mR=new Set(["docx","xlsx","pptx","doc","xls","ppt","odt","sqlite","sqlite3","db"]),gR=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","tif","tiff","pdf","woff","woff2","ttf","otf","eot","mp3","mp4","wav","ogg","flac","mov","avi","webm","m4a","csv","tsv","parquet","psd","sketch","fig","pyc"]),yR=new Set([".ds_store","thumbs.db","desktop.ini"]);function gm(t){let e=Ue.posix.basename(t);if(yR.has(e.toLowerCase()))return{skip:"asset"};if(e==="package.json"||/^requirements[\w.-]{0,40}\.txt$/i.test(e))return{kind:"manifest",lang:"other"};if(/^(?:GNU)?makefile$/i.test(e)||/^(?:Dockerfile|Containerfile|Justfile)(?:\..{1,40})?$/i.test(e))return{kind:"text",lang:"sh"};if(/^\.env\.(?:example|sample|template|dist|defaults?)$/i.test(e))return{skip:"asset"};if(/^\.env(?:\..{1,40})?$/i.test(e)||/\.env$/i.test(e))return{report:"environment/secrets file bundled with the skill \u2014 not read; review it by hand",severity:"warning"};let n=/\.([a-z0-9]{1,12})$/i.exec(e)?.[1]?.toLowerCase();return n===void 0||e.lastIndexOf(".")<=0?"probe":uR.has(n)?{kind:"instructions",lang:"other"}:tm[n]?{kind:"script",lang:tm[n]}:n==="mk"||n==="dockerfile"?{kind:"text",lang:"sh"}:fR.has(n)?{kind:"text",lang:"other"}:dR.has(n)?{kind:"text",lang:"other",note:{reason:`.${n} source \u2014 only command and exfiltration patterns were checked`,severity:"info"}}:pR.has(n)?{kind:"script",lang:"other",note:{reason:`.${n} script \u2014 only command and exfiltration patterns were checked`,severity:"warning"}}:hR.has(n)?{report:`binary executable or archive (.${n}) \u2014 cannot be reviewed as text`,severity:"warning"}:mR.has(n)?{report:`.${n} document/database \u2014 not read`,severity:"info"}:gR.has(n)?{skip:"asset"}:"probe"}function nm(t){if(Ue.posix.basename(t)==="SKILL.md")return!0;let e=gm(t);return e==="probe"?!0:"skip"in e?!1:"report"in e?e.severity!=="info":e.kind==="script"||e.kind==="manifest"||e.kind==="text"&&e.lang==="sh"}function bR(t){let e=/^#!\s{0,5}(\S{1,200})(?:\s{1,5}(\S{1,100}))?/.exec(t);if(!e)return;let n=Ue.posix.basename(e[1])==="env"?e[2]??"":Ue.posix.basename(e[1]);return/^(?:node|deno|bun|tsx|ts-node)$/.test(n)?"js":/^python/.test(n)?"py":/^(?:ba|z|k|da|fi)?sh$/.test(n)?"sh":/^ruby$/.test(n)?"rb":/^pwsh$/.test(n)?"ps":"other"}function wR(t){return t.length>=4&&t[0]===127&&t[1]===69&&t[2]===76&&t[3]===70?"ELF executable":t.length>=2&&t[0]===77&&t[1]===90?"Windows executable":t.length>=4&&(t.readUInt32BE(0)===4277009102||t.readUInt32BE(0)===4277009103||t.readUInt32BE(0)===3472551422||t.readUInt32BE(0)===3489328638||t.readUInt32BE(0)===3405691582)?"Mach-O/Java binary":t.length>=4&&t[0]===80&&t[1]===75&&t[2]===3&&t[3]===4?"ZIP archive":"binary file"}function vR(t){if((t[0]??"").replace(/^\u{FEFF}/u,"").trim()!=="---")return 0;for(let e=1;e<t.length&&e<500;e++)if(/^(?:---|\.\.\.)[ \t]*$/.test(t[e]))return e+1;return 0}var nn=gi;function fc(t){let e=nn(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(i=>i.length)),s="`".repeat(n+1);return`${s}${e}${s}`}function be(t,e=0,n=0){let s=Math.max(0,e-40),i=Math.min(t.length,s+220,e+Math.max(0,n)+60),r=nn(t.slice(s,i)).replace(/\s+/g," ").trim();return`${s>0?"\u2026":""}${r}${i<t.length?"\u2026":""}`}var Xe=2e3,ym=600;function Yi(t,e,n){return Object.assign([t.slice(e,n)],{index:e,input:t,groups:void 0})}function fe(t,e,n){if(e.length<=Xe){if(n&&!n(e))return;let s=t.exec(e);return s?{index:s.index,match:s}:void 0}for(let s=0;s<e.length;s+=Xe-ym){let i=e.slice(s,s+Xe),r=n&&!n(i)?null:t.exec(i);if(r)return{index:s+r.index,match:r};if(s+Xe>=e.length)break}}function vt(t,e,n=50){let s=[];if(e.length<=Xe){for(let r of e.matchAll(t))if(s.push({index:r.index??0,match:r}),s.length>=n)break;return s}let i=new Set;for(let r=0;r<e.length;r+=Xe-ym){for(let o of e.slice(r,r+Xe).matchAll(t)){let a=r+(o.index??0);if(!i.has(a)&&(i.add(a),s.push({index:a,match:o}),s.length>=n))return s}if(r+Xe>=e.length)break}return s}var bm=20,wm=4e3,vm=200,xm=2e4,xR=/\|\s{0,5}[({]?\s{0,3}(?:while|until)\b/,sm=/\bdo\b/g,im=/\bdone\b/g,_R=/\|\s{0,5}rev\s{0,5}\|/,SR=t=>Es.test(t)||Tm.test(t)||_R.test(t);function ER(t){let e=[],n=[],s="",i=0,r=0,o=-2,a=!1,c=0,l=!1;for(let u of t.active){let f=t.lines[u];s!==""&&u!==o+1&&(e.push({text:s,line:i}),s="",a=!1),o=u,s===""&&(i=u+1,r=0);let d=f.trimEnd(),p=d.endsWith("\\")&&!d.endsWith("\\\\"),h=(d.endsWith("|")||d.endsWith("&&"))&&!(t.kind==="instructions"&&!t.fenced[u]&&f.trimStart().startsWith("|")),m=!1;if(!a&&d.includes("|")&&(t.kind!=="instructions"||t.fenced[u]===1)&&xR.test(d)&&SR(d)){let g=d.match(sm)?.length??0,b=d.match(im)?.length??0;(g===0||g>b)&&(m=!0,c=g-b,l=g>0)}if(p||h||a||m){let g=a||m?f.trim():f,b=a||m;if(r<(b?vm:bm)&&s.length+g.length<(b?xm:wm)){let w=!1;if(a){let k=g.match(sm)?.length??0,R=g.match(im)?.length??0;k>0&&(l=!0),c+=k-R,w=l&&c<=0||!l&&R>0}let y=p||h||m&&/(?:\bdo|[;{(])$/.test(g)?" ":"; ",v=a||m?g:d;s+=`${p?v.slice(0,-1):v}${w?"":y}`,r++,m&&(a=!0),w&&(e.push({text:s,line:i}),s="",a=!1);continue}n.push(i),a=!1}e.push({text:s+f,line:i}),s=""}return s!==""&&e.push({text:s,line:i}),{lines:e,capped:n}}var kR=/\b(?:never|don't|dont|do\s{1,5}not|avoid|must\s{1,5}not|mustn't|should\s{1,5}not|shouldn't|refuse\s{1,5}to)\b(?!\s{1,5}(?:mind|hesitate|forget|stop|skip|fail|neglect)\w{0,4}\b)/gi,_m=/[,;:.!?]|\b(?:but|and|then|instead|so)\b/i,RR=2,CR=/^(?:run|pipe|use|execute|invoke|call|send|pass|type|paste)$/i;function Sm(t){return t.match(/[A-Za-z0-9_'-]+/g)??[]}var AR=/\b(?:detect\w{0,10}|block(?:s|ed|ing)?|prevent\w{0,10}|reject\w{0,10}|forbid\w{0,10}|prohibit\w{0,10}|den(?:y|ies|ied)|malicious|dangerous|insecure|unsafe|vulnerab\w{0,10}|exploit\w{0,10}|injection|attack\w{0,10}|(?:not|un)\s{0,3}supported|anti-?pattern|example\s{1,5}of)\b/gi,$R=/^[`'")\]\s]{0,6}(?:is|are|was|would\s{1,5}be|looks)\s{1,5}(?:dangerous|insecure|unsafe|malicious|risky|an?\s{1,5}(?:security\s{1,5})?(?:risk|red\s{1,5}flag|attack))\b/i;function Em(t,e,n){let s;e.lastIndex=0;for(let i of t.matchAll(e))s=i;return s?n(t.slice((s.index??0)+s[0].length)):!1}function km(t,e){return Em(t.slice(Math.max(0,e-80),e),kR,n=>{if(n.length>30||_m.test(n))return!1;let s=Sm(n);return s.length===0||s.length===1&&CR.test(s[0])})}function wc(t,e,n){return $R.test(t.slice(e+n,e+n+60))?!0:Em(t.slice(Math.max(0,e-80),e),AR,s=>s.length<=30&&!_m.test(s)&&Sm(s).length<=RR)}var PR=new RegExp([String.raw`https?:\/\/`,String.raw`\b(?:[a-z0-9-]{1,63}\.){1,5}[a-z]{2,24}(?::\d{1,5})?\/\S`,String.raw`\b(?:[a-z0-9-]{1,63}\.){2,5}[a-z]{2,24}\b`,String.raw`\b[a-z0-9-]{1,63}\.(?:com|net|org|io|dev|app|xyz|ru|cn|info|biz|co|me|tk|top|site|online|cloud|run|link|ly|gg|ai|so|to)\b`,String.raw`\b\d{1,3}(?:\.\d{1,3}){3}\b`,String.raw`\[[0-9a-f:]{2,45}\]|\b(?:[0-9a-f]{1,4}:){2,7}[0-9a-f]{0,4}\b`,String.raw`\b[a-z][a-z0-9-]{0,62}(?:\.[a-z0-9-]{1,63}){0,5}:\d{2,5}\b`,String.raw`\[\.\]|\(\.\)|\{\.\}|\[dot\]|\(dot\)`,String.raw`\w\s{1,3}\.(?:com|net|org|io|dev|app|xyz|ru|cn|info|biz|co|me|tk|top|site|sh)\b`,String.raw`\w["']{1,2}\.[a-z]{2,24}\b`,String.raw`\$\{?[A-Za-z_][A-Za-z0-9_]{0,60}\}?`,String.raw`\$\(`].join("|"),"i"),Rm=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b/gi,TR=/^(?:-K|--config|-i|--input-file|-T|--upload-file|--url|--url-query)(?:=|$)|^-K\S/;function IR(t){let e=0;for(let n of t.matchAll(Rm)){if(++e>8)break;if(Cm(t,n).some(s=>TR.test(s)||!s.startsWith("-")&&/[/.:@=$~\d[]/.test(s)))return!0}return Am(t)&&(qi(t,Es,!1)!==void 0||MR(t))}function Cm(t,e){return t.slice((e.index??0)+e[0].length,(e.index??0)+e[0].length+300).split(/[|;&)`\n]/,1)[0].trim().split(/\s+/,16).map(s=>s.replace(/[.,:;!?'")\]]+$/,"")).filter(Boolean)}function Am(t,e=4){let n=t.slice(0,600),s=0;for(let i of n.matchAll(Rm)){if(++s>e)break;let r=NR(i[0].toLowerCase(),Cm(n,i));if(r!==void 0&&jR(r))return!0}return!1}var OR={curl:new Set(["-o","-H","-d","-X","-u","-A","-e","-m","-w","-b","-c","-x","-F","-r","-z","-E","--output","--header","--data","--request","--user","--user-agent","--referer","--max-time","--cookie","--proxy","--retry","--connect-timeout"]),wget:new Set(["-O","-o","-P","-t","-T","-U","-e","-w","-Q","-a","-B","--output-document","--directory-prefix","--user-agent","--tries","--timeout","--header"]),iwr:new Set(["-outfile","-method","-headers","-body","-contenttype","-useragent","-credential","-timeoutsec","-proxy","-websession"])},LR=new Set(["a","an","the","it","its","this","that","these","those","into","to","from","with","without","and","or","then","as","in","on","for","at","by","is","are","was","be","directly","blindly","output","outputs","piped","pipe","piping","command","commands","script","scripts","file","files","content","contents","data","result","results","url","urls","link","links","anything","something","remote","untrusted","unverified","unknown","here","there","when","which","only","not","never","always","unsafe","safely","instead","again","install","installer","installers","download","downloads","downloaded","run","runs","running","execute","bash","sh","shell","silently","quietly","foo","bar","baz","example","examples","yourscript","your-script","your-host","your-server","yourhost","host","hostname","server","domain","site","website","get","docs","doc","mirror","some","my","your","somewhere","test","tests","x","y","z","xxx","target","endpoint","api","repo","package","tool","app","service","path","name","address","ip"]);function NR(t,e){let n=t==="curl"||t==="wget"?t:"iwr",s=OR[n];for(let i=0;i<e.length;i++){let r=e[i];if(n==="iwr"&&r.toLowerCase()==="-uri")return e[i+1];let o=n==="iwr"?r.toLowerCase():r;if(s.has(o)){i++;continue}if(!r.startsWith("-"))return r}}function jR(t){return/^[a-z][a-z0-9_-]{0,62}$/i.test(t)&&!LR.has(t.toLowerCase())}function MR(t){let e=xc(t,!1).slice(0,50);for(let n=0;n<e.length;n++){if(!Es.test(e[n].text))continue;let s=Lm(e[n].text,"remote");if(s)for(let i=n+1;i<e.length&&i<=n+8;i++){let r=e[i].text;if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(r))continue;let o=Om.exec(r);if(o&&Ge(o[1])===s)return!0}}return!1}function vc(t){let e=t.slice(0,600);return PR.test(e)||IR(e)}function Ji(t,e,n,s,i,r=!1){return t.kind!=="instructions"||t.fenced[e]||!km(n,s)&&!wc(n,s,i)?"none":vc(n.slice(s,s+Math.max(i,1)+80))?"lowconf":r?$m(n,s,s+i)||DR(n)?"skip":"lowconf":"skip"}function DR(t){return t.trimStart().startsWith("|")}var FR=/\b(?:(?:rule|instructions?|prompt|policy|directive|task|goal|job)\s{1,5}(?:is|are|now)|you\s{1,5}are|you\s{1,5}will|from\s{1,5}now\s{1,5}on|always|remember\s{1,5}(?:that|to)|act\s{1,5}as|your\s{1,5}new)\b[^.!?]{0,40}$/i;function HR(t,e,n){if(!$m(t,e,n))return!1;let s=t.slice(Math.max(0,e-200),e),i=Math.max(s.lastIndexOf('"'),s.lastIndexOf("`"),s.lastIndexOf("\u201C"));return!FR.test(s.slice(0,Math.max(0,i)))}function $m(t,e,n){let s=t.slice(Math.max(0,e-Xe),e),i=t.slice(n,n+Xe);for(let r of['"',"`"])if((s.split(r).length-1)%2===1&&i.includes(r))return!0;return s.lastIndexOf("\u201C")>s.lastIndexOf("\u201D")&&i.includes("\u201D")}var BR=/^\s{0,10}\|\s{0,5}`?(?:--[\w-]{2,60}|bypassPermissions)`?\s{0,5}\|/,WR=/`[^`]{0,200}`|\b(?:run|use|execute|launch|invoke|start|pass|add|set|enable|always|call|claude|codex|npx|bash|sh)\b/i;function GR(t){return BR.test(t)?!t.split(/(?<!\\)\|/).slice(2).some(n=>WR.test(n)):!1}function xc(t,e,n){let s=[],i=0,r="",o=0;for(let a=0;a<t.length;a++){let c=t[a];if(r){c==="\\"&&r==='"'?a++:c===r&&(r="",n&&n.length<50&&n.push({start:o+1,end:a}));continue}if(e&&(c==='"'||c==="'")&&(a===0||/[\s=(:,[{]/.test(t[a-1]))){r=c,o=a;continue}if(e&&c==="\\"){a++;continue}let l="";c==="|"?l=t[a+1]==="|"?"||":t[a+1]==="&"?"|&":"|":c==="&"?l=t[a+1]==="&"?"&&":t[a-1]===">"||t[a+1]===">"?"":"&":c===";"&&(l=";"),l&&(s.push({text:t.slice(i,a),start:i,sep:l==="|&"?"|":l}),a+=l.length-1,i=a+1)}return s.push({text:t.slice(i),start:i,sep:""}),s}var UR=String.raw`(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|aria2c|downloadstring|downloadfile)`,Es=new RegExp(String.raw`(?:^|[\s(\x60{>"':=])${UR}\b`,"i"),Pm=/(?:^|[\s(`{>"':=])(?:base64\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}(?:-d|--decode|-D)\b|xxd\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}-r\b|openssl\s{1,5}(?:base64|enc)\b[^|;&\n]{0,80}\s-d\b|uudecode\b)/i,VR=String.raw`(?:python[0-9.]{0,5}|node|perl|ruby|php|deno|bun)(?=\s{0,5}$|\s{1,5}-(?:\s|$)|\s{1,5}run\s{1,5}-(?:\s|$)|\s{1,5}(?:\/dev\/stdin|\/proc\/self\/fd\/0)\b|\s{0,5}[;&|)}\x60'"])`,zR=String.raw`(?:\$\{?SHELL\}?(?!\w)|(?:source|\.)\s{1,5}\/dev\/stdin\b|(?:ba|z|k|da|fi|a)?sh\b|`+String.raw`python[0-9.]{0,5}\s{1,5}-c\s{1,5}["']?[^|\n]{0,80}?(?:exec|eval)\s{0,5}\(\s{0,5}sys\.stdin|`+String.raw`g?awk\s{1,5}(?:-\S{1,20}\s{1,5}){0,3}["']?[^|\n]{0,60}?system\s{0,5}\(\s{0,5}\$0|`+String.raw`${VR}|iex\b|invoke-expression\b|pwsh\b|powershell\b)`,qR=String.raw`(?:`+[String.raw`sudo(?:\s{1,5}-{1,2}[\w-]{1,20}(?:[= ]\s{0,3}[\w.@:-]{1,40})?){0,5}`,String.raw`env(?:\s{1,5}-\S{1,20}){0,3}(?:\s{1,5}[^\s=]{1,40}=\S{0,100}){0,5}`,String.raw`xargs(?:\s{1,5}-\S{1,20}(?:\s{1,5}[^\s-]\S{0,20})?){0,4}`,String.raw`busybox`,String.raw`nice(?:\s{1,5}-n\s{0,3}-?\d{1,3}|\s{1,5}-\d{1,3})?`,String.raw`timeout(?:\s{1,5}-\S{1,20}){0,3}\s{1,5}[\d.]{1,8}[smhd]?`,String.raw`nohup`,String.raw`exec`,String.raw`command`,String.raw`stdbuf(?:\s{1,5}-\S{1,20}){0,3}`,String.raw`[A-Za-z_]\w{0,40}=\S{0,100}`].join("|")+String.raw`)\s{1,5}`,_c=String.raw`^\s{0,5}[({]?\s{0,3}(?:${qR}){0,6}`+String.raw`(?:[\w./-]{0,40}\/)?(?:env\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?`,rm=new RegExp(_c+zR,"i"),KR=new RegExp(String.raw`(?:(?<![.\w$])(?:eval|exec\w{0,8}|system|popen|spawn\w{0,8}|compile|Function)|(?:instance_|class_|module_)eval|`+String.raw`\b(?:vm|child_process|os|subprocess|Kernel)["']?\)?\.(?:run\w{2,20}|compile\w{0,12}|exec\w{0,8}|spawn\w{0,8}|system|popen|call|check_output|Popen|eval|Script))\b`+String.raw`(?:\s{0,5}\(\s{0,5}|\s{1,5})(?!["'\x60][^"'\x60]{0,60}["'\x60]\s{0,3}[);,])`,"g"),YR=new RegExp(String.raw`readFileSync\s{0,5}\(\s{0,5}(?:0\b|process\.stdin|["']\/dev\/stdin)|process\.stdin|\/dev\/stdin|php:\/\/stdin|sys\.stdin|`+String.raw`open\s{0,5}\(\s{0,5}0\b|fileinput|\bSTDIN\b|\$stdin|\bARGF\b|<STDIN>|<>|\bgets\b|\breadlines?\b|\binput\s{0,5}\(|\$_(?!\w)`,"gi"),JR=/\beval\s{0,5}\(?\s{0,5}do\s{0,5}\{[^}\n]{0,100}(?:<STDIN>|<>)/i,XR=/(?:^|[;\s{(])\$?([A-Za-z_]\w{0,30})\s{0,3}=\s{0,3}[^;\n=]{0,60}$/,ZR=600,QR=150;function eC(t){let e=t.slice(0,ZR),n=[];for(let r of e.matchAll(YR))if(n.push(r.index??0),n.length>=16)break;if(n.length===0)return!1;if(JR.test(e))return!0;let s=0,i=0;for(let r of e.matchAll(KR)){if(++s>40)break;let o=(r.index??0)+r[0].length;for(;i<n.length&&n[i]<o;)i++;let a=n[i];if(a!==void 0&&a-o<=QR&&!/[;\n]/.test(e.slice(o,a)))return!0}for(let r of n.slice(0,4)){let o=XR.exec(e.slice(Math.max(0,r-80),r));if(o&&new RegExp(String.raw`\b(?:eval|exec|system)\s{0,5}\(?\s{0,5}\$?${o[1]}\b`).test(e.slice(r)))return!0}return!1}var tC=String.raw`(?:`+[String.raw`(?:node(?:js)?|bun|deno)\s{1,5}(?:--?[\w-]{1,30}(?:=\S{1,30})?\s{1,5}){0,3}?(?:-e|-p|-pe|--eval|--print|eval)`,String.raw`python[0-9.]{0,5}\s{1,5}(?:-[\w-]{1,10}\s{1,5}){0,3}?-c`,String.raw`ruby\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}?-[a-z]{0,4}e`,String.raw`perl\s{1,5}(?:-[\w=:.-]{1,20}\s{1,5}){0,3}?-[a-z]{0,4}e`,String.raw`php\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}?-r`].join("|")+String.raw`)\s{1,5}["']?`,nC=new RegExp(`${_c}${tC}`,"i"),sC=new RegExp(`${_c}perl\\s{1,5}(?:-[\\w=:.-]{1,20}\\s{1,5}){0,3}?-[a-z]{0,3}[np][a-z]{0,3}e\\s{1,5}["']?(?=[^\\n]{0,300}?eval\\b)`,"i");function om(t){let e=nC.exec(t);return e&&eC(t.slice(e.index+e[0].length))?!0:sC.test(t)}var iC=/^\s{0,5}[({]?\s{0,3}(?:sudo\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?(?:[\w./-]{0,40}\/)?tee\b/i,rC=/^\s{0,5}[({]?\s{0,3}(?:while|until)\b[^;|]{0,150}?\bread\b([^;|]{0,100})/i,oC=/^\s{0,5}(?:do\s{1,5})?(?:(?:(?:command|builtin)\s{1,5})?(?:eval|source|\.)\s{1,5}|(?:sudo\s{1,5})?(?:[\w./-]{0,40}\/)?(?:ba|z|k|da)?sh\s{1,5}(?:(?:-\S{1,5}|<<<)\s{1,5}){0,2}|sudo\s{1,5})?["']?\$\{?([A-Za-z_]\w{0,40})\}?/i,aC=/^\s{0,5}(?:do\s{1,5})?(?:echo|printf)\s{1,5}(?:-\S{1,5}\s{1,5}){0,2}(?:["']%s["']\s{1,5})?["']?\$\{?([A-Za-z_]\w{0,40})\}?/i,cC=/^\s*do\b/,lC=/^\s*done\b/,uC=new Set(["-p","-d","-n","-N","-t","-u","-i"]),fC=250;function dC(t){let e=new Set,n=t.trim().split(/\s+/).slice(0,12);for(let s=0;s<n.length;s++){let i=n[s];if(uC.has(i)){s++;continue}i.startsWith("-")||/^[A-Za-z_]\w{0,40}$/.test(i)&&e.add(i)}return e.size===0&&e.add("REPLY"),e}function pC(t,e,n){let s=n[e];if(s===void 0){let i=t[e],r=i.text.slice(0,400);if(lC.test(r))s={kind:"done"};else{s={kind:cC.test(r)?"do":"other"};let o=oC.exec(r);o&&(s.runs=o[1]);let a=i.sep==="|"&&e+1<t.length?aC.exec(r):null;a&&(s.echoes=a[1])}n[e]=s}return s}function hC(t,e,n){let s=t[e].text;if(!s.includes("read")||!/while|until/i.test(s))return;let i=rC.exec(s.slice(0,400));if(!i)return;let r=dC(i[1]??""),o=0;for(let a=e+1;a<t.length&&a<=e+fC;a++){let c=pC(t,a,n);if(c.kind==="done"){if(--o<=0)return;continue}c.kind==="do"&&o++;let l=t[a];if(c.runs!==void 0&&r.has(c.runs))return l.start+Math.min(l.text.length,60);if(c.echoes!==void 0&&r.has(c.echoes)&&Im(t[a+1].text))return t[a+1].start+Math.min(t[a+1].text.length,60)}}var mC=new RegExp(String.raw`^\s{0,5}[({]?\s{0,3}(?:sudo\s{1,5})?(?:`+[String.raw`rev\b`,String.raw`tr\s{1,5}(?:-\S{1,5}\s{1,5}){0,2}["']?\[?([a-z0-9])-[a-z0-9](?:[a-z0-9]-[a-z0-9]){0,3}\]?["']?\s{1,5}["']?\[?(?!\1)[a-z0-9]-[a-z0-9]`,String.raw`tr\s{1,5}(?:-\S{1,5}\s{1,5}){0,2}["']?([a-z])[a-z]{9,}["']?\s{1,5}["']?(?!\2)[a-z][a-z]{9,}`,String.raw`(?:base32|basenc)\s{1,5}(?:-\S{1,12}\s{1,5}){0,3}(?:-[a-z]{0,3}d[a-z]{0,3}|--decode)\b`,String.raw`(?:printf|echo)\s{1,5}(?:-\S{1,4}\s{1,5}){0,2}(?:["']%b["']\s{1,5})?\$?["']?(?:\\x[2-7][0-9a-f]|\\0[4-7][0-7]|\\1[0-7][0-7]|\\u00[2-7][0-9a-f]){4,}`].join("|")+String.raw`)`,"i"),Tm=new RegExp(`${Pm.source}|${mC.source}`,"i"),gC=16;function yC(t){let e="",n=0,s=0,i=!1,r=t.length;for(;n<r&&e.length<600&&s<400;){for(;n<r&&t.charCodeAt(n)<=32;)n++;if(n>=r)break;let o=n,a=0;for(;n<r;){let u=t.charCodeAt(n);if(a!==0)u===92&&a===34?n++:u===a&&(a=0);else if(u===34||u===39)a=u;else if(u<=32)break;n++}let c=t.slice(o,Math.min(n,o+700));s++;let l=/^[A-Za-z_]\w{0,40}=/.test(c);l&&i||(i=l,e+=`${e===""?"":" "}${l?"V=1":c}`)}return e.length>=600||n>=r?e.slice(0,600):`${e} ${t.slice(n,n+600)}`.slice(0,600)}function Im(t){if(!am.test(t))return!1;let e=yC(t);if(!am.test(e))return!1;if(rm.test(e)||om(e))return!0;if(e.includes(">(")&&iC.test(e)){let n=e.indexOf(">(");for(let s=0;n>=0&&s<4;s++){let i=e.slice(n+2);if(rm.test(i)||om(i))return!0;n=e.indexOf(">(",n+2)}}return!1}function qi(t,e,n,s=0){if(!t.includes("|"))return;let i=[],r=xc(t,n,i),o=bC(t,r,e);if(o||s>0)return o;for(let a of i){let c=qi(t.slice(a.start,a.end),e,!0,s+1);if(c)return{index:a.start+c.index,match:Yi(t,a.start+c.index,a.start+c.index+c.match[0].length)}}}var am=/sh\b|SHELL|stdin|awk|python|node|perl|ruby|php|deno|bun|iex|invoke-expression|pwsh|powershell/i;function bC(t,e,n){let s=new Array(e.length),i=c=>(s[c]===void 0&&(s[c]=Im(e[c].text)),s[c]),r=new Array(e.length),o=new Array(e.length),a=c=>(r[c]===void 0&&(r[c]=hC(e,c,o)??null),r[c]??void 0);for(let c=0;c<e.length;c++){if(e[c].sep!=="|")continue;let l=n.exec(e[c].text);if(l)for(let u=1;u<=gC&&c+u<e.length;u++){let f=e[c+u],d=i(c+u)?void 0:a(c+u);if(d!==void 0||i(c+u)){let p=e[c].start+l.index,h=Math.min(t.length,d??f.start+Math.min(f.text.length,60));return{index:p,match:Yi(t,p,h)}}if(f.sep!=="|")break}}}var wC=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)sum|shasum)\b(?=[^|;&]{0,300}\s(?:-c|--check)\b)|gpg\b(?=[^|;&]{0,300}\s--verify\b)|gpgv\b|cosign\s{1,5}verify(?:-blob)?\b|minisign\s{1,5}-V\b|slsa-verifier\s{1,5}verify|openssl\s{1,5}dgst\b(?=[^|;&]{0,300}\s-verify\b))/i,vC=/^\s{0,5}(?:sudo\s{1,5})?(?:sha(?:1|224|256|384|512)sum|shasum)\b[^|;&]{0,300}\s(?:-c|--check)(?:\s{1,5}|=)(\S{1,300})/i,Om=/^\s{0,5}(?:sudo\s{1,5}(?:-\S{1,20}\s{1,5}){0,5})?(?:(?:[\w./-]{0,40}\/)?(?:(?:ba|z|k|da)?sh|source|\.|python[0-9.]{0,5}|node|perl|ruby|pwsh|powershell)\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?(\S{1,300})/i,xC=/^\s{0,5}(?:export\s{1,5}|local\s{1,5}|readonly\s{1,5})?([A-Za-z_]\w{0,60})=["']?(?:\$\(|`)\s{0,5}(?:curl|wget|iwr|irm)\b/i,_C=/^\s{0,5}(?:eval|(?:ba|z|k|da)?sh\s{1,5}(?:-c|<<<)|iex|invoke-expression)\s{0,5}\(?\s{0,5}["']?\$\{?([A-Za-z_]\w{0,60})\}?/i;function Ge(t){return Ue.posix.basename(t.replace(/^['"]+|['"]+$/g,"").replace(/\\/g,"/"))}function cm(t){return new Set(t.split(/\s+/).filter(Boolean).map(Ge))}function Lm(t,e){let n=/(?:^|\s)>{1,2}\s{0,3}(\S{1,300})/.exec(t);if(e==="encoded")return n?Ge(n[1]):void 0;let s=/https?:\/\/[^\s'"`)]{1,2000}/i.exec(t)?.[0];if(/\bcurl\b/i.test(t)){let i=/(?:\s-[a-zA-Z]{0,10}o\s{0,3}|\s--output[= ]\s{0,3})(\S{1,300})/.exec(t);return i?Ge(i[1]):/\s-[a-zA-Z]{0,10}O\b|\s--remote-name\b/.test(t)&&s?Ge(s.split(/[?#]/)[0]):n?Ge(n[1]):void 0}if(/\bwget\b/i.test(t)){let i=/(?:\s-[a-zA-Z]{0,10}O\s{0,3}|\s--output-document[= ]\s{0,3})(\S{1,300})/.exec(t);return i?i[1]==="-"?void 0:Ge(i[1]):s?Ge(s.split(/[?#]/)[0]):void 0}return n?Ge(n[1]):void 0}var SC=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)|md5|b2)sum|shasum|openssl\s{1,5}dgst)\b(?![^|;&]{0,300}\s(?:-c|--check)\b)[^|;&]{0,300}>{1,2}\s{0,3}(\S{1,300})/i,EC=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)|md5|b2)sum|shasum|openssl\s{1,5}dgst)\b/i,kC=/curl|wget|iwr|irm|invoke-web|base64|xxd|openssl|uudecode|sum\b|gpg|cosign|minisign|slsa/i,Ss=class{manifestExists;produced=new Map;fetchedVars=new Map;generated=new Set;feeds=0;constructor(e=()=>!1){this.manifestExists=e}feed(e,n,s){let i=++this.feeds;if(this.produced.size===0&&this.fetchedVars.size===0&&!kC.test(e))return;let r=xc(e,s).slice(0,500),o=r.findIndex(u=>/(?:^|\s)#/.test(u.text));if(o>=0){let u=r[o];r=[...r.slice(0,o),{...u,text:u.text.slice(0,u.text.search(/(?:^|\s)#/)),sep:""}]}let a=r.map(u=>wC.test(u.text)),c=(u,f)=>{for(let d=u;d<f;d++){let p=r[d].sep;if(p!=="&&"&&!(p==="|"&&a[d+1]))return!1}return!0},l=new Map;for(let u=0;u<r.length;u++){let f=r[u],d=f.text,p=f.start+Math.max(0,d.search(/\S/)),h=xC.exec(d);if(h){this.fetchedVars.set(h[1],{line:n,feed:i,index:p});continue}let m=Es.test(d)&&(/https?:\/\//i.test(d)||Am(d,1)),g=Pm.test(d);if(m||g){let I=m?"remote":"encoded",C=Lm(d,I);C&&this.produced.set(C,{kind:I,line:n,feed:i,seg:u,index:p});continue}let b=SC.exec(d);if(b){this.generated.add(Ge(b[1]));continue}if(a[u]){for(let I of this.verifiedFiles(d,u>0&&r[u-1].sep==="|"?r[u-1].text:void 0))l.set(I,[...l.get(I)??[],u]);continue}let w=_C.exec(d);if(w&&this.fetchedVars.has(w[1])){let I=this.fetchedVars.get(w[1]);return this.hit("remote-exec",e,I.feed===i?I.index:p,f.start+d.length,I.line)}if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(d))continue;let y=Om.exec(d);if(!y)continue;let v=Ge(y[1]),k=this.produced.get(v);if(!(!k||k.kind==="remote"&&k.feed===i&&(l.get(v)??[]).some(I=>I>k.seg&&c(k.seg,u))))return this.hit(k.kind==="remote"?"remote-exec":"encoded-exec",e,k.feed===i?k.index:p,f.start+d.length,k.line)}}verifiedFiles(e,n){let s=[...this.produced.keys()];if(/--ignore-missing\b|<<<|<\(/.test(e))return[];let i=vC.exec(e)?.[1];if(i!==void 0){if(i==="-"||i==="/dev/stdin"){if(n===void 0||EC.test(n)||/<\(|\$\(/.test(n))return[];let c=cm(n);return s.filter(l=>c.has(l))}let o=Ge(i);return i.startsWith("<")||this.generated.has(o)?[]:!(this.produced.get(o)?.kind==="remote")&&!this.manifestExists(i.replace(/^['"]+|['"]+$/g,""))?[]:s}let r=cm(e);return s.filter(o=>r.has(o))}hit(e,n,s,i,r){let o=Math.min(s,n.length);return{rule:e,found:{index:o,match:Yi(n,o,Math.max(o,Math.min(n.length,i)))},fromLine:r}}},RC=[{requires:t=>t.includes("<("),pattern:/(?:^|[\s;&|(`])(?:(?:[\w./-]{0,40}\/)?(?:ba|z|k)?sh|source|\.)\s{1,5}(?:<\s{0,3})?<\(\s{0,5}(?:curl|wget)\b/i},{requires:t=>t.includes(">(")&&/curl|wget/i.test(t),pattern:/(?:^|[\s;&|(`])(?:curl|wget)\b[^\n;&|]{0,300}>\s{0,3}>\(\s{0,5}(?:sudo\s{1,5})?(?:[\w./-]{0,40}\/)?(?:ba|z|k|da)?sh\b/i},{requires:t=>t.includes("$(")||t.includes("`"),pattern:/\b(?:(?:ba|z|k)?sh\s{1,5}(?:-c|<<<)|eval|python[0-9.]{0,5}\s{1,5}-c|node\s{1,5}-e|perl\s{1,5}-e|ruby\s{1,5}-e)\s{0,5}["']?(?:\$\(|`)\s{0,5}(?:curl|wget)\b/i},{requires:t=>/iex|invoke-expression/i.test(t)&&/iwr|irm|curl|wget|invoke-web|invoke-rest|downloadstring|webclient/i.test(t),pattern:/\b(?:iex|invoke-expression)\b[^\n]{0,120}\b(?:iwr|irm|curl|wget|invoke-webrequest|invoke-restmethod|downloadstring|net\.webclient)\b/i}],CC=[{requires:t=>t.includes("$(")&&/base64|xxd/i.test(t),pattern:/\b(?:eval|(?:ba|z|k)?sh\s{1,5}-c)\s{0,5}["']?\$\([^)\n]{0,300}(?:base64\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}(?:-d|--decode|-D)|xxd\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}-r)\b/i},{requires:t=>/atob|Buffer\.from|b64decode|decodebytes|codecs\.decode|FromBase64String|a85decode|b32decode/i.test(t),pattern:/\b(?:eval|exec|Function|Invoke-Expression|iex)\s{0,5}\(?[^\n]{0,80}?(?:atob|Buffer\.from|b64decode|b32decode|a85decode|decodebytes|codecs\.decode|FromBase64String)\b/i},{requires:t=>/powershell|pwsh/i.test(t)&&/\s-(?:e|ec|enc|encodedcommand)\s{1,5}[A-Za-z0-9+/]{20}/i.test(t),pattern:/\b(?:powershell|pwsh)(?:\.exe)?\b[^\n]{0,300}\s-(?:e|ec|enc|encodedcommand)\s{1,5}[A-Za-z0-9+/]{20,}/i}],AC=/\b(?:eval|exec|Function)\s{0,5}\(\s{0,5}(?:await\s{1,5})?\(?\s{0,5}(?:await\s{1,5})?(?:fetch|requests\.get|urlopen|urllib\.request\.urlopen|http\.get)\s{0,5}\(/i,dc=String.raw`(?:urllib\.request|urllib2|requests|httpx)`,Vi=new RegExp([String.raw`\bfrom\s{1,5}${dc}\s{1,5}import\s{1,5}\(?(?<list>[^\n;#]{1,300})`,String.raw`\bfrom\s{1,5}urllib\s{1,5}import\s{1,5}\(?(?<ulist>[^\n;#]{1,300})`,String.raw`\bimport\s{1,5}${dc}\s{1,5}as\s{1,5}(?<mod>[A-Za-z_]\w{0,39})\b`,String.raw`(?:^|[\s;(])(?<fn>[A-Za-z_]\w{0,39})\s{0,3}=\s{0,3}(?:urllib\.request\.urlopen|urllib2\.urlopen|urlopen|requests\.(?:get|post)|httpx\.(?:get|post))\s{0,3}(?=$|[\s;#)])`,String.raw`(?:^|[\s;(])(?<modassign>[A-Za-z_]\w{0,39})\s{0,3}=\s{0,3}${dc}\s{0,3}(?=$|[\s;#)])`].join("|"),"g"),$C=/\b(?:eval|exec)\s{0,5}\(\s{0,5}(?:compile\s{0,5}\(\s{0,5})?([A-Za-z_][\w.]{0,60})\s{0,5}\(/g,gc=["urlopen","get","post","request"],PC=new Set(gc),lm=/urlopen|urllib|requests|httpx/,um=new WeakMap;function TC(t,e){let n=[];if(t.length<=Xe){Vi.lastIndex=0;for(let s=Vi.exec(t);s!==null&&n.length<20;s=Vi.exec(t))n.push(s)}else for(let s of vt(Vi,t,20))n.push(s.match);for(let s of n){let i=s.groups??{};if(i.list!==void 0)for(let r of i.list.split(",").slice(0,12)){let[o,a]=r.trim().replace(/[()]/g,"").split(/\s{1,5}as\s{1,5}/i);o!==void 0&&PC.has(o)&&e.add((a??o).trim())}else if(i.ulist!==void 0)for(let r of i.ulist.split(",").slice(0,12)){let[o,a]=r.trim().replace(/[()]/g,"").split(/\s{1,5}as\s{1,5}/i);if(o==="request")for(let c of gc)e.add(`${(a??o).trim()}.${c}`)}else if(i.mod!==void 0||i.modassign!==void 0)for(let r of gc)e.add(`${i.mod??i.modassign}.${r}`);else i.fn!==void 0&&e.add(i.fn)}}function IC(t){let e=um.get(t);if(e!==void 0)return e;let n=null;if(lm.test(t.content)){let s=Fm(t),i=new Map,r=new Set;for(let o of t.active){let a=t.lines[o];if(!a.includes("import")&&!a.includes("=")||!lm.test(a))continue;if(a.length<300){if(r.has(`${s(o)}|${a}`))continue;r.size<5e3&&r.add(`${s(o)}|${a}`)}let c=s(o),l=i.get(c);l||i.set(c,l=new Set),TC(a,l)}n={blockOf:s,byBlock:i}}return um.set(t,n),n}function Nm(t,e,n){let s=fe(AC,e);if(s)return s;let i=IC(t),r=i?.byBlock.get(i.blockOf(n));if(!(!r||r.size===0||!e.includes("("))){for(let o of vt($C,e,20))if(r.has(o.match[1]))return o}}var OC={js:[/(?<![.\w$])eval\s{0,5}\(/,/\bnew\s{1,5}Function\s{0,5}\(/,/\bvm\.(?:runInNewContext|runInThisContext|runInContext|compileFunction)\s{0,5}\(|\bnew\s{1,5}vm\.Script\s{0,5}\(/],py:[/(?<![.\w])(?:exec|eval)\s{0,5}\(/],sh:[/(?:^|[\s;&|(])eval\s{1,5}\S/],ps:[/\b(?:Invoke-Expression|iex)\b/i],rb:[/(?<![.\w])eval\s{0,5}[( ]/]},LC={js:[/(?<![.\w$])require\s{0,5}\(\s{0,5}(?!['"][^'"\n]{0,300}['"]\s{0,5}\))[^)\s]/,/(?<![.\w$])import\s{0,5}\(\s{0,5}(?!['"][^'"\n]{0,300}['"]\s{0,5}\))[^)\s]/],py:[/(?<![.\w])__import__\s{0,5}\(\s{0,5}(?!['"])/,/\bimportlib\.import_module\s{0,5}\(\s{0,5}(?!['"])/,/\b(?:pickle|marshal)\.loads?\s{0,5}\(/]},NC=new RegExp([String.raw`(?:^|[\s;&|(\x60$])(?:curl|wget|nc|ncat|netcat|socat|scp|sftp|telnet)\s`,String.raw`\/dev\/(?:tcp|udp)\/`,String.raw`(?<![.\w$])fetch\s{0,5}\(`,String.raw`\baxios\b`,String.raw`\bhttps?\.(?:get|request)\s{0,5}\(`,String.raw`\brequire\s{0,5}\(\s{0,5}['"](?:node:)?(?:https?|net|dgram)['"]`,String.raw`\bfrom\s{1,5}['"](?:node:)?(?:https?|net|dgram)['"]`,String.raw`\bnew\s{1,5}WebSocket\b`,String.raw`\bXMLHttpRequest\b`,String.raw`\b(?:node-fetch|undici)\b`,String.raw`\brequests\.(?:get|post|put|patch|request|Session)\b`,String.raw`\burllib\.request\b`,String.raw`\burlopen\s{0,5}\(`,String.raw`\bhttp\.client\b`,String.raw`\bhttpx\.`,String.raw`\baiohttp\b`,String.raw`\bsocket\.(?:socket|create_connection)\b`,String.raw`\bsmtplib\b`,String.raw`\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b`,String.raw`\bNet\.WebClient\b`,String.raw`\bSystem\.Net\.Http\b`,String.raw`\bNet::HTTP\b`,String.raw`\bopen-uri\b`,String.raw`\bURI\.open\b`,String.raw`\bdns\.(?:resolve|lookup)\s{0,5}\(`].join("|"),"i"),jC=new RegExp([String.raw`JSON\.stringify\(\s{0,5}process\.env\s{0,5}\)`,String.raw`Object\.(?:entries|keys|values)\(\s{0,5}process\.env\s{0,5}\)`,String.raw`json\.dumps\(\s{0,5}(?:dict\(\s{0,5})?os\.environ`,String.raw`\bstr\(\s{0,5}os\.environ\s{0,5}\)`,String.raw`\bos\.environ\.items\(\s{0,5}\)`,String.raw`(?:^|[\s;&(])(?:printenv|env)\s{0,5}[|>]`,String.raw`\$\(\s{0,5}(?:printenv|env)\s{0,5}\)`,String.raw`\x60\s{0,5}(?:printenv|env)\s{0,5}\x60`,String.raw`\bprintenv\s{0,5}$`,String.raw`\/proc\/(?:self|\d{1,10}|\$\$)\/environ`,String.raw`\b(?:Get-ChildItem|gci|dir|ls)\s{1,5}env:`,String.raw`\[Environment\]::GetEnvironmentVariables\(\s{0,5}\)`,String.raw`\bENV\.to_h\b`].join("|"),"i"),MC=new RegExp([String.raw`(?:^|[\s'"\/\\~(])\.ssh(?=[\s'")]|\/?['"]|\/?$)`,String.raw`\.ssh\/(?:id_\w{1,40}|[\w.-]{1,80}\.(?:pem|key))\b`,String.raw`\bid_(?:rsa|ed25519|ecdsa|dsa)\b`,String.raw`(?:^|[\s'"\/\\~(])\.(?:aws|gnupg)(?=[\/\\'"\s)]|$)`,String.raw`(?:^|[\s'"\/\\~(])\.(?:netrc|git-credentials)\b`,String.raw`\bsecurity\s{1,5}(?:find-generic-password|find-internet-password|dump-keychain)\b`,String.raw`\bsecret-tool\s{1,5}lookup\b`,String.raw`\bwallet\.dat\b`,String.raw`\.config\/solana\/id\.json`,String.raw`\bkeystore\/UTC--`,String.raw`\.ethereum\/keystore`,String.raw`\bLogin Data\b`,String.raw`\bseed[_\s-]?phrase\b`].join("|"),"i"),DC=[/\b(?:ignore|disregard|forget)\s{1,5}(?:all\s{1,5}|any\s{1,5}|every\s{1,5})?(?:of\s{1,5})?(?:the\s{1,5}|your\s{1,5}|my\s{1,5}|these\s{1,5}|those\s{1,5})?(?:previous|prior|above|earlier|preceding|system|developer|safety)\s{1,5}(?:instructions?|prompts?|rules|guidelines|directives|messages?|context)\b(?![\w/-]|\.[\w/]|\s{1,5}(?:files?|folders?|director(?:y|ies)|docs?|pages?|in\s{1,5}\S{0,80}\/))/i,/\byou\s{1,5}are\s{1,5}(?:now\s{1,5})?(?:in\s{1,5})?(?:DAN|developer\s{1,5}mode|jailbroken|jailbreak\s{1,5}mode|unrestricted\s{1,5}mode|god\s{1,5}mode)\b/i,/<\|im_start\|>|<\|(?:system|endoftext)\|>|<<SYS>>|\[\/?INST\]/i,/\b(?:new|updated|actual|real)\s{1,5}system\s{1,5}prompt\b/i,/\b(?:these|this|the\s{1,5}following)\s{1,5}instructions?\s{1,5}(?:take|takes|have|has)\s{1,5}(?:precedence|priority)\s{1,5}over\s{1,5}(?:all\s{1,5}|any\s{1,5}|the\s{1,5})?(?:system|safety)\b/i],FC=/ignore|disregard|forget|you\s{1,5}are|<\||<<SYS|INST\]|system\s{1,5}prompt|precedence|priority/i,HC=/user|silently/i,BC=/without|disable|turn\s{1,5}off|bypass|circumvent|skip|override|approve/i,WC=[/\b(?:without|w\/o)\s{1,5}(?:the\s{1,5})?user'?s?\s{1,5}(?:knowledge|knowing|noticing|awareness)\b/i,/\b(?:hide|conceal|obscure)\s{1,5}(?:this|these|it|them|that|the\s{1,5}[\w\s-]{1,30}?)\s{1,5}from\s{1,5}(?:the\s{1,5})?user\b/i,/\bsilently\s{1,5}(?:upload|send|post|exfiltrate|transmit|forward)\b/i],GC=[/\b(?:do\s{1,5}not|don't|never)\s{1,5}(?:tell|inform|notify|alert|warn)\s{1,5}(?:the\s{1,5})?user\b(?!\s{1,5}to\b)/i,/\b(?:do\s{1,5}not|don't|never)\s{1,5}(?:mention|reveal|disclose)\s{1,5}(?:this|that|it|these\s{1,5}(?:steps|instructions))\s{1,5}to\s{1,5}(?:the\s{1,5})?user\b/i],UC=/--dangerously-skip-permissions\b|--dangerously-bypass-approvals-and-sandbox\b|\bbypassPermissions\b|--yolo\b|--allow-all-tools\b/i,VC=[/\bwithout\s{1,5}(?:first\s{1,5})?(?:asking|prompting|checking\s{1,5}with)\s{1,5}(?:the\s{1,5}user\s{1,5})?(?:for\s{1,5})?(?:permission|confirmation|approval|consent)\b(?!\s{1,5}(?:on|for)\s{1,5}(?:each|every|individual|single)\b)/i,/\b(?:disable|turn\s{1,5}off|bypass|circumvent|skip|override)\s{1,5}(?:the\s{1,5}|any\s{1,5}|all\s{1,5})?(?:sandbox(?:ing)?|safety\s{1,5}(?:checks?|guardrails?|filters?|prompts?)|guardrails?|permission\s{1,5}(?:prompts?|checks?|dialogs?)|approval\s{1,5}(?:prompts?|steps?)|content\s{1,5}(?:filters?|polic(?:y|ies)))\b/i,/\bauto[-\s]?approve\s{1,5}(?:all|every|any)\b/i],zC=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/gi,fm=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/i,qC=/\b(?:all\s{1,5}(?:the\s{1,5}|your\s{1,5})?(?:secrets|credentials|tokens|keys|passwords)|env(?:ironment)?\s{1,5}var(?:iable)?s?|private\s{1,5}keys?|ssh\s{1,5}keys?|id_rsa|session\s{1,5}cookies|browser\s{1,5}cookies|wallets?|seed\s{1,5}phrases?|keychain)\b|\.env\b|~\/\.ssh\b|\.aws\/credentials\b/i,KC=/\b(?:secrets?|credentials?|api[\s_-]?keys?|access[\s_-]?tokens?|auth(?:entication)?\s{1,5}tokens?|bearer\s{1,5}tokens?|passwords?(?!\s{1,5}reset))\b/i,YC=/\b(?:to|into|at|via)\b/i,JC=/webhook|pastebin|paste\.|hastebin|discord|telegram|ngrok|requestbin|pipedream|interactsh|burpcollaborator|\.onion\b|https?:\/\/\d{1,3}(?:\.\d{1,3}){3}/i,XC=/https?:\/\/|\bserver\b|\bendpoint\b|\bremote\b|\bexternal\b|third[-\s]party|\battacker\b|e-?mail\s{1,5}address/i,ZC=/\bexternal\b|third[-\s]party|\battacker\b/i,QC=/\b(?:header|authorization|authenticate|bearer\s{1,5}auth)\b|\s-H\s/i,eA=/\sstyle\s{0,5}=\s{0,5}["'][^"'>]{0,200}(?:display\s{0,5}:\s{0,5}none|visibility\s{0,5}:\s{0,5}hidden|font-size\s{0,5}:\s{0,5}0(?:px|pt|em|rem)?\s{0,5}(?:;|["'])|opacity\s{0,5}:\s{0,5}0(?:\.0{1,5})?\s{0,5}(?:;|["']))/i,tA=/\shidden(?:\s|=|\/|$)/i,nA=/^\s{0,20}(?:promptci-ignore|markdownlint|prettier|eslint|cspell|textlint|vale\b|toc\b|omit\s{1,5}in\s{1,5}toc|end\s{0,5}toc|mdformat|lint|region|endregion|#region|#endregion|@formatter|todo\b|fixme\b|xxx\b)/i,sA=/\b(?:ignore|disregard|forget)\b[^\n]{0,40}\b(?:instructions?|prompts?|rules|guidelines)\b|\bsystem\s{1,5}prompt\b|\b(?:curl|wget|iwr|invoke-webrequest)\b|\bbase64\s{1,5}-d\b|~\/\.ssh|\b(?:send|upload|exfiltrate)\b[^\n]{0,40}\b(?:secrets?|credentials?|keys?|tokens?|\.env)\b/i,iA=/\byou\b|\b(?:must|always|never|approve|run|ignore|execute|send|upload|install|delete|disable|download|fetch|read|print|reveal)\b/i,rA=new RegExp([String.raw`\b(?:ignore|disregard|forget)\b[^\n]{0,40}\b(?:instructions?|prompts?|rules|guidelines)\b`,String.raw`\byou\s{1,5}(?:must|are\s{1,5}now|will\s{1,5}now|should\s{1,5}(?:always|never|secretly|silently))\b`,String.raw`\b(?:assistant|claude|the\s{1,5}(?:ai|agent|model|llm))\s{0,5}[:,]`,String.raw`\b(?:dear|hey)\s{1,5}(?:ai|assistant|claude|agent|model)\b`,String.raw`\bsystem\s{1,5}prompt\b`,String.raw`\b(?:curl|wget|iwr|invoke-webrequest)\b`,String.raw`\bbase64\s{1,5}-d\b`,String.raw`\b(?:read|send|upload|post|print|cat|copy|dump|exfiltrate|include|attach|paste)\b[^\n]{0,40}(?:\b(?:secrets?|credentials?|api[_\s-]?keys?|passwords?|private\s{1,5}keys?)\b|~\/\.ssh|\.env\b)`,String.raw`\b(?:run|execute|download|upload|send|install)\s{1,5}(?:this|the\s{1,5}following|it)\b`].join("|"),"i"),oA=/(?<![A-Za-z0-9+/=])[A-Za-z0-9+/]{200,}={0,2}(?![A-Za-z0-9+/=])/g,aA=/\b(?:pip[0-9.]{0,5}|pipx|uvx|uv|npm|pnpm|yarn|bun|npx|bunx|go|cargo|gem|deno)\b/i,cA=/\bgit\+(?:https?|ssh|git|file):\/\/[^\s'"<>)`]{1,500}|\bgithub:[\w.-]{1,100}\/[\w.-]{1,100}(?:#[^\s'"<>)`]{0,100})?/gi,lA=/(?<=[\w.-])@(?:latest|master|main|HEAD)(?![\w.-])/gi,uA=/\b(?:npx|bunx|pnpm\s{1,5}dlx|yarn\s{1,5}dlx|uvx|pipx\s{1,5}run|npm\s{1,5}(?:i|install|exec|add)|pnpm\s{1,5}(?:add|i|install)|yarn\s{1,5}add|bun\s{1,5}(?:add|i|install|x)|go\s{1,5}(?:install|run)|deno\s{1,5}(?:run|install))\b[^\n;&|]{0,200}$/i,fA=/\b(?:npm\s{1,5}(?:i|install|add)|pnpm\s{1,5}(?:add|i|install)|yarn\s{1,5}add|bun\s{1,5}(?:add|i|install))\b([^\n;&|]{0,500})/i,dA=/\bcargo\s{1,5}install\b[^\n;&|]{0,300}--git\s{1,5}\S/i,pA=new RegExp([String.raw`https?:\/\/raw\.githubusercontent\.com\/[^/\s]{1,100}\/[^/\s]{1,100}\/(?:refs\/heads\/)?(?:main|master|HEAD|develop|dev|trunk)\/[^\s'"<>)\x60]{0,300}`,String.raw`https?:\/\/github\.com\/[^/\s]{1,100}\/[^/\s]{1,100}\/raw\/(?:refs\/heads\/)?(?:main|master|HEAD|develop|dev|trunk)\/[^\s'"<>)\x60]{0,300}`,String.raw`https?:\/\/github\.com\/[^/\s]{1,100}\/[^/\s]{1,100}\/releases\/latest\/download\/[^\s'"<>)\x60]{0,300}`,String.raw`https?:\/\/gist\.githubusercontent\.com\/[^/\s]{1,100}\/[0-9a-f]{1,64}\/raw\/(?![0-9a-f]{40}\/)[^\s'"<>)\x60]{1,300}`].join("|"),"i"),hA=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|fetch|urlopen|requests\.get|download|downloadstring)\b/i,mA=/(?:\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|ps1|rb|pl)(?:[?#]|$)|install)/i,gA=/(?:\bfrom\s{1,5}|\bimport\s{0,5}\(\s{0,5}|\bimport\s{1,5}|\brequire\s{0,5}\(\s{0,5})['"](https?:\/\/[^'"\n]{1,500})['"]/g;function Sc(t){if(!t)return!1;let e=t.replace(/^semver:/i,"").trim();return/^[0-9a-f]{7,40}$/i.test(e)||/^v?\d{1,10}(?:\.\d{1,10}){1,4}(?:[-+.][\w.-]{0,50})?$/.test(e)}function Ec(t){let e=t.indexOf("#");if(e>=0){let a=t.slice(e+1);if(!/^(?:egg|subdirectory)=/.test(a))return a.split("&")[0]}let s=(e>=0?t.slice(0,e):t).replace(/^(?:git\+)?[a-z]{1,10}:\/\//i,"").replace(/^github:/i,""),i=s.indexOf("/"),r=i>=0?s.slice(i+1):s,o=r.lastIndexOf("@");return o>=0?r.slice(o+1):void 0}function jm(t){let e=t.trim();return/^(?:git\+|git:|github:|gitlab:|bitbucket:)/i.test(e)||/^[A-Za-z0-9][\w.-]{0,100}\/[\w.-]{1,100}(?:#.{0,100})?$/.test(e)?!Sc(Ec(e.startsWith("git")||e.includes(":")?e:`github:${e}`)):/^https?:\/\//i.test(e)?!/\d+\.\d+\.\d+|#sha(?:256|512)=/i.test(e):!1}function yA(t){if(/@(?:latest|master|main|head)/i.test(t)){for(let e of vt(lA,t,10))if(uA.test(t.slice(Math.max(0,e.index-230),e.index)))return e}}var bA=String.raw`((?:\$\{?[A-Za-z_][A-Za-z0-9_]{0,60}\}?\/|\{baseDir\}\/|\.\/)?[\w@.\-/]{1,200}\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|mts|rb|pl|ps1))(?![\w.\-/])`,wA=new RegExp(String.raw`(?:^|[\s\x60'"(;&|])(?:sudo\s{1,5})?(?:bash|sh|zsh|python[0-9.]{0,5}|node|deno\s{1,5}run(?:\s{1,5}-\S{1,40}){0,8}|bun(?:\s{1,5}run)?|tsx|ts-node|ruby|perl|pwsh(?:\s{1,5}-File)?|powershell(?:\.exe)?(?:\s{1,5}-\S{1,40}){0,8}?\s{1,5}-File|source|uv\s{1,5}run)\s{1,5}${bA}`,"gi"),vA=new RegExp(String.raw`(?:^|[\s\x60'"(;&|])(\.\/[\w@.\-/]{1,200}\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|rb|pl|ps1))(?![\w.\-/])`,"g"),xA=new Set(["json","jsonc","json5","yaml","yml","toml"]),_A=/\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|mts|rb|pl|ps1)\b/i,dm={info:0,warning:1,high:2,critical:3},SA=5,In=25;function _s(t,e){let n=dm[t.severity]-dm[e.severity];return n!==0?n>0:t.confidence>e.confidence}var yc=class{groups=new Map;accepts(e,n,s,i){let r=this.groups.get(`${e}|${n}`);if(!r||r.hits.length<In)return!0;let o={excerpt:"",severity:s,confidence:i};return r.hits.some(a=>_s(o,a))}count(e,n){let s=this.groups.get(`${e}|${n}`);s&&s.total++}add(e,n,s){let i=`${e}|${n}`,r=this.groups.get(i);if(r||(r={rule:e,file:n,hits:[],total:0},this.groups.set(i,r)),r.hits.some(a=>a.line===s.line&&a.excerpt===s.excerpt))return;if(r.total++,r.hits.length<In){r.hits.push(s);return}let o=0;for(let a=1;a<r.hits.length;a++)_s(r.hits[o],r.hits[a])&&(o=a);_s(s,r.hits[o])&&(r.hits[o]=s)}toIssues(e){return[...this.groups.values()].filter(n=>n.hits.length>0).sort((n,s)=>n.rule.localeCompare(s.rule)||n.file.localeCompare(s.file)).map(({rule:n,file:s,hits:i,total:r})=>EA(e,n,s,i,r))}};function EA(t,e,n,s,i){let r=lR[e],o=s.map((d,p)=>({h:d,order:p})).sort((d,p)=>_s(d.h,p.h)?-1:_s(p.h,d.h)?1:d.order-p.order),a=o[0].h,c=o.slice(0,SA).sort((d,p)=>(d.h.line??0)-(p.h.line??0)||d.order-p.order).map(d=>d.h),l=nn(n),u=c.map(d=>e==="unscanned-files"?d.excerpt:`${l}: ${d.excerpt}`);i>c.length&&u.push(e==="unscanned-files"?`\u2026and ${i-c.length} more unscanned item(s)`:`${l}: \u2026and ${i-c.length} more match(es)`);let f=n===t?fc(t):`${fc(n)} (bundled with ${fc(t)})`;return{id:`skill-supply-chain-${e}-${le(`${t}|${n}`)}`,severity:a.severity,category:r.category,title:r.title,summary:`${f}: ${r.summary}`,filePaths:n===t?[t]:[n,t],locations:c.map(d=>d.line===void 0?{filePath:n}:{filePath:n,startLine:d.line,endLine:d.line}),evidence:u,recommendation:r.recommendation,confidence:a.confidence,tags:[bc,e]}}var Mm=t=>typeof t=="function"?t():t,kA=.4;function Ki(t,e,n,s,i,r,o){e!=="skip"&&(e==="lowconf"?t(n,s,()=>`(looks like documentation, but names a target) ${Mm(i)}`,r,kA):t(n,s,i,r,o))}var RA=/[|&;<$`]|>\(|iex|invoke-expression|atob|decode|FromBase64|powershell|pwsh/i;function Dm(t,e){let n=[];if(!RA.test(t))return n;let s=qi(t,Es,e);s&&n.push({rule:"remote-exec",found:s});let i=qi(t,Tm,e);if(i&&n.push({rule:"encoded-exec",found:i}),!n.some(r=>r.rule==="remote-exec"))for(let r of RC){let o=fe(r.pattern,t,r.requires);if(o){n.push({rule:"remote-exec",found:o});break}}if(!n.some(r=>r.rule==="encoded-exec"))for(let r of CC){let o=fe(r.pattern,t,r.requires);if(o){n.push({rule:"encoded-exec",found:o});break}}return n}function Fm(t){if(t.kind!=="instructions")return()=>0;let e=new Int32Array(t.lines.length),n=0;for(let s=0;s<t.lines.length;s++)t.fenced[s]&&!(s>0&&t.fenced[s-1])&&n++,e[s]=t.fenced[s]?n:-(s+1);return s=>e[s]}function CA(t,e,n,s,i){let r=new Set,o=Fm(t),a=new Ss(i),c=Number.NaN;for(let{text:l,line:u}of e){let f=u-1,d=t.kind!=="instructions"||t.fenced[f]===1,p=o(f);p!==c&&(a=new Ss(i),c=p);let h=Dm(l,d),m=a.feed(l,u,d);m&&h.push({rule:m.rule,found:m.found,note:m.fromLine!==u?`(fetched/decoded at line ${m.fromLine}) `:void 0});for(let{rule:g,found:b,note:w}of h){let y=b.match[0].length,v=Ji(t,f,l,b.index,y);Ki(s,v,g,u,()=>`${w??""}${be(l,b.index,y)}`,"high",.85),v!=="skip"&&r.add(u)}}if(t.kind==="instructions")for(let{text:l,line:u}of n){if(r.has(u))continue;let f=Nm(t,l,u-1);f&&(r.add(u),s("remote-eval",u,be(l,f.index,f.match[0].length),"high",.85))}return r}function AA(t,e){for(let n of t.active){let s=fe(e,t.lines[n]);if(s)return{line:n+1,index:s.index}}}function $A(t,e,n){let s=AA(t,NC),i=[],r=[],o=OC[t.lang]??[],a=LC[t.lang]??[];for(let l of t.active){let u=l+1;if(e.has(u))continue;let f=t.lines[l],d=Nm(t,f,l);if(d){n("remote-eval",u,be(f,d.index,d.match[0].length),"high",.85);continue}if(i.length+r.length>=In)continue;let p=o.map(m=>fe(m,f)).find(Boolean);if(p){i.push({line:u,index:p.index});continue}let h=a.map(m=>fe(m,f)).find(Boolean);h&&r.push({line:u,index:h.index})}if(s&&(i.length>0||r.length>0)){n("remote-eval",s.line,`network call: ${be(t.lines[s.line-1],s.index)}`,"high",.75);for(let l of[...i,...r])n("remote-eval",l.line,be(t.lines[l.line-1],l.index),"high",.75)}else for(let l of i)n("dynamic-eval",l.line,be(t.lines[l.line-1],l.index),"warning",.6);if(!s)return;let c=[];for(let l of t.active){if(c.length>=In)break;let u=t.lines[l],f=fe(jC,u)??fe(MC,u);f&&(/(?:\s-i\s{0,5}|IdentityFile\s{1,5}|identity_file\s{0,5}=\s{0,5})\S{0,300}$/.test(u.slice(Math.max(0,f.index-300),f.index+1))||c.push({line:l+1,index:f.index}))}if(c.length!==0){n("credential-exfil",s.line,`network call: ${be(t.lines[s.line-1],s.index)}`,"high",.7);for(let l of c)n("credential-exfil",l.line,`credential/env read: ${be(t.lines[l.line-1],l.index)}`,"high",.7)}}function zi(t,e,n,s,i={}){for(let r of s){let o=fe(r,n);if(!o)continue;let a=o.match[0].length;if(i.skipQuoted&&HR(n,o.index,o.index+a))continue;let c;if(i.negatable===!1?c=!t.fenced[e]&&wc(n,o.index,a)?vc(n.slice(o.index,o.index+a+80))?"lowconf":"skip":"none":c=Ji(t,e,n,o.index,a,i.targetless),c!=="skip")return{found:o,verdict:c}}}function PA(t){for(let e of vt(zC,t,20)){let n=km(t,e.index),s=e.index+e.match[0].length,i=t.slice(s,s+120),r=qC.exec(i),o=r?null:KC.exec(i),a=r??o;if(!a)continue;let c=s+a.index+a[0].length,l=YC.exec(t.slice(c,c+120));if(!l)continue;let u=c+l.index+l[0].length,f=t.slice(u,u+100),d=JC.test(f);if(!d&&QC.test(t))continue;let p=vc(f),h={index:e.index,strong:d,negated:n,target:p};if(d)return{...h,severity:"high",confidence:.75};if(r&&XC.test(f))return{...h,severity:"warning",confidence:.6};if(o&&ZC.test(f))return{...h,severity:"warning",confidence:.6}}}function TA(t){let e=[],n=0;for(let s of t.split(/(?<=[.!?;])\s+/)){let i=t.indexOf(s,n);e.push({text:s,offset:i}),n=i+s.length}return e}function IA(t,e){let n=(s,i,r,o,a,c)=>Ki(e,o.verdict,s,i,be(r,o.found.index,o.found.match[0].length),a,c);for(let s of t.active){let i=t.lines[s];if(i.length<8)continue;let r=s+1;if(FC.test(i)){let o=zi(t,s,i,DC,{skipQuoted:!0,targetless:!0});o&&n("instruction-override",r,i,o,"high",.8)}if(HC.test(i)){let o=zi(t,s,i,WC,{targetless:!0}),a=o?void 0:zi(t,s,i,GC,{negatable:!1});o?n("conceal-from-user",r,i,o,"high",.75):a&&n("conceal-from-user",r,i,a,"warning",.6)}if(BC.test(i)){let o=zi(t,s,i,VC,{targetless:!0});o&&n("permission-bypass",r,i,o,"warning",.6)}if(fm.test(i))for(let o of TA(i)){if(!fm.test(o.text))continue;let a=PA(o.text);if(!a)continue;let c=o.offset+a.index,u=!t.fenced[s]&&(a.negated||wc(i,c,10))?a.target?"lowconf":"skip":"none";Ki(e,u,"exfil-instruction",r,be(i,c,60),a.severity,a.confidence);break}}}function OA(t,e){for(let n of t.active){let s=t.lines[n],i=fe(UC,s);if(!i||t.kind==="instructions"&&!t.fenced[n]&&GR(s))continue;let r=i.match[0].length;Ki(e,Ji(t,n,s,i.index,r,!0),"permission-bypass",n+1,()=>be(s,i.index,r),"warning",.7)}}var LA=/[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}]/u,NA=/\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Emoji_Component}/u,jA=/[\p{L}\p{M}]/u,MA=/\p{Script=Mongolian}/u,DA=/\p{Cf}/u,FA=[[0,8],[10,31],[127,159],[847,847],[1536,1541],[1564,1564],[1757,1757],[1807,1807],[2192,2193],[2274,2274],[4447,4448],[6068,6069],[6155,6159],[8203,8207],[8232,8238],[8288,8297],[12644,12644],[65024,65039],[65279,65279],[65440,65440],[917504,917631],[917760,917999]],pm=t=>"\\u{"+t.toString(16)+"}",pc=new RegExp("["+FA.map(([t,e])=>pm(t)+"-"+pm(e)).join("")+"\\p{Cf}]","gu");function hc(t){return t>=65024&&t<=65039||t>=917760&&t<=917999}function Hm(t,e){if(e<=0)return;let n=t.charCodeAt(e-1);if(n>=56320&&n<=57343&&e>=2){let s=t.charCodeAt(e-2);if(s>=55296&&s<=56319)return(s-55296)*1024+(n-56320)+65536}return n}var mc=t=>t===void 0?void 0:String.fromCodePoint(t);function HA(t,e,n,s,i,r){if(n===9||n>=32&&n<127)return;if(n>=917504&&n<=917631)return i===127988?void 0:"severe";if(n>=8234&&n<=8238||n>=8294&&n<=8297)return"severe";if(n===65279&&s&&e===0)return;let o=Hm(t,e),a=t.codePointAt(e+(n>65535?2:1));if(n===8204||n===8205){let c=l=>l!==void 0&&l>127&&(NA.test(mc(l))||jA.test(mc(l)));return c(o)||c(a)?void 0:"mild"}if(n===8206||n===8207||n===1564||n>=1536&&n<=1541||n===1757||n===1807||n===2192||n===2193||n===2274)return r()?void 0:"mild";if(hc(n)){let c=a===void 0||!hc(a);return o!==void 0&&o>127&&!hc(o)&&c?void 0:"mild"}if(n>=6155&&n<=6159&&n!==6158)return o!==void 0&&MA.test(mc(o))?void 0:"mild";if(n===4447||n===4448){let c=l=>l!==void 0&&l>=4352&&l<=4607;return c(o)||c(a)?void 0:"mild"}if(n===12644||n===65440||n===847||n===6068||n===6069||n===8232||n===8233||n<32||n>=127&&n<=159||DA.test(String.fromCodePoint(n)))return"mild"}function BA(t,e){for(let n of t.active){let s=t.lines[n];pc.lastIndex=0;let i=pc.exec(s);if(i===null)continue;let r,o=()=>r??=LA.test(s),a=new Map,c=!1,l=-1,u=-1,f;for(;i!==null;){let d=i.index,p=s.codePointAt(d);if(p>=917504&&p<=917631){let m=Hm(s,d);(m===void 0||m<917504||m>917631)&&(f=m)}let h=HA(s,d,p,n===0,f,o);h&&(h==="severe"&&(c=!0,u<0&&(u=d)),a.set(p,(a.get(p)??0)+1),l<0&&(l=d)),i=pc.exec(s)}a.size!==0&&e("hidden-unicode",n+1,()=>{let d=[...a.entries()].sort((h,m)=>h[0]-m[0]).slice(0,4).map(([h,m])=>`${mi(h)}\xD7${m}`).join(" "),p=a.size>4?` (+${a.size-4} more kinds)`:"";return`${d}${p} in: ${be(s,c?u:l,1)}`},c?"high":"warning",c?.9:.7)}}function WA(t,e){let n=0,s=t.length-1;for(;n<s;){let i=n+s+1>>1;t[i]<=e?n=i:s=i-1}return n+1}function GA(t){let e=0,n=-1;for(;e<t.length;){let s=t.indexOf("<",e);if(s<0)return;n!==t.length&&n<=s&&(n=t.indexOf(">",s+1),n<0&&(n=t.length));let i=n,r=t.indexOf("<",s+1);if(r>=0&&r<i){e=r;continue}if(e=i+1,i-s>600||!/^<[a-z]/i.test(t.slice(s,s+2)))continue;let o=t.slice(s,i);if(eA.test(o)||tA.test(o))return{index:s,match:Yi(t,s,i+1)}}}function UA(t,e){t.content.includes("<!--")&&VA(t,e);for(let n of t.active){if(t.fenced[n])continue;let s=t.lines[n];if(!s.includes("<")||!/style|hidden/i.test(s))continue;let i=GA(s);i&&e("hidden-html-element",n+1,be(s,i.index,i.match[0].length),"warning",.6)}for(let n of t.active){let s=t.lines[n];if(s.length<200)continue;let i=vt(oA,s,5).find(r=>{let o=r.match[0];return/(?:base64,|data:[^,\s]{0,100},)\s{0,5}$/i.test(s.slice(Math.max(0,r.index-120),r.index))||!/[0-9]/.test(o)||!/[A-Z]/.test(o)||!/[a-z]/.test(o)?!1:(o.match(/\//g)?.length??0)<=o.length/10});i&&e("encoded-blob",n+1,`${i.match[0].length}-char encoded string: ${i.match[0].slice(0,40)}\u2026`,"warning",.5)}}function VA(t,e){let n=t.lines.map((o,a)=>t.fenced[a]?"":o),s=n.join(`
92
- `),i=[0];for(let o=0;o<n.length-1;o++)i.push(i[o]+n[o].length+1);let r=0;for(;r<s.length;){let o=s.indexOf("<!--",r);if(o<0)break;let a=s.indexOf("-->",o+4),c=a<0?s.length:a;r=a<0?s.length:a+3;let l=s.slice(o+4,c);if(nA.test(l.slice(0,200))&&l.length<=120&&!sA.test(l)&&!iA.test(l))continue;let u=fe(rA,l);if(!u)continue;let f=WA(i,o+4+u.index),d=t.lines[f-1]??"",p=o+4+u.index-i[f-1];e("hidden-html-comment",f,()=>be(d,p,u.match[0].length),"warning",.6)}}function zA(t,e){if(t.kind!=="instructions")return e;let n=[];for(let s of e){if(t.fenced[s.line-1]){n.push(s);continue}if(s.text.includes("`"))for(let i of vt(/`([^`\n]{1,1000})`/g,s.text,50))Ji(t,s.line-1,s.text,i.index,i.match[0].length)!=="skip"&&n.push({text:i.match[1],line:s.line})}return n}function hm(t,e,n,s){let i=(r,o,a,c=.6)=>s("unpinned-remote-dep",r,be(o,a,80),"warning",c);if(t.kind==="manifest")return KA(t,i,s);for(let{text:r,line:o}of e){if(n.has(o))continue;if(aA.test(r)){let f=vt(cA,r,10).find(d=>!Sc(Ec(d.match[0])));if(f){i(o,r,f.index);continue}}let a=yA(r);if(a){i(o,r,a.index,.5);continue}let c=fe(fA,r);if(c&&(c.match[1]??"").trim().split(/\s+/).filter(p=>p&&!p.startsWith("-")).find(p=>!p.startsWith("@")&&!p.startsWith(".")&&!p.startsWith("/")&&!p.startsWith("file:")&&!/\.(?:js|mjs|cjs|ts|json|md|sh|py|txt)$/i.test(p)&&(/^[A-Za-z0-9][\w.-]{0,100}\/[\w.-]{1,100}(?:#\S{0,100})?$/.test(p)||/^https?:\/\//i.test(p))&&jm(p))){i(o,r,c.index);continue}let l=fe(dA,r);if(l&&!/--(?:rev|tag)\s{1,5}\S/.test(r)){i(o,r,l.index);continue}let u=fe(pA,r);if(u&&fe(hA,r)&&mA.test(u.match[0])){i(o,r,u.index);continue}if(t.kind==="script"&&t.lang==="js"){let f=vt(gA,r,10).find(d=>!/@v?\d+(?:\.\d+)*|@[0-9a-f]{7,40}|\/v?\d+\.\d+\.\d+\//i.test(d.match[1]));f&&i(o,r,f.index)}}return[]}function qA(t,e,n){let s=e.scripts;if(typeof s=="object"&&s!==null)for(let[a,c]of Object.entries(s).slice(0,100)){if(typeof c!="string")continue;let l=new Ss().feed(c,1,!0);for(let{rule:u,found:f}of[...Dm(c,!0),...l?[l]:[]])n(u,Ye(t.content,`"${a}"`),`scripts.${nn(a)}: ${be(c,f.index,f.match[0].length)}`,"high",.85)}let i=e.bin,r=typeof i=="string"?[i]:typeof i=="object"&&i!==null?Object.values(i).filter(a=>typeof a=="string"):[],o=Ue.posix.dirname(t.path);return r.slice(0,5).map(a=>Ue.posix.normalize(`${o}/${a.replace(/\\/g,"/")}`)).filter(a=>a.startsWith(`${o}/`))}function KA(t,e,n){if(Ue.posix.basename(t.path)==="package.json"){let i;try{i=JSON.parse(t.content)}catch{return[]}if(typeof i!="object"||i===null)return[];let r=qA(t,i,n),o=0;for(let a of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){let c=i[a];if(!(typeof c!="object"||c===null))for(let[l,u]of Object.entries(c)){if(typeof u!="string")continue;let f=u.trim();if(f===""||f==="*"||f==="latest"||jm(f)){if(++o>In)return r;let d=Ye(t.content,`"${l}"`);e(d,t.lines[d-1]??`"${l}": "${u}"`,0)}}}return r}for(let i of t.active){let r=t.lines[i].replace(/\s#.*$/,""),o=fe(/\bgit\+[a-z]{1,10}:\/\/\S{1,500}/i,r);if(o&&!Sc(Ec(o.match[0]))){e(i+1,r,o.index);continue}let a=fe(/\bhttps?:\/\/\S{1,500}?\.(?:zip|tar\.gz|tgz|whl)\S{0,200}/i,r);a&&!/\d+\.\d+|#sha256=/i.test(a.match[0])&&e(i+1,r,a.index)}return[]}function YA(t,e,n,s,i){let r=/^(.*?)\/?skills\/[^/]+$/.exec(e)?.[1],o=f=>{let d=f,p,h=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?\/(.*)$/.exec(d);if(h){let m=h[1];if(d=h[2],m==="CLAUDE_SKILL_DIR"||m==="SKILL_DIR")p=[e];else if(m==="CLAUDE_PLUGIN_ROOT"&&r!==void 0)p=[r||"."];else if(m==="CLAUDE_PROJECT_DIR")p=["."];else return}else if(d.startsWith("{baseDir}/"))d=d.slice(10),p=[e];else{if(d=d.replace(/^\.\//,""),!d.includes("/"))return;p=[...new Set([e,...r?[r]:[],"."])]}if(!(!d||d.includes("..")||d.startsWith("/")))return p.map(m=>m==="."?d:`${m}/${d}`)},a=new Map,c=0,l=0,u=f=>{let d=a.get(f);if(d!==void 0)return d;if(c>=JA)return;c++;let p=at(t,f);return a.set(f,p),p};for(let f of n.active){let d=n.lines[f];if(!(n.fenced[f]&&xA.has(n.fenceLang.get(f)??""))&&_A.test(d))for(let p of[wA,vA])for(let h of vt(p,d,10)){let m=h.match[1],g=m.replace(/^\.\//,""),b=o(m);if(!b)continue;let w=!1,y=!1;for(let v of b){let k=u(v);if(k===void 0)y=!0;else if(k){w=!0;break}}if(!w){if(y)return;if(!(s().has(g)||s().has(m))&&(i("missing-script",f+1,`${nn(m)} not found (looked in: ${b.map(nn).join(", ")})`,"warning",.6),++l>=In))return}}}}var JA=200,XA=3e6;function mm(t,e,n){let s=Buffer.alloc(n),i=ut.readSync(t,s,0,n,e);return s.subarray(0,i)}function ZA(t,e,n,s,i){let r=n.split(/\r?\n/),o=[];for(let l=0;l<r.length;l++){let u=r[l];u.length>0&&QA.test(u)&&o.push(l)}let a=new Uint8Array(r.length),c=new Map;if(e.kind==="instructions"&&(n.includes("```")||n.includes("~~~"))){let l=xe(n.replace(/\r\n/g,`
93
- `));for(let u=0;u<r.length;u++){let f=l[u];f?.inFence&&(a[u]=1,f.lang&&c.set(u,f.lang))}}return{path:t,kind:e.kind,lang:e.lang,content:n,lines:r,active:o,fenced:a,fenceLang:c,frontmatterEnd:s&&!i?vR(r):0,tail:i}}var QA=/[^ \t\r]/;function e$(t){let e=1;for(let n=t.indexOf(10);n>=0;n=t.indexOf(10,n+1))e++;return e}function t$(t,e,n,s,i){let r=s?"high":"warning",o=n?{kind:"instructions",lang:"other"}:gm(e);if(typeof o=="object"&&"skip"in o)return{docs:[],unscanned:[]};if(typeof o=="object"&&"report"in o)return{docs:[],unscanned:[{path:e,reason:o.report,severity:o.severity}]};let a=It(t,e);if(!a)return{docs:[],unscanned:[]};if(!ae(t,a))return{docs:[],unscanned:[{path:e,reason:"symlink to a location outside the repository \u2014 not read",severity:"warning"}]};let c;try{let l=ut.statSync(a);if(!l.isFile())return{docs:[],unscanned:[]};let u=l.size;if(i.files<=0||i.bytes<=0||i.lines<=0)return{docs:[],unscanned:[{path:e,reason:"per-scan budget exhausted \u2014 not scanned",severity:r}]};if(c=ut.openSync(a,"r"),o==="probe"){let g=mm(c,0,Math.min(u,Kn));if(Vt(g))return{docs:[],unscanned:[{path:e,reason:`${wR(g)} \u2014 cannot be reviewed as text`,severity:"warning"}]};let b=bR(g.toString("utf8").split(/\r?\n/,1)[0]??"");o=b?{kind:"script",lang:b}:{kind:"text",lang:"other"}}let f=o,d=f.note?[{path:e,reason:f.note.reason,severity:f.note.severity}]:[];i.files--;let p=(g,b,w)=>{let y=mm(c,g,b);return i.bytes-=y.length,i.lines-=e$(y),ZA(e,f,y.toString("utf8"),n&&!w,w)};if(u<=2*ce){let g=Math.min(u,i.bytes),b=[p(0,g,!1)];return g<u&&d.push({path:e,reason:"per-scan budget exhausted part-way \u2014 the rest was not scanned",severity:r}),{docs:b,unscanned:d}}let h=[p(0,Math.min(ce,i.bytes),!1)],m=Math.min(ce,i.bytes);return m>0&&h.push(p(u-m,m,!0)),d.push({path:e,reason:`larger than 1 MB (${Math.round(u/1024)} KB) \u2014 only the first and last 500 KB were scanned`,severity:m>0?"warning":r}),{docs:h,unscanned:d}}catch{return{docs:[],unscanned:[]}}finally{c!==void 0&&ut.closeSync(c)}}function n$(t,e,n,s,i,r,o){let a=(p,h,m,g,b)=>{if(!r.accepts(p,n.path,g,b)){r.count(p,n.path);return}let w=n.tail?"(end of file) ":n.frontmatterEnd>0&&h<=n.frontmatterEnd?"(frontmatter) ":"";r.add(p,n.path,{line:n.tail?void 0:h,excerpt:`${w}${Mm(m)}`,severity:g,confidence:b})};if(BA(n,a),OA(n,a),n.kind==="manifest")return hm(n,[],new Set,a);let{lines:c,capped:l}=ER(n);l.length>0&&o.push({path:n.path,reason:`continuation chain longer than ${bm} lines / ${wm} characters at line ${l[0]} \u2014 split for scanning (a download-fed loop body is followed up to ${vm} lines / ${xm} characters)`,severity:"warning"});let u=zA(n,c),d=CA(n,c,u,a,p=>{let h=p.replace(/^\.\//,"");return!h||h.startsWith("/")||/^[a-z]:/i.test(h)?!1:[`${Ue.posix.dirname(n.path)}/${h}`,`${e}/${h}`,h].some(m=>at(t,m))});return hm(n,u,d,a),n.kind==="instructions"?(IA(n,a),UA(n,a),s&&!n.tail&&YA(t,e,n,i,a)):$A(n,d,a),[]}var s$=["node_modules",".git","worktrees",".worktrees"],i$={node_modules:/(?:^|[\s'"`(=:/])node_modules\//m,".git":/(?:^|[\s'"`(=:])(?:\.\/)?\.git\//m,worktrees:/(?:^|[\s'"`(=:])(?:\.\/)?worktrees\//m,".worktrees":/(?:^|[\s'"`(=:])(?:\.\/)?\.worktrees\//m};function r$(t,e){let n=It(t,`${e}/hooks`);if(!n)return!1;try{return ut.readdirSync(n).some(s=>!s.endsWith(".sample"))}catch{return!1}}function o$(t,e,n){switch(t.kind){case"dependency-dir":{let s=Ue.posix.basename(t.path),i=s==="node_modules"?" (only package manifests and their bin targets were read)":"";return e.has(s)?{path:t.path,reason:`dependency/VCS directory the skill runs or references by path \u2014 not walked${i}`,severity:"high"}:s===".git"&&r$(n,t.path)?{path:t.path,reason:"git directory with hooks \u2014 hooks run on git operations and were not scanned",severity:"warning"}:{path:t.path,reason:`dependency/VCS directory \u2014 not walked${i}`,severity:"info"}}case"include":return{path:t.path,reason:`${t.count??0} file(s) outside the configured include patterns \u2014 not scanned`,severity:"info"};default:return{path:t.path,reason:`bundle too large to list \u2014 ${t.count??"more"} further file(s) not scanned`,severity:"warning"}}}function kc(t,e={}){let n=t.aiConfig??{},s=n.allSkills??n.skills??[],i=new Set(n.skills??[]),r=s.map(p=>Ue.posix.dirname(p)),o=p=>{let h=-1;return r.forEach((m,g)=>{aa(m)||!(p===m||p.startsWith(`${m}/`))||(h<0||m.length>r[h].length)&&(h=g)}),h},a=s.map((p,h)=>{let m={skillMd:p,dir:r[h],collector:new yc,unscanned:[],alreadyReported:()=>new Set,referenced:new Set,queue:{priority:[],rest:[]},loaded:!1};if(i.has(p)){let g;m.alreadyReported=()=>g??=new Set(lc(m.headContent??"").map(b=>b.ref))}return m});for(let p of n.skillFiles??[]){let h=o(p);h>=0&&(nm(p)?a[h].queue.priority:a[h].queue.rest).push(p)}for(let p of n.skillFilesOverCap??[]){let h=o(p);h>=0&&a[h].unscanned.push({path:p,reason:"over the per-skill file cap \u2014 not scanned",severity:nm(p)?"high":"warning"})}let c={bytes:e.bytes??aR,files:e.files??cR,lines:e.lines??XA},l=(p,h)=>{if(!(h.kind!=="instructions"&&h.kind!=="script"&&!(h.kind==="text"&&h.lang==="sh")))for(let m of s$)i$[m].test(h.content)&&p.referenced.add(m)},u=new Set,f=(p,h,m,g)=>{if(u.has(h))return{docs:[],unscanned:[]};u.add(h);let b=t$(t.repoRoot,h,m,g,c);p.unscanned.push(...b.unscanned);let w=[];m&&(p.headContent=b.docs[0]?.content);for(let y of b.docs)l(p,y),w.push(...n$(t.repoRoot,p.dir,y,m,p.alreadyReported,p.collector,p.unscanned));for(let y of w)o(y)>=0&&f(p,y,!1,!0);return b};for(let p of a){let h=f(p,p.skillMd,!0,!0);p.loaded=h.docs.length>0||h.unscanned.length>0;for(let m of p.queue.priority)f(p,m,!1,!0)}for(let p of a)for(let h of p.queue.rest)f(p,h,!1,!1);let d=[];for(let p of a)if(p.loaded){for(let h of n.skillBundleSkips??[])o(h.path)===a.indexOf(p)&&p.unscanned.push(o$(h,p.referenced,t.repoRoot));for(let h of p.unscanned)p.collector.add("unscanned-files",p.skillMd,{excerpt:`${nn(h.path)}: ${h.reason}`,severity:h.severity,confidence:.8});d.push(...p.collector.toIssues(p.skillMd))}return Te(t.repoRoot,d)}var Rc=x(require("node:path"),1);var a$={idPrefix:"agent",noun:"Subagent",why:"A subagent needs `name` and `description` frontmatter to be registered.",recommendation:"Add frontmatter with `name` and `description` at the top of the agent file."},c$=new Set(["sonnet","opus","haiku","inherit","default","opusplan"]),l$=new Set(["Task","Bash","BashOutput","KillBash","KillShell","Glob","Grep","LS","Read","Edit","MultiEdit","Write","NotebookRead","NotebookEdit","WebFetch","WebSearch","TodoWrite","SlashCommand","ExitPlanMode","Agent"]),u$=.8,f$=5;function ks(t,e){return`ai-config-agent-${t}-${le(e)}`}function d$(t){let e=new Set;for(let n of t.split(/\r?\n/)){let s=n.trim().toLowerCase().replace(/\s+/g," ");s.length>=8&&e.add(s)}return e}function p$(t,e){if(t.size===0||e.size===0)return 0;let n=0,[s,i]=t.size<=e.size?[t,e]:[e,t];for(let o of s)i.has(o)&&n++;let r=t.size+e.size-n;return r===0?0:n/r}function Cc(t){let e=[],n=[];for(let i of t.aiConfig.agents){let r=ie(t.repoRoot,i);if(r===void 0)continue;let o=gt(r);if(e.push(...Ot(i,r,o,a$)),!o.present)continue;let a=typeof o.data.name=="string"?o.data.name.trim():void 0,c=typeof o.data.description=="string"?o.data.description.trim():void 0;a||e.push(F({id:ks("missing-name",i),title:"Subagent frontmatter is missing `name`",summary:`${i} has no \`name\` field, so it cannot be invoked by name.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:o.fenceEndLine>0?o.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(o.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter.",confidence:.85})),c||e.push(F({id:ks("missing-description",i),title:"Subagent frontmatter is missing `description`",summary:`${i} has no \`description\`. The description tells the orchestrator when to delegate to this agent.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:o.fenceEndLine>0?o.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(o.data).join(", ")||"(none)"}`],recommendation:"Add a `description` explaining what the agent is for and when to use it.",confidence:.85}));let l=typeof o.data.model=="string"?o.data.model.trim():void 0;l&&!c$.has(l.toLowerCase())&&!/^claude-/i.test(l)&&e.push(F({id:ks("unknown-model",`${i}|${l}`),title:"Subagent references an unrecognized model",summary:`${i}: \`model: ${l}\` is not a known alias (sonnet, opus, haiku, inherit) or a \`claude-*\` id.`,filePaths:[i],locations:[{filePath:i,startLine:o.keyLines.model??1,endLine:o.keyLines.model??1}],evidence:[`model: ${l}`],recommendation:"Use a supported model alias or a full model id, or remove `model` to inherit the session model.",confidence:.5}));let u=_n(o.data.tools),f=u.filter(h=>h!=="*"&&!h.startsWith("mcp__")&&!l$.has(h));f.length>0&&e.push(F({id:ks("unknown-tools",`${i}|${f.join(",")}`),severity:"info",title:"Subagent grants tools that may not exist",summary:`${i} lists ${f.length} tool name(s) that are not built-in tools or \`mcp__*\` tools: ${f.join(", ")}.`,filePaths:[i],locations:[{filePath:i,startLine:o.keyLines.tools??1,endLine:o.keyLines.tools??1}],evidence:[`Unrecognized: ${f.join(", ")}`,`Declared tools: ${u.join(", ")}`],recommendation:"Check the tool names against the built-in tool set (or your MCP server tool names) for typos.",confidence:.4}));let d=r.split(/\r?\n/).slice(Math.max(0,o.bodyStartLine-1)).join(`
94
- `),p=d$(d);n.push({filePath:i,bodyLines:p})}let s=n.filter(i=>i.bodyLines.size>=f$);for(let i=0;i<s.length;i++)for(let r=i+1;r<s.length;r++){let o=s[i],a=s[r],c=p$(o.bodyLines,a.bodyLines);if(c>=u$){let l=[o.filePath,a.filePath].sort();e.push(F({id:ks("dup-prompt",l.join("|")),title:"Two subagents share near-identical system prompts",summary:`${qt(Rc.basename(l[0]))} and ${qt(Rc.basename(l[1]))} have ${Math.round(c*100)}% identical prompt bodies, which usually means a copy-paste that should be consolidated.`,filePaths:l,locations:l.map(u=>({filePath:u,startLine:1,endLine:1})),evidence:[`Body similarity: ${Math.round(c*100)}%`,`Agents: ${l.join(", ")}`],recommendation:"Differentiate the agents' instructions, or merge them into one agent if they do the same job.",confidence:c===1?.8:.55}))}}return Te(t.repoRoot,e)}var h$=/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|dash)\b/i;function Xi(t,e){return`ai-config-hook-${t}-${le(e)}`}function $c(t,e,n){if(Array.isArray(t)){for(let i of t)$c(i,e,n);return}if(typeof t!="object"||t===null)return;let s=t;s.type==="command"&&typeof s.command=="string"&&n.push({command:s.command,event:e});for(let[i,r]of Object.entries(s))typeof r=="object"&&r!==null&&$c(r,e===""?i:e,n)}var m$=new Set(["bash","sh","zsh","dash","node","deno","python","python3","ruby","ts-node","tsx","pwsh","powershell"]),g$=new Set(["npx","bunx","pnpm","yarn","uv","uvx","env","timeout","nice","sudo","exec","command"]);function Ac(t){return t.replace(/^['"]|['"]$/g,"").replace(/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/,"")}function y$(t){let e=new Set,n=(s,i)=>{if(s.startsWith("-"))return;let r=s.replace(/^['"]|['"]$/g,""),o=Ac(s);if(!o||o.includes("$")||/[<>{}*?|"'`]/.test(o)||o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)||/^https?:/i.test(o)||o.includes("..")||!Zn.test(o))return;let a=r.startsWith("./")||r.startsWith(".claude/")||/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/.test(r);(i||a)&&e.add(o.replace(/\\/g,"/"))};for(let s of t.split(/&&|\|\||;|\|/)){let i=s.trim().split(/\s+/).filter(Boolean);if(i.length===0)continue;let r=Ac(i[0]);if(m$.has(r)||g$.has(r)){for(let o=1;o<i.length;o++)if(!i[o].startsWith("-")&&Zn.test(Ac(i[o]))){n(i[o],!0);break}}else n(i[0],!0);for(let o=1;o<i.length;o++)n(i[o],!1)}return[...e]}function b$(t,e){let n="";for(let s=0;s<e;s++){let i=t[s];n?i===n&&(n=""):(i==='"'||i==="'")&&(n=i)}return n!==""}function w$(t){for(let e of t.matchAll(/\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/g))if(!b$(t,e.index))return!0;return!1}function Pc(t){let e=[];for(let n of t.aiConfig.settings){let s=ie(t.repoRoot,n);if(s===void 0)continue;let i;try{i=JSON.parse(s)}catch(c){e.push(F({id:Xi("invalid-json",n),severity:"high",title:"Settings file is not valid JSON",summary:`${n} could not be parsed as JSON, so Claude Code cannot load its hooks or permissions.`,filePaths:[n],locations:[{filePath:n,startLine:1,endLine:1}],evidence:[`Parse error: ${c.message}`],recommendation:"Fix the JSON syntax (trailing commas and comments are not allowed in settings.json).",confidence:.95}));continue}if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.hooks;if(r===void 0)continue;let o=[];$c(r,"",o);let a=new Set;for(let{command:c,event:l}of o){let u=Ye(s,c);h$.test(c)&&e.push(F({id:Xi("curl-pipe-sh",`${n}|${c}`),severity:"high",impact:"high",title:"Hook pipes a remote download into a shell",summary:`A ${l||"hook"} command in ${n} pipes \`curl\`/\`wget\` output directly into a shell, running whatever the remote host serves with your permissions.`,filePaths:[n],locations:[{filePath:n,startLine:u,endLine:u}],evidence:[`Command: ${c.slice(0,160)}`],recommendation:"Download to a file, review it, and pin a checksum before executing \u2014 never pipe a network fetch straight into sh/bash.",confidence:.85})),w$(c)&&e.push(F({id:Xi("unquoted-project-dir",`${n}|${c}`),severity:"info",title:"Hook uses an unquoted $CLAUDE_PROJECT_DIR path",summary:`A ${l||"hook"} command in ${n} expands \`$CLAUDE_PROJECT_DIR\` unquoted; if the project path contains a space the command breaks or runs the wrong file.`,filePaths:[n],locations:[{filePath:n,startLine:u,endLine:u}],evidence:[`Command: ${c.slice(0,160)}`],recommendation:'Wrap the path in double quotes, e.g. `"$CLAUDE_PROJECT_DIR/script.sh"`.',confidence:.5}));for(let f of y$(c)){if(at(t.repoRoot,f))continue;let d=`${n}|${f}`;a.has(d)||(a.add(d),e.push(F({id:Xi("missing-script",d),title:"Hook command references a script that does not exist",summary:`A ${l||"hook"} command in ${n} runs \`${f}\`, but that file is not present in the repository.`,filePaths:[n],locations:[{filePath:n,startLine:u,endLine:u}],evidence:[`Referenced script: ${f}`,`Command: ${c.slice(0,160)}`],recommendation:"Add the script, fix the path, or remove the hook.",confidence:.75})))}}}return Te(t.repoRoot,e)}function Rs(t,e){return`ai-config-mcp-${t}-${le(e)}`}function v$(t,e){let n=[],s=0,i=!1,r=!1,o="",a=null;for(let c=e;c<t.length;c++){let l=t[c];if(i){if(r){r=!1,o+=l;continue}if(l==="\\"){r=!0;continue}if(l==='"'){i=!1,s===1&&(a=o);continue}o+=l;continue}if(l==='"'){i=!0,o="";continue}if(l==="{"||l==="["){s++;continue}if(l==="}"||l==="]"){if(s--,s===0)break;continue}if(l===":"){s===1&&a!==null&&(n.push(a),a=null);continue}if(l===","){a=null;continue}}return n}function x$(t){let e=/"mcpServers"\s*:/.exec(t);if(!e)return[];let n=t.indexOf("{",e.index+e[0].length);if(n<0)return[];let s=v$(t,n),i=new Map;for(let r of s)i.set(r,(i.get(r)??0)+1);return[...i.entries()].filter(([,r])=>r>1).map(([r])=>r).sort()}function _$(t){let e=t.trim();return!!(e===""||/^<.+>$/.test(e)||/^(your|my)[-_ ]/i.test(e)||/^x{3,}$/i.test(e)||/^\.\.\.+$/.test(e)||/\b(changeme|change[-_]me|replace[-_]?me|placeholder|example[-_]?key|todo|tbd)\b/i.test(e))}function S$(t,e){let n=new Set,s=(i,r)=>{let o=i.replace(/^['"]|['"]$/g,"");if(!o||o.startsWith("-")||o.includes("$")||/[<>{}*?]/.test(o)||o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)||/^https?:/i.test(o)||o.includes(".."))return;let a=o.startsWith("./")||o.startsWith(".claude/");r&&!a||(a||o.includes("/")&&Zn.test(o))&&n.add(o.replace(/\\/g,"/"))};t&&s(t,!1);for(let i of e)s(i,!0);return[...n]}function Tc(t){let e=[];for(let n of t.aiConfig.mcp){let s=ie(t.repoRoot,n);if(s===void 0)continue;let i;try{i=JSON.parse(s)}catch(o){e.push(F({id:Rs("invalid-json",n),severity:"high",title:"MCP config is not valid JSON",summary:`${n} could not be parsed as JSON, so no MCP servers will load from it.`,filePaths:[n],locations:[{filePath:n,startLine:1,endLine:1}],evidence:[`Parse error: ${o.message}`],recommendation:"Fix the JSON syntax (no trailing commas, no comments).",confidence:.95}));continue}if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.mcpServers;if(!(typeof r!="object"||r===null||Array.isArray(r))){for(let o of x$(s))e.push(F({id:Rs("duplicate-name",`${n}|${o}`),title:"Duplicate MCP server name",summary:`${n} defines the server "${o}" more than once. JSON keeps only the last definition and silently discards the earlier one.`,filePaths:[n],locations:[{filePath:n,startLine:Ye(s,`"${o}"`),endLine:Ye(s,`"${o}"`)}],evidence:[`Duplicated server name: ${o}`],recommendation:"Rename or remove the duplicate so each server name is unique.",confidence:.85}));for(let[o,a]of Object.entries(r)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let c=a,l=typeof c.command=="string"?c.command:void 0,u=typeof c.url=="string"?c.url:void 0,f=Array.isArray(c.args)?c.args.filter(p=>typeof p=="string"):[],d=Ye(s,`"${o}"`);if(!l&&!u&&e.push(F({id:Rs("no-command-or-url",`${n}|${o}`),title:"MCP server has neither a command nor a url",summary:`${n}: server "${o}" defines no \`command\` (stdio) and no \`url\` (http/sse), so it cannot start.`,filePaths:[n],locations:[{filePath:n,startLine:d,endLine:d}],evidence:[`Server: ${o}`,`Keys: ${Object.keys(c).join(", ")||"(none)"}`],recommendation:"Add a `command` (with `args`) for a stdio server, or a `url` for a remote server.",confidence:.8})),typeof c.env=="object"&&c.env!==null&&!Array.isArray(c.env))for(let[p,h]of Object.entries(c.env))typeof h!="string"||!_$(h)||e.push(F({id:Rs("placeholder-env",`${n}|${o}|${p}`),title:"MCP server env value is an unfilled placeholder",summary:`${n}: server "${o}" sets \`env.${p}\` to a placeholder (${JSON.stringify(h)}) that was never replaced with a real value.`,filePaths:[n],locations:[{filePath:n,startLine:Ye(s,`"${p}"`),endLine:Ye(s,`"${p}"`)}],evidence:[`${p}: ${h}`],recommendation:'Replace the placeholder with a real value, or reference a shell variable like `"${'+p+'}"`.',confidence:.7}));for(let p of S$(l,f))at(t.repoRoot,p)||e.push(F({id:Rs("missing-command",`${n}|${o}|${p}`),title:"MCP server command path does not exist",summary:`${n}: server "${o}" references the local path \`${p}\`, which is not present in the repository.`,filePaths:[n],locations:[{filePath:n,startLine:d,endLine:d}],evidence:[`Referenced path: ${p}`,`Server: ${o}`],recommendation:"Fix the path, add the missing file, or install the server so the path resolves.",confidence:.7}))}}}return Te(t.repoRoot,e)}var Wm=x(Et(),1);var E$={idPrefix:"cursor",noun:"Cursor rule",why:"A .mdc rule needs metadata (`description`, `globs`, or `alwaysApply`) to control when it applies.",recommendation:"Add a frontmatter block describing the rule and its trigger (globs or alwaysApply).",noFrontmatterTitle:"Cursor rule is missing frontmatter",noFrontmatterSeverity:"warning",noFrontmatterConfidence:.7},k$=["**/node_modules/**","**/.git/**"];function Bm(t,e){return`ai-config-cursor-${t}-${le(e)}`}function R$(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function Ic(t){let e=[],n=t.aiConfig.cursorRules,s=null,i=r=>(s??=ct(t.repoRoot,["**/*"],k$),Wm.default.some(s,r,{dot:!0}));for(let r of n){let o=ie(t.repoRoot,r);if(o===void 0)continue;let a=gt(o);if(e.push(...Ot(r,o,a,E$)),!a.present)continue;let c=typeof a.data.description=="string"?a.data.description.trim():"",l=_n(a.data.globs),u=a.data.alwaysApply===!0||typeof a.data.alwaysApply=="string"&&a.data.alwaysApply.trim().toLowerCase()==="true";!c&&l.length===0&&!u&&e.push(F({id:Bm("no-trigger",r),title:"Cursor rule has no trigger",summary:`${r} defines no \`description\`, no \`globs\`, and \`alwaysApply\` is not set, so Cursor has no signal for when to apply it.`,filePaths:[r],locations:[{filePath:r,startLine:1,endLine:a.fenceEndLine>0?a.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(a.data).join(", ")||"(none)"}`],recommendation:"Add a `description` (agent-requested), `globs` (auto-attached), or `alwaysApply: true`.",confidence:.7}));for(let f of l){if(!R$(f))continue;let d=f.replace(/^\//,""),p=d.includes("/")?[d]:[d,`**/${d}`];i(p)||e.push(F({id:Bm("dead-glob",`${r}|${f}`),title:"Cursor rule glob matches no files",summary:`${r}: the \`globs\` pattern \`${f}\` matches no files in the repository, so this auto-attached rule never fires.`,filePaths:[r],locations:[{filePath:r,startLine:a.keyLines.globs??1,endLine:a.keyLines.globs??1}],evidence:[`Glob: ${f}`],recommendation:"Update the glob to match real paths, or remove the rule if the code it targeted is gone.",confidence:.6}))}}return Te(t.repoRoot,e)}var Lc=x(Et(),1);var C$={idPrefix:"copilot",noun:"Copilot instructions file",why:"A `.instructions.md` file uses an `applyTo:` frontmatter glob to control which files it applies to.",recommendation:'Add a frontmatter block with an `applyTo:` glob (use `applyTo: "**"` to apply to every request).',noFrontmatterTitle:"Copilot instructions file is missing frontmatter",noFrontmatterSeverity:"warning",noFrontmatterConfidence:.7},A$=["**/node_modules/**","**/.git/**"],$$=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/worktrees/**","**/.worktrees/**"];function Oc(t,e){return`ai-config-copilot-${t}-${le(e)}`}function P$(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function T$(t){let e=t.trim();return e==="**"||e==="**/*"}function Nc(t){let e=[],n=t.aiConfig.copilotInstructions,s=null,i=null,r=a=>(s??=ct(t.repoRoot,["**/*"],A$),Lc.default.some(s,a,{dot:!0})),o=a=>(i??=ct(t.repoRoot,["**/*"],$$),Lc.default.some(i,a,{dot:!0}));for(let a of n){let c=ie(t.repoRoot,a);if(c===void 0)continue;let l=gt(c);if(e.push(...Ot(a,c,l,C$)),!l.present)continue;let u=_n(l.data.applyTo);if(u.length===0){e.push(F({id:Oc("no-applyto",a),title:"Copilot instructions file has no applyTo glob",summary:`${a} defines no \`applyTo\` glob, so Copilot applies it to every request by default \u2014 often unintentional.`,filePaths:[a],locations:[{filePath:a,startLine:1,endLine:l.fenceEndLine>0?l.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(l.data).join(", ")||"(none)"}`],recommendation:'Add an `applyTo:` glob scoping the file to the paths it is about, or set `applyTo: "**"` to make the always-on scope explicit.',confidence:.7}));continue}let f=l.keyLines.applyTo??1;for(let d of u){if(!P$(d)||T$(d))continue;let p=d.replace(/^\//,""),h=p.includes("/")?[p]:[p,`**/${p}`];r(h)?o(h)||e.push(F({id:Oc("ignored-glob",`${a}|${d}`),severity:"info",title:"Copilot instructions applyTo glob matches only ignored files",summary:`${a}: the \`applyTo\` glob \`${d}\` matches only ignored or build-output files, so it rarely applies to files you edit.`,filePaths:[a],locations:[{filePath:a,startLine:f,endLine:f}],evidence:[`Glob: ${d}`],recommendation:"Point the glob at source paths, or remove the file if it was meant to target generated output.",confidence:.55})):e.push(F({id:Oc("dead-glob",`${a}|${d}`),title:"Copilot instructions applyTo glob matches no files",summary:`${a}: the \`applyTo\` glob \`${d}\` matches no files in the repository, so this instructions file never applies.`,filePaths:[a],locations:[{filePath:a,startLine:f,endLine:f}],evidence:[`Glob: ${d}`],recommendation:"Update the glob to match real paths, or remove the file if the code it targeted is gone.",confidence:.6}))}}return Te(t.repoRoot,e)}var I$=[{label:"TypeScript",re:/\btypescript\b/i},{label:"JavaScript",re:/\bjavascript\b/i},{label:"Python",re:/\bpython\b/i},{label:"Rust",re:/\brust\b/i},{label:"Go",re:/\bgolang\b/i},{label:"Ruby",re:/\bruby\b|\brails\b/i},{label:"Java",re:/\bjava\b(?!script)/i},{label:"Kotlin",re:/\bkotlin\b/i},{label:"Swift",re:/\bswift\b/i},{label:"C#",re:/\bc#|\bcsharp\b|\bdotnet\b|\.net\b/i},{label:"React",re:/\breact\b/i},{label:"Vue",re:/\bvue\b/i},{label:"Svelte",re:/\bsvelte\b/i},{label:"Django",re:/\bdjango\b/i}],O$=2;function jc(t){let e=[],n=i=>i==="windsurf",s=[...t.files.filter(i=>i.fileType==="windsurf").map(i=>[i]),...Qn(Yt(t.files,t.aliasFiles??[],n))];for(let i of s){let r=i[0],o=new Set;for(let a of r.sections){let c=a.heading;if(c)for(let l of I$)l.re.test(c)&&o.add(l.label)}if(o.size>=O$){let a=[...o].sort();e.push({id:`ai-config-windsurf-scope-${le(L(r))}`,severity:"info",category:"ai_config",title:".windsurfrules mixes language-specific rules in a workspace-wide file",summary:`This \`.windsurfrules\` has headings for multiple languages/frameworks (${a.join(", ")}), but it applies to the whole workspace on every request. Language- or framework-specific rules are cheaper as glob-scoped rules that load only for matching files.`,filePaths:i.map(c=>c.path),locations:i.map(c=>({filePath:c.path,startLine:1})),evidence:[`Scoped topics found in headings: ${a.join(", ")}`],recommendation:"Clarify the intended scope: keep genuinely workspace-wide conventions in `.windsurfrules`, and move language- or framework-specific rules into glob-scoped `.windsurf/rules/*.md` files, each with a glob trigger.",confidence:.6})}}return e}var Gm=x(require("node:crypto"),1),Um=x(require("node:path"),1);var L$=Ce,N$=[/\bdo\s+not\b/i,/\bdon['’]?t\b/i,/\bnever\b/i,/\bavoid\b/i,/\brefrain\s+from\b/i,/\bmust\s+not\b/i,/\bmustn['’]?t\b/i,/\bshould\s+not\b/i,/\bshouldn['’]?t\b/i,/\bcannot\b/i,/\bcan['’]?t\b/i,/\bwon['’]?t\b/i,/\bno\s+longer\b/i],j$=/^(use|always|prefer|ensure|make\s+sure|keep|run|write|add|follow|call|set|return|check|verify|read|ask|include|place|put|store|document|test|update|create|define|import|export|name|group|split|choose|pick|apply|treat|surface|confirm|report|explain|favor|favour|default\s+to|stick\s+to|remember\s+to|be\s+sure\s+to)\b/i,M$=/\b(must|should|always|shall)\b/i,D$=8,F$=.4;function H$(t){return t.replace(/^\s*#{1,6}\s+/,"").replace(/^\s*[-*+]\s+/,"").replace(/^\s*\d+[.)]\s+/,"").replace(/^\s*>\s+/,"").trim()}function B$(t){return t.replace(/^[*_`]+/,"").trimStart()}function W$(t){let e=t.split(/\r?\n/),n=[],s=!1;for(let i of e){if(/^\s*(```|~~~)/.test(i)){s=!s;continue}if(s)continue;let o=H$(i);if(o)for(let a of o.split(/(?<=[.!?])\s+/)){let c=a.trim();c.split(/\s+/).length>=3&&n.push(c)}}return n}function G$(t){let e=B$(t);if(j$.test(e))return"positive";for(let n of N$)if(n.test(t))return"negative";return M$.test(t)?"positive":"none"}function U$(t){return`negative-overload-${Gm.createHash("sha1").update(`negative-overload:${t}`).digest("hex").slice(0,12)}`}function Mc(t){let e=[];for(let n of t){if(!L$.has(n.fileType))continue;let s=W$(n.content),i=[],r=0;for(let f of s){let d=G$(f);d==="negative"?i.push(f):d==="positive"&&r++}let o=i.length+r;if(o<D$)continue;let a=i.length/o;if(a<=F$)continue;let c=Um.basename(n.path),l=Math.round(a*100),u=i.slice(0,3).map(f=>q(f,100));e.push({id:U$(L(n)),severity:"info",category:"agent_practices",title:"High proportion of negative instructions",summary:`About ${l}% of the directive sentences in "${c}" are phrased as prohibitions (${i.length} of ${o}). Models tend to follow positive directives more reliably than prohibitions, so heavily negative guidance can be harder to apply.`,filePaths:[n.path],locations:[],evidence:u.map(f=>`Negative directive: "${f}"`),recommendation:`Where practical, rephrase prohibitions as positive directives \u2014 e.g. instead of "don't use var", write "always use const or let". Keep prohibitions for the cases where no positive form is possible.`,confidence:.5})}return e}var Vm=x(require("node:crypto"),1),zm=x(require("node:path"),1);var V$=Ce,z$=[/\bnever\b/i,/\bcritical\b/i,/\bmust\s+not\b/i,/\bsecurity\b/i,/\bdangerous\b/i],q$=100,K$=.6;function Y$(t){return z$.some(e=>e.test(t))}function J$(t){return`buried-critical-${Vm.createHash("sha1").update(`buried-critical:${t}`).digest("hex").slice(0,12)}`}function Dc(t){let e=[];for(let n of t){if(!V$.has(n.fileType))continue;let s=n.content.split(/\r?\n/);s.length>0&&s[s.length-1]===""&&s.pop();let i=s.length;if(i<=q$)continue;let r=Math.floor(i/2),o=[],a=0,c=!1;for(let h=0;h<i;h++){let m=s[h]??"";if(/^\s*(```|~~~)/.test(m)){c=!c;continue}c||Y$(m)&&(o.push(h+1),h>=r&&a++)}if(o.length===0)continue;let l=a/o.length;if(l<=K$)continue;let u=zm.basename(n.path),f=Math.round(l*100),d=o.filter(h=>h>r),p=s[(d[0]??o[0])-1]??"";e.push({id:J$(L(n)),severity:"info",category:"structure",title:"Critical instructions near the bottom of a long file",summary:`${f}% of the high-severity lines in "${u}" (${a} of ${o.length}) sit in the bottom half of a ${i}-line file. Models weight earlier context more heavily, so critical guidance placed late may be applied less reliably.`,filePaths:[n.path],locations:d.slice(0,5).map(h=>({filePath:n.path,startLine:h,endLine:h})),evidence:[`Keyword lines in bottom half: ${d.slice(0,8).join(", ")}`+(d.length>8?", \u2026":""),`e.g. line ${d[0]??o[0]}: "${q(p,100)}"`],recommendation:'Promote the highest-stakes instructions (security rules, "never"/"must not" constraints) toward the top of the file, or add a short summary of them near the top that points to the detail below.',confidence:.5})}return e}var qm=x(require("node:crypto"),1);var X$=Ce,Z$=6,Q$=.65,eP=40,tP=8;function nP(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+[.)]\s+/gm,"").replace(/\s+/g," ").trim()}function sP(t){return new Set(t.match(/\b\w+\b/g)??[])}function iP(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let s of t)e.has(s)&&n++;return n/(t.size+e.size-n)}function rP(t){let e=t.text.split(`
84
+ `;function ws(t){return`${bs.join(t)}${t}`}var Gi=[{id:"no-secret-safeguard",title:"Missing secret safeguard instruction",summary:"Environment variables are used in this repository, but no instruction found warning the agent never to print or commit secrets.",patterns:[/never\s+.*(print|commit|log|expose)\s+.*(secret|password|token|key|credential)/i,/do\s+not\s+.*(print|commit|log|expose)\s+.*(secret|password|token|key|credential)/i,/secrets?\s+must\s+never\s+be/i,/keep\s+secrets?\s+secure/i],recommendation:'Add a rule such as: "Never print or commit secrets, API keys, or credentials. If you need to use an environment variable, use it silently without echoing its value."',severity:"warning",confidence:.8,fixRecipe:"Never print or commit secrets, API keys, or credentials. If you need to use an environment variable, use it silently without echoing its value."},{id:"no-supabase-service-role-rule",title:"Missing Supabase service role safeguard",summary:"Supabase is used in this repository, but no instruction found warning that the service role key must only be used server-side.",patterns:[/service\s+role\s+key\s+must\s+(stay|only\s+be\s+used)\s+server-side/i,/never\s+expose\s+supabase\s+service\s+role/i,/supabase\s+service\s+role\s+key.*server-side/i],recommendation:'Add a rule such as: "The Supabase service role key must stay server-side and never be exposed to the client."',severity:"warning",confidence:.85,fixRecipe:"Keep SUPABASE_SERVICE_ROLE_KEY server-side only. Never expose it in browser code, logs, or committed files."},{id:"no-upload-boundary-docs",title:"Missing data boundary documentation for uploads",summary:"Upload features detected, but no instruction found defining data boundaries or validation requirements for user-provided files.",patterns:[/validate\s+user\s+(provided|uploaded)\s+files/i,/data\s+boundary\s+for\s+uploads/i,/upload\s+validation/i,/limit\s+upload\s+size/i],recommendation:"Add guidance on how to safely handle and validate user uploads to prevent security risks.",severity:"info",confidence:.7,fixRecipe:"Before handling user uploads, document what file types are allowed, the max file size, and the sanitization steps required."},{id:"no-promptci-report-safeguard",title:"Missing safeguard for .promptci/ reports",summary:".promptci/ folder exists, but no instruction found warning the agent not to commit generated reports to the repository.",patterns:[/do\s+not\s+commit\s+\.promptci/i,/never\s+commit\s+\.promptci/i,/\.promptci\/\s+reports\s+should\s+not\s+be\s+committed/i],recommendation:'Add a rule such as: "Do not commit .promptci/ reports to the repository."',severity:"info",confidence:.8,fixRecipe:"Do not commit .promptci/ reports to the repository."}],Zk=[{pattern:/\brm\s+-(?:rf|fr)\b/i,name:"rm -rf"},{pattern:/drop\s+table/i,name:"drop table"},{pattern:/git\s+push\s+--force/i,name:"git push --force"}];function Ui(t){return`security-pack-${zi.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Qk(t,e){return`destructive-command-${zi.createHash("sha1").update(`destructive-command:${t}:${e}`).digest("hex").slice(0,12)}`}function eR(t){return`security-pack-inspect-reports-first-${zi.createHash("sha1").update(`inspect-reports-first:${t}`).digest("hex").slice(0,12)}`}function vs(t,e){return e.some(n=>n.test(t))}function Vi(t,e){return t.startsWith("!")?!1:t.replace(/^\/+|\/+$/g,"").split("/").includes(e)}function Gh(t){let{files:e,repoRoot:n}=t;if(e.length===0)return[];let s=[],i=e.map(y=>y.content).join(`
85
+ `),r=e.map(y=>y.path);if([".env",".env.example",".env.local",".env.development",".env.production"].some(y=>We.existsSync(je.join(n,y)))||t.files.some(y=>/env\s+vars|environment\s+variables/i.test(y.content))){let y=Gi.find(v=>v.id==="no-secret-safeguard");vs(i,y.patterns)||s.push({id:Ui(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:["Environment variables detected but no safeguard instruction found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}let c={...t.packageJson.dependencies,...t.packageJson.devDependencies,...t.packageJson.peerDependencies};if(We.existsSync(je.join(n,"supabase/migrations"))||Object.keys(c).some(y=>y==="@supabase/supabase-js"||y.startsWith("@supabase/"))){let y=Gi.find(v=>v.id==="no-supabase-service-role-rule");vs(i,y.patterns)||s.push({id:Ui(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:["Supabase detected but no service role safeguard instruction found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}if(t.files.some(y=>{let v=y.path.replace(/\\/g,"/");return v.includes("/api/upload")||v.includes("/uploads/")||/multer|busboy|formidable/i.test(y.content)})){let y=Gi.find(v=>v.id==="no-upload-boundary-docs");vs(i,y.patterns)||s.push({id:Ui(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:["Upload features detected but no data boundary documentation found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}if(We.existsSync(je.join(n,".promptci"))){let y=Gi.find(v=>v.id==="no-promptci-report-safeguard");vs(i,y.patterns)||s.push({id:Ui(y.id),severity:y.severity,category:"security",title:y.title,summary:y.summary,filePaths:r,locations:[],evidence:[".promptci/ folder detected but no report safeguard instruction found."],recommendation:y.recommendation,fixRecipe:y.fixRecipe,confidence:y.confidence})}for(let y of e)for(let v of Zk)if(v.pattern.test(y.content)){let R=[/ask\s+(before|for\s+approval)/i,/confirm\s+before/i,/be\s+careful\s+with/i,/destructive\s+operation/i,/\bdanger(?:ous)?\b/i];vs(y.content,R)||s.push({id:Qk(L(y),v.name),severity:"warning",category:"security",title:`Destructive command "${v.name}" without safety language`,summary:`Instruction file contains a destructive command "${v.name}" but lacks safety language (e.g., "Ask before running").`,filePaths:[y.path],locations:[],evidence:[`Destructive command "${v.name}" found in ${je.basename(y.path)} without safety language.`],recommendation:`Add safety language such as "Ask for confirmation before running ${v.name}" to ensure destructive operations are not performed accidentally.`,confidence:.7})}let d=je.join(n,".gitignore"),p="";try{We.existsSync(d)&&ae(n,d)&&(p=We.readFileSync(d,"utf8"))}catch{}let h=p.split(/\r?\n/).map(y=>y.trim()).filter(y=>y&&!y.startsWith("#"));h.some(y=>Vi(y,".promptci"))||s.push({id:"security-pack-no-promptci-gitignore",severity:"info",category:"security",title:"Missing .promptci/ ignore in .gitignore",summary:"The .promptci/ directory is not ignored in .gitignore, which may lead to committing large generated scan reports to the repository.",filePaths:[".gitignore"],locations:[],evidence:[".promptci/ entry not found in .gitignore"],recommendation:"Add the following to `.gitignore` so generated reports stay out of git while the shared baseline and config remain committed:\n"+bs.map(y=>` ${y}`).join(`
86
+ `)+"\n\nUse `.promptci/*` rather than `.promptci/` \u2014 git does not descend into an ignored directory, so the `!` negations only work against the directory's contents.",fixRecipe:oc,autoApplySafe:!0,confidence:.9});let b=["coverage","dist","build",".next","bin","obj","temp","tmp","logs"].filter(y=>{let v=je.join(n,y);try{if(We.existsSync(v)&&We.statSync(v).isDirectory())return!h.some(T=>Vi(T,y))}catch{}return!1});b.length>0&&s.push({id:"security-pack-unignored-dirs",severity:"warning",category:"context_bloat",title:"Unignored build, output, or coverage directories",summary:`The repository contains directory/directories (${b.join(", ")}) that are commonly generated but not ignored in .gitignore. AI tools may ingest these, inflating token costs.`,filePaths:[".gitignore"],locations:[],evidence:b.map(y=>`Directory "${y}" exists but is not ignored in .gitignore.`),recommendation:`Add generated directories to .gitignore. For example: "${b.map(y=>`${y}/`).join(", ")}"`,fixRecipe:b.map(y=>`echo "${y}/" >> .gitignore`).join(`
87
+ `),autoApplySafe:!0,confidence:.8});let w=!1;try{let y=je.join(n,".promptci","config.json");if(We.existsSync(y)&&ae(n,y)){let v=JSON.parse(We.readFileSync(y,"utf8"));if(Array.isArray(v.include)){let R=["**/*","**/*.md","*","*.*","**"];w=v.include.some(k=>R.includes(k.trim()))}}}catch{}if(w){let y=e.filter(v=>{let R=je.relative(n,v.path).replace(/\\/g,"/");return R.includes(".promptci/")||R.includes("coverage/")||R.includes(".next/")});y.length>0&&s.push({id:"security-pack-broad-include",severity:"warning",category:"context_bloat",title:"Broad include pattern scanning generated directories",summary:"PromptCI configuration has a broad include pattern that matches generated directories such as .promptci/ or coverage/, causing them to be unnecessarily scanned.",filePaths:[".promptci/config.json"],locations:[],evidence:y.map(v=>`Scanned generated file: ${je.relative(n,v.path).replace(/\\/g,"/")}`),recommendation:"Refine the include patterns in .promptci/config.json or add exclusions to avoid scanning generated/temporary documents.",fixRecipe:'Modify .promptci/config.json to restrict "include" to specific instruction files, or add exclusions to "exclude".',confidence:.95})}for(let y of e){let v=[{re:/read\s+.*\.promptci\s+before/i,label:"Instruction to read .promptci reports first"},{re:/inspect\s+.*\.promptci\s+before/i,label:"Instruction to inspect .promptci reports first"},{re:/check\s+.*\.promptci\s+before/i,label:"Instruction to check .promptci reports first"},{re:/read\s+.*report.*\s+before\s+.*(source|docs|code)/i,label:"Instruction to read generated reports before source"},{re:/inspect\s+.*report.*\s+before\s+.*(source|docs|code)/i,label:"Instruction to inspect generated reports before source"}];for(let R of v)if(R.re.test(y.content)){s.push({id:eR(L(y)),severity:"info",category:"context_bloat",title:"Instruction prioritizing generated reports over source docs",summary:`Instruction file "${je.basename(y.path)}" tells the agent to inspect generated reports before source files, which can cause circular or outdated guidance ingestion.`,filePaths:[y.path],locations:[],evidence:[vn(y.content,R.re,R.label)],recommendation:"Recommend linking to latest reports or directing the agent to read source documents first instead of generated reports.",fixRecipe:"Update the instruction to prioritize reading source files and configuration rather than relying on generated reports.",confidence:.7});break}}return s}var _e=x(require("node:path"),1),Ee=x(require("node:fs"),1);function Uh(t){let e=[],{packageJson:n,repoRoot:s,files:i}=t,r=!!(n.dependencies.next||n.devDependencies.next),o=Ee.existsSync(_e.join(s,"next.config.js"))||Ee.existsSync(_e.join(s,"next.config.mjs"))||Ee.existsSync(_e.join(s,"next.config.ts"))||Ee.existsSync(_e.join(s,"apps","web","next.config.js"))||Ee.existsSync(_e.join(s,"apps","web","next.config.mjs"))||Ee.existsSync(_e.join(s,"apps","web","next.config.ts"));if(!r&&!o)return[];let a=Ee.existsSync(_e.join(s,"app"))||Ee.existsSync(_e.join(s,"src","app"))||Ee.existsSync(_e.join(s,"apps","web","app"))||Ee.existsSync(_e.join(s,"apps","web","src","app")),c=Ee.existsSync(_e.join(s,"pages"))||Ee.existsSync(_e.join(s,"src","pages"))||Ee.existsSync(_e.join(s,"apps","web","pages"))||Ee.existsSync(_e.join(s,"apps","web","src","pages"));if(a&&(i.some(u=>u.content.toLowerCase().includes("app router")||u.content.toLowerCase().includes("server component")||u.content.toLowerCase().includes("client component"))||e.push({id:"nextjs-missing-app-router-guidance",severity:"warning",category:"structure",title:"Missing Next.js App Router Guidance",summary:"The project uses the App Router, but the instructions do not mention App Router specific rules like Server vs Client components.",filePaths:i.map(u=>u.path),locations:[],evidence:['App directory detected, but no "App Router" or "Server/Client Component" mention in instructions.'],recommendation:"Add guidance for Next.js App Router, specifically regarding Server and Client Component usage.",confidence:.9})),a&&!c){let l=i.filter(u=>u.content.toLowerCase().includes("pages router")||u.content.toLowerCase().includes("getstaticprops")||u.content.toLowerCase().includes("getserversideprops"));l.length>0&&e.push({id:"nextjs-stale-pages-router-guidance",severity:"warning",category:"stale_instruction",title:"Stale Pages Router Guidance",summary:"The project uses the App Router exclusively, but instructions still reference Pages Router concepts like getStaticProps.",filePaths:l.map(u=>u.path),locations:l.map(u=>({filePath:u.path})),evidence:["Pages Router specific terms found in an App Router project."],recommendation:"Remove or update Pages Router specific instructions to align with App Router.",confidence:.8})}return e}var Pn=x(require("node:path"),1),ac=x(require("node:fs"),1);function Vh(t){let e=[],{manifests:n,repoRoot:s,files:i}=t,r=!!n.pyproject,o=n.requirements!==void 0,a=ac.existsSync(Pn.join(s,"Pipfile")),c=ac.existsSync(Pn.join(s,"environment.yml"));if(!r&&!o&&!a&&!c)return[];(n.pyproject?.includes("pytest")||n.requirements?.includes("pytest"))&&(i.some(p=>p.content.toLowerCase().includes("pytest")||p.content.toLowerCase().includes("test guidance"))||e.push({id:"python-missing-pytest-guidance",severity:"info",category:"structure",title:"Missing Pytest Guidance",summary:"The project uses pytest, but no testing guidance was found in the instructions.",filePaths:i.map(p=>p.path),locations:[],evidence:["pytest detected in dependencies, but no mention in instructions."],recommendation:"Add guidance on how to run and write tests using pytest.",confidence:.8}));let u=[],f=[];return a&&u.push("Pipenv (Pipfile)"),a&&f.push(Pn.join(s,"Pipfile")),c&&u.push("Conda (environment.yml)"),c&&f.push(Pn.join(s,"environment.yml")),r&&n.pyproject?.includes("[tool.poetry]")&&u.push("Poetry (pyproject.toml)"),r&&n.pyproject?.includes("[tool.poetry]")&&f.push(Pn.join(s,"pyproject.toml")),u.length>1&&e.push({id:"python-multiple-env-managers",severity:"warning",category:"conflict",title:"Multiple Python Environment Managers",summary:`Multiple environment managers detected: ${u.join(", ")}. This can lead to conflicting instructions.`,filePaths:f.length>0?f:i.map(d=>d.path),locations:[],evidence:[`Detected: ${u.join(", ")}`],recommendation:"Decide on a single environment manager and remove the others, or clearly document when to use each.",confidence:.9}),e}var cc=x(require("node:path"),1),lc=x(require("node:fs"),1);function zh(t){let e=[],{repoRoot:n,files:s}=t,i=lc.existsSync(cc.join(n,"Assets")),r=lc.existsSync(cc.join(n,"ProjectSettings","ProjectVersion.txt")),o=s.map(d=>d.content).join(`
88
+ `),a=/\bunity\b.*\b(lts|editor|hub|engine)\b|\bmonobehaviour\b|\bunityengine\b|\bgameobject\b|\bprefab\b|\bscriptableobject\b/i.test(o);if(!(i&&r)&&!a)return[];let c=s.map(d=>d.path);return/monobehaviour\s+(?:lifecycle|guidance|rules?)|\blifecycle\s+(?:method|methods|guidance|rules?)|instantiate\b.*monobehaviour|avoid\b.*update|new\s+monobehaviour|awake\(\)|start\(\)|update\(\)/i.test(o)||e.push({id:"unity-missing-monobehaviour-guidance",severity:"warning",category:"structure",title:"Missing Unity MonoBehaviour Lifecycle Guidance",summary:'Unity project detected, but instructions lack guidelines on MonoBehaviour lifecycle (e.g. not calling "new" on MonoBehaviours, avoiding empty Update methods).',filePaths:c,locations:[],evidence:["Unity detected, but no MonoBehaviour lifecycle rules found in instructions."],recommendation:'Add guidance warning never to use "new" to instantiate MonoBehaviours, and advising on efficient Update() / Awake() / Start() usage.',fixRecipe:'Do not instantiate MonoBehaviours using the "new" keyword; always use GameObject.AddComponent or Object.Instantiate. Avoid leaving empty Awake, Start, or Update methods in scripts as they still incur Unity lifecycle overhead.',confidence:.8}),/\[serializefield\]|serializefield\b|prefab\s+(?:safety|workflow|guidance|rules?)|meta\s+file/i.test(o)||e.push({id:"unity-missing-serialization-guidance",severity:"warning",category:"structure",title:"Missing Unity Serialization and Prefab Safety Guidance",summary:"Unity project detected, but instructions lack safety rules for Prefabs and [SerializeField] parameters.",filePaths:c,locations:[],evidence:["Unity detected, but no SerializeField or prefab rules found in instructions."],recommendation:"Add rules for using [SerializeField] for private variables to expose them in the inspector, and avoiding editing .meta files manually.",fixRecipe:"Use [SerializeField] to expose private fields in the Unity Inspector instead of making them public. Never manually edit or delete .meta files; let the Unity Editor manage them to prevent serialization breakages.",confidence:.8}),/play\s+mode|test\s+runner|unity\s+test/i.test(o)||e.push({id:"unity-missing-test-guidance",severity:"info",category:"structure",title:"Missing Unity Play Mode and Test Runner Guidance",summary:"Unity project detected, but instructions do not guide agents to test changes in Play Mode or Unity Test Runner.",filePaths:c,locations:[],evidence:["Unity detected, but no Play Mode/Test Runner verification found in instructions."],recommendation:"Add instructions telling agents to run tests using Unity Test Runner or test changes in Play Mode.",fixRecipe:"Verify gameplay and UI changes by testing in the Unity Editor Play Mode or running Unity Test Runner (Window > General > Test Runner).",confidence:.75}),e}var uc=x(require("node:fs"),1);function qh(t){let e=[],{repoRoot:n,files:s}=t,i=t.projectType==="dotnet";if(!i)try{i=uc.readdirSync(n).some(u=>u.endsWith(".sln")||u.endsWith(".csproj"))}catch{}let r=s.map(u=>u.content).join(`
89
+ `),o=/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(r);if(!i&&!o)return[];let a=s.map(u=>u.path);/dotnet\s+(build|test|restore|run)/i.test(r)||e.push({id:"dotnet-missing-validation-commands",severity:"warning",category:"structure",title:"Missing .NET Validation Commands",summary:'The project uses .NET, but instructions do not mention dotnet validation commands like "dotnet build" or "dotnet test".',filePaths:a,locations:[],evidence:[".NET detected, but no dotnet build/test commands found in instructions."],recommendation:'Add instructions telling the agent to run "dotnet build" and "dotnet test" to verify changes.',fixRecipe:"Before saying work is complete, run dotnet build && dotnet test to verify changes.",confidence:.85});let l;try{let f=uc.readdirSync(n).find(d=>d.endsWith(".csproj"));if(f){let d=ie(n,f)??"",p=/<TargetFramework>(.*?)<\/TargetFramework>/.exec(d);p&&(l=p[1]?.trim())}}catch{}if(l){let u=/\b(netcoreapp\d+\.\d+|net5\.0|netcore)\b/i.test(r);/^net(?:[6-9]|[1-9]\d+)\.0/.test(l)&&u&&e.push({id:"dotnet-obsolete-framework-reference",severity:"warning",category:"stale_instruction",title:".NET Obsolete Framework Reference",summary:`The project targets modern .NET (${l}), but instructions still reference obsolete versions like .NET Core 3.1 or .NET 5.0.`,filePaths:a,locations:[],evidence:[`Project targets ${l}; obsolete framework references found in instructions.`],recommendation:`Update instructions to reference the current target framework version (${l}).`,fixRecipe:`Target .NET ${l} as the framework for this project. Do not use legacy .NET Core 3.1 or .NET 5.0 APIs.`,confidence:.8})}return e}var Kh=x(require("node:path"),1),Yh=x(require("node:fs"),1);function Jh(t){let e=[],{repoRoot:n,files:s}=t,i=Yh.existsSync(Kh.join(n,"go.mod")),r=s.map(l=>l.content).join(`
90
+ `),o=/\bgo\.mod\b/i.test(r)||/`[^`\n]*\bgo\s+(?:build|test|run|get|mod)\b[^`\n]*`/i.test(r);if(!i&&!o)return[];let a=s.map(l=>l.path);return/\bgo\s+test\b/i.test(r)||e.push({id:"go-missing-testing-commands",severity:"warning",category:"structure",title:"Missing Go Testing Commands",summary:'Go project detected, but instructions do not mention Go testing commands like "go test ./...".',filePaths:a,locations:[],evidence:['Go detected, but no "go test" command found in instructions.'],recommendation:'Add instructions telling the agent to run "go test ./..." to verify changes.',fixRecipe:"Before saying work is complete, run go test ./... to verify all tests pass.",confidence:.85}),e}var Xh=x(require("node:path"),1),Zh=x(require("node:fs"),1);function Qh(t){let e=[],{repoRoot:n,files:s}=t,i=Zh.existsSync(Xh.join(n,"Cargo.toml")),r=s.map(u=>u.content).join(`
91
+ `),o=/\bcargo\.toml\b|\bcargo\s+(build|test|run|clippy|fmt)\b/i.test(r);if(!i&&!o)return[];let a=s.map(u=>u.path);/cargo\s+(test|clippy|fmt)/i.test(r)||e.push({id:"rust-missing-verification-commands",severity:"warning",category:"structure",title:"Missing Rust Verification Commands",summary:'Rust project detected, but instructions do not mention Cargo verification commands like "cargo test" or "cargo clippy".',filePaths:a,locations:[],evidence:["Rust detected, but no cargo test/clippy/fmt commands found in instructions."],recommendation:"Add instructions telling the agent to run cargo test, cargo clippy, and cargo fmt to verify changes.",fixRecipe:"Before saying work is complete, verify changes by running cargo fmt, cargo clippy, and cargo test.",confidence:.85});let l;if(i)try{let u=ie(n,"Cargo.toml")??"",f=/^rust-version\s*=\s*["'](.*?)["']/m.exec(u);f&&(l=f[1]?.trim())}catch{}if(l){let u=p=>{let h=/^(\d+)\.(\d+)/.exec(p);return h?`${h[1]}.${h[2]}`:void 0},d=/\bRust\s+(\d+\.\d+(?:\.\d+)?)\b/i.exec(r);if(d){let p=d[1];u(p)!==u(l)&&e.push({id:"rust-version-mismatch",severity:"warning",category:"stale_instruction",title:"Rust Version Mismatch",summary:`Instructions mention Rust version ${p}, but Cargo.toml specifies rust-version = "${l}".`,filePaths:a,locations:[],evidence:[`Cargo.toml requires rust-version = ${l}; instructions mention Rust ${p}`],recommendation:`Update instructions to match the Rust version specified in Cargo.toml (${l}).`,fixRecipe:`Target Rust ${l} as the Minimum Supported Rust Version (MSRV) for this project.`,confidence:.8})}}return e}function em(t){let e=[];return e.push(...Uh(t)),e.push(...Vh(t)),e.push(...zh(t)),e.push(...qh(t)),e.push(...Jh(t)),e.push(...Qh(t)),e}var nm=x(require("node:path"),1),sm=x(require("node:crypto"),1);function xs(t,e){let n=sm.createHash("sha1").update(`prompt-cache-${t}:${e}`).digest("hex").slice(0,12);return`prompt-cache-${t}-${n}`}var tR=[{re:/\b(?:last\s+updated|last\s+modified|updated\s+at|modified\s+at|date)\b\s*:\s*\b\d{4}-\d{2}-\d{2}\b/i,label:'Dated "last updated"/"modified" line'},{re:/\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}\b/i,label:"ISO 8601 timestamp"},{re:/\b(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b/i,label:"Long-form calendar date"}],nR=[{re:/health\s+score\s*:\s*\d+/i,label:"Health-score line from a scan report"},{re:/files\s+scanned\s*:\s*\d+/i,label:"File-count line from a scan report"},{re:/promptci\s+report/i,label:"PromptCI report heading"},{re:/\bgenerated\s+by\s+promptci\b/i,label:"PromptCI generated-by marker"},{re:/latest\s+scan\s+results/i,label:'Pasted "latest scan results" section'},{re:/scan\s+history/i,label:'Pasted "scan history" section'}],sR=[{re:/current\s+branch\s*:\s*\S+/i,label:"Current-branch line"},{re:/git\s+branch\s*:\s*\S+/i,label:"Git-branch line"},{re:/current\s+task\s*:\s*\S+/i,label:"Current-task line"}],tm=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i;function im(t){let e=[],n=t.filter(s=>Ce.has(s.fileType));for(let s of n){let i=nm.basename(s.path);for(let c of tR)if(c.re.test(s.content)){e.push({id:xs("volatile-timestamp",L(s)),severity:"warning",category:"context_bloat",title:"Volatile timestamp in instruction file",summary:`The instruction file "${i}" contains a volatile date or timestamp. Frequently changing dates in persistent instruction files invalidate prompt caches.`,filePaths:[s.path],locations:[],evidence:[vn(s.content,c.re,c.label)],recommendation:"Move volatile dates to a separate task-specific prompt or scratch file, or remove them from canonical instructions.",fixRecipe:'Remove the "Last updated: <date>" or timestamp line from the file.',confidence:.85});break}for(let c of nR)if(c.re.test(s.content)){e.push({id:xs("pasted-report",L(s)),severity:"warning",category:"context_bloat",title:"Pasted scan report or summary in instructions",summary:`The instruction file "${i}" contains pasted scan results or reports. Committing generated reports into canonical instruction files breaks prompt caching and bloats context.`,filePaths:[s.path],locations:[],evidence:[vn(s.content,c.re,c.label)],recommendation:"Link to the generated report file or read it on-demand instead of pasting its contents into canonical instructions.",fixRecipe:"Delete the pasted report summary block and reference the report file path instead.",confidence:.9});break}for(let c of sR)if(c.re.test(s.content)){e.push({id:xs("volatile-branch-task",L(s)),severity:"warning",category:"context_bloat",title:"Volatile branch or task status in instructions",summary:`The instruction file "${i}" contains active git branch or task details. Frequently updated task status or branch names break prompt caching.`,filePaths:[s.path],locations:[],evidence:[vn(s.content,c.re,c.label)],recommendation:"Move branch-specific notes and active task details to git commit messages, PR descriptions, or a temporary scratch file.",fixRecipe:"Remove active branch and task notes from the persistent instructions.",confidence:.85});break}if(tm.test(s.content)){let c=s.content.match(tm)?.[0]??"";e.push({id:xs("local-paths",L(s)),severity:"warning",category:"context_bloat",title:"Local machine paths in instructions",summary:`The instruction file "${i}" contains absolute local machine paths ("${c}"). These paths change per environment, preventing prompt caching and causing instruction drift.`,filePaths:[s.path],locations:[],evidence:[`Found absolute local path: ${c}`],recommendation:"Use repository-relative paths instead of absolute local machine paths.",fixRecipe:"Replace absolute local paths with repository-relative paths.",confidence:.8})}let r=s.content.split(/\r?\n/),o=0,a=0;for(let c of r){let l=c.trim();if(l.startsWith("|")&&l.endsWith("|")){if(/^\|[-\s:|]+\|$/.test(l))continue;a++}else a>o&&(o=a),a=0}a>o&&(o=a),o>15&&e.push({id:xs("large-table",L(s)),severity:"warning",category:"context_bloat",title:"Large table in instruction file",summary:`The instruction file "${i}" contains a large Markdown table (${o} rows). Large tables bloat prompt context and reduce caching friendliness.`,filePaths:[s.path],locations:[],evidence:[`Markdown table with ${o} rows found in ${i}.`],recommendation:"Move large tables to separate documentation files (e.g. under docs/) or load them on-demand via tools instead of keeping them in always-loaded instructions.",fixRecipe:"Extract the table to a separate document and link to it.",confidence:.9})}return e}var fc=x(require("node:path"),1);var rm=12,iR={idPrefix:"skill",noun:"Skill",why:"Claude Code treats frontmatter as optional, but strict Agent Skills loaders (for example Codex) skip a skill without `name` and `description`.",recommendation:"Add a frontmatter block with `name` and `description` at the top of the SKILL.md file.",noFrontmatterSeverity:"warning"};function Tn(t,e,n=""){return`ai-config-skill-${t}-${le(`${e}|${n}`)}`}function rR(t){return t.toLowerCase().replace(/[`*_~]/g,"").replace(/[^a-z0-9]+/g," ").trim()}function oR(t){if(!t)return!1;let e=t.trim();if(/^(https?:|mailto:|#|\/\/)/i.test(e)||/^[a-zA-Z]:[\\/]/.test(e)||/[<>{}*?|"\s]/.test(e)||e.includes(".."))return!1;let n=e.split("#")[0],s=n.includes("/"),i=/\.[a-z0-9]{1,6}$/i.test(n);return s&&i}function dc(t){let e=[],n=new Set,s=(r,o)=>{if(!oR(r))return;let a=r.split("#")[0];n.has(a)||(n.add(a),e.push({ref:a,line:o}))},i=t.split(/\r?\n/);for(let r=0;r<i.length;r++){let o=i[r];for(let a of o.matchAll(/\[[^\]]*\]\(([^)]+)\)/g))s(a[1].split(/\s+/)[0].replace(/^<|>$/g,""),r+1);for(let a of o.matchAll(/`([^`]+)`/g))s(a[1].trim(),r+1)}return e}function aR(t,e){if(e.startsWith("/")){let r=e.slice(1);return cR.has(r.split("/")[0])?void 0:[r]}let n=/^(.*?)\/?skills\/[^/]+$/.exec(t)?.[1],i=[t,...n&&n!==".claude"&&n!==".agents"?[n]:[],"."];return[...new Set(i.map(r=>r==="."||r===""?e:`${r}/${e}`))]}var cR=new Set(["usr","var","etc","opt","tmp","home","Users","Library","bin","sbin","dev","proc","mnt","private","System"]);function lR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uR(t,e){let s="[^`;\\n]{0,40}";return new RegExp(`\\b(?:do\\s+not|don'?t|never|must\\s+not|should\\s+not|shouldn'?t)\\s+(?:\\w+\\s+)?(?:commit|stage|check\\s+in|add|push|track)\\b(?:${s}\`[^\`\\n]{1,100}\`){0,4}${s}\`?${lR(e)}`,"i").test(t)}function pc(t){let e=[],n=[],s;for(let i of t.aiConfig.skills){let r=ie(t.repoRoot,i);if(r===void 0)continue;let o=Kt(fc.dirname(i)).split("/").pop()??"",a=gt(r);if(e.push(...Lt(i,r,a,iR)),!a.present)continue;let c=typeof a.data.name=="string"?a.data.name.trim():void 0,l=typeof a.data.description=="string"?a.data.description.trim():void 0;c?c!==o&&o&&e.push(H({id:Tn("name-dir-mismatch",i),title:"Skill `name` does not match its directory",summary:`${i}: frontmatter \`name: ${c}\` does not match the skill directory \`${o}/\`. Claude resolves skills by directory name.`,filePaths:[i],locations:[{filePath:i,startLine:a.keyLines.name??1,endLine:a.keyLines.name??1}],evidence:[`name: ${c}`,`directory: ${o}`],recommendation:"Rename the directory or the `name` field so they match.",confidence:.6})):e.push(H({id:Tn("missing-name",i),title:"Skill frontmatter is missing `name`",summary:`${i} has no \`name\` field. Claude uses \`name\` to identify and invoke the skill.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:a.fenceEndLine>0?a.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(a.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter matching the skill directory name.",confidence:.85})),l?l.length<rm&&e.push(H({id:Tn("empty-description",i),title:"Skill `description` is too short to trigger reliably",summary:`${i}: \`description\` is only ${l.length} characters. Claude matches the description against the user's request to decide when to invoke the skill.`,filePaths:[i],locations:[{filePath:i,startLine:a.keyLines.description??1,endLine:a.keyLines.description??1}],evidence:[`description: ${l}`],recommendation:"Expand the description to describe the task and its trigger conditions.",confidence:.7})):e.push(H({id:Tn("missing-description",i),title:"Skill frontmatter is missing `description`",summary:`${i} has no \`description\`. The description is the trigger text Claude matches against \u2014 without it the skill rarely activates.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:a.fenceEndLine>0?a.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(a.data).join(", ")||"(none)"}`],recommendation:"Add a `description` that says what the skill does and when to use it.",confidence:.85}));let u=Kt(fc.dirname(i)),f=r.split(/\r?\n/);for(let{ref:d,line:p}of dc(r)){if(ga(d)||/^\/?\.git\//.test(d))continue;let h=aR(u,d);if(!h||h.some(g=>at(t.repoRoot,g))||(s??=Si(t.repoRoot),h.some(g=>s(g)))||uR(f[p-1]??"",d))continue;let m=d.startsWith("/");e.push(H({id:Tn("dead-ref",i,d),title:"Skill references a bundled file that does not exist",summary:m?`${i} references \`${d}\`, but no such file exists at that path from the repository root.`:`${i} references \`${d}\`, but no such file exists relative to the skill directory or the repository root.`,filePaths:[i],locations:[{filePath:i,startLine:p,endLine:p}],evidence:[`Reference: ${d}`,`Looked in: ${h.join(", ")}`],recommendation:"Add the referenced file, fix the path, or remove the reference.",confidence:.75}))}l&&n.push({filePath:i,description:l})}return e.push(...fR(n)),Te(t.repoRoot,e)}function fR(t){let e=[],n=new Map;for(let s of t){if(s.description.length<rm)continue;let i=rR(s.description);if(!i)continue;let r=n.get(i)??[];r.push(s),n.set(i,r)}for(let s of n.values()){if(s.length<2)continue;let i=[...s].sort((o,a)=>o.filePath.localeCompare(a.filePath)),r=i.map(o=>o.filePath);e.push(H({id:Tn("overlap",r.join("|")),title:"Multiple skills share the same trigger description",summary:`${r.length} skills have effectively identical \`description\` text, so Claude cannot tell which to invoke for a given request.`,filePaths:r,locations:i.map(o=>({filePath:o.filePath,startLine:1,endLine:1})),evidence:[`Shared description: ${i[0].description}`,`Skills: ${r.join(", ")}`],recommendation:"Give each skill a distinct description that states its unique trigger conditions.",confidence:.75}))}return e}var ut=x(require("node:fs"),1),Ue=x(require("node:path"),1);var xc="skill-supply-chain",dR=20*1024*1024,pR=2e3,hR={"remote-exec":{title:"Skill may download and execute remote code",category:"security",summary:"content fetched from the network appears to be executed \u2014 piped or substituted into an interpreter, or downloaded and run without verification. Whatever the server returns at run time runs with the user's permissions, and it can change after the skill was reviewed.",recommendation:"Consider vendoring the script into the skill directory (so it is reviewed with the skill), or download it to a file, verify a pinned checksum, and only then run it."},"encoded-exec":{title:"Skill may decode and execute an encoded payload",category:"security",summary:"an encoded string appears to be decoded and executed. Encoding hides what actually runs from anyone reviewing the skill.",recommendation:"Replace the encoded payload with the plain-text commands it runs, so the behavior can be reviewed."},"remote-eval":{title:"Skill may evaluate code fetched from the network",category:"security",summary:"code appears to be evaluated dynamically (eval/exec, `new Function`, a dynamic import, or deserialization) alongside network calls \u2014 the shape of a remote-code loader.",recommendation:"Review what the evaluated code is built from. If it comes from the network, replace the loader with code bundled in the skill."},"dynamic-eval":{title:"Skill script evaluates dynamically built code",category:"security",summary:"a bundled script uses eval/exec, `new Function`, or Invoke-Expression. What it runs cannot be read from the script itself.",recommendation:"Consider replacing dynamic evaluation with direct code so the script's behavior is reviewable."},"credential-exfil":{title:"Skill script reads credentials and makes network calls",category:"security",summary:"a bundled file reads a credential store (SSH keys, cloud credentials, wallets, the keychain) or dumps the whole environment, and the same file makes network calls \u2014 a possible credential-exfiltration path.",recommendation:"Confirm the script needs this access. A skill should read only the specific variable it needs and send it only to the service that requires it; remove bulk environment dumps and credential-file reads."},"exfil-instruction":{title:"Skill instructions may direct sending secrets off-machine",category:"security",summary:"the instructions appear to tell the agent to send, upload or post secrets, credentials or environment variables to a destination.",recommendation:"Remove the instruction. Skills should never direct an agent to transmit credentials anywhere; if an API call needs a key, reference the environment variable by name only."},"instruction-override":{title:"Skill contains prompt-injection style override text",category:"security",summary:`the text appears to try to override the agent's existing instructions (e.g. "ignore previous instructions") or embeds chat-template role tokens. A skill has no legitimate reason to do this.`,recommendation:"Remove the override text. If the skill documents injection strings as examples, quote them so they read as data."},"conceal-from-user":{title:"Skill instructions may hide actions from the user",category:"security",summary:"the instructions appear to tell the agent to act silently or keep something from the user.",recommendation:"Remove the concealment. Every action a skill takes should be visible to the person running it."},"permission-bypass":{title:"Skill may disable agent permission or safety prompts",category:"security",summary:"the skill appears to turn off permission prompts, approvals or sandboxing (for example `--dangerously-skip-permissions`), so later actions would run without the user confirming them.",recommendation:"Remove the bypass and let the agent's normal permission prompts apply; grant narrowly scoped `allowed-tools` instead if needed."},"hidden-unicode":{title:"Skill contains invisible or bidirectional Unicode characters",category:"security",summary:"the file contains characters that do not render \u2014 Unicode tag characters and bidi controls can smuggle instructions or reorder text so what a reviewer sees differs from what the agent reads.",recommendation:"Remove the invisible characters (the evidence shows them as <U+XXXX>, and decodes tag-character payloads) and re-review the affected lines."},"hidden-html-comment":{title:"Skill hides agent-directed text in an HTML comment",category:"security",summary:"an HTML comment contains agent-directed or sensitive text. Rendered previews hide comments, but the agent reads them.",recommendation:"Move the text into visible prose (or delete it) so reviewers see everything the agent is told."},"hidden-html-element":{title:"Skill hides text from rendered view with HTML/CSS",category:"security",summary:"an HTML element hides its content from rendered previews (`display:none`, `visibility:hidden`, `hidden`), but the agent still reads it.",recommendation:"Remove the hiding markup so the content is visible to reviewers, or delete the hidden content."},"encoded-blob":{title:"Skill instructions contain a large encoded blob",category:"security",summary:"the instruction text contains a long base64-like string whose content cannot be reviewed by reading the skill.",recommendation:"Replace the blob with the plain content it encodes, or move binary assets into bundled files."},"unpinned-remote-dep":{title:"Skill pulls a remote dependency without a pinned version",category:"security",summary:"the skill installs or fetches remote code by a mutable reference (a git URL without a commit or tag, `@latest`, or a script on a branch), so what runs can change after the skill was reviewed.",recommendation:"Pin the dependency to an exact version, tag or commit SHA (and prefer a checksum for downloaded scripts)."},"missing-script":{title:"Skill invokes a script that is not bundled with it",category:"ai_config",summary:"the skill tells the agent to run a script that exists neither in the skill directory nor at that path in the repo, so what actually runs cannot be reviewed with the skill.",recommendation:"Bundle the script in the skill directory, fix the path, or remove the instruction."},"unscanned-files":{title:"Some skill content was not fully scanned",category:"security",summary:"part of this skill could not be checked by the supply-chain scan \u2014 binaries, archives or compiled-language sources it cannot analyze, files beyond the per-skill cap or the per-scan budget, the middle of very large files, or directories it does not walk. Anything in those parts was not checked.",recommendation:"Review the listed content by hand. A skill that ships binaries or very large files deserves extra scrutiny before installing."}},mR=new Set(["md","mdx","markdown","txt"]),gR=new Set(["yml","yaml","json","jsonc","json5","toml","ini","cfg","conf","html","htm","xhtml","xml","svg"]),om={sh:"sh",bash:"sh",zsh:"sh",ksh:"sh",fish:"sh",command:"sh",js:"js",mjs:"js",cjs:"js",ts:"js",mts:"js",cts:"js",jsx:"js",tsx:"js",py:"py",pyw:"py",rb:"rb",ps1:"ps",psm1:"ps",pl:"other",php:"other",lua:"other",bat:"other",cmd:"other"},yR=new Set(["go","rs","java","c","cc","cpp","cxx","h","hpp","cs","swift","kt","kts","groovy","gradle","scala","tf","hcl","sql","service","desktop"]),bR=new Set(["vbs","vba","vbe","hta","applescript","wsf","jse","reg"]),wR=new Set(["exe","dll","so","dylib","wasm","jar","war","class","zip","tar","gz","tgz","bz2","xz","7z","rar","msi","dmg","pkg","deb","rpm","appimage","apk","bin","o","a","lnk","scr","com","pif","scpt","node"]),vR=new Set(["docx","xlsx","pptx","doc","xls","ppt","odt","sqlite","sqlite3","db"]),xR=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","tif","tiff","pdf","woff","woff2","ttf","otf","eot","mp3","mp4","wav","ogg","flac","mov","avi","webm","m4a","csv","tsv","parquet","psd","sketch","fig","pyc"]),SR=new Set([".ds_store","thumbs.db","desktop.ini"]);function xm(t){let e=Ue.posix.basename(t);if(SR.has(e.toLowerCase()))return{skip:"asset"};if(e==="package.json"||/^requirements[\w.-]{0,40}\.txt$/i.test(e))return{kind:"manifest",lang:"other"};if(/^(?:GNU)?makefile$/i.test(e)||/^(?:Dockerfile|Containerfile|Justfile)(?:\..{1,40})?$/i.test(e))return{kind:"text",lang:"sh"};if(/^\.env\.(?:example|sample|template|dist|defaults?)$/i.test(e))return{skip:"asset"};if(/^\.env(?:\..{1,40})?$/i.test(e)||/\.env$/i.test(e))return{report:"environment/secrets file bundled with the skill \u2014 not read; review it by hand",severity:"warning"};let n=/\.([a-z0-9]{1,12})$/i.exec(e)?.[1]?.toLowerCase();return n===void 0||e.lastIndexOf(".")<=0?"probe":mR.has(n)?{kind:"instructions",lang:"other"}:om[n]?{kind:"script",lang:om[n]}:n==="mk"||n==="dockerfile"?{kind:"text",lang:"sh"}:gR.has(n)?{kind:"text",lang:"other"}:yR.has(n)?{kind:"text",lang:"other",note:{reason:`.${n} source \u2014 only command and exfiltration patterns were checked`,severity:"info"}}:bR.has(n)?{kind:"script",lang:"other",note:{reason:`.${n} script \u2014 only command and exfiltration patterns were checked`,severity:"warning"}}:wR.has(n)?{report:`binary executable or archive (.${n}) \u2014 cannot be reviewed as text`,severity:"warning"}:vR.has(n)?{report:`.${n} document/database \u2014 not read`,severity:"info"}:xR.has(n)?{skip:"asset"}:"probe"}function am(t){if(Ue.posix.basename(t)==="SKILL.md")return!0;let e=xm(t);return e==="probe"?!0:"skip"in e?!1:"report"in e?e.severity!=="info":e.kind==="script"||e.kind==="manifest"||e.kind==="text"&&e.lang==="sh"}function _R(t){let e=/^#!\s{0,5}(\S{1,200})(?:\s{1,5}(\S{1,100}))?/.exec(t);if(!e)return;let n=Ue.posix.basename(e[1])==="env"?e[2]??"":Ue.posix.basename(e[1]);return/^(?:node|deno|bun|tsx|ts-node)$/.test(n)?"js":/^python/.test(n)?"py":/^(?:ba|z|k|da|fi)?sh$/.test(n)?"sh":/^ruby$/.test(n)?"rb":/^pwsh$/.test(n)?"ps":"other"}function ER(t){return t.length>=4&&t[0]===127&&t[1]===69&&t[2]===76&&t[3]===70?"ELF executable":t.length>=2&&t[0]===77&&t[1]===90?"Windows executable":t.length>=4&&(t.readUInt32BE(0)===4277009102||t.readUInt32BE(0)===4277009103||t.readUInt32BE(0)===3472551422||t.readUInt32BE(0)===3489328638||t.readUInt32BE(0)===3405691582)?"Mach-O/Java binary":t.length>=4&&t[0]===80&&t[1]===75&&t[2]===3&&t[3]===4?"ZIP archive":"binary file"}function kR(t){if((t[0]??"").replace(/^\u{FEFF}/u,"").trim()!=="---")return 0;for(let e=1;e<t.length&&e<500;e++)if(/^(?:---|\.\.\.)[ \t]*$/.test(t[e]))return e+1;return 0}var nn=gi;function hc(t){let e=nn(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(i=>i.length)),s="`".repeat(n+1);return`${s}${e}${s}`}function be(t,e=0,n=0){let s=Math.max(0,e-40),i=Math.min(t.length,s+220,e+Math.max(0,n)+60),r=nn(t.slice(s,i)).replace(/\s+/g," ").trim();return`${s>0?"\u2026":""}${r}${i<t.length?"\u2026":""}`}var Xe=2e3,Sm=600;function Xi(t,e,n){return Object.assign([t.slice(e,n)],{index:e,input:t,groups:void 0})}function fe(t,e,n){if(e.length<=Xe){if(n&&!n(e))return;let s=t.exec(e);return s?{index:s.index,match:s}:void 0}for(let s=0;s<e.length;s+=Xe-Sm){let i=e.slice(s,s+Xe),r=n&&!n(i)?null:t.exec(i);if(r)return{index:s+r.index,match:r};if(s+Xe>=e.length)break}}function vt(t,e,n=50){let s=[];if(e.length<=Xe){for(let r of e.matchAll(t))if(s.push({index:r.index??0,match:r}),s.length>=n)break;return s}let i=new Set;for(let r=0;r<e.length;r+=Xe-Sm){for(let o of e.slice(r,r+Xe).matchAll(t)){let a=r+(o.index??0);if(!i.has(a)&&(i.add(a),s.push({index:a,match:o}),s.length>=n))return s}if(r+Xe>=e.length)break}return s}var _m=20,Em=4e3,km=200,Rm=2e4,RR=/\|\s{0,5}[({]?\s{0,3}(?:while|until)\b/,cm=/\bdo\b/g,lm=/\bdone\b/g,CR=/\|\s{0,5}rev\s{0,5}\|/,AR=t=>Es.test(t)||jm.test(t)||CR.test(t);function $R(t){let e=[],n=[],s="",i=0,r=0,o=-2,a=!1,c=0,l=!1;for(let u of t.active){let f=t.lines[u];s!==""&&u!==o+1&&(e.push({text:s,line:i}),s="",a=!1),o=u,s===""&&(i=u+1,r=0);let d=f.trimEnd(),p=d.endsWith("\\")&&!d.endsWith("\\\\"),h=(d.endsWith("|")||d.endsWith("&&"))&&!(t.kind==="instructions"&&!t.fenced[u]&&f.trimStart().startsWith("|")),m=!1;if(!a&&d.includes("|")&&(t.kind!=="instructions"||t.fenced[u]===1)&&RR.test(d)&&AR(d)){let g=d.match(cm)?.length??0,b=d.match(lm)?.length??0;(g===0||g>b)&&(m=!0,c=g-b,l=g>0)}if(p||h||a||m){let g=a||m?f.trim():f,b=a||m;if(r<(b?km:_m)&&s.length+g.length<(b?Rm:Em)){let w=!1;if(a){let R=g.match(cm)?.length??0,k=g.match(lm)?.length??0;R>0&&(l=!0),c+=R-k,w=l&&c<=0||!l&&k>0}let y=p||h||m&&/(?:\bdo|[;{(])$/.test(g)?" ":"; ",v=a||m?g:d;s+=`${p?v.slice(0,-1):v}${w?"":y}`,r++,m&&(a=!0),w&&(e.push({text:s,line:i}),s="",a=!1);continue}n.push(i),a=!1}e.push({text:s+f,line:i}),s=""}return s!==""&&e.push({text:s,line:i}),{lines:e,capped:n}}var PR=/\b(?:never|don't|dont|do\s{1,5}not|avoid|must\s{1,5}not|mustn't|should\s{1,5}not|shouldn't|refuse\s{1,5}to)\b(?!\s{1,5}(?:mind|hesitate|forget|stop|skip|fail|neglect)\w{0,4}\b)/gi,Cm=/[,;:.!?]|\b(?:but|and|then|instead|so)\b/i,TR=2,IR=/^(?:run|pipe|use|execute|invoke|call|send|pass|type|paste)$/i;function Am(t){return t.match(/[A-Za-z0-9_'-]+/g)??[]}var OR=/\b(?:detect\w{0,10}|block(?:s|ed|ing)?|prevent\w{0,10}|reject\w{0,10}|forbid\w{0,10}|prohibit\w{0,10}|den(?:y|ies|ied)|malicious|dangerous|insecure|unsafe|vulnerab\w{0,10}|exploit\w{0,10}|injection|attack\w{0,10}|(?:not|un)\s{0,3}supported|anti-?pattern|example\s{1,5}of)\b/gi,LR=/^[`'")\]\s]{0,6}(?:is|are|was|would\s{1,5}be|looks)\s{1,5}(?:dangerous|insecure|unsafe|malicious|risky|an?\s{1,5}(?:security\s{1,5})?(?:risk|red\s{1,5}flag|attack))\b/i;function $m(t,e,n){let s;e.lastIndex=0;for(let i of t.matchAll(e))s=i;return s?n(t.slice((s.index??0)+s[0].length)):!1}function Pm(t,e){return $m(t.slice(Math.max(0,e-80),e),PR,n=>{if(n.length>30||Cm.test(n))return!1;let s=Am(n);return s.length===0||s.length===1&&IR.test(s[0])})}function Sc(t,e,n){return LR.test(t.slice(e+n,e+n+60))?!0:$m(t.slice(Math.max(0,e-80),e),OR,s=>s.length<=30&&!Cm.test(s)&&Am(s).length<=TR)}var NR=new RegExp([String.raw`https?:\/\/`,String.raw`\b(?:[a-z0-9-]{1,63}\.){1,5}[a-z]{2,24}(?::\d{1,5})?\/\S`,String.raw`\b(?:[a-z0-9-]{1,63}\.){2,5}[a-z]{2,24}\b`,String.raw`\b[a-z0-9-]{1,63}\.(?:com|net|org|io|dev|app|xyz|ru|cn|info|biz|co|me|tk|top|site|online|cloud|run|link|ly|gg|ai|so|to)\b`,String.raw`\b\d{1,3}(?:\.\d{1,3}){3}\b`,String.raw`\[[0-9a-f:]{2,45}\]|\b(?:[0-9a-f]{1,4}:){2,7}[0-9a-f]{0,4}\b`,String.raw`\b[a-z][a-z0-9-]{0,62}(?:\.[a-z0-9-]{1,63}){0,5}:\d{2,5}\b`,String.raw`\[\.\]|\(\.\)|\{\.\}|\[dot\]|\(dot\)`,String.raw`\w\s{1,3}\.(?:com|net|org|io|dev|app|xyz|ru|cn|info|biz|co|me|tk|top|site|sh)\b`,String.raw`\w["']{1,2}\.[a-z]{2,24}\b`,String.raw`\$\{?[A-Za-z_][A-Za-z0-9_]{0,60}\}?`,String.raw`\$\(`].join("|"),"i"),Tm=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b/gi,jR=/^(?:-K|--config|-i|--input-file|-T|--upload-file|--url|--url-query)(?:=|$)|^-K\S/;function MR(t){let e=0;for(let n of t.matchAll(Tm)){if(++e>8)break;if(Im(t,n).some(s=>jR.test(s)||!s.startsWith("-")&&/[/.:@=$~\d[]/.test(s)))return!0}return Om(t)&&(Yi(t,Es,!1)!==void 0||WR(t))}function Im(t,e){return t.slice((e.index??0)+e[0].length,(e.index??0)+e[0].length+300).split(/[|;&)`\n]/,1)[0].trim().split(/\s+/,16).map(s=>s.replace(/[.,:;!?'")\]]+$/,"")).filter(Boolean)}function Om(t,e=4){let n=t.slice(0,600),s=0;for(let i of n.matchAll(Tm)){if(++s>e)break;let r=HR(i[0].toLowerCase(),Im(n,i));if(r!==void 0&&BR(r))return!0}return!1}var DR={curl:new Set(["-o","-H","-d","-X","-u","-A","-e","-m","-w","-b","-c","-x","-F","-r","-z","-E","--output","--header","--data","--request","--user","--user-agent","--referer","--max-time","--cookie","--proxy","--retry","--connect-timeout"]),wget:new Set(["-O","-o","-P","-t","-T","-U","-e","-w","-Q","-a","-B","--output-document","--directory-prefix","--user-agent","--tries","--timeout","--header"]),iwr:new Set(["-outfile","-method","-headers","-body","-contenttype","-useragent","-credential","-timeoutsec","-proxy","-websession"])},FR=new Set(["a","an","the","it","its","this","that","these","those","into","to","from","with","without","and","or","then","as","in","on","for","at","by","is","are","was","be","directly","blindly","output","outputs","piped","pipe","piping","command","commands","script","scripts","file","files","content","contents","data","result","results","url","urls","link","links","anything","something","remote","untrusted","unverified","unknown","here","there","when","which","only","not","never","always","unsafe","safely","instead","again","install","installer","installers","download","downloads","downloaded","run","runs","running","execute","bash","sh","shell","silently","quietly","foo","bar","baz","example","examples","yourscript","your-script","your-host","your-server","yourhost","host","hostname","server","domain","site","website","get","docs","doc","mirror","some","my","your","somewhere","test","tests","x","y","z","xxx","target","endpoint","api","repo","package","tool","app","service","path","name","address","ip"]);function HR(t,e){let n=t==="curl"||t==="wget"?t:"iwr",s=DR[n];for(let i=0;i<e.length;i++){let r=e[i];if(n==="iwr"&&r.toLowerCase()==="-uri")return e[i+1];let o=n==="iwr"?r.toLowerCase():r;if(s.has(o)){i++;continue}if(!r.startsWith("-"))return r}}function BR(t){return/^[a-z][a-z0-9_-]{0,62}$/i.test(t)&&!FR.has(t.toLowerCase())}function WR(t){let e=Ec(t,!1).slice(0,50);for(let n=0;n<e.length;n++){if(!Es.test(e[n].text))continue;let s=Fm(e[n].text,"remote");if(s)for(let i=n+1;i<e.length&&i<=n+8;i++){let r=e[i].text;if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(r))continue;let o=Dm.exec(r);if(o&&Ge(o[1])===s)return!0}}return!1}function _c(t){let e=t.slice(0,600);return NR.test(e)||MR(e)}function Zi(t,e,n,s,i,r=!1){return t.kind!=="instructions"||t.fenced[e]||!Pm(n,s)&&!Sc(n,s,i)?"none":_c(n.slice(s,s+Math.max(i,1)+80))?"lowconf":r?Lm(n,s,s+i)||GR(n)?"skip":"lowconf":"skip"}function GR(t){return t.trimStart().startsWith("|")}var UR=/\b(?:(?:rule|instructions?|prompt|policy|directive|task|goal|job)\s{1,5}(?:is|are|now)|you\s{1,5}are|you\s{1,5}will|from\s{1,5}now\s{1,5}on|always|remember\s{1,5}(?:that|to)|act\s{1,5}as|your\s{1,5}new)\b[^.!?]{0,40}$/i;function VR(t,e,n){if(!Lm(t,e,n))return!1;let s=t.slice(Math.max(0,e-200),e),i=Math.max(s.lastIndexOf('"'),s.lastIndexOf("`"),s.lastIndexOf("\u201C"));return!UR.test(s.slice(0,Math.max(0,i)))}function Lm(t,e,n){let s=t.slice(Math.max(0,e-Xe),e),i=t.slice(n,n+Xe);for(let r of['"',"`"])if((s.split(r).length-1)%2===1&&i.includes(r))return!0;return s.lastIndexOf("\u201C")>s.lastIndexOf("\u201D")&&i.includes("\u201D")}var zR=/^\s{0,10}\|\s{0,5}`?(?:--[\w-]{2,60}|bypassPermissions)`?\s{0,5}\|/,qR=/`[^`]{0,200}`|\b(?:run|use|execute|launch|invoke|start|pass|add|set|enable|always|call|claude|codex|npx|bash|sh)\b/i;function KR(t){return zR.test(t)?!t.split(/(?<!\\)\|/).slice(2).some(n=>qR.test(n)):!1}function Ec(t,e,n){let s=[],i=0,r="",o=0;for(let a=0;a<t.length;a++){let c=t[a];if(r){c==="\\"&&r==='"'?a++:c===r&&(r="",n&&n.length<50&&n.push({start:o+1,end:a}));continue}if(e&&(c==='"'||c==="'")&&(a===0||/[\s=(:,[{]/.test(t[a-1]))){r=c,o=a;continue}if(e&&c==="\\"){a++;continue}let l="";c==="|"?l=t[a+1]==="|"?"||":t[a+1]==="&"?"|&":"|":c==="&"?l=t[a+1]==="&"?"&&":t[a-1]===">"||t[a+1]===">"?"":"&":c===";"&&(l=";"),l&&(s.push({text:t.slice(i,a),start:i,sep:l==="|&"?"|":l}),a+=l.length-1,i=a+1)}return s.push({text:t.slice(i),start:i,sep:""}),s}var YR=String.raw`(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|aria2c|downloadstring|downloadfile)`,Es=new RegExp(String.raw`(?:^|[\s(\x60{>"':=])${YR}\b`,"i"),Nm=/(?:^|[\s(`{>"':=])(?:base64\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}(?:-d|--decode|-D)\b|xxd\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}-r\b|openssl\s{1,5}(?:base64|enc)\b[^|;&\n]{0,80}\s-d\b|uudecode\b)/i,JR=String.raw`(?:python[0-9.]{0,5}|node|perl|ruby|php|deno|bun)(?=\s{0,5}$|\s{1,5}-(?:\s|$)|\s{1,5}run\s{1,5}-(?:\s|$)|\s{1,5}(?:\/dev\/stdin|\/proc\/self\/fd\/0)\b|\s{0,5}[;&|)}\x60'"])`,XR=String.raw`(?:\$\{?SHELL\}?(?!\w)|(?:source|\.)\s{1,5}\/dev\/stdin\b|(?:ba|z|k|da|fi|a)?sh\b|`+String.raw`python[0-9.]{0,5}\s{1,5}-c\s{1,5}["']?[^|\n]{0,80}?(?:exec|eval)\s{0,5}\(\s{0,5}sys\.stdin|`+String.raw`g?awk\s{1,5}(?:-\S{1,20}\s{1,5}){0,3}["']?[^|\n]{0,60}?system\s{0,5}\(\s{0,5}\$0|`+String.raw`${JR}|iex\b|invoke-expression\b|pwsh\b|powershell\b)`,ZR=String.raw`(?:`+[String.raw`sudo(?:\s{1,5}-{1,2}[\w-]{1,20}(?:[= ]\s{0,3}[\w.@:-]{1,40})?){0,5}`,String.raw`env(?:\s{1,5}-\S{1,20}){0,3}(?:\s{1,5}[^\s=]{1,40}=\S{0,100}){0,5}`,String.raw`xargs(?:\s{1,5}-\S{1,20}(?:\s{1,5}[^\s-]\S{0,20})?){0,4}`,String.raw`busybox`,String.raw`nice(?:\s{1,5}-n\s{0,3}-?\d{1,3}|\s{1,5}-\d{1,3})?`,String.raw`timeout(?:\s{1,5}-\S{1,20}){0,3}\s{1,5}[\d.]{1,8}[smhd]?`,String.raw`nohup`,String.raw`exec`,String.raw`command`,String.raw`stdbuf(?:\s{1,5}-\S{1,20}){0,3}`,String.raw`[A-Za-z_]\w{0,40}=\S{0,100}`].join("|")+String.raw`)\s{1,5}`,kc=String.raw`^\s{0,5}[({]?\s{0,3}(?:${ZR}){0,6}`+String.raw`(?:[\w./-]{0,40}\/)?(?:env\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?`,um=new RegExp(kc+XR,"i"),QR=new RegExp(String.raw`(?:(?<![.\w$])(?:eval|exec\w{0,8}|system|popen|spawn\w{0,8}|compile|Function)|(?:instance_|class_|module_)eval|`+String.raw`\b(?:vm|child_process|os|subprocess|Kernel)["']?\)?\.(?:run\w{2,20}|compile\w{0,12}|exec\w{0,8}|spawn\w{0,8}|system|popen|call|check_output|Popen|eval|Script))\b`+String.raw`(?:\s{0,5}\(\s{0,5}|\s{1,5})(?!["'\x60][^"'\x60]{0,60}["'\x60]\s{0,3}[);,])`,"g"),eC=new RegExp(String.raw`readFileSync\s{0,5}\(\s{0,5}(?:0\b|process\.stdin|["']\/dev\/stdin)|process\.stdin|\/dev\/stdin|php:\/\/stdin|sys\.stdin|`+String.raw`open\s{0,5}\(\s{0,5}0\b|fileinput|\bSTDIN\b|\$stdin|\bARGF\b|<STDIN>|<>|\bgets\b|\breadlines?\b|\binput\s{0,5}\(|\$_(?!\w)`,"gi"),tC=/\beval\s{0,5}\(?\s{0,5}do\s{0,5}\{[^}\n]{0,100}(?:<STDIN>|<>)/i,nC=/(?:^|[;\s{(])\$?([A-Za-z_]\w{0,30})\s{0,3}=\s{0,3}[^;\n=]{0,60}$/,sC=600,iC=150;function rC(t){let e=t.slice(0,sC),n=[];for(let r of e.matchAll(eC))if(n.push(r.index??0),n.length>=16)break;if(n.length===0)return!1;if(tC.test(e))return!0;let s=0,i=0;for(let r of e.matchAll(QR)){if(++s>40)break;let o=(r.index??0)+r[0].length;for(;i<n.length&&n[i]<o;)i++;let a=n[i];if(a!==void 0&&a-o<=iC&&!/[;\n]/.test(e.slice(o,a)))return!0}for(let r of n.slice(0,4)){let o=nC.exec(e.slice(Math.max(0,r-80),r));if(o&&new RegExp(String.raw`\b(?:eval|exec|system)\s{0,5}\(?\s{0,5}\$?${o[1]}\b`).test(e.slice(r)))return!0}return!1}var oC=String.raw`(?:`+[String.raw`(?:node(?:js)?|bun|deno)\s{1,5}(?:--?[\w-]{1,30}(?:=\S{1,30})?\s{1,5}){0,3}?(?:-e|-p|-pe|--eval|--print|eval)`,String.raw`python[0-9.]{0,5}\s{1,5}(?:-[\w-]{1,10}\s{1,5}){0,3}?-c`,String.raw`ruby\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}?-[a-z]{0,4}e`,String.raw`perl\s{1,5}(?:-[\w=:.-]{1,20}\s{1,5}){0,3}?-[a-z]{0,4}e`,String.raw`php\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}?-r`].join("|")+String.raw`)\s{1,5}["']?`,aC=new RegExp(`${kc}${oC}`,"i"),cC=new RegExp(`${kc}perl\\s{1,5}(?:-[\\w=:.-]{1,20}\\s{1,5}){0,3}?-[a-z]{0,3}[np][a-z]{0,3}e\\s{1,5}["']?(?=[^\\n]{0,300}?eval\\b)`,"i");function fm(t){let e=aC.exec(t);return e&&rC(t.slice(e.index+e[0].length))?!0:cC.test(t)}var lC=/^\s{0,5}[({]?\s{0,3}(?:sudo\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?(?:[\w./-]{0,40}\/)?tee\b/i,uC=/^\s{0,5}[({]?\s{0,3}(?:while|until)\b[^;|]{0,150}?\bread\b([^;|]{0,100})/i,fC=/^\s{0,5}(?:do\s{1,5})?(?:(?:(?:command|builtin)\s{1,5})?(?:eval|source|\.)\s{1,5}|(?:sudo\s{1,5})?(?:[\w./-]{0,40}\/)?(?:ba|z|k|da)?sh\s{1,5}(?:(?:-\S{1,5}|<<<)\s{1,5}){0,2}|sudo\s{1,5})?["']?\$\{?([A-Za-z_]\w{0,40})\}?/i,dC=/^\s{0,5}(?:do\s{1,5})?(?:echo|printf)\s{1,5}(?:-\S{1,5}\s{1,5}){0,2}(?:["']%s["']\s{1,5})?["']?\$\{?([A-Za-z_]\w{0,40})\}?/i,pC=/^\s*do\b/,hC=/^\s*done\b/,mC=new Set(["-p","-d","-n","-N","-t","-u","-i"]),gC=250;function yC(t){let e=new Set,n=t.trim().split(/\s+/).slice(0,12);for(let s=0;s<n.length;s++){let i=n[s];if(mC.has(i)){s++;continue}i.startsWith("-")||/^[A-Za-z_]\w{0,40}$/.test(i)&&e.add(i)}return e.size===0&&e.add("REPLY"),e}function bC(t,e,n){let s=n[e];if(s===void 0){let i=t[e],r=i.text.slice(0,400);if(hC.test(r))s={kind:"done"};else{s={kind:pC.test(r)?"do":"other"};let o=fC.exec(r);o&&(s.runs=o[1]);let a=i.sep==="|"&&e+1<t.length?dC.exec(r):null;a&&(s.echoes=a[1])}n[e]=s}return s}function wC(t,e,n){let s=t[e].text;if(!s.includes("read")||!/while|until/i.test(s))return;let i=uC.exec(s.slice(0,400));if(!i)return;let r=yC(i[1]??""),o=0;for(let a=e+1;a<t.length&&a<=e+gC;a++){let c=bC(t,a,n);if(c.kind==="done"){if(--o<=0)return;continue}c.kind==="do"&&o++;let l=t[a];if(c.runs!==void 0&&r.has(c.runs))return l.start+Math.min(l.text.length,60);if(c.echoes!==void 0&&r.has(c.echoes)&&Mm(t[a+1].text))return t[a+1].start+Math.min(t[a+1].text.length,60)}}var vC=new RegExp(String.raw`^\s{0,5}[({]?\s{0,3}(?:sudo\s{1,5})?(?:`+[String.raw`rev\b`,String.raw`tr\s{1,5}(?:-\S{1,5}\s{1,5}){0,2}["']?\[?([a-z0-9])-[a-z0-9](?:[a-z0-9]-[a-z0-9]){0,3}\]?["']?\s{1,5}["']?\[?(?!\1)[a-z0-9]-[a-z0-9]`,String.raw`tr\s{1,5}(?:-\S{1,5}\s{1,5}){0,2}["']?([a-z])[a-z]{9,}["']?\s{1,5}["']?(?!\2)[a-z][a-z]{9,}`,String.raw`(?:base32|basenc)\s{1,5}(?:-\S{1,12}\s{1,5}){0,3}(?:-[a-z]{0,3}d[a-z]{0,3}|--decode)\b`,String.raw`(?:printf|echo)\s{1,5}(?:-\S{1,4}\s{1,5}){0,2}(?:["']%b["']\s{1,5})?\$?["']?(?:\\x[2-7][0-9a-f]|\\0[4-7][0-7]|\\1[0-7][0-7]|\\u00[2-7][0-9a-f]){4,}`].join("|")+String.raw`)`,"i"),jm=new RegExp(`${Nm.source}|${vC.source}`,"i"),xC=16;function SC(t){let e="",n=0,s=0,i=!1,r=t.length;for(;n<r&&e.length<600&&s<400;){for(;n<r&&t.charCodeAt(n)<=32;)n++;if(n>=r)break;let o=n,a=0;for(;n<r;){let u=t.charCodeAt(n);if(a!==0)u===92&&a===34?n++:u===a&&(a=0);else if(u===34||u===39)a=u;else if(u<=32)break;n++}let c=t.slice(o,Math.min(n,o+700));s++;let l=/^[A-Za-z_]\w{0,40}=/.test(c);l&&i||(i=l,e+=`${e===""?"":" "}${l?"V=1":c}`)}return e.length>=600||n>=r?e.slice(0,600):`${e} ${t.slice(n,n+600)}`.slice(0,600)}function Mm(t){if(!dm.test(t))return!1;let e=SC(t);if(!dm.test(e))return!1;if(um.test(e)||fm(e))return!0;if(e.includes(">(")&&lC.test(e)){let n=e.indexOf(">(");for(let s=0;n>=0&&s<4;s++){let i=e.slice(n+2);if(um.test(i)||fm(i))return!0;n=e.indexOf(">(",n+2)}}return!1}function Yi(t,e,n,s=0){if(!t.includes("|"))return;let i=[],r=Ec(t,n,i),o=_C(t,r,e);if(o||s>0)return o;for(let a of i){let c=Yi(t.slice(a.start,a.end),e,!0,s+1);if(c)return{index:a.start+c.index,match:Xi(t,a.start+c.index,a.start+c.index+c.match[0].length)}}}var dm=/sh\b|SHELL|stdin|awk|python|node|perl|ruby|php|deno|bun|iex|invoke-expression|pwsh|powershell/i;function _C(t,e,n){let s=new Array(e.length),i=c=>(s[c]===void 0&&(s[c]=Mm(e[c].text)),s[c]),r=new Array(e.length),o=new Array(e.length),a=c=>(r[c]===void 0&&(r[c]=wC(e,c,o)??null),r[c]??void 0);for(let c=0;c<e.length;c++){if(e[c].sep!=="|")continue;let l=n.exec(e[c].text);if(l)for(let u=1;u<=xC&&c+u<e.length;u++){let f=e[c+u],d=i(c+u)?void 0:a(c+u);if(d!==void 0||i(c+u)){let p=e[c].start+l.index,h=Math.min(t.length,d??f.start+Math.min(f.text.length,60));return{index:p,match:Xi(t,p,h)}}if(f.sep!=="|")break}}}var EC=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)sum|shasum)\b(?=[^|;&]{0,300}\s(?:-c|--check)\b)|gpg\b(?=[^|;&]{0,300}\s--verify\b)|gpgv\b|cosign\s{1,5}verify(?:-blob)?\b|minisign\s{1,5}-V\b|slsa-verifier\s{1,5}verify|openssl\s{1,5}dgst\b(?=[^|;&]{0,300}\s-verify\b))/i,kC=/^\s{0,5}(?:sudo\s{1,5})?(?:sha(?:1|224|256|384|512)sum|shasum)\b[^|;&]{0,300}\s(?:-c|--check)(?:\s{1,5}|=)(\S{1,300})/i,Dm=/^\s{0,5}(?:sudo\s{1,5}(?:-\S{1,20}\s{1,5}){0,5})?(?:(?:[\w./-]{0,40}\/)?(?:(?:ba|z|k|da)?sh|source|\.|python[0-9.]{0,5}|node|perl|ruby|pwsh|powershell)\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?(\S{1,300})/i,RC=/^\s{0,5}(?:export\s{1,5}|local\s{1,5}|readonly\s{1,5})?([A-Za-z_]\w{0,60})=["']?(?:\$\(|`)\s{0,5}(?:curl|wget|iwr|irm)\b/i,CC=/^\s{0,5}(?:eval|(?:ba|z|k|da)?sh\s{1,5}(?:-c|<<<)|iex|invoke-expression)\s{0,5}\(?\s{0,5}["']?\$\{?([A-Za-z_]\w{0,60})\}?/i;function Ge(t){return Ue.posix.basename(t.replace(/^['"]+|['"]+$/g,"").replace(/\\/g,"/"))}function pm(t){return new Set(t.split(/\s+/).filter(Boolean).map(Ge))}function Fm(t,e){let n=/(?:^|\s)>{1,2}\s{0,3}(\S{1,300})/.exec(t);if(e==="encoded")return n?Ge(n[1]):void 0;let s=/https?:\/\/[^\s'"`)]{1,2000}/i.exec(t)?.[0];if(/\bcurl\b/i.test(t)){let i=/(?:\s-[a-zA-Z]{0,10}o\s{0,3}|\s--output[= ]\s{0,3})(\S{1,300})/.exec(t);return i?Ge(i[1]):/\s-[a-zA-Z]{0,10}O\b|\s--remote-name\b/.test(t)&&s?Ge(s.split(/[?#]/)[0]):n?Ge(n[1]):void 0}if(/\bwget\b/i.test(t)){let i=/(?:\s-[a-zA-Z]{0,10}O\s{0,3}|\s--output-document[= ]\s{0,3})(\S{1,300})/.exec(t);return i?i[1]==="-"?void 0:Ge(i[1]):s?Ge(s.split(/[?#]/)[0]):void 0}return n?Ge(n[1]):void 0}var AC=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)|md5|b2)sum|shasum|openssl\s{1,5}dgst)\b(?![^|;&]{0,300}\s(?:-c|--check)\b)[^|;&]{0,300}>{1,2}\s{0,3}(\S{1,300})/i,$C=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)|md5|b2)sum|shasum|openssl\s{1,5}dgst)\b/i,PC=/curl|wget|iwr|irm|invoke-web|base64|xxd|openssl|uudecode|sum\b|gpg|cosign|minisign|slsa/i,_s=class{manifestExists;produced=new Map;fetchedVars=new Map;generated=new Set;feeds=0;constructor(e=()=>!1){this.manifestExists=e}feed(e,n,s){let i=++this.feeds;if(this.produced.size===0&&this.fetchedVars.size===0&&!PC.test(e))return;let r=Ec(e,s).slice(0,500),o=r.findIndex(u=>/(?:^|\s)#/.test(u.text));if(o>=0){let u=r[o];r=[...r.slice(0,o),{...u,text:u.text.slice(0,u.text.search(/(?:^|\s)#/)),sep:""}]}let a=r.map(u=>EC.test(u.text)),c=(u,f)=>{for(let d=u;d<f;d++){let p=r[d].sep;if(p!=="&&"&&!(p==="|"&&a[d+1]))return!1}return!0},l=new Map;for(let u=0;u<r.length;u++){let f=r[u],d=f.text,p=f.start+Math.max(0,d.search(/\S/)),h=RC.exec(d);if(h){this.fetchedVars.set(h[1],{line:n,feed:i,index:p});continue}let m=Es.test(d)&&(/https?:\/\//i.test(d)||Om(d,1)),g=Nm.test(d);if(m||g){let T=m?"remote":"encoded",C=Fm(d,T);C&&this.produced.set(C,{kind:T,line:n,feed:i,seg:u,index:p});continue}let b=AC.exec(d);if(b){this.generated.add(Ge(b[1]));continue}if(a[u]){for(let T of this.verifiedFiles(d,u>0&&r[u-1].sep==="|"?r[u-1].text:void 0))l.set(T,[...l.get(T)??[],u]);continue}let w=CC.exec(d);if(w&&this.fetchedVars.has(w[1])){let T=this.fetchedVars.get(w[1]);return this.hit("remote-exec",e,T.feed===i?T.index:p,f.start+d.length,T.line)}if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(d))continue;let y=Dm.exec(d);if(!y)continue;let v=Ge(y[1]),R=this.produced.get(v);if(!(!R||R.kind==="remote"&&R.feed===i&&(l.get(v)??[]).some(T=>T>R.seg&&c(R.seg,u))))return this.hit(R.kind==="remote"?"remote-exec":"encoded-exec",e,R.feed===i?R.index:p,f.start+d.length,R.line)}}verifiedFiles(e,n){let s=[...this.produced.keys()];if(/--ignore-missing\b|<<<|<\(/.test(e))return[];let i=kC.exec(e)?.[1];if(i!==void 0){if(i==="-"||i==="/dev/stdin"){if(n===void 0||$C.test(n)||/<\(|\$\(/.test(n))return[];let c=pm(n);return s.filter(l=>c.has(l))}let o=Ge(i);return i.startsWith("<")||this.generated.has(o)?[]:!(this.produced.get(o)?.kind==="remote")&&!this.manifestExists(i.replace(/^['"]+|['"]+$/g,""))?[]:s}let r=pm(e);return s.filter(o=>r.has(o))}hit(e,n,s,i,r){let o=Math.min(s,n.length);return{rule:e,found:{index:o,match:Xi(n,o,Math.max(o,Math.min(n.length,i)))},fromLine:r}}},TC=[{requires:t=>t.includes("<("),pattern:/(?:^|[\s;&|(`])(?:(?:[\w./-]{0,40}\/)?(?:ba|z|k)?sh|source|\.)\s{1,5}(?:<\s{0,3})?<\(\s{0,5}(?:curl|wget)\b/i},{requires:t=>t.includes(">(")&&/curl|wget/i.test(t),pattern:/(?:^|[\s;&|(`])(?:curl|wget)\b[^\n;&|]{0,300}>\s{0,3}>\(\s{0,5}(?:sudo\s{1,5})?(?:[\w./-]{0,40}\/)?(?:ba|z|k|da)?sh\b/i},{requires:t=>t.includes("$(")||t.includes("`"),pattern:/\b(?:(?:ba|z|k)?sh\s{1,5}(?:-c|<<<)|eval|python[0-9.]{0,5}\s{1,5}-c|node\s{1,5}-e|perl\s{1,5}-e|ruby\s{1,5}-e)\s{0,5}["']?(?:\$\(|`)\s{0,5}(?:curl|wget)\b/i},{requires:t=>/iex|invoke-expression/i.test(t)&&/iwr|irm|curl|wget|invoke-web|invoke-rest|downloadstring|webclient/i.test(t),pattern:/\b(?:iex|invoke-expression)\b[^\n]{0,120}\b(?:iwr|irm|curl|wget|invoke-webrequest|invoke-restmethod|downloadstring|net\.webclient)\b/i}],IC=[{requires:t=>t.includes("$(")&&/base64|xxd/i.test(t),pattern:/\b(?:eval|(?:ba|z|k)?sh\s{1,5}-c)\s{0,5}["']?\$\([^)\n]{0,300}(?:base64\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}(?:-d|--decode|-D)|xxd\s{1,5}(?:-\S{1,10}\s{1,5}){0,3}-r)\b/i},{requires:t=>/atob|Buffer\.from|b64decode|decodebytes|codecs\.decode|FromBase64String|a85decode|b32decode/i.test(t),pattern:/\b(?:eval|exec|Function|Invoke-Expression|iex)\s{0,5}\(?[^\n]{0,80}?(?:atob|Buffer\.from|b64decode|b32decode|a85decode|decodebytes|codecs\.decode|FromBase64String)\b/i},{requires:t=>/powershell|pwsh/i.test(t)&&/\s-(?:e|ec|enc|encodedcommand)\s{1,5}[A-Za-z0-9+/]{20}/i.test(t),pattern:/\b(?:powershell|pwsh)(?:\.exe)?\b[^\n]{0,300}\s-(?:e|ec|enc|encodedcommand)\s{1,5}[A-Za-z0-9+/]{20,}/i}],OC=/\b(?:eval|exec|Function)\s{0,5}\(\s{0,5}(?:await\s{1,5})?\(?\s{0,5}(?:await\s{1,5})?(?:fetch|requests\.get|urlopen|urllib\.request\.urlopen|http\.get)\s{0,5}\(/i,mc=String.raw`(?:urllib\.request|urllib2|requests|httpx)`,qi=new RegExp([String.raw`\bfrom\s{1,5}${mc}\s{1,5}import\s{1,5}\(?(?<list>[^\n;#]{1,300})`,String.raw`\bfrom\s{1,5}urllib\s{1,5}import\s{1,5}\(?(?<ulist>[^\n;#]{1,300})`,String.raw`\bimport\s{1,5}${mc}\s{1,5}as\s{1,5}(?<mod>[A-Za-z_]\w{0,39})\b`,String.raw`(?:^|[\s;(])(?<fn>[A-Za-z_]\w{0,39})\s{0,3}=\s{0,3}(?:urllib\.request\.urlopen|urllib2\.urlopen|urlopen|requests\.(?:get|post)|httpx\.(?:get|post))\s{0,3}(?=$|[\s;#)])`,String.raw`(?:^|[\s;(])(?<modassign>[A-Za-z_]\w{0,39})\s{0,3}=\s{0,3}${mc}\s{0,3}(?=$|[\s;#)])`].join("|"),"g"),LC=/\b(?:eval|exec)\s{0,5}\(\s{0,5}(?:compile\s{0,5}\(\s{0,5})?([A-Za-z_][\w.]{0,60})\s{0,5}\(/g,wc=["urlopen","get","post","request"],NC=new Set(wc),hm=/urlopen|urllib|requests|httpx/,mm=new WeakMap;function jC(t,e){let n=[];if(t.length<=Xe){qi.lastIndex=0;for(let s=qi.exec(t);s!==null&&n.length<20;s=qi.exec(t))n.push(s)}else for(let s of vt(qi,t,20))n.push(s.match);for(let s of n){let i=s.groups??{};if(i.list!==void 0)for(let r of i.list.split(",").slice(0,12)){let[o,a]=r.trim().replace(/[()]/g,"").split(/\s{1,5}as\s{1,5}/i);o!==void 0&&NC.has(o)&&e.add((a??o).trim())}else if(i.ulist!==void 0)for(let r of i.ulist.split(",").slice(0,12)){let[o,a]=r.trim().replace(/[()]/g,"").split(/\s{1,5}as\s{1,5}/i);if(o==="request")for(let c of wc)e.add(`${(a??o).trim()}.${c}`)}else if(i.mod!==void 0||i.modassign!==void 0)for(let r of wc)e.add(`${i.mod??i.modassign}.${r}`);else i.fn!==void 0&&e.add(i.fn)}}function MC(t){let e=mm.get(t);if(e!==void 0)return e;let n=null;if(hm.test(t.content)){let s=Um(t),i=new Map,r=new Set;for(let o of t.active){let a=t.lines[o];if(!a.includes("import")&&!a.includes("=")||!hm.test(a))continue;if(a.length<300){if(r.has(`${s(o)}|${a}`))continue;r.size<5e3&&r.add(`${s(o)}|${a}`)}let c=s(o),l=i.get(c);l||i.set(c,l=new Set),jC(a,l)}n={blockOf:s,byBlock:i}}return mm.set(t,n),n}function Hm(t,e,n){let s=fe(OC,e);if(s)return s;let i=MC(t),r=i?.byBlock.get(i.blockOf(n));if(!(!r||r.size===0||!e.includes("("))){for(let o of vt(LC,e,20))if(r.has(o.match[1]))return o}}var DC={js:[/(?<![.\w$])eval\s{0,5}\(/,/\bnew\s{1,5}Function\s{0,5}\(/,/\bvm\.(?:runInNewContext|runInThisContext|runInContext|compileFunction)\s{0,5}\(|\bnew\s{1,5}vm\.Script\s{0,5}\(/],py:[/(?<![.\w])(?:exec|eval)\s{0,5}\(/],sh:[/(?:^|[\s;&|(])eval\s{1,5}\S/],ps:[/\b(?:Invoke-Expression|iex)\b/i],rb:[/(?<![.\w])eval\s{0,5}[( ]/]},FC={js:[/(?<![.\w$])require\s{0,5}\(\s{0,5}(?!['"][^'"\n]{0,300}['"]\s{0,5}\))[^)\s]/,/(?<![.\w$])import\s{0,5}\(\s{0,5}(?!['"][^'"\n]{0,300}['"]\s{0,5}\))[^)\s]/],py:[/(?<![.\w])__import__\s{0,5}\(\s{0,5}(?!['"])/,/\bimportlib\.import_module\s{0,5}\(\s{0,5}(?!['"])/,/\b(?:pickle|marshal)\.loads?\s{0,5}\(/]},HC=new RegExp([String.raw`(?:^|[\s;&|(\x60$])(?:curl|wget|nc|ncat|netcat|socat|scp|sftp|telnet)\s`,String.raw`\/dev\/(?:tcp|udp)\/`,String.raw`(?<![.\w$])fetch\s{0,5}\(`,String.raw`\baxios\b`,String.raw`\bhttps?\.(?:get|request)\s{0,5}\(`,String.raw`\brequire\s{0,5}\(\s{0,5}['"](?:node:)?(?:https?|net|dgram)['"]`,String.raw`\bfrom\s{1,5}['"](?:node:)?(?:https?|net|dgram)['"]`,String.raw`\bnew\s{1,5}WebSocket\b`,String.raw`\bXMLHttpRequest\b`,String.raw`\b(?:node-fetch|undici)\b`,String.raw`\brequests\.(?:get|post|put|patch|request|Session)\b`,String.raw`\burllib\.request\b`,String.raw`\burlopen\s{0,5}\(`,String.raw`\bhttp\.client\b`,String.raw`\bhttpx\.`,String.raw`\baiohttp\b`,String.raw`\bsocket\.(?:socket|create_connection)\b`,String.raw`\bsmtplib\b`,String.raw`\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b`,String.raw`\bNet\.WebClient\b`,String.raw`\bSystem\.Net\.Http\b`,String.raw`\bNet::HTTP\b`,String.raw`\bopen-uri\b`,String.raw`\bURI\.open\b`,String.raw`\bdns\.(?:resolve|lookup)\s{0,5}\(`].join("|"),"i"),BC=new RegExp([String.raw`JSON\.stringify\(\s{0,5}process\.env\s{0,5}\)`,String.raw`Object\.(?:entries|keys|values)\(\s{0,5}process\.env\s{0,5}\)`,String.raw`json\.dumps\(\s{0,5}(?:dict\(\s{0,5})?os\.environ`,String.raw`\bstr\(\s{0,5}os\.environ\s{0,5}\)`,String.raw`\bos\.environ\.items\(\s{0,5}\)`,String.raw`(?:^|[\s;&(])(?:printenv|env)\s{0,5}[|>]`,String.raw`\$\(\s{0,5}(?:printenv|env)\s{0,5}\)`,String.raw`\x60\s{0,5}(?:printenv|env)\s{0,5}\x60`,String.raw`\bprintenv\s{0,5}$`,String.raw`\/proc\/(?:self|\d{1,10}|\$\$)\/environ`,String.raw`\b(?:Get-ChildItem|gci|dir|ls)\s{1,5}env:`,String.raw`\[Environment\]::GetEnvironmentVariables\(\s{0,5}\)`,String.raw`\bENV\.to_h\b`].join("|"),"i"),WC=new RegExp([String.raw`(?:^|[\s'"\/\\~(])\.ssh(?=[\s'")]|\/?['"]|\/?$)`,String.raw`\.ssh\/(?:id_\w{1,40}|[\w.-]{1,80}\.(?:pem|key))\b`,String.raw`\bid_(?:rsa|ed25519|ecdsa|dsa)\b`,String.raw`(?:^|[\s'"\/\\~(])\.(?:aws|gnupg)(?=[\/\\'"\s)]|$)`,String.raw`(?:^|[\s'"\/\\~(])\.(?:netrc|git-credentials)\b`,String.raw`\bsecurity\s{1,5}(?:find-generic-password|find-internet-password|dump-keychain)\b`,String.raw`\bsecret-tool\s{1,5}lookup\b`,String.raw`\bwallet\.dat\b`,String.raw`\.config\/solana\/id\.json`,String.raw`\bkeystore\/UTC--`,String.raw`\.ethereum\/keystore`,String.raw`\bLogin Data\b`,String.raw`\bseed[_\s-]?phrase\b`].join("|"),"i"),GC=[/\b(?:ignore|disregard|forget)\s{1,5}(?:all\s{1,5}|any\s{1,5}|every\s{1,5})?(?:of\s{1,5})?(?:the\s{1,5}|your\s{1,5}|my\s{1,5}|these\s{1,5}|those\s{1,5})?(?:previous|prior|above|earlier|preceding|system|developer|safety)\s{1,5}(?:instructions?|prompts?|rules|guidelines|directives|messages?|context)\b(?![\w/-]|\.[\w/]|\s{1,5}(?:files?|folders?|director(?:y|ies)|docs?|pages?|in\s{1,5}\S{0,80}\/))/i,/\byou\s{1,5}are\s{1,5}(?:now\s{1,5})?(?:in\s{1,5})?(?:DAN|developer\s{1,5}mode|jailbroken|jailbreak\s{1,5}mode|unrestricted\s{1,5}mode|god\s{1,5}mode)\b/i,/<\|im_start\|>|<\|(?:system|endoftext)\|>|<<SYS>>|\[\/?INST\]/i,/\b(?:new|updated|actual|real)\s{1,5}system\s{1,5}prompt\b/i,/\b(?:these|this|the\s{1,5}following)\s{1,5}instructions?\s{1,5}(?:take|takes|have|has)\s{1,5}(?:precedence|priority)\s{1,5}over\s{1,5}(?:all\s{1,5}|any\s{1,5}|the\s{1,5})?(?:system|safety)\b/i],UC=/ignore|disregard|forget|you\s{1,5}are|<\||<<SYS|INST\]|system\s{1,5}prompt|precedence|priority/i,VC=/user|silently/i,zC=/without|disable|turn\s{1,5}off|bypass|circumvent|skip|override|approve/i,qC=[/\b(?:without|w\/o)\s{1,5}(?:the\s{1,5})?user'?s?\s{1,5}(?:knowledge|knowing|noticing|awareness)\b/i,/\b(?:hide|conceal|obscure)\s{1,5}(?:this|these|it|them|that|the\s{1,5}[\w\s-]{1,30}?)\s{1,5}from\s{1,5}(?:the\s{1,5})?user\b/i,/\bsilently\s{1,5}(?:upload|send|post|exfiltrate|transmit|forward)\b/i],KC=[/\b(?:do\s{1,5}not|don't|never)\s{1,5}(?:tell|inform|notify|alert|warn)\s{1,5}(?:the\s{1,5})?user\b(?!\s{1,5}to\b)/i,/\b(?:do\s{1,5}not|don't|never)\s{1,5}(?:mention|reveal|disclose)\s{1,5}(?:this|that|it|these\s{1,5}(?:steps|instructions))\s{1,5}to\s{1,5}(?:the\s{1,5})?user\b/i],YC=/--dangerously-skip-permissions\b|--dangerously-bypass-approvals-and-sandbox\b|\bbypassPermissions\b|--yolo\b|--allow-all-tools\b/i,JC=[/\bwithout\s{1,5}(?:first\s{1,5})?(?:asking|prompting|checking\s{1,5}with)\s{1,5}(?:the\s{1,5}user\s{1,5})?(?:for\s{1,5})?(?:permission|confirmation|approval|consent)\b(?!\s{1,5}(?:on|for)\s{1,5}(?:each|every|individual|single)\b)/i,/\b(?:disable|turn\s{1,5}off|bypass|circumvent|skip|override)\s{1,5}(?:the\s{1,5}|any\s{1,5}|all\s{1,5})?(?:sandbox(?:ing)?|safety\s{1,5}(?:checks?|guardrails?|filters?|prompts?)|guardrails?|permission\s{1,5}(?:prompts?|checks?|dialogs?)|approval\s{1,5}(?:prompts?|steps?)|content\s{1,5}(?:filters?|polic(?:y|ies)))\b/i,/\bauto[-\s]?approve\s{1,5}(?:all|every|any)\b/i],XC=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/gi,gm=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/i,ZC=/\b(?:all\s{1,5}(?:the\s{1,5}|your\s{1,5})?(?:secrets|credentials|tokens|keys|passwords)|env(?:ironment)?\s{1,5}var(?:iable)?s?|private\s{1,5}keys?|ssh\s{1,5}keys?|id_rsa|session\s{1,5}cookies|browser\s{1,5}cookies|wallets?|seed\s{1,5}phrases?|keychain)\b|\.env\b|~\/\.ssh\b|\.aws\/credentials\b/i,QC=/\b(?:secrets?|credentials?|api[\s_-]?keys?|access[\s_-]?tokens?|auth(?:entication)?\s{1,5}tokens?|bearer\s{1,5}tokens?|passwords?(?!\s{1,5}reset))\b/i,eA=/\b(?:to|into|at|via)\b/i,tA=/webhook|pastebin|paste\.|hastebin|discord|telegram|ngrok|requestbin|pipedream|interactsh|burpcollaborator|\.onion\b|https?:\/\/\d{1,3}(?:\.\d{1,3}){3}/i,nA=/https?:\/\/|\bserver\b|\bendpoint\b|\bremote\b|\bexternal\b|third[-\s]party|\battacker\b|e-?mail\s{1,5}address/i,sA=/\bexternal\b|third[-\s]party|\battacker\b/i,iA=/\b(?:header|authorization|authenticate|bearer\s{1,5}auth)\b|\s-H\s/i,rA=/\sstyle\s{0,5}=\s{0,5}["'][^"'>]{0,200}(?:display\s{0,5}:\s{0,5}none|visibility\s{0,5}:\s{0,5}hidden|font-size\s{0,5}:\s{0,5}0(?:px|pt|em|rem)?\s{0,5}(?:;|["'])|opacity\s{0,5}:\s{0,5}0(?:\.0{1,5})?\s{0,5}(?:;|["']))/i,oA=/\shidden(?:\s|=|\/|$)/i,aA=/^\s{0,20}(?:promptci-ignore|markdownlint|prettier|eslint|cspell|textlint|vale\b|toc\b|omit\s{1,5}in\s{1,5}toc|end\s{0,5}toc|mdformat|lint|region|endregion|#region|#endregion|@formatter|todo\b|fixme\b|xxx\b)/i,cA=/\b(?:ignore|disregard|forget)\b[^\n]{0,40}\b(?:instructions?|prompts?|rules|guidelines)\b|\bsystem\s{1,5}prompt\b|\b(?:curl|wget|iwr|invoke-webrequest)\b|\bbase64\s{1,5}-d\b|~\/\.ssh|\b(?:send|upload|exfiltrate)\b[^\n]{0,40}\b(?:secrets?|credentials?|keys?|tokens?|\.env)\b/i,lA=/\byou\b|\b(?:must|always|never|approve|run|ignore|execute|send|upload|install|delete|disable|download|fetch|read|print|reveal)\b/i,uA=new RegExp([String.raw`\b(?:ignore|disregard|forget)\b[^\n]{0,40}\b(?:instructions?|prompts?|rules|guidelines)\b`,String.raw`\byou\s{1,5}(?:must|are\s{1,5}now|will\s{1,5}now|should\s{1,5}(?:always|never|secretly|silently))\b`,String.raw`\b(?:assistant|claude|the\s{1,5}(?:ai|agent|model|llm))\s{0,5}[:,]`,String.raw`\b(?:dear|hey)\s{1,5}(?:ai|assistant|claude|agent|model)\b`,String.raw`\bsystem\s{1,5}prompt\b`,String.raw`\b(?:curl|wget|iwr|invoke-webrequest)\b`,String.raw`\bbase64\s{1,5}-d\b`,String.raw`\b(?:read|send|upload|post|print|cat|copy|dump|exfiltrate|include|attach|paste)\b[^\n]{0,40}(?:\b(?:secrets?|credentials?|api[_\s-]?keys?|passwords?|private\s{1,5}keys?)\b|~\/\.ssh|\.env\b)`,String.raw`\b(?:run|execute|download|upload|send|install)\s{1,5}(?:this|the\s{1,5}following|it)\b`].join("|"),"i"),fA=/(?<![A-Za-z0-9+/=])[A-Za-z0-9+/]{200,}={0,2}(?![A-Za-z0-9+/=])/g,dA=/\b(?:pip[0-9.]{0,5}|pipx|uvx|uv|npm|pnpm|yarn|bun|npx|bunx|go|cargo|gem|deno)\b/i,pA=/\bgit\+(?:https?|ssh|git|file):\/\/[^\s'"<>)`]{1,500}|\bgithub:[\w.-]{1,100}\/[\w.-]{1,100}(?:#[^\s'"<>)`]{0,100})?/gi,hA=/(?<=[\w.-])@(?:latest|master|main|HEAD)(?![\w.-])/gi,mA=/\b(?:npx|bunx|pnpm\s{1,5}dlx|yarn\s{1,5}dlx|uvx|pipx\s{1,5}run|npm\s{1,5}(?:i|install|exec|add)|pnpm\s{1,5}(?:add|i|install)|yarn\s{1,5}add|bun\s{1,5}(?:add|i|install|x)|go\s{1,5}(?:install|run)|deno\s{1,5}(?:run|install))\b[^\n;&|]{0,200}$/i,gA=/\b(?:npm\s{1,5}(?:i|install|add)|pnpm\s{1,5}(?:add|i|install)|yarn\s{1,5}add|bun\s{1,5}(?:add|i|install))\b([^\n;&|]{0,500})/i,yA=/\bcargo\s{1,5}install\b[^\n;&|]{0,300}--git\s{1,5}\S/i,bA=new RegExp([String.raw`https?:\/\/raw\.githubusercontent\.com\/[^/\s]{1,100}\/[^/\s]{1,100}\/(?:refs\/heads\/)?(?:main|master|HEAD|develop|dev|trunk)\/[^\s'"<>)\x60]{0,300}`,String.raw`https?:\/\/github\.com\/[^/\s]{1,100}\/[^/\s]{1,100}\/raw\/(?:refs\/heads\/)?(?:main|master|HEAD|develop|dev|trunk)\/[^\s'"<>)\x60]{0,300}`,String.raw`https?:\/\/github\.com\/[^/\s]{1,100}\/[^/\s]{1,100}\/releases\/latest\/download\/[^\s'"<>)\x60]{0,300}`,String.raw`https?:\/\/gist\.githubusercontent\.com\/[^/\s]{1,100}\/[0-9a-f]{1,64}\/raw\/(?![0-9a-f]{40}\/)[^\s'"<>)\x60]{1,300}`].join("|"),"i"),wA=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|fetch|urlopen|requests\.get|download|downloadstring)\b/i,vA=/(?:\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|ps1|rb|pl)(?:[?#]|$)|install)/i,xA=/(?:\bfrom\s{1,5}|\bimport\s{0,5}\(\s{0,5}|\bimport\s{1,5}|\brequire\s{0,5}\(\s{0,5})['"](https?:\/\/[^'"\n]{1,500})['"]/g;function Rc(t){if(!t)return!1;let e=t.replace(/^semver:/i,"").trim();return/^[0-9a-f]{7,40}$/i.test(e)||/^v?\d{1,10}(?:\.\d{1,10}){1,4}(?:[-+.][\w.-]{0,50})?$/.test(e)}function Cc(t){let e=t.indexOf("#");if(e>=0){let a=t.slice(e+1);if(!/^(?:egg|subdirectory)=/.test(a))return a.split("&")[0]}let s=(e>=0?t.slice(0,e):t).replace(/^(?:git\+)?[a-z]{1,10}:\/\//i,"").replace(/^github:/i,""),i=s.indexOf("/"),r=i>=0?s.slice(i+1):s,o=r.lastIndexOf("@");return o>=0?r.slice(o+1):void 0}function Bm(t){let e=t.trim();return/^(?:git\+|git:|github:|gitlab:|bitbucket:)/i.test(e)||/^[A-Za-z0-9][\w.-]{0,100}\/[\w.-]{1,100}(?:#.{0,100})?$/.test(e)?!Rc(Cc(e.startsWith("git")||e.includes(":")?e:`github:${e}`)):/^https?:\/\//i.test(e)?!/\d+\.\d+\.\d+|#sha(?:256|512)=/i.test(e):!1}function SA(t){if(/@(?:latest|master|main|head)/i.test(t)){for(let e of vt(hA,t,10))if(mA.test(t.slice(Math.max(0,e.index-230),e.index)))return e}}var _A=String.raw`((?:\$\{?[A-Za-z_][A-Za-z0-9_]{0,60}\}?\/|\{baseDir\}\/|\.\/)?[\w@.\-/]{1,200}\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|mts|rb|pl|ps1))(?![\w.\-/])`,EA=new RegExp(String.raw`(?:^|[\s\x60'"(;&|])(?:sudo\s{1,5})?(?:bash|sh|zsh|python[0-9.]{0,5}|node|deno\s{1,5}run(?:\s{1,5}-\S{1,40}){0,8}|bun(?:\s{1,5}run)?|tsx|ts-node|ruby|perl|pwsh(?:\s{1,5}-File)?|powershell(?:\.exe)?(?:\s{1,5}-\S{1,40}){0,8}?\s{1,5}-File|source|uv\s{1,5}run)\s{1,5}${_A}`,"gi"),kA=new RegExp(String.raw`(?:^|[\s\x60'"(;&|])(\.\/[\w@.\-/]{1,200}\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|rb|pl|ps1))(?![\w.\-/])`,"g"),RA=new Set(["json","jsonc","json5","yaml","yml","toml"]),CA=/\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|mts|rb|pl|ps1)\b/i,ym={info:0,warning:1,high:2,critical:3},AA=5,In=25;function Ss(t,e){let n=ym[t.severity]-ym[e.severity];return n!==0?n>0:t.confidence>e.confidence}var vc=class{groups=new Map;accepts(e,n,s,i){let r=this.groups.get(`${e}|${n}`);if(!r||r.hits.length<In)return!0;let o={excerpt:"",severity:s,confidence:i};return r.hits.some(a=>Ss(o,a))}count(e,n){let s=this.groups.get(`${e}|${n}`);s&&s.total++}add(e,n,s){let i=`${e}|${n}`,r=this.groups.get(i);if(r||(r={rule:e,file:n,hits:[],total:0},this.groups.set(i,r)),r.hits.some(a=>a.line===s.line&&a.excerpt===s.excerpt))return;if(r.total++,r.hits.length<In){r.hits.push(s);return}let o=0;for(let a=1;a<r.hits.length;a++)Ss(r.hits[o],r.hits[a])&&(o=a);Ss(s,r.hits[o])&&(r.hits[o]=s)}toIssues(e){return[...this.groups.values()].filter(n=>n.hits.length>0).sort((n,s)=>n.rule.localeCompare(s.rule)||n.file.localeCompare(s.file)).map(({rule:n,file:s,hits:i,total:r})=>$A(e,n,s,i,r))}};function $A(t,e,n,s,i){let r=hR[e],o=s.map((d,p)=>({h:d,order:p})).sort((d,p)=>Ss(d.h,p.h)?-1:Ss(p.h,d.h)?1:d.order-p.order),a=o[0].h,c=o.slice(0,AA).sort((d,p)=>(d.h.line??0)-(p.h.line??0)||d.order-p.order).map(d=>d.h),l=nn(n),u=c.map(d=>e==="unscanned-files"?d.excerpt:`${l}: ${d.excerpt}`);i>c.length&&u.push(e==="unscanned-files"?`\u2026and ${i-c.length} more unscanned item(s)`:`${l}: \u2026and ${i-c.length} more match(es)`);let f=n===t?hc(t):`${hc(n)} (bundled with ${hc(t)})`;return{id:`skill-supply-chain-${e}-${le(`${t}|${n}`)}`,severity:a.severity,category:r.category,title:r.title,summary:`${f}: ${r.summary}`,filePaths:n===t?[t]:[n,t],locations:c.map(d=>d.line===void 0?{filePath:n}:{filePath:n,startLine:d.line,endLine:d.line}),evidence:u,recommendation:r.recommendation,confidence:a.confidence,tags:[xc,e]}}var Wm=t=>typeof t=="function"?t():t,PA=.4;function Ji(t,e,n,s,i,r,o){e!=="skip"&&(e==="lowconf"?t(n,s,()=>`(looks like documentation, but names a target) ${Wm(i)}`,r,PA):t(n,s,i,r,o))}var TA=/[|&;<$`]|>\(|iex|invoke-expression|atob|decode|FromBase64|powershell|pwsh/i;function Gm(t,e){let n=[];if(!TA.test(t))return n;let s=Yi(t,Es,e);s&&n.push({rule:"remote-exec",found:s});let i=Yi(t,jm,e);if(i&&n.push({rule:"encoded-exec",found:i}),!n.some(r=>r.rule==="remote-exec"))for(let r of TC){let o=fe(r.pattern,t,r.requires);if(o){n.push({rule:"remote-exec",found:o});break}}if(!n.some(r=>r.rule==="encoded-exec"))for(let r of IC){let o=fe(r.pattern,t,r.requires);if(o){n.push({rule:"encoded-exec",found:o});break}}return n}function Um(t){if(t.kind!=="instructions")return()=>0;let e=new Int32Array(t.lines.length),n=0;for(let s=0;s<t.lines.length;s++)t.fenced[s]&&!(s>0&&t.fenced[s-1])&&n++,e[s]=t.fenced[s]?n:-(s+1);return s=>e[s]}function IA(t,e,n,s,i){let r=new Set,o=Um(t),a=new _s(i),c=Number.NaN;for(let{text:l,line:u}of e){let f=u-1,d=t.kind!=="instructions"||t.fenced[f]===1,p=o(f);p!==c&&(a=new _s(i),c=p);let h=Gm(l,d),m=a.feed(l,u,d);m&&h.push({rule:m.rule,found:m.found,note:m.fromLine!==u?`(fetched/decoded at line ${m.fromLine}) `:void 0});for(let{rule:g,found:b,note:w}of h){let y=b.match[0].length,v=Zi(t,f,l,b.index,y);Ji(s,v,g,u,()=>`${w??""}${be(l,b.index,y)}`,"high",.85),v!=="skip"&&r.add(u)}}if(t.kind==="instructions")for(let{text:l,line:u}of n){if(r.has(u))continue;let f=Hm(t,l,u-1);f&&(r.add(u),s("remote-eval",u,be(l,f.index,f.match[0].length),"high",.85))}return r}function OA(t,e){for(let n of t.active){let s=fe(e,t.lines[n]);if(s)return{line:n+1,index:s.index}}}function LA(t,e,n){let s=OA(t,HC),i=[],r=[],o=DC[t.lang]??[],a=FC[t.lang]??[];for(let l of t.active){let u=l+1;if(e.has(u))continue;let f=t.lines[l],d=Hm(t,f,l);if(d){n("remote-eval",u,be(f,d.index,d.match[0].length),"high",.85);continue}if(i.length+r.length>=In)continue;let p=o.map(m=>fe(m,f)).find(Boolean);if(p){i.push({line:u,index:p.index});continue}let h=a.map(m=>fe(m,f)).find(Boolean);h&&r.push({line:u,index:h.index})}if(s&&(i.length>0||r.length>0)){n("remote-eval",s.line,`network call: ${be(t.lines[s.line-1],s.index)}`,"high",.75);for(let l of[...i,...r])n("remote-eval",l.line,be(t.lines[l.line-1],l.index),"high",.75)}else for(let l of i)n("dynamic-eval",l.line,be(t.lines[l.line-1],l.index),"warning",.6);if(!s)return;let c=[];for(let l of t.active){if(c.length>=In)break;let u=t.lines[l],f=fe(BC,u)??fe(WC,u);f&&(/(?:\s-i\s{0,5}|IdentityFile\s{1,5}|identity_file\s{0,5}=\s{0,5})\S{0,300}$/.test(u.slice(Math.max(0,f.index-300),f.index+1))||c.push({line:l+1,index:f.index}))}if(c.length!==0){n("credential-exfil",s.line,`network call: ${be(t.lines[s.line-1],s.index)}`,"high",.7);for(let l of c)n("credential-exfil",l.line,`credential/env read: ${be(t.lines[l.line-1],l.index)}`,"high",.7)}}function Ki(t,e,n,s,i={}){for(let r of s){let o=fe(r,n);if(!o)continue;let a=o.match[0].length;if(i.skipQuoted&&VR(n,o.index,o.index+a))continue;let c;if(i.negatable===!1?c=!t.fenced[e]&&Sc(n,o.index,a)?_c(n.slice(o.index,o.index+a+80))?"lowconf":"skip":"none":c=Zi(t,e,n,o.index,a,i.targetless),c!=="skip")return{found:o,verdict:c}}}function NA(t){for(let e of vt(XC,t,20)){let n=Pm(t,e.index),s=e.index+e.match[0].length,i=t.slice(s,s+120),r=ZC.exec(i),o=r?null:QC.exec(i),a=r??o;if(!a)continue;let c=s+a.index+a[0].length,l=eA.exec(t.slice(c,c+120));if(!l)continue;let u=c+l.index+l[0].length,f=t.slice(u,u+100),d=tA.test(f);if(!d&&iA.test(t))continue;let p=_c(f),h={index:e.index,strong:d,negated:n,target:p};if(d)return{...h,severity:"high",confidence:.75};if(r&&nA.test(f))return{...h,severity:"warning",confidence:.6};if(o&&sA.test(f))return{...h,severity:"warning",confidence:.6}}}function jA(t){let e=[],n=0;for(let s of t.split(/(?<=[.!?;])\s+/)){let i=t.indexOf(s,n);e.push({text:s,offset:i}),n=i+s.length}return e}function MA(t,e){let n=(s,i,r,o,a,c)=>Ji(e,o.verdict,s,i,be(r,o.found.index,o.found.match[0].length),a,c);for(let s of t.active){let i=t.lines[s];if(i.length<8)continue;let r=s+1;if(UC.test(i)){let o=Ki(t,s,i,GC,{skipQuoted:!0,targetless:!0});o&&n("instruction-override",r,i,o,"high",.8)}if(VC.test(i)){let o=Ki(t,s,i,qC,{targetless:!0}),a=o?void 0:Ki(t,s,i,KC,{negatable:!1});o?n("conceal-from-user",r,i,o,"high",.75):a&&n("conceal-from-user",r,i,a,"warning",.6)}if(zC.test(i)){let o=Ki(t,s,i,JC,{targetless:!0});o&&n("permission-bypass",r,i,o,"warning",.6)}if(gm.test(i))for(let o of jA(i)){if(!gm.test(o.text))continue;let a=NA(o.text);if(!a)continue;let c=o.offset+a.index,u=!t.fenced[s]&&(a.negated||Sc(i,c,10))?a.target?"lowconf":"skip":"none";Ji(e,u,"exfil-instruction",r,be(i,c,60),a.severity,a.confidence);break}}}function DA(t,e){for(let n of t.active){let s=t.lines[n],i=fe(YC,s);if(!i||t.kind==="instructions"&&!t.fenced[n]&&KR(s))continue;let r=i.match[0].length;Ji(e,Zi(t,n,s,i.index,r,!0),"permission-bypass",n+1,()=>be(s,i.index,r),"warning",.7)}}var FA=/[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}]/u,HA=/\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Emoji_Component}/u,BA=/[\p{L}\p{M}]/u,WA=/\p{Script=Mongolian}/u,GA=/\p{Cf}/u,UA=[[0,8],[10,31],[127,159],[847,847],[1536,1541],[1564,1564],[1757,1757],[1807,1807],[2192,2193],[2274,2274],[4447,4448],[6068,6069],[6155,6159],[8203,8207],[8232,8238],[8288,8297],[12644,12644],[65024,65039],[65279,65279],[65440,65440],[917504,917631],[917760,917999]],bm=t=>"\\u{"+t.toString(16)+"}",gc=new RegExp("["+UA.map(([t,e])=>bm(t)+"-"+bm(e)).join("")+"\\p{Cf}]","gu");function yc(t){return t>=65024&&t<=65039||t>=917760&&t<=917999}function Vm(t,e){if(e<=0)return;let n=t.charCodeAt(e-1);if(n>=56320&&n<=57343&&e>=2){let s=t.charCodeAt(e-2);if(s>=55296&&s<=56319)return(s-55296)*1024+(n-56320)+65536}return n}var bc=t=>t===void 0?void 0:String.fromCodePoint(t);function VA(t,e,n,s,i,r){if(n===9||n>=32&&n<127)return;if(n>=917504&&n<=917631)return i===127988?void 0:"severe";if(n>=8234&&n<=8238||n>=8294&&n<=8297)return"severe";if(n===65279&&s&&e===0)return;let o=Vm(t,e),a=t.codePointAt(e+(n>65535?2:1));if(n===8204||n===8205){let c=l=>l!==void 0&&l>127&&(HA.test(bc(l))||BA.test(bc(l)));return c(o)||c(a)?void 0:"mild"}if(n===8206||n===8207||n===1564||n>=1536&&n<=1541||n===1757||n===1807||n===2192||n===2193||n===2274)return r()?void 0:"mild";if(yc(n)){let c=a===void 0||!yc(a);return o!==void 0&&o>127&&!yc(o)&&c?void 0:"mild"}if(n>=6155&&n<=6159&&n!==6158)return o!==void 0&&WA.test(bc(o))?void 0:"mild";if(n===4447||n===4448){let c=l=>l!==void 0&&l>=4352&&l<=4607;return c(o)||c(a)?void 0:"mild"}if(n===12644||n===65440||n===847||n===6068||n===6069||n===8232||n===8233||n<32||n>=127&&n<=159||GA.test(String.fromCodePoint(n)))return"mild"}function zA(t,e){for(let n of t.active){let s=t.lines[n];gc.lastIndex=0;let i=gc.exec(s);if(i===null)continue;let r,o=()=>r??=FA.test(s),a=new Map,c=!1,l=-1,u=-1,f;for(;i!==null;){let d=i.index,p=s.codePointAt(d);if(p>=917504&&p<=917631){let m=Vm(s,d);(m===void 0||m<917504||m>917631)&&(f=m)}let h=VA(s,d,p,n===0,f,o);h&&(h==="severe"&&(c=!0,u<0&&(u=d)),a.set(p,(a.get(p)??0)+1),l<0&&(l=d)),i=gc.exec(s)}a.size!==0&&e("hidden-unicode",n+1,()=>{let d=[...a.entries()].sort((h,m)=>h[0]-m[0]).slice(0,4).map(([h,m])=>`${mi(h)}\xD7${m}`).join(" "),p=a.size>4?` (+${a.size-4} more kinds)`:"";return`${d}${p} in: ${be(s,c?u:l,1)}`},c?"high":"warning",c?.9:.7)}}function qA(t,e){let n=0,s=t.length-1;for(;n<s;){let i=n+s+1>>1;t[i]<=e?n=i:s=i-1}return n+1}function KA(t){let e=0,n=-1;for(;e<t.length;){let s=t.indexOf("<",e);if(s<0)return;n!==t.length&&n<=s&&(n=t.indexOf(">",s+1),n<0&&(n=t.length));let i=n,r=t.indexOf("<",s+1);if(r>=0&&r<i){e=r;continue}if(e=i+1,i-s>600||!/^<[a-z]/i.test(t.slice(s,s+2)))continue;let o=t.slice(s,i);if(rA.test(o)||oA.test(o))return{index:s,match:Xi(t,s,i+1)}}}function YA(t,e){t.content.includes("<!--")&&JA(t,e);for(let n of t.active){if(t.fenced[n])continue;let s=t.lines[n];if(!s.includes("<")||!/style|hidden/i.test(s))continue;let i=KA(s);i&&e("hidden-html-element",n+1,be(s,i.index,i.match[0].length),"warning",.6)}for(let n of t.active){let s=t.lines[n];if(s.length<200)continue;let i=vt(fA,s,5).find(r=>{let o=r.match[0];return/(?:base64,|data:[^,\s]{0,100},)\s{0,5}$/i.test(s.slice(Math.max(0,r.index-120),r.index))||!/[0-9]/.test(o)||!/[A-Z]/.test(o)||!/[a-z]/.test(o)?!1:(o.match(/\//g)?.length??0)<=o.length/10});i&&e("encoded-blob",n+1,`${i.match[0].length}-char encoded string: ${i.match[0].slice(0,40)}\u2026`,"warning",.5)}}function JA(t,e){let n=t.lines.map((o,a)=>t.fenced[a]?"":o),s=n.join(`
92
+ `),i=[0];for(let o=0;o<n.length-1;o++)i.push(i[o]+n[o].length+1);let r=0;for(;r<s.length;){let o=s.indexOf("<!--",r);if(o<0)break;let a=s.indexOf("-->",o+4),c=a<0?s.length:a;r=a<0?s.length:a+3;let l=s.slice(o+4,c);if(aA.test(l.slice(0,200))&&l.length<=120&&!cA.test(l)&&!lA.test(l))continue;let u=fe(uA,l);if(!u)continue;let f=qA(i,o+4+u.index),d=t.lines[f-1]??"",p=o+4+u.index-i[f-1];e("hidden-html-comment",f,()=>be(d,p,u.match[0].length),"warning",.6)}}function XA(t,e){if(t.kind!=="instructions")return e;let n=[];for(let s of e){if(t.fenced[s.line-1]){n.push(s);continue}if(s.text.includes("`"))for(let i of vt(/`([^`\n]{1,1000})`/g,s.text,50))Zi(t,s.line-1,s.text,i.index,i.match[0].length)!=="skip"&&n.push({text:i.match[1],line:s.line})}return n}function wm(t,e,n,s){let i=(r,o,a,c=.6)=>s("unpinned-remote-dep",r,be(o,a,80),"warning",c);if(t.kind==="manifest")return QA(t,i,s);for(let{text:r,line:o}of e){if(n.has(o))continue;if(dA.test(r)){let f=vt(pA,r,10).find(d=>!Rc(Cc(d.match[0])));if(f){i(o,r,f.index);continue}}let a=SA(r);if(a){i(o,r,a.index,.5);continue}let c=fe(gA,r);if(c&&(c.match[1]??"").trim().split(/\s+/).filter(p=>p&&!p.startsWith("-")).find(p=>!p.startsWith("@")&&!p.startsWith(".")&&!p.startsWith("/")&&!p.startsWith("file:")&&!/\.(?:js|mjs|cjs|ts|json|md|sh|py|txt)$/i.test(p)&&(/^[A-Za-z0-9][\w.-]{0,100}\/[\w.-]{1,100}(?:#\S{0,100})?$/.test(p)||/^https?:\/\//i.test(p))&&Bm(p))){i(o,r,c.index);continue}let l=fe(yA,r);if(l&&!/--(?:rev|tag)\s{1,5}\S/.test(r)){i(o,r,l.index);continue}let u=fe(bA,r);if(u&&fe(wA,r)&&vA.test(u.match[0])){i(o,r,u.index);continue}if(t.kind==="script"&&t.lang==="js"){let f=vt(xA,r,10).find(d=>!/@v?\d+(?:\.\d+)*|@[0-9a-f]{7,40}|\/v?\d+\.\d+\.\d+\//i.test(d.match[1]));f&&i(o,r,f.index)}}return[]}function ZA(t,e,n){let s=e.scripts;if(typeof s=="object"&&s!==null)for(let[a,c]of Object.entries(s).slice(0,100)){if(typeof c!="string")continue;let l=new _s().feed(c,1,!0);for(let{rule:u,found:f}of[...Gm(c,!0),...l?[l]:[]])n(u,Ye(t.content,`"${a}"`),`scripts.${nn(a)}: ${be(c,f.index,f.match[0].length)}`,"high",.85)}let i=e.bin,r=typeof i=="string"?[i]:typeof i=="object"&&i!==null?Object.values(i).filter(a=>typeof a=="string"):[],o=Ue.posix.dirname(t.path);return r.slice(0,5).map(a=>Ue.posix.normalize(`${o}/${a.replace(/\\/g,"/")}`)).filter(a=>a.startsWith(`${o}/`))}function QA(t,e,n){if(Ue.posix.basename(t.path)==="package.json"){let i;try{i=JSON.parse(t.content)}catch{return[]}if(typeof i!="object"||i===null)return[];let r=ZA(t,i,n),o=0;for(let a of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){let c=i[a];if(!(typeof c!="object"||c===null))for(let[l,u]of Object.entries(c)){if(typeof u!="string")continue;let f=u.trim();if(f===""||f==="*"||f==="latest"||Bm(f)){if(++o>In)return r;let d=Ye(t.content,`"${l}"`);e(d,t.lines[d-1]??`"${l}": "${u}"`,0)}}}return r}for(let i of t.active){let r=t.lines[i].replace(/\s#.*$/,""),o=fe(/\bgit\+[a-z]{1,10}:\/\/\S{1,500}/i,r);if(o&&!Rc(Cc(o.match[0]))){e(i+1,r,o.index);continue}let a=fe(/\bhttps?:\/\/\S{1,500}?\.(?:zip|tar\.gz|tgz|whl)\S{0,200}/i,r);a&&!/\d+\.\d+|#sha256=/i.test(a.match[0])&&e(i+1,r,a.index)}return[]}function e$(t,e,n,s,i){let r=/^(.*?)\/?skills\/[^/]+$/.exec(e)?.[1],o=f=>{let d=f,p,h=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?\/(.*)$/.exec(d);if(h){let m=h[1];if(d=h[2],m==="CLAUDE_SKILL_DIR"||m==="SKILL_DIR")p=[e];else if(m==="CLAUDE_PLUGIN_ROOT"&&r!==void 0)p=[r||"."];else if(m==="CLAUDE_PROJECT_DIR")p=["."];else return}else if(d.startsWith("{baseDir}/"))d=d.slice(10),p=[e];else{if(d=d.replace(/^\.\//,""),!d.includes("/"))return;p=[...new Set([e,...r?[r]:[],"."])]}if(!(!d||d.includes("..")||d.startsWith("/")))return p.map(m=>m==="."?d:`${m}/${d}`)},a=new Map,c=0,l=0,u=f=>{let d=a.get(f);if(d!==void 0)return d;if(c>=t$)return;c++;let p=at(t,f);return a.set(f,p),p};for(let f of n.active){let d=n.lines[f];if(!(n.fenced[f]&&RA.has(n.fenceLang.get(f)??""))&&CA.test(d))for(let p of[EA,kA])for(let h of vt(p,d,10)){let m=h.match[1],g=m.replace(/^\.\//,""),b=o(m);if(!b)continue;let w=!1,y=!1;for(let v of b){let R=u(v);if(R===void 0)y=!0;else if(R){w=!0;break}}if(!w){if(y)return;if(!(s().has(g)||s().has(m))&&(i("missing-script",f+1,`${nn(m)} not found (looked in: ${b.map(nn).join(", ")})`,"warning",.6),++l>=In))return}}}}var t$=200,n$=3e6;function vm(t,e,n){let s=Buffer.alloc(n),i=ut.readSync(t,s,0,n,e);return s.subarray(0,i)}function s$(t,e,n,s,i){let r=n.split(/\r?\n/),o=[];for(let l=0;l<r.length;l++){let u=r[l];u.length>0&&i$.test(u)&&o.push(l)}let a=new Uint8Array(r.length),c=new Map;if(e.kind==="instructions"&&(n.includes("```")||n.includes("~~~"))){let l=xe(n.replace(/\r\n/g,`
93
+ `));for(let u=0;u<r.length;u++){let f=l[u];f?.inFence&&(a[u]=1,f.lang&&c.set(u,f.lang))}}return{path:t,kind:e.kind,lang:e.lang,content:n,lines:r,active:o,fenced:a,fenceLang:c,frontmatterEnd:s&&!i?kR(r):0,tail:i}}var i$=/[^ \t\r]/;function r$(t){let e=1;for(let n=t.indexOf(10);n>=0;n=t.indexOf(10,n+1))e++;return e}function o$(t,e,n,s,i){let r=s?"high":"warning",o=n?{kind:"instructions",lang:"other"}:xm(e);if(typeof o=="object"&&"skip"in o)return{docs:[],unscanned:[]};if(typeof o=="object"&&"report"in o)return{docs:[],unscanned:[{path:e,reason:o.report,severity:o.severity}]};let a=Ot(t,e);if(!a)return{docs:[],unscanned:[]};if(!ae(t,a))return{docs:[],unscanned:[{path:e,reason:"symlink to a location outside the repository \u2014 not read",severity:"warning"}]};let c;try{let l=ut.statSync(a);if(!l.isFile())return{docs:[],unscanned:[]};let u=l.size;if(i.files<=0||i.bytes<=0||i.lines<=0)return{docs:[],unscanned:[{path:e,reason:"per-scan budget exhausted \u2014 not scanned",severity:r}]};if(c=ut.openSync(a,"r"),o==="probe"){let g=vm(c,0,Math.min(u,Kn));if(zt(g))return{docs:[],unscanned:[{path:e,reason:`${ER(g)} \u2014 cannot be reviewed as text`,severity:"warning"}]};let b=_R(g.toString("utf8").split(/\r?\n/,1)[0]??"");o=b?{kind:"script",lang:b}:{kind:"text",lang:"other"}}let f=o,d=f.note?[{path:e,reason:f.note.reason,severity:f.note.severity}]:[];i.files--;let p=(g,b,w)=>{let y=vm(c,g,b);return i.bytes-=y.length,i.lines-=r$(y),s$(e,f,y.toString("utf8"),n&&!w,w)};if(u<=2*ce){let g=Math.min(u,i.bytes),b=[p(0,g,!1)];return g<u&&d.push({path:e,reason:"per-scan budget exhausted part-way \u2014 the rest was not scanned",severity:r}),{docs:b,unscanned:d}}let h=[p(0,Math.min(ce,i.bytes),!1)],m=Math.min(ce,i.bytes);return m>0&&h.push(p(u-m,m,!0)),d.push({path:e,reason:`larger than 1 MB (${Math.round(u/1024)} KB) \u2014 only the first and last 500 KB were scanned`,severity:m>0?"warning":r}),{docs:h,unscanned:d}}catch{return{docs:[],unscanned:[]}}finally{c!==void 0&&ut.closeSync(c)}}function a$(t,e,n,s,i,r,o){let a=(p,h,m,g,b)=>{if(!r.accepts(p,n.path,g,b)){r.count(p,n.path);return}let w=n.tail?"(end of file) ":n.frontmatterEnd>0&&h<=n.frontmatterEnd?"(frontmatter) ":"";r.add(p,n.path,{line:n.tail?void 0:h,excerpt:`${w}${Wm(m)}`,severity:g,confidence:b})};if(zA(n,a),DA(n,a),n.kind==="manifest")return wm(n,[],new Set,a);let{lines:c,capped:l}=$R(n);l.length>0&&o.push({path:n.path,reason:`continuation chain longer than ${_m} lines / ${Em} characters at line ${l[0]} \u2014 split for scanning (a download-fed loop body is followed up to ${km} lines / ${Rm} characters)`,severity:"warning"});let u=XA(n,c),d=IA(n,c,u,a,p=>{let h=p.replace(/^\.\//,"");return!h||h.startsWith("/")||/^[a-z]:/i.test(h)?!1:[`${Ue.posix.dirname(n.path)}/${h}`,`${e}/${h}`,h].some(m=>at(t,m))});return wm(n,u,d,a),n.kind==="instructions"?(MA(n,a),YA(n,a),s&&!n.tail&&e$(t,e,n,i,a)):LA(n,d,a),[]}var c$=["node_modules",".git","worktrees",".worktrees"],l$={node_modules:/(?:^|[\s'"`(=:/])node_modules\//m,".git":/(?:^|[\s'"`(=:])(?:\.\/)?\.git\//m,worktrees:/(?:^|[\s'"`(=:])(?:\.\/)?worktrees\//m,".worktrees":/(?:^|[\s'"`(=:])(?:\.\/)?\.worktrees\//m};function u$(t,e){let n=Ot(t,`${e}/hooks`);if(!n)return!1;try{return ut.readdirSync(n).some(s=>!s.endsWith(".sample"))}catch{return!1}}function f$(t,e,n){switch(t.kind){case"dependency-dir":{let s=Ue.posix.basename(t.path),i=s==="node_modules"?" (only package manifests and their bin targets were read)":"";return e.has(s)?{path:t.path,reason:`dependency/VCS directory the skill runs or references by path \u2014 not walked${i}`,severity:"high"}:s===".git"&&u$(n,t.path)?{path:t.path,reason:"git directory with hooks \u2014 hooks run on git operations and were not scanned",severity:"warning"}:{path:t.path,reason:`dependency/VCS directory \u2014 not walked${i}`,severity:"info"}}case"include":return{path:t.path,reason:`${t.count??0} file(s) outside the configured include patterns \u2014 not scanned`,severity:"info"};default:return{path:t.path,reason:`bundle too large to list \u2014 ${t.count??"more"} further file(s) not scanned`,severity:"warning"}}}function Ac(t,e={}){let n=t.aiConfig??{},s=n.allSkills??n.skills??[],i=new Set(n.skills??[]),r=s.map(p=>Ue.posix.dirname(p)),o=p=>{let h=-1;return r.forEach((m,g)=>{la(m)||!(p===m||p.startsWith(`${m}/`))||(h<0||m.length>r[h].length)&&(h=g)}),h},a=s.map((p,h)=>{let m={skillMd:p,dir:r[h],collector:new vc,unscanned:[],alreadyReported:()=>new Set,referenced:new Set,queue:{priority:[],rest:[]},loaded:!1};if(i.has(p)){let g;m.alreadyReported=()=>g??=new Set(dc(m.headContent??"").map(b=>b.ref))}return m});for(let p of n.skillFiles??[]){let h=o(p);h>=0&&(am(p)?a[h].queue.priority:a[h].queue.rest).push(p)}for(let p of n.skillFilesOverCap??[]){let h=o(p);h>=0&&a[h].unscanned.push({path:p,reason:"over the per-skill file cap \u2014 not scanned",severity:am(p)?"high":"warning"})}let c={bytes:e.bytes??dR,files:e.files??pR,lines:e.lines??n$},l=(p,h)=>{if(!(h.kind!=="instructions"&&h.kind!=="script"&&!(h.kind==="text"&&h.lang==="sh")))for(let m of c$)l$[m].test(h.content)&&p.referenced.add(m)},u=new Set,f=(p,h,m,g)=>{if(u.has(h))return{docs:[],unscanned:[]};u.add(h);let b=o$(t.repoRoot,h,m,g,c);p.unscanned.push(...b.unscanned);let w=[];m&&(p.headContent=b.docs[0]?.content);for(let y of b.docs)l(p,y),w.push(...a$(t.repoRoot,p.dir,y,m,p.alreadyReported,p.collector,p.unscanned));for(let y of w)o(y)>=0&&f(p,y,!1,!0);return b};for(let p of a){let h=f(p,p.skillMd,!0,!0);p.loaded=h.docs.length>0||h.unscanned.length>0;for(let m of p.queue.priority)f(p,m,!1,!0)}for(let p of a)for(let h of p.queue.rest)f(p,h,!1,!1);let d=[];for(let p of a)if(p.loaded){for(let h of n.skillBundleSkips??[])o(h.path)===a.indexOf(p)&&p.unscanned.push(f$(h,p.referenced,t.repoRoot));for(let h of p.unscanned)p.collector.add("unscanned-files",p.skillMd,{excerpt:`${nn(h.path)}: ${h.reason}`,severity:h.severity,confidence:.8});d.push(...p.collector.toIssues(p.skillMd))}return Te(t.repoRoot,d)}var $c=x(require("node:path"),1);var d$={idPrefix:"agent",noun:"Subagent",why:"A subagent needs `name` and `description` frontmatter to be registered.",recommendation:"Add frontmatter with `name` and `description` at the top of the agent file."},p$=new Set(["sonnet","opus","haiku","inherit","default","opusplan"]),h$=new Set(["Task","Bash","BashOutput","KillBash","KillShell","Glob","Grep","LS","Read","Edit","MultiEdit","Write","NotebookRead","NotebookEdit","WebFetch","WebSearch","TodoWrite","SlashCommand","ExitPlanMode","Agent"]),m$=.8,g$=5;function ks(t,e){return`ai-config-agent-${t}-${le(e)}`}function y$(t){let e=new Set;for(let n of t.split(/\r?\n/)){let s=n.trim().toLowerCase().replace(/\s+/g," ");s.length>=8&&e.add(s)}return e}function b$(t,e){if(t.size===0||e.size===0)return 0;let n=0,[s,i]=t.size<=e.size?[t,e]:[e,t];for(let o of s)i.has(o)&&n++;let r=t.size+e.size-n;return r===0?0:n/r}function Pc(t){let e=[],n=[];for(let i of t.aiConfig.agents){let r=ie(t.repoRoot,i);if(r===void 0)continue;let o=gt(r);if(e.push(...Lt(i,r,o,d$)),!o.present)continue;let a=typeof o.data.name=="string"?o.data.name.trim():void 0,c=typeof o.data.description=="string"?o.data.description.trim():void 0;a||e.push(H({id:ks("missing-name",i),title:"Subagent frontmatter is missing `name`",summary:`${i} has no \`name\` field, so it cannot be invoked by name.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:o.fenceEndLine>0?o.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(o.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter.",confidence:.85})),c||e.push(H({id:ks("missing-description",i),title:"Subagent frontmatter is missing `description`",summary:`${i} has no \`description\`. The description tells the orchestrator when to delegate to this agent.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:o.fenceEndLine>0?o.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(o.data).join(", ")||"(none)"}`],recommendation:"Add a `description` explaining what the agent is for and when to use it.",confidence:.85}));let l=typeof o.data.model=="string"?o.data.model.trim():void 0;l&&!p$.has(l.toLowerCase())&&!/^claude-/i.test(l)&&e.push(H({id:ks("unknown-model",`${i}|${l}`),title:"Subagent references an unrecognized model",summary:`${i}: \`model: ${l}\` is not a known alias (sonnet, opus, haiku, inherit) or a \`claude-*\` id.`,filePaths:[i],locations:[{filePath:i,startLine:o.keyLines.model??1,endLine:o.keyLines.model??1}],evidence:[`model: ${l}`],recommendation:"Use a supported model alias or a full model id, or remove `model` to inherit the session model.",confidence:.5}));let u=xn(o.data.tools),f=u.filter(h=>h!=="*"&&!h.startsWith("mcp__")&&!h$.has(h));f.length>0&&e.push(H({id:ks("unknown-tools",`${i}|${f.join(",")}`),severity:"info",title:"Subagent grants tools that may not exist",summary:`${i} lists ${f.length} tool name(s) that are not built-in tools or \`mcp__*\` tools: ${f.join(", ")}.`,filePaths:[i],locations:[{filePath:i,startLine:o.keyLines.tools??1,endLine:o.keyLines.tools??1}],evidence:[`Unrecognized: ${f.join(", ")}`,`Declared tools: ${u.join(", ")}`],recommendation:"Check the tool names against the built-in tool set (or your MCP server tool names) for typos.",confidence:.4}));let d=r.split(/\r?\n/).slice(Math.max(0,o.bodyStartLine-1)).join(`
94
+ `),p=y$(d);n.push({filePath:i,bodyLines:p})}let s=n.filter(i=>i.bodyLines.size>=g$);for(let i=0;i<s.length;i++)for(let r=i+1;r<s.length;r++){let o=s[i],a=s[r],c=b$(o.bodyLines,a.bodyLines);if(c>=m$){let l=[o.filePath,a.filePath].sort();e.push(H({id:ks("dup-prompt",l.join("|")),title:"Two subagents share near-identical system prompts",summary:`${Kt($c.basename(l[0]))} and ${Kt($c.basename(l[1]))} have ${Math.round(c*100)}% identical prompt bodies, which usually means a copy-paste that should be consolidated.`,filePaths:l,locations:l.map(u=>({filePath:u,startLine:1,endLine:1})),evidence:[`Body similarity: ${Math.round(c*100)}%`,`Agents: ${l.join(", ")}`],recommendation:"Differentiate the agents' instructions, or merge them into one agent if they do the same job.",confidence:c===1?.8:.55}))}}return Te(t.repoRoot,e)}var w$=/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|dash)\b/i;function Qi(t,e){return`ai-config-hook-${t}-${le(e)}`}function Ic(t,e,n){if(Array.isArray(t)){for(let i of t)Ic(i,e,n);return}if(typeof t!="object"||t===null)return;let s=t;s.type==="command"&&typeof s.command=="string"&&n.push({command:s.command,event:e});for(let[i,r]of Object.entries(s))typeof r=="object"&&r!==null&&Ic(r,e===""?i:e,n)}var v$=new Set(["bash","sh","zsh","dash","node","deno","python","python3","ruby","ts-node","tsx","pwsh","powershell"]),x$=new Set(["npx","bunx","pnpm","yarn","uv","uvx","env","timeout","nice","sudo","exec","command"]);function Tc(t){return t.replace(/^['"]|['"]$/g,"").replace(/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/,"")}function S$(t){let e=new Set,n=(s,i)=>{if(s.startsWith("-"))return;let r=s.replace(/^['"]|['"]$/g,""),o=Tc(s);if(!o||o.includes("$")||/[<>{}*?|"'`]/.test(o)||o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)||/^https?:/i.test(o)||o.includes("..")||!Zn.test(o))return;let a=r.startsWith("./")||r.startsWith(".claude/")||/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/.test(r);(i||a)&&e.add(o.replace(/\\/g,"/"))};for(let s of t.split(/&&|\|\||;|\|/)){let i=s.trim().split(/\s+/).filter(Boolean);if(i.length===0)continue;let r=Tc(i[0]);if(v$.has(r)||x$.has(r)){for(let o=1;o<i.length;o++)if(!i[o].startsWith("-")&&Zn.test(Tc(i[o]))){n(i[o],!0);break}}else n(i[0],!0);for(let o=1;o<i.length;o++)n(i[o],!1)}return[...e]}function _$(t,e){let n="";for(let s=0;s<e;s++){let i=t[s];n?i===n&&(n=""):(i==='"'||i==="'")&&(n=i)}return n!==""}function E$(t){for(let e of t.matchAll(/\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/g))if(!_$(t,e.index))return!0;return!1}function Oc(t){let e=[];for(let n of t.aiConfig.settings){let s=ie(t.repoRoot,n);if(s===void 0)continue;let i;try{i=JSON.parse(s)}catch(c){e.push(H({id:Qi("invalid-json",n),severity:"high",title:"Settings file is not valid JSON",summary:`${n} could not be parsed as JSON, so Claude Code cannot load its hooks or permissions.`,filePaths:[n],locations:[{filePath:n,startLine:1,endLine:1}],evidence:[`Parse error: ${c.message}`],recommendation:"Fix the JSON syntax (trailing commas and comments are not allowed in settings.json).",confidence:.95}));continue}if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.hooks;if(r===void 0)continue;let o=[];Ic(r,"",o);let a=new Set;for(let{command:c,event:l}of o){let u=Ye(s,c);w$.test(c)&&e.push(H({id:Qi("curl-pipe-sh",`${n}|${c}`),severity:"high",impact:"high",title:"Hook pipes a remote download into a shell",summary:`A ${l||"hook"} command in ${n} pipes \`curl\`/\`wget\` output directly into a shell, running whatever the remote host serves with your permissions.`,filePaths:[n],locations:[{filePath:n,startLine:u,endLine:u}],evidence:[`Command: ${c.slice(0,160)}`],recommendation:"Download to a file, review it, and pin a checksum before executing \u2014 never pipe a network fetch straight into sh/bash.",confidence:.85})),E$(c)&&e.push(H({id:Qi("unquoted-project-dir",`${n}|${c}`),severity:"info",title:"Hook uses an unquoted $CLAUDE_PROJECT_DIR path",summary:`A ${l||"hook"} command in ${n} expands \`$CLAUDE_PROJECT_DIR\` unquoted; if the project path contains a space the command breaks or runs the wrong file.`,filePaths:[n],locations:[{filePath:n,startLine:u,endLine:u}],evidence:[`Command: ${c.slice(0,160)}`],recommendation:'Wrap the path in double quotes, e.g. `"$CLAUDE_PROJECT_DIR/script.sh"`.',confidence:.5}));for(let f of S$(c)){if(at(t.repoRoot,f))continue;let d=`${n}|${f}`;a.has(d)||(a.add(d),e.push(H({id:Qi("missing-script",d),title:"Hook command references a script that does not exist",summary:`A ${l||"hook"} command in ${n} runs \`${f}\`, but that file is not present in the repository.`,filePaths:[n],locations:[{filePath:n,startLine:u,endLine:u}],evidence:[`Referenced script: ${f}`,`Command: ${c.slice(0,160)}`],recommendation:"Add the script, fix the path, or remove the hook.",confidence:.75})))}}}return Te(t.repoRoot,e)}function Rs(t,e){return`ai-config-mcp-${t}-${le(e)}`}function k$(t,e){let n=[],s=0,i=!1,r=!1,o="",a=null;for(let c=e;c<t.length;c++){let l=t[c];if(i){if(r){r=!1,o+=l;continue}if(l==="\\"){r=!0;continue}if(l==='"'){i=!1,s===1&&(a=o);continue}o+=l;continue}if(l==='"'){i=!0,o="";continue}if(l==="{"||l==="["){s++;continue}if(l==="}"||l==="]"){if(s--,s===0)break;continue}if(l===":"){s===1&&a!==null&&(n.push(a),a=null);continue}if(l===","){a=null;continue}}return n}function R$(t){let e=/"mcpServers"\s*:/.exec(t);if(!e)return[];let n=t.indexOf("{",e.index+e[0].length);if(n<0)return[];let s=k$(t,n),i=new Map;for(let r of s)i.set(r,(i.get(r)??0)+1);return[...i.entries()].filter(([,r])=>r>1).map(([r])=>r).sort()}function C$(t){let e=t.trim();return!!(e===""||/^<.+>$/.test(e)||/^(your|my)[-_ ]/i.test(e)||/^x{3,}$/i.test(e)||/^\.\.\.+$/.test(e)||/\b(changeme|change[-_]me|replace[-_]?me|placeholder|example[-_]?key|todo|tbd)\b/i.test(e))}function A$(t,e){let n=new Set,s=(i,r)=>{let o=i.replace(/^['"]|['"]$/g,"");if(!o||o.startsWith("-")||o.includes("$")||/[<>{}*?]/.test(o)||o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)||/^https?:/i.test(o)||o.includes(".."))return;let a=o.startsWith("./")||o.startsWith(".claude/");r&&!a||(a||o.includes("/")&&Zn.test(o))&&n.add(o.replace(/\\/g,"/"))};t&&s(t,!1);for(let i of e)s(i,!0);return[...n]}function Lc(t){let e=[];for(let n of t.aiConfig.mcp){let s=ie(t.repoRoot,n);if(s===void 0)continue;let i;try{i=JSON.parse(s)}catch(o){e.push(H({id:Rs("invalid-json",n),severity:"high",title:"MCP config is not valid JSON",summary:`${n} could not be parsed as JSON, so no MCP servers will load from it.`,filePaths:[n],locations:[{filePath:n,startLine:1,endLine:1}],evidence:[`Parse error: ${o.message}`],recommendation:"Fix the JSON syntax (no trailing commas, no comments).",confidence:.95}));continue}if(typeof i!="object"||i===null||Array.isArray(i))continue;let r=i.mcpServers;if(!(typeof r!="object"||r===null||Array.isArray(r))){for(let o of R$(s))e.push(H({id:Rs("duplicate-name",`${n}|${o}`),title:"Duplicate MCP server name",summary:`${n} defines the server "${o}" more than once. JSON keeps only the last definition and silently discards the earlier one.`,filePaths:[n],locations:[{filePath:n,startLine:Ye(s,`"${o}"`),endLine:Ye(s,`"${o}"`)}],evidence:[`Duplicated server name: ${o}`],recommendation:"Rename or remove the duplicate so each server name is unique.",confidence:.85}));for(let[o,a]of Object.entries(r)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let c=a,l=typeof c.command=="string"?c.command:void 0,u=typeof c.url=="string"?c.url:void 0,f=Array.isArray(c.args)?c.args.filter(p=>typeof p=="string"):[],d=Ye(s,`"${o}"`);if(!l&&!u&&e.push(H({id:Rs("no-command-or-url",`${n}|${o}`),title:"MCP server has neither a command nor a url",summary:`${n}: server "${o}" defines no \`command\` (stdio) and no \`url\` (http/sse), so it cannot start.`,filePaths:[n],locations:[{filePath:n,startLine:d,endLine:d}],evidence:[`Server: ${o}`,`Keys: ${Object.keys(c).join(", ")||"(none)"}`],recommendation:"Add a `command` (with `args`) for a stdio server, or a `url` for a remote server.",confidence:.8})),typeof c.env=="object"&&c.env!==null&&!Array.isArray(c.env))for(let[p,h]of Object.entries(c.env))typeof h!="string"||!C$(h)||e.push(H({id:Rs("placeholder-env",`${n}|${o}|${p}`),title:"MCP server env value is an unfilled placeholder",summary:`${n}: server "${o}" sets \`env.${p}\` to a placeholder (${JSON.stringify(h)}) that was never replaced with a real value.`,filePaths:[n],locations:[{filePath:n,startLine:Ye(s,`"${p}"`),endLine:Ye(s,`"${p}"`)}],evidence:[`${p}: ${h}`],recommendation:'Replace the placeholder with a real value, or reference a shell variable like `"${'+p+'}"`.',confidence:.7}));for(let p of A$(l,f))at(t.repoRoot,p)||e.push(H({id:Rs("missing-command",`${n}|${o}|${p}`),title:"MCP server command path does not exist",summary:`${n}: server "${o}" references the local path \`${p}\`, which is not present in the repository.`,filePaths:[n],locations:[{filePath:n,startLine:d,endLine:d}],evidence:[`Referenced path: ${p}`,`Server: ${o}`],recommendation:"Fix the path, add the missing file, or install the server so the path resolves.",confidence:.7}))}}}return Te(t.repoRoot,e)}var qm=x(Et(),1);var $$={idPrefix:"cursor",noun:"Cursor rule",why:"A .mdc rule needs metadata (`description`, `globs`, or `alwaysApply`) to control when it applies.",recommendation:"Add a frontmatter block describing the rule and its trigger (globs or alwaysApply).",noFrontmatterTitle:"Cursor rule is missing frontmatter",noFrontmatterSeverity:"warning",noFrontmatterConfidence:.7},P$=["**/node_modules/**","**/.git/**"];function zm(t,e){return`ai-config-cursor-${t}-${le(e)}`}function T$(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function Nc(t){let e=[],n=t.aiConfig.cursorRules,s=null,i=r=>(s??=ct(t.repoRoot,["**/*"],P$),qm.default.some(s,r,{dot:!0}));for(let r of n){let o=ie(t.repoRoot,r);if(o===void 0)continue;let a=gt(o);if(e.push(...Lt(r,o,a,$$)),!a.present)continue;let c=typeof a.data.description=="string"?a.data.description.trim():"",l=xn(a.data.globs),u=a.data.alwaysApply===!0||typeof a.data.alwaysApply=="string"&&a.data.alwaysApply.trim().toLowerCase()==="true";!c&&l.length===0&&!u&&e.push(H({id:zm("no-trigger",r),title:"Cursor rule has no trigger",summary:`${r} defines no \`description\`, no \`globs\`, and \`alwaysApply\` is not set, so Cursor has no signal for when to apply it.`,filePaths:[r],locations:[{filePath:r,startLine:1,endLine:a.fenceEndLine>0?a.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(a.data).join(", ")||"(none)"}`],recommendation:"Add a `description` (agent-requested), `globs` (auto-attached), or `alwaysApply: true`.",confidence:.7}));for(let f of l){if(!T$(f))continue;let d=f.replace(/^\//,""),p=d.includes("/")?[d]:[d,`**/${d}`];i(p)||e.push(H({id:zm("dead-glob",`${r}|${f}`),title:"Cursor rule glob matches no files",summary:`${r}: the \`globs\` pattern \`${f}\` matches no files in the repository, so this auto-attached rule never fires.`,filePaths:[r],locations:[{filePath:r,startLine:a.keyLines.globs??1,endLine:a.keyLines.globs??1}],evidence:[`Glob: ${f}`],recommendation:"Update the glob to match real paths, or remove the rule if the code it targeted is gone.",confidence:.6}))}}return Te(t.repoRoot,e)}var Mc=x(Et(),1);var I$={idPrefix:"copilot",noun:"Copilot instructions file",why:"A `.instructions.md` file uses an `applyTo:` frontmatter glob to control which files it applies to.",recommendation:'Add a frontmatter block with an `applyTo:` glob (use `applyTo: "**"` to apply to every request).',noFrontmatterTitle:"Copilot instructions file is missing frontmatter",noFrontmatterSeverity:"warning",noFrontmatterConfidence:.7},O$=["**/node_modules/**","**/.git/**"],L$=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/worktrees/**","**/.worktrees/**"];function jc(t,e){return`ai-config-copilot-${t}-${le(e)}`}function N$(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function j$(t){let e=t.trim();return e==="**"||e==="**/*"}function Dc(t){let e=[],n=t.aiConfig.copilotInstructions,s=null,i=null,r=a=>(s??=ct(t.repoRoot,["**/*"],O$),Mc.default.some(s,a,{dot:!0})),o=a=>(i??=ct(t.repoRoot,["**/*"],L$),Mc.default.some(i,a,{dot:!0}));for(let a of n){let c=ie(t.repoRoot,a);if(c===void 0)continue;let l=gt(c);if(e.push(...Lt(a,c,l,I$)),!l.present)continue;let u=xn(l.data.applyTo);if(u.length===0){e.push(H({id:jc("no-applyto",a),title:"Copilot instructions file has no applyTo glob",summary:`${a} defines no \`applyTo\` glob, so Copilot applies it to every request by default \u2014 often unintentional.`,filePaths:[a],locations:[{filePath:a,startLine:1,endLine:l.fenceEndLine>0?l.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(l.data).join(", ")||"(none)"}`],recommendation:'Add an `applyTo:` glob scoping the file to the paths it is about, or set `applyTo: "**"` to make the always-on scope explicit.',confidence:.7}));continue}let f=l.keyLines.applyTo??1;for(let d of u){if(!N$(d)||j$(d))continue;let p=d.replace(/^\//,""),h=p.includes("/")?[p]:[p,`**/${p}`];r(h)?o(h)||e.push(H({id:jc("ignored-glob",`${a}|${d}`),severity:"info",title:"Copilot instructions applyTo glob matches only ignored files",summary:`${a}: the \`applyTo\` glob \`${d}\` matches only ignored or build-output files, so it rarely applies to files you edit.`,filePaths:[a],locations:[{filePath:a,startLine:f,endLine:f}],evidence:[`Glob: ${d}`],recommendation:"Point the glob at source paths, or remove the file if it was meant to target generated output.",confidence:.55})):e.push(H({id:jc("dead-glob",`${a}|${d}`),title:"Copilot instructions applyTo glob matches no files",summary:`${a}: the \`applyTo\` glob \`${d}\` matches no files in the repository, so this instructions file never applies.`,filePaths:[a],locations:[{filePath:a,startLine:f,endLine:f}],evidence:[`Glob: ${d}`],recommendation:"Update the glob to match real paths, or remove the file if the code it targeted is gone.",confidence:.6}))}}return Te(t.repoRoot,e)}var M$=[{label:"TypeScript",re:/\btypescript\b/i},{label:"JavaScript",re:/\bjavascript\b/i},{label:"Python",re:/\bpython\b/i},{label:"Rust",re:/\brust\b/i},{label:"Go",re:/\bgolang\b/i},{label:"Ruby",re:/\bruby\b|\brails\b/i},{label:"Java",re:/\bjava\b(?!script)/i},{label:"Kotlin",re:/\bkotlin\b/i},{label:"Swift",re:/\bswift\b/i},{label:"C#",re:/\bc#|\bcsharp\b|\bdotnet\b|\.net\b/i},{label:"React",re:/\breact\b/i},{label:"Vue",re:/\bvue\b/i},{label:"Svelte",re:/\bsvelte\b/i},{label:"Django",re:/\bdjango\b/i}],D$=2;function Fc(t){let e=[],n=i=>i==="windsurf",s=[...t.files.filter(i=>i.fileType==="windsurf").map(i=>[i]),...Qn(Yt(t.files,t.aliasFiles??[],n))];for(let i of s){let r=i[0],o=new Set;for(let a of r.sections){let c=a.heading;if(c)for(let l of M$)l.re.test(c)&&o.add(l.label)}if(o.size>=D$){let a=[...o].sort();e.push({id:`ai-config-windsurf-scope-${le(L(r))}`,severity:"info",category:"ai_config",title:".windsurfrules mixes language-specific rules in a workspace-wide file",summary:`This \`.windsurfrules\` has headings for multiple languages/frameworks (${a.join(", ")}), but it applies to the whole workspace on every request. Language- or framework-specific rules are cheaper as glob-scoped rules that load only for matching files.`,filePaths:i.map(c=>c.path),locations:i.map(c=>({filePath:c.path,startLine:1})),evidence:[`Scoped topics found in headings: ${a.join(", ")}`],recommendation:"Clarify the intended scope: keep genuinely workspace-wide conventions in `.windsurfrules`, and move language- or framework-specific rules into glob-scoped `.windsurf/rules/*.md` files, each with a glob trigger.",confidence:.6})}}return e}var Km=x(require("node:crypto"),1),Ym=x(require("node:path"),1);var F$=Ce,H$=[/\bdo\s+not\b/i,/\bdon['’]?t\b/i,/\bnever\b/i,/\bavoid\b/i,/\brefrain\s+from\b/i,/\bmust\s+not\b/i,/\bmustn['’]?t\b/i,/\bshould\s+not\b/i,/\bshouldn['’]?t\b/i,/\bcannot\b/i,/\bcan['’]?t\b/i,/\bwon['’]?t\b/i,/\bno\s+longer\b/i],B$=/^(use|always|prefer|ensure|make\s+sure|keep|run|write|add|follow|call|set|return|check|verify|read|ask|include|place|put|store|document|test|update|create|define|import|export|name|group|split|choose|pick|apply|treat|surface|confirm|report|explain|favor|favour|default\s+to|stick\s+to|remember\s+to|be\s+sure\s+to)\b/i,W$=/\b(must|should|always|shall)\b/i,G$=8,U$=.4;function V$(t){return t.replace(/^\s*#{1,6}\s+/,"").replace(/^\s*[-*+]\s+/,"").replace(/^\s*\d+[.)]\s+/,"").replace(/^\s*>\s+/,"").trim()}function z$(t){return t.replace(/^[*_`]+/,"").trimStart()}function q$(t){let e=t.split(/\r?\n/),n=[],s=!1;for(let i of e){if(/^\s*(```|~~~)/.test(i)){s=!s;continue}if(s)continue;let o=V$(i);if(o)for(let a of o.split(/(?<=[.!?])\s+/)){let c=a.trim();c.split(/\s+/).length>=3&&n.push(c)}}return n}function K$(t){let e=z$(t);if(B$.test(e))return"positive";for(let n of H$)if(n.test(t))return"negative";return W$.test(t)?"positive":"none"}function Y$(t){return`negative-overload-${Km.createHash("sha1").update(`negative-overload:${t}`).digest("hex").slice(0,12)}`}function Hc(t){let e=[];for(let n of t){if(!F$.has(n.fileType))continue;let s=q$(n.content),i=[],r=0;for(let f of s){let d=K$(f);d==="negative"?i.push(f):d==="positive"&&r++}let o=i.length+r;if(o<G$)continue;let a=i.length/o;if(a<=U$)continue;let c=Ym.basename(n.path),l=Math.round(a*100),u=i.slice(0,3).map(f=>Y(f,100));e.push({id:Y$(L(n)),severity:"info",category:"agent_practices",title:"High proportion of negative instructions",summary:`About ${l}% of the directive sentences in "${c}" are phrased as prohibitions (${i.length} of ${o}). Models tend to follow positive directives more reliably than prohibitions, so heavily negative guidance can be harder to apply.`,filePaths:[n.path],locations:[],evidence:u.map(f=>`Negative directive: "${f}"`),recommendation:`Where practical, rephrase prohibitions as positive directives \u2014 e.g. instead of "don't use var", write "always use const or let". Keep prohibitions for the cases where no positive form is possible.`,confidence:.5})}return e}var Jm=x(require("node:crypto"),1),Xm=x(require("node:path"),1);var J$=Ce,X$=[/\bnever\b/i,/\bcritical\b/i,/\bmust\s+not\b/i,/\bsecurity\b/i,/\bdangerous\b/i],Z$=100,Q$=.6;function eP(t){return X$.some(e=>e.test(t))}function tP(t){return`buried-critical-${Jm.createHash("sha1").update(`buried-critical:${t}`).digest("hex").slice(0,12)}`}function Bc(t){let e=[];for(let n of t){if(!J$.has(n.fileType))continue;let s=n.content.split(/\r?\n/);s.length>0&&s[s.length-1]===""&&s.pop();let i=s.length;if(i<=Z$)continue;let r=Math.floor(i/2),o=[],a=0,c=!1;for(let h=0;h<i;h++){let m=s[h]??"";if(/^\s*(```|~~~)/.test(m)){c=!c;continue}c||eP(m)&&(o.push(h+1),h>=r&&a++)}if(o.length===0)continue;let l=a/o.length;if(l<=Q$)continue;let u=Xm.basename(n.path),f=Math.round(l*100),d=o.filter(h=>h>r),p=s[(d[0]??o[0])-1]??"";e.push({id:tP(L(n)),severity:"info",category:"structure",title:"Critical instructions near the bottom of a long file",summary:`${f}% of the high-severity lines in "${u}" (${a} of ${o.length}) sit in the bottom half of a ${i}-line file. Models weight earlier context more heavily, so critical guidance placed late may be applied less reliably.`,filePaths:[n.path],locations:d.slice(0,5).map(h=>({filePath:n.path,startLine:h,endLine:h})),evidence:[`Keyword lines in bottom half: ${d.slice(0,8).join(", ")}`+(d.length>8?", \u2026":""),`e.g. line ${d[0]??o[0]}: "${Y(p,100)}"`],recommendation:'Promote the highest-stakes instructions (security rules, "never"/"must not" constraints) toward the top of the file, or add a short summary of them near the top that points to the detail below.',confidence:.5})}return e}var Zm=x(require("node:crypto"),1);var nP=Ce,sP=6,iP=.65,rP=40,oP=8;function aP(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+[.)]\s+/gm,"").replace(/\s+/g," ").trim()}function cP(t){return new Set(t.match(/\b\w+\b/g)??[])}function lP(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let s of t)e.has(s)&&n++;return n/(t.size+e.size-n)}function uP(t){let e=t.text.split(`
95
95
  `),n=[],s=[],i=t.startLine,r=0,o=()=>{if(s.length===0)return;r++;let a=s.join(`
96
- `);if(!a.includes("```")&&!a.includes("~~~")){let c=nP(a),l=sP(c);c.length>=eP&&l.size>=tP&&n.push({number:r,text:a,startLine:i,tokens:l})}s=[]};for(let a=0;a<e.length;a++){let c=e[a]??"";c.trim()===""?o():(s.length===0&&(i=t.startLine+a),s.push(c))}return o(),n}function oP(t,e){return`within-section-dup-${qm.createHash("sha1").update(`within-section-dup:${t}:${e}`).digest("hex").slice(0,12)}`}function Fc(t){let e=[];for(let n of t)if(X$.has(n.fileType))for(let s of n.sections){let i=rP(s);if(i.length<Z$)continue;let r=null,o=0;for(let u=0;u<i.length;u++)for(let f=u+1;f<i.length;f++){let d=iP(i[u].tokens,i[f].tokens);d>=Q$&&(o++,(!r||d>r.sim)&&(r={a:i[u],b:i[f],sim:d}))}if(!r)continue;let a=s.heading??"(untitled section)",c=Math.round(r.sim*100),l=o>1?` (${o} similar pairs in total)`:"";e.push({id:oP(L(n),s.startLine),severity:"info",category:"duplicate",title:`Possible repetition within section: ${a}`,summary:`Within "${a}", paragraphs ${r.a.number} and ${r.b.number} are about ${c}% similar${l}. The section may be restating the same point several ways \u2014 consider consolidating.`,filePaths:[n.path],locations:[{filePath:n.path,startLine:r.a.startLine,endLine:r.a.startLine},{filePath:n.path,startLine:r.b.startLine,endLine:r.b.startLine}],evidence:[`Paragraph ${r.a.number}: "${q(r.a.text,120)}"`,`Paragraph ${r.b.number}: "${q(r.b.text,120)}"`],recommendation:"Merge the near-duplicate paragraphs into one clear statement. If both are intentional (e.g. a summary and a detailed version), make the distinction explicit.",confidence:.5})}return e}var aP=t=>Ce.has(t),Cs=t=>Jd(t.files,t.aliasFiles,aP),Hc=[{id:"duplicates",run:t=>Qo(t.files)},{id:"duplicate-headings",run:t=>ea(t.files)},{id:"within-section-dedup",run:t=>Fc(Cs(t))},{id:"conflicts",run:t=>na(t.files)},{id:"version-conflicts",run:t=>sa(t.files)},{id:"competing-tech-conflicts",run:t=>ia(t.files)},{id:"context-bloat",run:t=>kh(t.files,{totalWarning:t.contextBudget,totalHigh:t.contextBudget?t.contextBudget*2:void 0,fileWarning:t.fileContextBudget,fileHigh:t.fileContextBudget?t.fileContextBudget*2.5:void 0},t.aliasFiles)},{id:"stale-instructions",run:t=>Oh(t.files)},{id:"command-validity",run:t=>Lp(t)},{id:"missing-context",run:t=>Ah(t.files,t.projectType)},{id:"manifest-consistency",run:t=>La(t)},{id:"dependency-staleness",run:t=>Xa({...t,files:Cs(t)})},{id:"vague-guidance",run:t=>Mh(t.files,{severityOverride:t.vagueGuidanceSeverity})},{id:"dead-references",run:t=>ha(t.files,t.repoRoot)},{id:"agent-practices",run:t=>ma(t.files,t.aliasFiles)},{id:"canonical-owner",run:t=>yh(t.files)},{id:"ci-alignment",run:t=>xh(t)},{id:"security-pack",run:t=>Dh(t)},{id:"action-pinning",run:t=>Za(t)},{id:"framework-packs",run:t=>Yh(t)},{id:"prompt-cache-friendliness",run:t=>Qh(Cs(t))},{id:"ai-config-skills",run:t=>uc(t)},{id:"skill-supply-chain",run:t=>kc(t)},{id:"ai-config-subagents",run:t=>Cc(t)},{id:"ai-config-hooks-settings",run:t=>Pc(t)},{id:"ai-config-mcp",run:t=>Tc(t)},{id:"ai-config-cursor-rules",run:t=>Ic(t)},{id:"ai-config-copilot-instructions",run:t=>Nc(t)},{id:"ai-config-windsurf-rules",run:t=>jc(t)},{id:"negative-instructions",run:t=>Mc(Cs(t))},{id:"buried-critical",run:t=>Dc(Cs(t))},{id:"custom-rules",run:t=>Ba(t.files,t.customRules,t.repoRoot)}];function Bc(t){return Hc.flatMap(e=>e.run(t))}async function Wc(t){let e=await fs(t),n=Hc.find(i=>i.id==="context-bloat"),s=n?n.run(e):[];return{generatedAt:new Date().toISOString(),repoPath:e.repoRoot,metrics:e.metrics,packageJson:{packageManagerName:e.packageJson.packageManagerName,packageManager:e.packageJson.packageManager,enginesNode:e.packageJson.enginesNode,lockfiles:e.packageJson.lockfiles,scriptNames:Object.keys(e.packageJson.scripts).sort(),dependencyCount:Object.keys(e.packageJson.dependencies).length+Object.keys(e.packageJson.devDependencies).length+Object.keys(e.packageJson.peerDependencies).length},workflows:e.workflows,issues:s}}var sn=x(require("node:path"),1);function cP(t,e,n){let s=(n.aiConfig?.allSkills??n.aiConfig?.skills??[]).map(l=>sn.dirname(sn.resolve(n.repoRoot,l))+sn.sep),i=e.filter(l=>!s.some(u=>sn.resolve(l.filePath).startsWith(u))),r=l=>l.tags?.[0]===bc,o=Ci(t.filter(l=>!r(l)),e),a=Ci(t.filter(r),i),c=new Set([...o.suppressed,...a.suppressed]);return{active:t.filter(l=>!c.has(l)),suppressed:t.filter(l=>c.has(l))}}async function Me(t){let e=await fs(t),n=Bc(e),s=[...e.files,...e.onDemandFiles],i=ga(s),r=[...n,...ya(i)],{active:o,suppressed:a}=cP(r,i,e),c=wa(o),l=va(o),u,f;if(t.baseline){let d=kn(o,t.baseline,e.repoRoot);u=d.newIssues,f=d.baselinedIssues}return{schemaVersion:"0.1",generatedAt:new Date().toISOString(),repoPath:e.repoRoot,projectType:e.projectType,healthScore:c,metrics:e.metrics,filesScanned:[...s,...(e.aliasFiles??[]).map(d=>({...d,content:"",sections:[],lineCount:0,charCount:0,estimatedTokens:0}))],issues:o,topFixes:l,newIssues:u,baselinedIssues:f,suppressedIssues:a.length>0?a:void 0}}var De=x(require("node:path"),1),Zi=x(require("node:fs/promises"),1);function Km(t,e){return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")).some(n=>Gi(n,e))}function As(t,e){let n=De.resolve(t),s=De.isAbsolute(e)?De.resolve(e):De.resolve(n,e);if(!se(n,s))throw new Error(`Path traversal detected: "${e}" is outside repo root "${n}"`);return s}async function Gc(t,e){let n=[];if(t.id==="security-pack-no-promptci-gitignore"){let s=As(e,".gitignore"),i="";try{i=await Zi.readFile(s,"utf-8")}catch{}if(!Km(i,".promptci")){let r=i.includes(`\r
96
+ `);if(!a.includes("```")&&!a.includes("~~~")){let c=aP(a),l=cP(c);c.length>=rP&&l.size>=oP&&n.push({number:r,text:a,startLine:i,tokens:l})}s=[]};for(let a=0;a<e.length;a++){let c=e[a]??"";c.trim()===""?o():(s.length===0&&(i=t.startLine+a),s.push(c))}return o(),n}function fP(t,e){return`within-section-dup-${Zm.createHash("sha1").update(`within-section-dup:${t}:${e}`).digest("hex").slice(0,12)}`}function Wc(t){let e=[];for(let n of t)if(nP.has(n.fileType))for(let s of n.sections){let i=uP(s);if(i.length<sP)continue;let r=null,o=0;for(let u=0;u<i.length;u++)for(let f=u+1;f<i.length;f++){let d=lP(i[u].tokens,i[f].tokens);d>=iP&&(o++,(!r||d>r.sim)&&(r={a:i[u],b:i[f],sim:d}))}if(!r)continue;let a=s.heading??"(untitled section)",c=Math.round(r.sim*100),l=o>1?` (${o} similar pairs in total)`:"";e.push({id:fP(L(n),s.startLine),severity:"info",category:"duplicate",title:`Possible repetition within section: ${a}`,summary:`Within "${a}", paragraphs ${r.a.number} and ${r.b.number} are about ${c}% similar${l}. The section may be restating the same point several ways \u2014 consider consolidating.`,filePaths:[n.path],locations:[{filePath:n.path,startLine:r.a.startLine,endLine:r.a.startLine},{filePath:n.path,startLine:r.b.startLine,endLine:r.b.startLine}],evidence:[`Paragraph ${r.a.number}: "${Y(r.a.text,120)}"`,`Paragraph ${r.b.number}: "${Y(r.b.text,120)}"`],recommendation:"Merge the near-duplicate paragraphs into one clear statement. If both are intentional (e.g. a summary and a detailed version), make the distinction explicit.",confidence:.5})}return e}var dP=t=>Ce.has(t),Cs=t=>tp(t.files,t.aliasFiles,dP),Gc=[{id:"duplicates",run:t=>ta(t.files)},{id:"duplicate-headings",run:t=>na(t.files)},{id:"within-section-dedup",run:t=>Wc(Cs(t))},{id:"conflicts",run:t=>ia(t.files)},{id:"version-conflicts",run:t=>ra(t.files)},{id:"competing-tech-conflicts",run:t=>oa(t.files)},{id:"context-bloat",run:t=>Ph(t.files,{totalWarning:t.contextBudget,totalHigh:t.contextBudget?t.contextBudget*2:void 0,fileWarning:t.fileContextBudget,fileHigh:t.fileContextBudget?t.fileContextBudget*2.5:void 0},t.aliasFiles)},{id:"stale-instructions",run:t=>Dh(t.files)},{id:"command-validity",run:t=>Fp(t)},{id:"missing-context",run:t=>Oh(t.files,t.projectType)},{id:"manifest-consistency",run:t=>Ma(t)},{id:"dependency-staleness",run:t=>ec({...t,files:Cs(t)})},{id:"vague-guidance",run:t=>Wh(t.files,{severityOverride:t.vagueGuidanceSeverity})},{id:"dead-references",run:t=>ya(t.files,t.repoRoot)},{id:"agent-practices",run:t=>ba(t.files,t.aliasFiles)},{id:"canonical-owner",run:t=>Sh(t.files)},{id:"ci-alignment",run:t=>Rh(t)},{id:"security-pack",run:t=>Gh(t)},{id:"action-pinning",run:t=>tc(t)},{id:"framework-packs",run:t=>em(t)},{id:"prompt-cache-friendliness",run:t=>im(Cs(t))},{id:"ai-config-skills",run:t=>pc(t)},{id:"skill-supply-chain",run:t=>Ac(t)},{id:"ai-config-subagents",run:t=>Pc(t)},{id:"ai-config-hooks-settings",run:t=>Oc(t)},{id:"ai-config-mcp",run:t=>Lc(t)},{id:"ai-config-cursor-rules",run:t=>Nc(t)},{id:"ai-config-copilot-instructions",run:t=>Dc(t)},{id:"ai-config-windsurf-rules",run:t=>Fc(t)},{id:"negative-instructions",run:t=>Hc(Cs(t))},{id:"buried-critical",run:t=>Bc(Cs(t))},{id:"custom-rules",run:t=>Ua(t.files,t.customRules,t.repoRoot)}];function Uc(t){return Gc.flatMap(e=>e.run(t))}async function Vc(t){let e=await fs(t),n=Gc.find(i=>i.id==="context-bloat"),s=n?n.run(e):[];return{generatedAt:new Date().toISOString(),repoPath:e.repoRoot,metrics:e.metrics,packageJson:{packageManagerName:e.packageJson.packageManagerName,packageManager:e.packageJson.packageManager,enginesNode:e.packageJson.enginesNode,lockfiles:e.packageJson.lockfiles,scriptNames:Object.keys(e.packageJson.scripts).sort(),dependencyCount:Object.keys(e.packageJson.dependencies).length+Object.keys(e.packageJson.devDependencies).length+Object.keys(e.packageJson.peerDependencies).length},workflows:e.workflows,issues:s}}var sn=x(require("node:path"),1);function pP(t,e,n){let s=(n.aiConfig?.allSkills??n.aiConfig?.skills??[]).map(l=>sn.dirname(sn.resolve(n.repoRoot,l))+sn.sep),i=e.filter(l=>!s.some(u=>sn.resolve(l.filePath).startsWith(u))),r=l=>l.tags?.[0]===xc,o=$i(t.filter(l=>!r(l)),e),a=$i(t.filter(r),i),c=new Set([...o.suppressed,...a.suppressed]);return{active:t.filter(l=>!c.has(l)),suppressed:t.filter(l=>c.has(l))}}async function Me(t){let e=await fs(t),n=Uc(e),s=[...e.files,...e.onDemandFiles],i=wa(s),r=[...n,...va(i)],{active:o,suppressed:a}=pP(r,i,e),c=Sa(o),l=_a(o),u,f;if(t.baseline){let d=kn(o,t.baseline,e.repoRoot);u=d.newIssues,f=d.baselinedIssues}return{schemaVersion:"0.1",generatedAt:new Date().toISOString(),repoPath:e.repoRoot,projectType:e.projectType,healthScore:c,metrics:e.metrics,filesScanned:[...s,...(e.aliasFiles??[]).map(d=>({...d,content:"",sections:[],lineCount:0,charCount:0,estimatedTokens:0}))],issues:o,topFixes:l,newIssues:u,baselinedIssues:f,suppressedIssues:a.length>0?a:void 0}}var De=x(require("node:path"),1),er=x(require("node:fs/promises"),1);function Qm(t,e){return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")).some(n=>Vi(n,e))}function As(t,e){let n=De.resolve(t),s=De.isAbsolute(e)?De.resolve(e):De.resolve(n,e);if(!X(n,s))throw new Error(`Path traversal detected: "${e}" is outside repo root "${n}"`);return s}async function zc(t,e){let n=[];if(t.id==="security-pack-no-promptci-gitignore"){let s=As(e,".gitignore"),i="";try{i=await er.readFile(s,"utf-8")}catch{}if(!Qm(i,".promptci")){let r=i.includes(`\r
97
97
  `)?`\r
98
98
  `:`
99
99
  `,o=ws(r),a=i.endsWith(`
100
- `)||i.endsWith("\r")?o:`${r}${o}`;n.push({filePath:s,originalContent:i,newContent:i+a})}return n}if(t.id==="security-pack-unignored-dirs"){let s=As(e,".gitignore"),i="";try{i=await Zi.readFile(s,"utf-8")}catch{}let r="",o=i.includes(`\r
100
+ `)||i.endsWith("\r")?o:`${r}${o}`;n.push({filePath:s,originalContent:i,newContent:i+a})}return n}if(t.id==="security-pack-unignored-dirs"){let s=As(e,".gitignore"),i="";try{i=await er.readFile(s,"utf-8")}catch{}let r="",o=i.includes(`\r
101
101
  `)?`\r
102
102
  `:`
103
- `;for(let a of t.evidence){let c=/Directory "([^"]+)" exists/.exec(a);if(c&&c[1]){let l=c[1];Km(i,l)||(r+=`${l}/${o}`)}}if(r){let a=i.endsWith(`
104
- `)||i.endsWith("\r")?r:`${o}${r}`;n.push({filePath:s,originalContent:i,newContent:i+a})}return n}if(t.id.startsWith("stale-")&&t.category==="stale_instruction")return n;if(t.category==="duplicate"&&t.locations.length>=2){let s=t.locations.find(a=>De.basename(a.filePath).toLowerCase()==="agents.md");s||(s=t.locations[0]);let i=As(e,s.filePath),r=De.basename(i),o=new Map;for(let a of t.locations){let c=As(e,a.filePath);if(c===i)continue;let l=o.get(c)??[];l.push(a),o.set(c,l)}for(let[a,c]of o){let l;try{l=await Zi.readFile(a,"utf-8")}catch{continue}let u=l.split(/\r?\n/),f=l.includes(`\r
103
+ `;for(let a of t.evidence){let c=/Directory "([^"]+)" exists/.exec(a);if(c&&c[1]){let l=c[1];Qm(i,l)||(r+=`${l}/${o}`)}}if(r){let a=i.endsWith(`
104
+ `)||i.endsWith("\r")?r:`${o}${r}`;n.push({filePath:s,originalContent:i,newContent:i+a})}return n}if(t.id.startsWith("stale-")&&t.category==="stale_instruction")return n;if(t.category==="duplicate"&&t.locations.length>=2){let s=t.locations.find(a=>De.basename(a.filePath).toLowerCase()==="agents.md");s||(s=t.locations[0]);let i=As(e,s.filePath),r=De.basename(i),o=new Map;for(let a of t.locations){let c=As(e,a.filePath);if(c===i)continue;let l=o.get(c)??[];l.push(a),o.set(c,l)}for(let[a,c]of o){let l;try{l=await er.readFile(a,"utf-8")}catch{continue}let u=l.split(/\r?\n/),f=l.includes(`\r
105
105
  `)?`\r
106
106
  `:`
107
- `,d=De.relative(De.dirname(a),i).replace(/\\/g,"/"),p=d.startsWith(".")?d:`./${d}`,h=`See canonical instructions in [${r}](${p}) for details.`,m=c.map(b=>({startIdx:(b.startLine??1)-1,endIdx:(b.endLine??u.length)-1})).sort((b,w)=>w.startIdx-b.startIdx),g=u;for(let{startIdx:b,endIdx:w}of m){let y=g.slice(b,w+1),k=y.length>0&&y[0].trim().startsWith("#")?b+1:b;g=[...g.slice(0,k),h,...g.slice(w+1)]}n.push({filePath:a,originalContent:l,newContent:g.join(f)})}}return n}function Uc(t){return t.autoApplySafe===!0}var Ie=x(require("node:path"),1),Qi=require("node:fs");var lP=[/\b(?:last\s+updated|last\s+modified|updated\s+at|modified\s+at|date)\b\s*:\s*\b\d{4}-\d{2}-\d{2}\b/i,/\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}\b/i,/\b(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b/i],uP=[/health\s+score\s*:\s*\d+/i,/files\s+scanned\s*:\s*\**\s*\d+/i,/^#{1,6}\s*promptci\s+health\s+report\s*$/im,/\bgenerated\s+by\s+\[?promptci\b/i],fP=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],dP=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i,pP=[...lP,...uP,...fP,dP],hP=/^\s*(?:[-*]\s+)?(?:last\s+)?(?:updated|modified|date|generated)\s*(?:at|on|date)?\s*:\s*(?:\d{4}-\d{2}-\d{2}|\b(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b|\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}\b)/i;function Ym(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mP(t,e){let n=e.replace(/\//g,"\\"),s=e.replace(/\\/g,"/"),i=t,r=Ym(n),o=new RegExp(r+`([^\\s"'\\)\\>]*)`,"gi");i=i.replace(o,(l,u)=>{let f=u.replace(/\\/g,"/");return"."+(f.startsWith("/")?f:"/"+f)});let a=Ym(s),c=new RegExp(a+`([^\\s"'\\)\\>]*)`,"gi");return i=i.replace(c,(l,u)=>{let f=u;return"."+(f.startsWith("/")?f:"/"+f)}),i}function gP(t){let n=t.split(/\r?\n/).filter(i=>!hP.test(i)),s=t.includes(`\r
107
+ `,d=De.relative(De.dirname(a),i).replace(/\\/g,"/"),p=d.startsWith(".")?d:`./${d}`,h=`See canonical instructions in [${r}](${p}) for details.`,m=c.map(b=>({startIdx:(b.startLine??1)-1,endIdx:(b.endLine??u.length)-1})).sort((b,w)=>w.startIdx-b.startIdx),g=u;for(let{startIdx:b,endIdx:w}of m){let y=g.slice(b,w+1),R=y.length>0&&y[0].trim().startsWith("#")?b+1:b;g=[...g.slice(0,R),h,...g.slice(w+1)]}n.push({filePath:a,originalContent:l,newContent:g.join(f)})}}return n}function qc(t){return t.autoApplySafe===!0}var Ie=x(require("node:path"),1),tr=require("node:fs");var hP=[/\b(?:last\s+updated|last\s+modified|updated\s+at|modified\s+at|date)\b\s*:\s*\b\d{4}-\d{2}-\d{2}\b/i,/\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}\b/i,/\b(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b/i],mP=[/health\s+score\s*:\s*\d+/i,/files\s+scanned\s*:\s*\**\s*\d+/i,/^#{1,6}\s*promptci\s+health\s+report\s*$/im,/\bgenerated\s+by\s+\[?promptci\b/i],gP=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],yP=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i,bP=[...hP,...mP,...gP,yP],wP=/^\s*(?:[-*]\s+)?(?:last\s+)?(?:updated|modified|date|generated)\s*(?:at|on|date)?\s*:\s*(?:\d{4}-\d{2}-\d{2}|\b(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2}(?:st|nd|rd|th)?,\s+\d{4}\b|\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}\b)/i;function eg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vP(t,e){let n=e.replace(/\//g,"\\"),s=e.replace(/\\/g,"/"),i=t,r=eg(n),o=new RegExp(r+`([^\\s"'\\)\\>]*)`,"gi");i=i.replace(o,(l,u)=>{let f=u.replace(/\\/g,"/");return"."+(f.startsWith("/")?f:"/"+f)});let a=eg(s),c=new RegExp(a+`([^\\s"'\\)\\>]*)`,"gi");return i=i.replace(c,(l,u)=>{let f=u;return"."+(f.startsWith("/")?f:"/"+f)}),i}function xP(t){let n=t.split(/\r?\n/).filter(i=>!wP.test(i)),s=t.includes(`\r
108
108
  `);return n.join(s?`\r
109
109
  `:`
110
- `)}function yP(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}async function Vc(t,e){let n=Ie.resolve(e.repoRoot),s=e.characterLimit??2e3,i=e.docsDir;i||((0,Qi.existsSync)(Ie.join(n,"Docs"))?i="Docs":(0,Qi.existsSync)(Ie.join(n,"docs"))?i="docs/ai":i="Docs");let r=Ie.resolve(n,i),o=new Set,a=[],c=t.filter(l=>Ce.has(l.fileType)&&l.fileType!=="persona");for(let l of c){let u=l.content,f=gP(u);f=mP(f,n);let d=Ut(f,l.path),p=[];for(let w of d){if(!w.heading)continue;let y=w.text.length>s,v=pP.some(k=>k.test(w.text));if(y||v){let k=yP(w.heading);k||(k="section");let R=`${k}.md`,I=1;for(;o.has(R.toLowerCase())||(0,Qi.existsSync)(Ie.join(r,R));)I++,R=`${k}-${I}.md`;o.add(R.toLowerCase());let C=Ie.join(r,R),N=Ie.relative(Ie.dirname(l.path),C).replace(/\\/g,"/");p.push({section:w,targetPath:C,relPath:N})}}if(p.length===0){f!==u&&a.push({filePath:l.path,originalContent:u,newContent:f});continue}let h=f.replace(/\r\n/g,`
110
+ `)}function SP(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}async function Kc(t,e){let n=Ie.resolve(e.repoRoot),s=e.characterLimit??2e3,i=e.docsDir;i||((0,tr.existsSync)(Ie.join(n,"Docs"))?i="Docs":(0,tr.existsSync)(Ie.join(n,"docs"))?i="docs/ai":i="Docs");let r=Ie.resolve(n,i),o=new Set,a=[],c=t.filter(l=>Ce.has(l.fileType)&&l.fileType!=="persona");for(let l of c){let u=l.content,f=xP(u);f=vP(f,n);let d=Vt(f,l.path),p=[];for(let w of d){if(!w.heading)continue;let y=w.text.length>s,v=bP.some(R=>R.test(w.text));if(y||v){let R=SP(w.heading);R||(R="section");let k=`${R}.md`,T=1;for(;o.has(k.toLowerCase())||(0,tr.existsSync)(Ie.join(r,k));)T++,k=`${R}-${T}.md`;o.add(k.toLowerCase());let C=Ie.join(r,k),N=Ie.relative(Ie.dirname(l.path),C).replace(/\\/g,"/");p.push({section:w,targetPath:C,relPath:N})}}if(p.length===0){f!==u&&a.push({filePath:l.path,originalContent:u,newContent:f});continue}let h=f.replace(/\r\n/g,`
111
111
  `).split(`
112
112
  `),g=f.includes(`\r
113
113
  `)?`\r
114
114
  `:`
115
- `;p.sort((w,y)=>y.section.startLine-w.section.startLine);for(let w of p){let{section:y,targetPath:v,relPath:k}=w,R=y.text,I=/^(#{1,3})\s+(.+)$/m.exec(R);if(I){let B=I[2];R=R.replace(/^(#{1,3})\s+(.+)$/m,`# ${B}`)}a.push({filePath:v,originalContent:"",newContent:R+g});let C=y.startLine-1,N=y.endLine-1,E=[h[C],"",`For details, see [${i}/${Ie.basename(v)}](${k}).`];h.splice(C,N-C+1,...E)}let b=h.join(g);b!==u&&a.push({filePath:l.path,originalContent:u,newContent:b})}return{changes:a}}var er=x(require("node:fs/promises"),1),On=x(require("node:path"),1);var Jm=On.join(".promptci","config.json"),Zm=["info","warning","high","critical"],Qm=js;function bP(t){return typeof t=="string"&&Zm.includes(t)}function wP(t){return typeof t=="string"&&Qm.includes(t)}function Xm(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}async function ke(t){let e=K(On.resolve(t),Jm);if(e===null){let o=On.join(On.resolve(t),Jm),a=!1;try{await er.lstat(o),a=!0}catch{}return a&&process.stderr.write(`Warning: ignoring ${o}: it resolves outside the scan path through a symlink, so its settings were not applied.
116
- `),{}}let n;try{n=await er.readFile(e,"utf-8")}catch{return{}}let s;try{s=JSON.parse(n)}catch{throw new Error("Failed to parse .promptci/config.json: invalid JSON")}if(typeof s!="object"||s===null||Array.isArray(s))throw new Error(".promptci/config.json must be a JSON object");let i=s,r={};if("include"in i){if(!Xm(i.include))throw new Error("config.include must be an array of strings");r.include=i.include}if("exclude"in i){if(!Xm(i.exclude))throw new Error("config.exclude must be an array of strings");r.exclude=i.exclude}if("severityThreshold"in i){if(!bP(i.severityThreshold))throw new Error(`config.severityThreshold must be one of: ${Zm.join(", ")}`);r.severityThreshold=i.severityThreshold}if("projectType"in i){if(!wP(i.projectType))throw new Error(`config.projectType must be one of: ${Qm.join(", ")}`);r.projectType=i.projectType}if("contextBudget"in i){if(typeof i.contextBudget!="number"||i.contextBudget<=0)throw new Error("config.contextBudget must be a positive number");r.contextBudget=i.contextBudget}if("fileContextBudget"in i){if(typeof i.fileContextBudget!="number"||i.fileContextBudget<=0)throw new Error("config.fileContextBudget must be a positive number");r.fileContextBudget=i.fileContextBudget}if("targetModel"in i){if(typeof i.targetModel!="string"||$n(i.targetModel)===void 0)throw new Error(`config.targetModel must be one of: ${as.join(", ")} (or a family alias like "claude"/"gpt"/"gemini")`);r.targetModel=i.targetModel}if("vagueGuidanceSeverity"in i){if(i.vagueGuidanceSeverity!=="info"&&i.vagueGuidanceSeverity!=="warning")throw new Error("config.vagueGuidanceSeverity must be one of: info, warning");r.vagueGuidanceSeverity=i.vagueGuidanceSeverity}return r}var tg=x(require("node:path"),1),vP={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},xP=["critical","high","warning","info"],_P={critical:3,high:2,warning:1,info:0};function eg(t){return _P[t]}function zc(t,e){return eg(t)>=eg(e)}function $s(t,e){return t.issues.some(n=>zc(n.severity,e))}function SP(t,e){let n=t-e;return n>0?` \x1B[32m(\u2191${n} vs last run)\x1B[0m`:n<0?` \x1B[31m(\u2193${Math.abs(n)} vs last run)\x1B[0m`:" \x1B[90m(= no change vs last run)\x1B[0m"}function ng(t,e={}){let{healthScore:n,issues:s,topFixes:i}=t,r={};for(let p of s)r[p.severity]=(r[p.severity]??0)+1;let o=xP.filter(p=>(r[p]??0)>0).map(p=>`${vP[p]} ${r[p]} ${p}`).join(" \xB7 "),a=e.previousEntry!=null?SP(n,e.previousEntry.healthScore):"",c=` Health score: ${n}/100`;if(t.trend){let p=t.trend,h=p.scoreDelta,m;h>0?m=`\x1B[32m(+${h} vs last scan)\x1B[0m`:h<0?m=`\x1B[31m(${h} vs last scan)\x1B[0m`:m="\x1B[90m(+0 vs last scan)\x1B[0m",c+=` ${m}; new issues: ${p.newIssuesCount}; resolved: ${p.resolvedIssuesCount}`}else e.previousEntry!=null&&(c+=a);let l=[];l.push(""),l.push("\u2714 Scan complete"),l.push(""),l.push(c),l.push(` Issues: ${o||"none"}`),t.trend&&t.trend.streak>0&&l.push(` Streak: ${t.trend.streak} scan(s) without high/critical issues`),t.newIssues!==void 0&&t.baselinedIssues!==void 0&&l.push(` Baseline: ${t.baselinedIssues.length} issues in baseline, ${t.newIssues.length} new issues.`);let u=t.suppressedIssues?.length??0;u>0&&l.push(` Suppressed: ${u} (see report for details)`),i.length>0&&(l.push(""),l.push(" Top fixes:"),i.forEach((p,h)=>{l.push(` ${h+1}. ${p.title}`)}));let f=p=>tg.relative(process.cwd(),p)||p,d=[];return e.mdPath&&d.push(` Markdown : ${f(e.mdPath)}`),e.jsonPath&&d.push(` JSON : ${f(e.jsonPath)}`),d.length>0&&(l.push(""),l.push(" Output:"),l.push(...d)),l.push(""),l.join(`
117
- `)}var qc=["info","warning","high","critical"];function tr(t){return qc.includes(t)}async function sg(t){let e=t.scanPath??process.cwd(),n=xt.resolve(e);try{(await jt.stat(n)).isDirectory()||(console.error(`Error: "${n}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${n}"`),process.exit(1)}let s;try{s=await ke(n)}catch(u){console.error(`Error: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}let i=t.targetModel??s.targetModel;i!==void 0&&$n(i)===void 0&&(console.error(`Error: invalid --target-model value "${i}". Must be one of: ${as.join(", ")} (or a family alias like "claude"/"gpt"/"gemini").`),process.exit(1));let r=t.failOn??s.severityThreshold;r!==void 0&&!tr(r)&&(console.error(`Error: invalid --fail-on value "${r}". Must be one of: ${qc.join(", ")}`),process.exit(1)),t.failOnNew!==void 0&&!tr(t.failOnNew)&&(console.error(`Error: invalid --fail-on-new value "${t.failOnNew}". Must be one of: ${qc.join(", ")}`),process.exit(1)),t.failOnNew&&!t.baseline&&(console.error('Error: --fail-on-new requires a baseline to compare against. Pass --baseline <path> (e.g. --baseline .promptci/baseline.json), or create one first with "promptci scan --update-baseline".'),process.exit(1));let o;if(t.baseline){let u=xt.resolve(n,t.baseline);se(n,u)&&K(n,u)===null&&(console.error(`Error: baseline file "${u}" is a symlink that resolves outside the scan path; refusing to read it.`),process.exit(1));try{let f=await jt.readFile(u,"utf-8"),d;try{d=JSON.parse(f)}catch(p){console.error(`Error: baseline file "${u}" contains invalid JSON: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}try{xa(d),o=d}catch(p){console.error(`Error: baseline file "${u}" has an unexpected format: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}}catch(f){f.code!=="ENOENT"&&(console.error(`Error loading baseline: ${f instanceof Error?f.message:String(f)}`),process.exit(1)),o=[]}}let a=await Me({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,baseline:o,contextBudget:t.contextBudget??s.contextBudget,fileContextBudget:t.fileContextBudget??s.fileContextBudget,targetModel:i,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),c=t.output?await $i(a,{mdPath:xt.resolve(t.output),archive:!1}):await $i(a);if(t.updateBaseline){let u=En(a.issues,n),f=t.baseline?xt.resolve(n,t.baseline):xt.join(n,".promptci","baseline.json");zn(n,f)||(console.error(`Error: baseline file "${f}" resolves outside the scan path through a symlink; refusing to write it.`),process.exit(1)),await jt.mkdir(xt.dirname(f),{recursive:!0}),await jt.writeFile(f,JSON.stringify(u,null,2)),t.json||console.log(`
118
- Baseline updated: ${f}`)}if(t.json?process.stdout.write(Ai(a)+`
119
- `):process.stdout.write(ng(a,{mdPath:c.mdPath,jsonPath:c.jsonPath,previousEntry:c.archivedEntry})),r&&$s(a,r)){let u=a.issues.filter(d=>tr(d.severity)&&$s({...a,issues:[d]},r)).length,f=t.failOn!==void 0?"from --fail-on":"from severityThreshold in .promptci/config.json";console.error(`
115
+ `;p.sort((w,y)=>y.section.startLine-w.section.startLine);for(let w of p){let{section:y,targetPath:v,relPath:R}=w,k=y.text,T=/^(#{1,3})\s+(.+)$/m.exec(k);if(T){let W=T[2];k=k.replace(/^(#{1,3})\s+(.+)$/m,`# ${W}`)}a.push({filePath:v,originalContent:"",newContent:k+g});let C=y.startLine-1,N=y.endLine-1,E=[h[C],"",`For details, see [${i}/${Ie.basename(v)}](${R}).`];h.splice(C,N-C+1,...E)}let b=h.join(g);b!==u&&a.push({filePath:l.path,originalContent:u,newContent:b})}return{changes:a}}var nr=x(require("node:fs/promises"),1),On=x(require("node:path"),1);var tg=On.join(".promptci","config.json"),sg=["info","warning","high","critical"],ig=js;function _P(t){return typeof t=="string"&&sg.includes(t)}function EP(t){return typeof t=="string"&&ig.includes(t)}function ng(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}async function ke(t){let e=J(On.resolve(t),tg);if(e===null){let o=On.join(On.resolve(t),tg),a=!1;try{await nr.lstat(o),a=!0}catch{}return a&&process.stderr.write(`Warning: ignoring ${o}: it resolves outside the scan path through a symlink, so its settings were not applied.
116
+ `),{}}let n;try{n=await nr.readFile(e,"utf-8")}catch{return{}}let s;try{s=JSON.parse(n)}catch{throw new Error("Failed to parse .promptci/config.json: invalid JSON")}if(typeof s!="object"||s===null||Array.isArray(s))throw new Error(".promptci/config.json must be a JSON object");let i=s,r={};if("include"in i){if(!ng(i.include))throw new Error("config.include must be an array of strings");r.include=i.include}if("exclude"in i){if(!ng(i.exclude))throw new Error("config.exclude must be an array of strings");r.exclude=i.exclude}if("severityThreshold"in i){if(!_P(i.severityThreshold))throw new Error(`config.severityThreshold must be one of: ${sg.join(", ")}`);r.severityThreshold=i.severityThreshold}if("projectType"in i){if(!EP(i.projectType))throw new Error(`config.projectType must be one of: ${ig.join(", ")}`);r.projectType=i.projectType}if("contextBudget"in i){if(typeof i.contextBudget!="number"||i.contextBudget<=0)throw new Error("config.contextBudget must be a positive number");r.contextBudget=i.contextBudget}if("fileContextBudget"in i){if(typeof i.fileContextBudget!="number"||i.fileContextBudget<=0)throw new Error("config.fileContextBudget must be a positive number");r.fileContextBudget=i.fileContextBudget}if("targetModel"in i){if(typeof i.targetModel!="string"||$n(i.targetModel)===void 0)throw new Error(`config.targetModel must be one of: ${as.join(", ")} (or a family alias like "claude"/"gpt"/"gemini")`);r.targetModel=i.targetModel}if("vagueGuidanceSeverity"in i){if(i.vagueGuidanceSeverity!=="info"&&i.vagueGuidanceSeverity!=="warning")throw new Error("config.vagueGuidanceSeverity must be one of: info, warning");r.vagueGuidanceSeverity=i.vagueGuidanceSeverity}return r}var og=x(require("node:path"),1),kP={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},RP=["critical","high","warning","info"],CP={critical:3,high:2,warning:1,info:0};function rg(t){return CP[t]}function Yc(t,e){return rg(t)>=rg(e)}function $s(t,e){return t.issues.some(n=>Yc(n.severity,e))}function AP(t,e){let n=t-e;return n>0?` \x1B[32m(\u2191${n} vs last run)\x1B[0m`:n<0?` \x1B[31m(\u2193${Math.abs(n)} vs last run)\x1B[0m`:" \x1B[90m(= no change vs last run)\x1B[0m"}function ag(t,e={}){let{healthScore:n,issues:s,topFixes:i}=t,r={};for(let p of s)r[p.severity]=(r[p.severity]??0)+1;let o=RP.filter(p=>(r[p]??0)>0).map(p=>`${kP[p]} ${r[p]} ${p}`).join(" \xB7 "),a=e.previousEntry!=null?AP(n,e.previousEntry.healthScore):"",c=` Health score: ${n}/100`;if(t.trend){let p=t.trend,h=p.scoreDelta,m;h>0?m=`\x1B[32m(+${h} vs last scan)\x1B[0m`:h<0?m=`\x1B[31m(${h} vs last scan)\x1B[0m`:m="\x1B[90m(+0 vs last scan)\x1B[0m",c+=` ${m}; new issues: ${p.newIssuesCount}; resolved: ${p.resolvedIssuesCount}`}else e.previousEntry!=null&&(c+=a);let l=[];l.push(""),l.push("\u2714 Scan complete"),l.push(""),l.push(c),l.push(` Issues: ${o||"none"}`),t.trend&&t.trend.streak>0&&l.push(` Streak: ${t.trend.streak} scan(s) without high/critical issues`),t.newIssues!==void 0&&t.baselinedIssues!==void 0&&l.push(` Baseline: ${t.baselinedIssues.length} issues in baseline, ${t.newIssues.length} new issues.`);let u=t.suppressedIssues?.length??0;u>0&&l.push(` Suppressed: ${u} (see report for details)`),i.length>0&&(l.push(""),l.push(" Top fixes:"),i.forEach((p,h)=>{l.push(` ${h+1}. ${p.title}`)}));let f=p=>og.relative(process.cwd(),p)||p,d=[];return e.mdPath&&d.push(` Markdown : ${f(e.mdPath)}`),e.jsonPath&&d.push(` JSON : ${f(e.jsonPath)}`),d.length>0&&(l.push(""),l.push(" Output:"),l.push(...d)),l.push(""),l.join(`
117
+ `)}var Jc=["info","warning","high","critical"];function sr(t){return Jc.includes(t)}async function cg(t){let e=t.scanPath??process.cwd(),n=xt.resolve(e);try{(await Mt.stat(n)).isDirectory()||(console.error(`Error: "${n}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${n}"`),process.exit(1)}let s;try{s=await ke(n)}catch(u){console.error(`Error: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}let i=t.targetModel??s.targetModel;i!==void 0&&$n(i)===void 0&&(console.error(`Error: invalid --target-model value "${i}". Must be one of: ${as.join(", ")} (or a family alias like "claude"/"gpt"/"gemini").`),process.exit(1));let r=t.failOn??s.severityThreshold;r!==void 0&&!sr(r)&&(console.error(`Error: invalid --fail-on value "${r}". Must be one of: ${Jc.join(", ")}`),process.exit(1)),t.failOnNew!==void 0&&!sr(t.failOnNew)&&(console.error(`Error: invalid --fail-on-new value "${t.failOnNew}". Must be one of: ${Jc.join(", ")}`),process.exit(1)),t.failOnNew&&!t.baseline&&(console.error('Error: --fail-on-new requires a baseline to compare against. Pass --baseline <path> (e.g. --baseline .promptci/baseline.json), or create one first with "promptci scan --update-baseline".'),process.exit(1));let o;if(t.baseline){let u=xt.resolve(n,t.baseline);X(n,u)&&J(n,u)===null&&(console.error(`Error: baseline file "${u}" is a symlink that resolves outside the scan path; refusing to read it.`),process.exit(1));try{let f=await Mt.readFile(u,"utf-8"),d;try{d=JSON.parse(f)}catch(p){console.error(`Error: baseline file "${u}" contains invalid JSON: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}try{Ea(d),o=d}catch(p){console.error(`Error: baseline file "${u}" has an unexpected format: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}}catch(f){f.code!=="ENOENT"&&(console.error(`Error loading baseline: ${f instanceof Error?f.message:String(f)}`),process.exit(1)),o=[]}}let a=await Me({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,baseline:o,contextBudget:t.contextBudget??s.contextBudget,fileContextBudget:t.fileContextBudget??s.fileContextBudget,targetModel:i,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),c=t.output?await Ti(a,{mdPath:xt.resolve(t.output),archive:!1}):await Ti(a);if(t.updateBaseline){let u=En(a.issues,n),f=t.baseline?xt.resolve(n,t.baseline):xt.join(n,".promptci","baseline.json");zn(n,f)||(console.error(`Error: baseline file "${f}" resolves outside the scan path through a symlink; refusing to write it.`),process.exit(1)),await Mt.mkdir(xt.dirname(f),{recursive:!0}),await Mt.writeFile(f,JSON.stringify(u,null,2)),t.json||console.log(`
118
+ Baseline updated: ${f}`)}if(t.json?process.stdout.write(Pi(a)+`
119
+ `):process.stdout.write(ag(a,{mdPath:c.mdPath,jsonPath:c.jsonPath,previousEntry:c.archivedEntry})),r&&$s(a,r)){let u=a.issues.filter(d=>sr(d.severity)&&$s({...a,issues:[d]},r)).length,f=t.failOn!==void 0?"from --fail-on":"from severityThreshold in .promptci/config.json";console.error(`
120
120
  Failed: ${u} issue(s) at or above the "${r}" threshold (${f}). See ${c.mdPath} for details.
121
- Raise the gate with --fail-on <severity> or edit severityThreshold to only fail on higher severities.`),process.exit(1)}let l=t.failOnNew;if(l){let u=a.newIssues??[];if($s({...a,issues:u},l)){let f=u.filter(d=>tr(d.severity)&&$s({...a,issues:[d]},l)).length;console.error(`
121
+ Raise the gate with --fail-on <severity> or edit severityThreshold to only fail on higher severities.`),process.exit(1)}let l=t.failOnNew;if(l){let u=a.newIssues??[];if($s({...a,issues:u},l)){let f=u.filter(d=>sr(d.severity)&&$s({...a,issues:[d]},l)).length;console.error(`
122
122
  Failed: ${f} NEW issue(s) at or above "${l}" threshold. See ${c.mdPath} for details.`),process.exit(1)}}if(t.failOnBudget){let u=a.issues.filter(f=>f.category==="context_bloat");u.length>0&&(console.error(`
123
- Failed: ${u.length} context bloat issue(s) found and --fail-on-budget is enabled. See ${c.mdPath} for details.`),process.exit(1))}}var og=x(require("node:fs/promises"),1),Mt=x(require("node:path"),1);var EP=3,ig={critical:3,high:2,warning:1,info:0};function kP(t,e=EP){return[...t].sort((n,s)=>ig[s.severity]-ig[n.severity]||s.confidence-n.confidence||n.id.localeCompare(s.id)).slice(0,e)}var RP=/[\u0000-\u001f\u007f-\u009f]/g,Kc=t=>t.replace(RP," ").replace(/\s+/g," ").trim(),rg=160,CP=t=>{let e=Kc(t);return e.length>rg?`${e.slice(0,rg-1).trimEnd()}\u2026`:e};function AP(t,e){let n=t.locations[0],s=n?.filePath??t.filePaths[0];if(!s)return;let r=((Mt.isAbsolute(s)?Mt.relative(e,s):s)||s).split(Mt.sep).join("/");return n?.startLine!==void 0?`${r}:${n.startLine}`:r}function $P(t){let e=[""];if(t.filesScanned.length===0)return e.push("No instruction files found, so there is nothing to score."),e.push(""),e.join(`
124
- `);let n=t.issues.length;if(e.push(`PromptCI instruction health: ${t.healthScore}/100 (${Rn(t.healthScore)})`),n===0)e.push("No findings. Nice.");else{let s=kP(t.issues);e.push(""),e.push(`Top ${s.length} finding${s.length===1?"":"s"} (of ${n}):`),s.forEach((i,r)=>{let o=AP(i,t.repoPath);e.push(` ${r+1}. [${i.severity}] ${Kc(i.title)}${o?` (${Kc(o)})`:""}`),e.push(` Fix: ${CP(i.recommendation)}`)})}return e.push(""),e.join(`
125
- `)}async function ag(t){let e=Mt.resolve(t.scanPath??process.cwd());try{(await og.stat(e)).isDirectory()||(console.error(`Error: "${e}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${e}"`),process.exit(1)}let n;try{n=await ke(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Me({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude,contextBudget:n.contextBudget,fileContextBudget:n.fileContextBudget,targetModel:n.targetModel,vagueGuidanceSeverity:n.vagueGuidanceSeverity});process.stdout.write($P(s))}var Re=x(require("node:fs/promises"),1),rn=x(require("node:path"),1),ug=x(require("node:readline"),1);var Ps=js.filter(t=>t!=="auto"),cg={severityThreshold:"high",projectType:"auto"},lg={nextjs:"# Developer Instructions\n\n## Project Type\nNext.js & TypeScript\n\n## Project Rules\n- **App Router**: Follow the App Router conventions. Place pages in `app/page.tsx` and layout in `app/layout.tsx`.\n- **React Components**: \n - Use React Server Components (RSC) by default.\n - Only add the `'use client'` directive at the top of a file when using client-side state, event handlers, or React hooks (e.g. `useState`, `useEffect`).\n- **State Constraints**: Prefer local component state, React Context, or lightweight state managers. Ensure server and client state boundaries are clean.\n- **TypeScript**:\n - Enforce strict typing. Do not use `any` unless absolutely necessary.\n - Export types/interfaces properly.\n\n## Security Rules\n- **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.\n- **Input Validation**: Sanitize and validate all external parameters to prevent injection.\n\n## Commands & Scripts\n- Run local development server: `pnpm dev` (or `npm run dev` / `yarn dev`)\n- Run typecheck: `pnpm typecheck` (or `npm run typecheck`)\n- Run linting: `pnpm lint` (or `npm run lint`)\n- Run tests: `pnpm test` (or `npm run test` using Vitest)\n- Build for production: `pnpm build` (or `npm run build`)\n\n## Verification Loop\nBefore declaring a task done, follow these verification steps:\n1. Run `pnpm typecheck` to verify TypeScript type-safety.\n2. Run `pnpm lint` to check for code style issues.\n3. Run `pnpm test` to verify all tests pass.\n4. Run `pnpm build` to ensure production bundle compiles successfully.\n",typescript:`# Developer Instructions
123
+ Failed: ${u.length} context bloat issue(s) found and --fail-on-budget is enabled. See ${c.mdPath} for details.`),process.exit(1))}}var fg=x(require("node:fs/promises"),1),Dt=x(require("node:path"),1);var $P=3,lg={critical:3,high:2,warning:1,info:0};function PP(t,e=$P){return[...t].sort((n,s)=>lg[s.severity]-lg[n.severity]||s.confidence-n.confidence||n.id.localeCompare(s.id)).slice(0,e)}var TP=/[\u0000-\u001f\u007f-\u009f]/g,Xc=t=>t.replace(TP," ").replace(/\s+/g," ").trim(),ug=160,IP=t=>{let e=Xc(t);return e.length>ug?`${e.slice(0,ug-1).trimEnd()}\u2026`:e};function OP(t,e){let n=t.locations[0],s=n?.filePath??t.filePaths[0];if(!s)return;let r=((Dt.isAbsolute(s)?Dt.relative(e,s):s)||s).split(Dt.sep).join("/");return n?.startLine!==void 0?`${r}:${n.startLine}`:r}function LP(t){let e=[""];if(t.filesScanned.length===0)return e.push("No instruction files found, so there is nothing to score."),e.push(""),e.join(`
124
+ `);let n=t.issues.length;if(e.push(`PromptCI instruction health: ${t.healthScore}/100 (${Rn(t.healthScore)})`),n===0)e.push("No findings. Nice.");else{let s=PP(t.issues);e.push(""),e.push(`Top ${s.length} finding${s.length===1?"":"s"} (of ${n}):`),s.forEach((i,r)=>{let o=OP(i,t.repoPath);e.push(` ${r+1}. [${i.severity}] ${Xc(i.title)}${o?` (${Xc(o)})`:""}`),e.push(` Fix: ${IP(i.recommendation)}`)})}return e.push(""),e.join(`
125
+ `)}async function dg(t){let e=Dt.resolve(t.scanPath??process.cwd());try{(await fg.stat(e)).isDirectory()||(console.error(`Error: "${e}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${e}"`),process.exit(1)}let n;try{n=await ke(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Me({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude,contextBudget:n.contextBudget,fileContextBudget:n.fileContextBudget,targetModel:n.targetModel,vagueGuidanceSeverity:n.vagueGuidanceSeverity});process.stdout.write(LP(s))}var Re=x(require("node:fs/promises"),1),rn=x(require("node:path"),1),mg=x(require("node:readline"),1);var Ps=js.filter(t=>t!=="auto"),pg={severityThreshold:"high",projectType:"auto"},hg={nextjs:"# Developer Instructions\n\n## Project Type\nNext.js & TypeScript\n\n## Project Rules\n- **App Router**: Follow the App Router conventions. Place pages in `app/page.tsx` and layout in `app/layout.tsx`.\n- **React Components**: \n - Use React Server Components (RSC) by default.\n - Only add the `'use client'` directive at the top of a file when using client-side state, event handlers, or React hooks (e.g. `useState`, `useEffect`).\n- **State Constraints**: Prefer local component state, React Context, or lightweight state managers. Ensure server and client state boundaries are clean.\n- **TypeScript**:\n - Enforce strict typing. Do not use `any` unless absolutely necessary.\n - Export types/interfaces properly.\n\n## Security Rules\n- **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.\n- **Input Validation**: Sanitize and validate all external parameters to prevent injection.\n\n## Commands & Scripts\n- Run local development server: `pnpm dev` (or `npm run dev` / `yarn dev`)\n- Run typecheck: `pnpm typecheck` (or `npm run typecheck`)\n- Run linting: `pnpm lint` (or `npm run lint`)\n- Run tests: `pnpm test` (or `npm run test` using Vitest)\n- Build for production: `pnpm build` (or `npm run build`)\n\n## Verification Loop\nBefore declaring a task done, follow these verification steps:\n1. Run `pnpm typecheck` to verify TypeScript type-safety.\n2. Run `pnpm lint` to check for code style issues.\n3. Run `pnpm test` to verify all tests pass.\n4. Run `pnpm build` to ensure production bundle compiles successfully.\n",typescript:`# Developer Instructions
126
126
 
127
127
  ## Project Type
128
128
  TypeScript (General)
@@ -270,57 +270,57 @@ Before finalizing any changes, perform these steps:
270
270
  ## Commands & Scripts
271
271
  - Locate any setup, build, and test scripts in the root directory (e.g. \`Makefile\`, \`package.json\`, or shell scripts).
272
272
  - Run validation commands before considering a task completed.
273
- `};function nr(t,e){let n=rn.resolve(t),s=rn.resolve(n,e);if(!se(n,s))throw new Error(`Path escapes target directory: ${e}`);return s}async function Yc(t){try{return await Re.access(t),!0}catch{return!1}}async function fg(t,e){let n=nr(t,".promptci"),s=rn.join(n,"config.json");await Re.mkdir(n,{recursive:!0});let i=e?.interactive??!1,r=0,o=u=>{if(e?.answers&&r<e.answers.length){let d=e.answers[r];return r++,console.log(`${u}${d}`),Promise.resolve(d)}let f=ug.createInterface({input:process.stdin,output:process.stdout});return new Promise(d=>{f.question(u,p=>{f.close(),d(p.trim())})})},a="auto",c=await Yn(t);if(i){let u=await o(`We detected this is a ${c} repository. Confirm? (Y/n): `);if(u===""||u.toLowerCase()==="y"||u.toLowerCase()==="yes")a=c;else{let m=!1,g=0;for(;!m&&g<5;){g++;let b=Ps.map((v,k)=>`${k+1}: ${v}`).join(`
273
+ `};function ir(t,e){let n=rn.resolve(t),s=rn.resolve(n,e);if(!X(n,s))throw new Error(`Path escapes target directory: ${e}`);return s}async function Zc(t){try{return await Re.access(t),!0}catch{return!1}}async function gg(t,e){let n=ir(t,".promptci"),s=rn.join(n,"config.json");await Re.mkdir(n,{recursive:!0});let i=e?.interactive??!1,r=0,o=u=>{if(e?.answers&&r<e.answers.length){let d=e.answers[r];return r++,console.log(`${u}${d}`),Promise.resolve(d)}let f=mg.createInterface({input:process.stdin,output:process.stdout});return new Promise(d=>{f.question(u,p=>{f.close(),d(p.trim())})})},a="auto",c=await Yn(t);if(i){let u=await o(`We detected this is a ${c} repository. Confirm? (Y/n): `);if(u===""||u.toLowerCase()==="y"||u.toLowerCase()==="yes")a=c;else{let m=!1,g=0;for(;!m&&g<5;){g++;let b=Ps.map((v,R)=>`${R+1}: ${v}`).join(`
274
274
  `),w=await o(`Select project type:
275
275
  ${b}
276
- Enter choice (1-${Ps.length} or name): `),y=parseInt(w,10);if(y>=1&&y<=Ps.length)a=Ps[y-1],m=!0;else{let v=w.toLowerCase().trim();Ps.includes(v)?(a=v,m=!0):console.log("Invalid selection. Please try again.")}}m||(console.log("No valid selection received. Defaulting to project type: auto"),a="auto")}let d=!1;try{await Re.access(s),d=!0,console.log(`Config already exists: ${s}`)}catch{}if(!d){let m={...cg,projectType:a};await Re.writeFile(s,JSON.stringify(m,null,2)+`
277
- `,"utf-8"),console.log(`Created ${s}`)}let p=["AGENTS.md",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"],h=!1;for(let m of p){let g=nr(t,m);if(await Yc(g)){h=!0;break}}if(!h){let m=await o("We did not find any AI instruction files. Would you like to generate a starter template? (Y/n): ");if(m===""||m.toLowerCase()==="y"||m.toLowerCase()==="yes"){let b,w=0;for(;!b&&w<5;){w++;let y=await o(`Which file type would you like to create?
276
+ Enter choice (1-${Ps.length} or name): `),y=parseInt(w,10);if(y>=1&&y<=Ps.length)a=Ps[y-1],m=!0;else{let v=w.toLowerCase().trim();Ps.includes(v)?(a=v,m=!0):console.log("Invalid selection. Please try again.")}}m||(console.log("No valid selection received. Defaulting to project type: auto"),a="auto")}let d=!1;try{await Re.access(s),d=!0,console.log(`Config already exists: ${s}`)}catch{}if(!d){let m={...pg,projectType:a};await Re.writeFile(s,JSON.stringify(m,null,2)+`
277
+ `,"utf-8"),console.log(`Created ${s}`)}let p=["AGENTS.md",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"],h=!1;for(let m of p){let g=ir(t,m);if(await Zc(g)){h=!0;break}}if(!h){let m=await o("We did not find any AI instruction files. Would you like to generate a starter template? (Y/n): ");if(m===""||m.toLowerCase()==="y"||m.toLowerCase()==="yes"){let b,w=0;for(;!b&&w<5;){w++;let y=await o(`Which file type would you like to create?
278
278
  1: AGENTS.md (Recommended for monorepos & multi-agent instructions)
279
279
  2: .cursorrules (For Cursor users)
280
280
  3: CLAUDE.md (For Cline/Claude-dev users)
281
- Enter choice (1-3 or name): `);y==="1"||y.toLowerCase()==="agents.md"||y.toLowerCase()==="agents"?b="AGENTS.md":y==="2"||y.toLowerCase()===".cursorrules"||y.toLowerCase()==="cursorrules"?b=".cursorrules":y==="3"||y.toLowerCase()==="claude.md"||y.toLowerCase()==="claude"?b="CLAUDE.md":console.log("Invalid selection. Please try again.")}if(b){let y=nr(t,b);if(await Yc(y))console.log(`Safety Warning: File already exists: ${y}. Skip writing.`);else{let v=lg[a]||lg.unknown;await Re.mkdir(rn.dirname(y),{recursive:!0}),await Re.writeFile(y,v,"utf-8"),console.log(`Created starter template: ${y}`)}}else console.log("No valid template selection received. Skipping template generation.")}}}else{try{await Re.access(s),console.log(`Config already exists: ${s}`),console.log("Remove it first if you want to reinitialize.");return}catch{}await Re.writeFile(s,JSON.stringify(cg,null,2)+`
282
- `,"utf-8"),console.log(`Created ${s}`),console.log("Edit it to set include/exclude patterns, severityThreshold, and projectType.")}let l=nr(t,".gitignore");if(await Yc(l)){let u=await Re.readFile(l,"utf-8");if(!u.split(/\r?\n/).some(p=>{let h=p.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return h===".promptci"||h.startsWith(".promptci/")||h.endsWith("/.promptci")||h.includes("/.promptci/")})){let p;if(i){let h=await o("Ignore .promptci/ reports in .gitignore (keeping baseline.json and config.json committed)? (recommended) [Y/n]: ");p=h===""||h.toLowerCase()==="y"||h.toLowerCase()==="yes"}else p=!0;if(p){let h=u.includes(`\r
281
+ Enter choice (1-3 or name): `);y==="1"||y.toLowerCase()==="agents.md"||y.toLowerCase()==="agents"?b="AGENTS.md":y==="2"||y.toLowerCase()===".cursorrules"||y.toLowerCase()==="cursorrules"?b=".cursorrules":y==="3"||y.toLowerCase()==="claude.md"||y.toLowerCase()==="claude"?b="CLAUDE.md":console.log("Invalid selection. Please try again.")}if(b){let y=ir(t,b);if(await Zc(y))console.log(`Safety Warning: File already exists: ${y}. Skip writing.`);else{let v=hg[a]||hg.unknown;await Re.mkdir(rn.dirname(y),{recursive:!0}),await Re.writeFile(y,v,"utf-8"),console.log(`Created starter template: ${y}`)}}else console.log("No valid template selection received. Skipping template generation.")}}}else{try{await Re.access(s),console.log(`Config already exists: ${s}`),console.log("Remove it first if you want to reinitialize.");return}catch{}await Re.writeFile(s,JSON.stringify(pg,null,2)+`
282
+ `,"utf-8"),console.log(`Created ${s}`),console.log("Edit it to set include/exclude patterns, severityThreshold, and projectType.")}let l=ir(t,".gitignore");if(await Zc(l)){let u=await Re.readFile(l,"utf-8");if(!u.split(/\r?\n/).some(p=>{let h=p.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return h===".promptci"||h.startsWith(".promptci/")||h.endsWith("/.promptci")||h.includes("/.promptci/")})){let p;if(i){let h=await o("Ignore .promptci/ reports in .gitignore (keeping baseline.json and config.json committed)? (recommended) [Y/n]: ");p=h===""||h.toLowerCase()==="y"||h.toLowerCase()==="yes"}else p=!0;if(p){let h=u.includes(`\r
283
283
  `)?`\r
284
284
  `:`
285
285
  `,g=`${u.length>0&&!u.endsWith(`
286
- `)?h:""}${ws(h)}`;await Re.appendFile(l,g,"utf-8"),console.log("\u2714 Added .promptci/ report ignore to .gitignore (baseline.json and config.json stay committed)")}}}}var hg=x(require("node:fs/promises"),1),Jc=x(require("node:path"),1);var sr=x(require("node:fs/promises"),1),ft=x(require("node:path"),1),pg=x(require("node:readline/promises"),1);var on=class extends Error{constructor(e){super(e),this.name="NonInteractiveError"}},dg="=".repeat(80),PP="-".repeat(80);async function ir(t,e){let n=e.log??((h="")=>console.log(h)),s=e.interactive!==!1,i=e.promptText??`
287
- Apply this change? (y/N): `,r=!e.dryRun&&s&&!e.answers?pg.createInterface({input:e.input??process.stdin,output:process.stdout}):null,o=[],a=null,c=!1;r&&(r.on("line",h=>{if(a){let m=a;a=null,m(h)}else o.push(h)}),r.on("close",()=>{if(c=!0,a){let h=a;a=null,h(null)}}));function l(h){return process.stdout.write(h),o.length>0?Promise.resolve(o.shift()):c?Promise.resolve(null):new Promise(m=>{a=m})}let u=0,f=0,d=0,p=new Set;try{for(let h of t){let m=(h.skipIfModified??[]).map(v=>ft.resolve(e.repoRoot,v)).filter(v=>p.has(v));if(m.length>0){n(`
288
- `+dg);for(let k of h.headerLines??[])n(k);let v=m.map(k=>ft.relative(e.repoRoot,k)).join(", ");n(`Skipped: ${v} changed earlier in this run, so this fix's line numbers may be stale. Re-run the command to apply it against the updated file.`),f++;continue}let g=typeof h.changes=="function"?await h.changes():h.changes,b=TP(g);if(b.length===0)continue;n(`
289
- `+dg);let w=h.headerLines??[];for(let v of w)n(v);w.length>0&&n(PP);for(let v of b)IP(v,e.repoRoot,n);if(e.dryRun){n(`
290
- [Dry run] No changes written.`);continue}let y=!0;if(s)if(e.answers){let v=e.answers[d]??"n";d++,n(`${i}${v}`),y=v.toLowerCase().trim()==="y"}else if(r){let v=await l(i);if(v===null)throw new on("The confirmation prompt could not be answered: stdin is not an interactive terminal and ended with no answer. Re-run with --no-interactive to apply changes without prompting, pipe answers on stdin, or run inside a TTY.");y=v.toLowerCase().trim()==="y"}else y=!1;if(!y){n("Skipped.");continue}for(let v of b){let k=ft.resolve(e.repoRoot,v.filePath);if(!se(e.repoRoot,k))throw new Error(`Path traversal guard triggered: "${v.filePath}" is outside repo root.`);await sr.mkdir(ft.dirname(k),{recursive:!0}),await sr.writeFile(k,v.newContent,"utf-8"),p.add(k),n(`Applied change to ${ft.relative(e.repoRoot,k)}`)}u++}}finally{r?.close()}return{appliedCount:u,staleSkippedCount:f}}function TP(t){let e=new Map;for(let n of t){let s=ft.resolve(n.filePath),i=e.get(s);if(!i)e.set(s,n);else if(i.newContent!==n.newContent)throw new Error(`Conflicting changes for "${n.filePath}": two different rewrites of the same file cannot be applied sequentially. Merge them into one change before applying.`)}return[...e.values()]}function IP(t,e,n){let s=ft.relative(e,t.filePath);if(t.originalContent===""){n(`File: ${s} (new file)`);for(let l of t.newContent.split(/\r?\n/))n(`\x1B[32m+ ${l}\x1B[0m`);return}n(`File: ${s}`);let i=t.originalContent.split(/\r?\n/),r=t.newContent.split(/\r?\n/);if(i.length===r.length){for(let l=0;l<i.length;l++)i[l]!==r[l]&&(n(` Line ${l+1}:`),n(`\x1B[31m- ${i[l]}\x1B[0m`),n(`\x1B[32m+ ${r[l]}\x1B[0m`));return}let o=0;for(;o<i.length&&o<r.length&&i[o]===r[o];)o++;let a=i.length-1,c=r.length-1;for(;a>=o&&c>=o&&i[a]===r[c];)a--,c--;n(` Replacement in lines ${o+1} to ${a+1}:`);for(let l=o;l<=a;l++)i[l]!==void 0&&n(`\x1B[31m- ${i[l]}\x1B[0m`);for(let l=o;l<=c;l++)r[l]!==void 0&&n(`\x1B[32m+ ${r[l]}\x1B[0m`)}async function mg(t){let e=t.scanPath??process.cwd(),n=Jc.resolve(e);try{(await hg.stat(n)).isDirectory()||(console.error(`Error: "${n}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${n}"`),process.exit(1)}let s;try{s=await ke(n)}catch(l){console.error(`Error loading config: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}t.dryRun||console.log("Scanning repository to identify issues...");let i=await Me({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),r=i.issues.filter(l=>Uc(l));if(t.issueId){let l=r.find(u=>u.id===t.issueId);l||(console.error(`Error: No repairable issue found with ID "${t.issueId}".`),process.exit(1)),r=[l]}if(r.length===0){console.log("No repairable issues found.");return}let o=r.map(l=>({headerLines:[`Issue ID: ${l.id}`,`Title: ${l.title}`,`Severity: ${l.severity.toUpperCase()}`,`Summary: ${l.summary}`],changes:()=>Gc(l,n),skipIfModified:l.category==="duplicate"?l.locations.map(u=>Jc.resolve(n,u.filePath)):void 0})),a,c;try{({appliedCount:a,staleSkippedCount:c}=await ir(o,{repoRoot:n,dryRun:t.dryRun,interactive:t.interactive,answers:t.answers,promptText:`
286
+ `)?h:""}${ws(h)}`;await Re.appendFile(l,g,"utf-8"),console.log("\u2714 Added .promptci/ report ignore to .gitignore (baseline.json and config.json stay committed)")}}}}var wg=x(require("node:fs/promises"),1),Qc=x(require("node:path"),1);var rr=x(require("node:fs/promises"),1),ft=x(require("node:path"),1),bg=x(require("node:readline/promises"),1);var on=class extends Error{constructor(e){super(e),this.name="NonInteractiveError"}},yg="=".repeat(80),NP="-".repeat(80);async function or(t,e){let n=e.log??((h="")=>console.log(h)),s=e.interactive!==!1,i=e.promptText??`
287
+ Apply this change? (y/N): `,r=!e.dryRun&&s&&!e.answers?bg.createInterface({input:e.input??process.stdin,output:process.stdout}):null,o=[],a=null,c=!1;r&&(r.on("line",h=>{if(a){let m=a;a=null,m(h)}else o.push(h)}),r.on("close",()=>{if(c=!0,a){let h=a;a=null,h(null)}}));function l(h){return process.stdout.write(h),o.length>0?Promise.resolve(o.shift()):c?Promise.resolve(null):new Promise(m=>{a=m})}let u=0,f=0,d=0,p=new Set;try{for(let h of t){let m=(h.skipIfModified??[]).map(v=>ft.resolve(e.repoRoot,v)).filter(v=>p.has(v));if(m.length>0){n(`
288
+ `+yg);for(let R of h.headerLines??[])n(R);let v=m.map(R=>ft.relative(e.repoRoot,R)).join(", ");n(`Skipped: ${v} changed earlier in this run, so this fix's line numbers may be stale. Re-run the command to apply it against the updated file.`),f++;continue}let g=typeof h.changes=="function"?await h.changes():h.changes,b=jP(g);if(b.length===0)continue;n(`
289
+ `+yg);let w=h.headerLines??[];for(let v of w)n(v);w.length>0&&n(NP);for(let v of b)MP(v,e.repoRoot,n);if(e.dryRun){n(`
290
+ [Dry run] No changes written.`);continue}let y=!0;if(s)if(e.answers){let v=e.answers[d]??"n";d++,n(`${i}${v}`),y=v.toLowerCase().trim()==="y"}else if(r){let v=await l(i);if(v===null)throw new on("The confirmation prompt could not be answered: stdin is not an interactive terminal and ended with no answer. Re-run with --no-interactive to apply changes without prompting, pipe answers on stdin, or run inside a TTY.");y=v.toLowerCase().trim()==="y"}else y=!1;if(!y){n("Skipped.");continue}for(let v of b){let R=ft.resolve(e.repoRoot,v.filePath);if(!X(e.repoRoot,R))throw new Error(`Path traversal guard triggered: "${v.filePath}" is outside repo root.`);await rr.mkdir(ft.dirname(R),{recursive:!0}),await rr.writeFile(R,v.newContent,"utf-8"),p.add(R),n(`Applied change to ${ft.relative(e.repoRoot,R)}`)}u++}}finally{r?.close()}return{appliedCount:u,staleSkippedCount:f}}function jP(t){let e=new Map;for(let n of t){let s=ft.resolve(n.filePath),i=e.get(s);if(!i)e.set(s,n);else if(i.newContent!==n.newContent)throw new Error(`Conflicting changes for "${n.filePath}": two different rewrites of the same file cannot be applied sequentially. Merge them into one change before applying.`)}return[...e.values()]}function MP(t,e,n){let s=ft.relative(e,t.filePath);if(t.originalContent===""){n(`File: ${s} (new file)`);for(let l of t.newContent.split(/\r?\n/))n(`\x1B[32m+ ${l}\x1B[0m`);return}n(`File: ${s}`);let i=t.originalContent.split(/\r?\n/),r=t.newContent.split(/\r?\n/);if(i.length===r.length){for(let l=0;l<i.length;l++)i[l]!==r[l]&&(n(` Line ${l+1}:`),n(`\x1B[31m- ${i[l]}\x1B[0m`),n(`\x1B[32m+ ${r[l]}\x1B[0m`));return}let o=0;for(;o<i.length&&o<r.length&&i[o]===r[o];)o++;let a=i.length-1,c=r.length-1;for(;a>=o&&c>=o&&i[a]===r[c];)a--,c--;n(` Replacement in lines ${o+1} to ${a+1}:`);for(let l=o;l<=a;l++)i[l]!==void 0&&n(`\x1B[31m- ${i[l]}\x1B[0m`);for(let l=o;l<=c;l++)r[l]!==void 0&&n(`\x1B[32m+ ${r[l]}\x1B[0m`)}async function vg(t){let e=t.scanPath??process.cwd(),n=Qc.resolve(e);try{(await wg.stat(n)).isDirectory()||(console.error(`Error: "${n}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${n}"`),process.exit(1)}let s;try{s=await ke(n)}catch(l){console.error(`Error loading config: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}t.dryRun||console.log("Scanning repository to identify issues...");let i=await Me({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),r=i.issues.filter(l=>qc(l));if(t.issueId){let l=r.find(u=>u.id===t.issueId);l||(console.error(`Error: No repairable issue found with ID "${t.issueId}".`),process.exit(1)),r=[l]}if(r.length===0){console.log("No repairable issues found.");return}let o=r.map(l=>({headerLines:[`Issue ID: ${l.id}`,`Title: ${l.title}`,`Severity: ${l.severity.toUpperCase()}`,`Summary: ${l.summary}`],changes:()=>zc(l,n),skipIfModified:l.category==="duplicate"?l.locations.map(u=>Qc.resolve(n,u.filePath)):void 0})),a,c;try{({appliedCount:a,staleSkippedCount:c}=await or(o,{repoRoot:n,dryRun:t.dryRun,interactive:t.interactive,answers:t.answers,promptText:`
291
291
  Apply this fix? (y/N): `}))}catch(l){throw l instanceof on&&(console.error(`Error: ${l.message}`),process.exit(1)),l}if(a>0&&!t.dryRun){console.log(`
292
292
  Re-scanning repository...`);let l=await Me({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity});console.log(`
293
293
  Fixes complete. Initial score: ${i.healthScore}/100 -> New score: ${l.healthScore}/100`),c>0&&console.log(`${c} fix(es) were skipped because an earlier fix changed the same file. Run \`promptci fix\` again to apply them.`)}else t.dryRun?console.log(`
294
294
  Dry run complete. No changes were made.`):console.log(`
295
- No changes applied.`)}var Dt=x(require("node:fs/promises"),1),de=x(require("node:path"),1),yg=x(require("node:os"),1),bg=require("node:child_process");var wg=["info","warning","high","critical"];function OP(t){return wg.includes(t)}async function LP(t){try{return await Dt.access(t),!0}catch{return!1}}function an(t,e){return(0,bg.execFileSync)("git",t,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:32*1024*1024}).trim()}function gg(t,e,n){an(["worktree","add","--detach",n,e],t)}function NP(t){try{return an(["rev-parse","--is-shallow-repository"],t)==="true"}catch{return!1}}function jP(t,e){try{an(["worktree","remove","--force",e],t)}catch{}}async function vg(t){let e=t.scanPath??process.cwd(),n=de.resolve(e);t.failOn!==void 0&&!OP(t.failOn)&&(console.error(`Error: invalid --fail-on value "${t.failOn}". Must be one of: ${wg.join(", ")}`),process.exit(1));let s;try{s=de.resolve(an(["rev-parse","--show-toplevel"],n))}catch{console.error(`Error: Path "${n}" is not inside a git repository, or git is not installed.`),process.exit(1)}let i=de.relative(s,n),r;try{r=an(["rev-parse","--verify",`${t.baseBranch}^{commit}`],s)}catch{let p=NP(s);console.error(`Error: Could not resolve base branch/commit "${t.baseBranch}".`),console.error(p?"This checkout is shallow, so the base ref is not present locally. In GitHub Actions, use `actions/checkout` with `fetch-depth: 0`; locally, run `git fetch --unshallow`.":`Fetch it first (e.g. \`git fetch origin ${t.baseBranch.replace(/^origin\//,"")}\`), or pass a ref that exists in this checkout via --base.`),process.exit(1)}let o;if(!t.workingTree)try{o=an(["rev-parse","--verify","HEAD^{commit}"],s)}catch{console.error("Error: Could not resolve HEAD. Use --working-tree to compare uncommitted files."),process.exit(1)}let a;try{a=await ke(n)}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}let c=await Dt.mkdtemp(de.join(yg.tmpdir(),"promptci-review-")),l=de.join(c,"base"),u=de.join(c,"head"),f=[],d=!1;try{try{gg(s,r,l),f.push(l),o&&(gg(s,o,u),f.push(u))}catch(j){console.error(`Error: Could not check out a temporary worktree: ${j instanceof Error?j.message:String(j)}`),process.exitCode=1;return}let p=de.join(l,i);if(i!==""&&!await LP(p)){let j=de.join(c,"empty-base");await Dt.mkdir(j,{recursive:!0}),p=j,console.error(`Note: "${i.replace(/\\/g,"/")}" does not exist in the base commit (${r.slice(0,8)}); every finding under it is reported as new.`)}let h=o?de.join(u,i):n,m={projectType:a.projectType,include:a.include,exclude:a.exclude,contextBudget:a.contextBudget,fileContextBudget:a.fileContextBudget,targetModel:a.targetModel,vagueGuidanceSeverity:a.vagueGuidanceSeverity},g=await Me({repoPath:p,...m}),b=await Me({repoPath:h,...m}),w=(j,T)=>(de.isAbsolute(j)?de.relative(T,j):j).replace(/\\/g,"/"),y=(j,T)=>j.map(X=>({...X,filePaths:X.filePaths.map(ee=>w(ee,T)),locations:X.locations.map(ee=>({...ee,filePath:w(ee.filePath,T)}))})),v=(j,T)=>j.map(X=>{let ee=X.filePaths.map(dt=>de.resolve(T,dt)),ve=X.locations.map(dt=>({...dt,filePath:de.resolve(T,dt.filePath)}));return{...X,filePaths:ee,locations:ve}}),k=y(g.issues,p),R=y(b.issues,h),I=g.healthScore,C=b.healthScore,N=C-I,J=En(k),E=En(R),{newIssues:B}=kn(R,J),{newIssues:W}=kn(k,E),we=v(B,n),_=v(W,n);if(t.json){let j={baseScore:I,currentScore:C,scoreDelta:N,newIssuesCount:we.length,resolvedIssuesCount:_.length,newIssues:we.map(T=>({id:T.id,category:T.category,severity:T.severity,title:T.title,summary:T.summary,filePaths:T.filePaths,locations:T.locations})),resolvedIssues:_.map(T=>({id:T.id,category:T.category,severity:T.severity,title:T.title}))};process.stdout.write(JSON.stringify(j,null,2)+`
296
- `)}else{console.log(`PromptCI Branch Review (compared to ${t.baseBranch})`),console.log("--------------------------------------------------");let j="\x1B[32m";if(N<0?j="\x1B[31m":N===0&&(j="\x1B[0m"),console.log(`Health Score: ${I} -> ${C} (${j}${N>=0?"+":""}${N}\x1B[0m points)`),console.log(`New Issues: ${we.length}`),console.log(`Resolved: ${_.length}`),we.length>0){console.log(`
297
- [+] New Issues:`);for(let T of we){let X=T.locations.length>0?`${T.locations[0].filePath}:${T.locations[0].startLine??""}`:T.filePaths.join(", "),ee=T.severity==="critical"||T.severity==="high"?"\x1B[31m":"\x1B[33m";console.log(` - ${ee}${T.severity.toUpperCase()}\x1B[0m: ${T.title} (${X})`),console.log(` Summary: ${T.summary}`),console.log(` Recommend: ${T.recommendation}`)}}if(_.length>0){console.log(`
298
- [-] Resolved Issues:`);for(let T of _)console.log(` - \x1B[32mRESOLVED\x1B[0m: ${T.title}`)}}t.failOnRegression&&(N<0||we.length>0)&&(d=!0,t.json||console.error(`
299
- \x1B[31mFailed: Regression detected in instruction files.\x1B[0m`));let S=t.failOn;if(S){let j=b.issues.filter(T=>zc(T.severity,S)).length;j>0&&(d=!0,t.json||console.error(`
300
- \x1B[31mFailed: ${j} issue(s) at or above "${S}" threshold on this branch.\x1B[0m`))}}finally{for(let p of f)jP(s,p);try{await Dt.rm(c,{recursive:!0,force:!0})}catch{}try{an(["worktree","prune"],s)}catch{}}d&&process.exit(1)}var _g=x(require("node:fs/promises"),1),Sg=x(require("node:path"),1);async function Eg(t){let e=Sg.resolve(t);try{(await _g.stat(e)).isDirectory()||(console.error(`Error: "${e}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${e}"`),process.exit(1)}return e}function xg(t){return{critical:0,high:1,warning:2,info:3}[t.severity]}function MP(t){let e=[];if(e.push("Context analysis complete"),e.push(""),e.push(`Repo: ${t.repoPath}`),e.push(`Instruction files: ${t.metrics.instructionFileCount}`),e.push(`Estimated instruction tokens: ${t.metrics.estimatedInstructionTokens}`),e.push(`Package manager: ${t.packageJson.packageManagerName}`),t.packageJson.enginesNode&&e.push(`Node engine: ${t.packageJson.enginesNode}`),t.packageJson.scriptNames.length>0&&e.push(`Package scripts: ${t.packageJson.scriptNames.join(", ")}`),e.push(`Workflow commands: ${t.workflows.commands.length}`),e.push(""),t.metrics.largestInstructionFiles.length>0){e.push("Largest instruction files:");for(let n of t.metrics.largestInstructionFiles)e.push(`- ${n.path}: ~${n.estimatedTokens} tokens`);e.push("")}if(t.issues.length===0)e.push("No context issues found.");else{e.push("Context issues:");for(let n of[...t.issues].sort((s,i)=>xg(s)-xg(i)))e.push(`- [${n.severity}] ${n.title}`)}return e.push(""),e.join(`
301
- `)}async function kg(t){let e=await Eg(t.scanPath??process.cwd()),n;try{n=await ke(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Wc({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude});t.json?process.stdout.write(JSON.stringify(s,null,2)+`
302
- `):process.stdout.write(MP(s))}async function Rg(t){let e=t.write===!0&&t.dryRun!==!0;t.write&&t.dryRun&&(console.error("Error: --write and --dry-run cannot be combined."),process.exit(1));let n=await Eg(t.scanPath??process.cwd()),s;try{s=await ke(n)}catch(c){console.error(`Error loading config: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}let i=await zo({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude}),{changes:r}=await Vc(i,{repoRoot:n});if(r.length===0){cn("No cache optimization changes needed.");return}cn(e?`
295
+ No changes applied.`)}var Ft=x(require("node:fs/promises"),1),de=x(require("node:path"),1),Sg=x(require("node:os"),1),_g=require("node:child_process");var Eg=["info","warning","high","critical"];function DP(t){return Eg.includes(t)}async function FP(t){try{return await Ft.access(t),!0}catch{return!1}}function an(t,e){return(0,_g.execFileSync)("git",t,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:32*1024*1024}).trim()}function xg(t,e,n){an(["worktree","add","--detach",n,e],t)}function HP(t){try{return an(["rev-parse","--is-shallow-repository"],t)==="true"}catch{return!1}}function BP(t,e){try{an(["worktree","remove","--force",e],t)}catch{}}async function kg(t){let e=t.scanPath??process.cwd(),n=de.resolve(e);t.failOn!==void 0&&!DP(t.failOn)&&(console.error(`Error: invalid --fail-on value "${t.failOn}". Must be one of: ${Eg.join(", ")}`),process.exit(1));let s;try{s=de.resolve(an(["rev-parse","--show-toplevel"],n))}catch{console.error(`Error: Path "${n}" is not inside a git repository, or git is not installed.`),process.exit(1)}let i=de.relative(s,n),r;try{r=an(["rev-parse","--verify",`${t.baseBranch}^{commit}`],s)}catch{let p=HP(s);console.error(`Error: Could not resolve base branch/commit "${t.baseBranch}".`),console.error(p?"This checkout is shallow, so the base ref is not present locally. In GitHub Actions, use `actions/checkout` with `fetch-depth: 0`; locally, run `git fetch --unshallow`.":`Fetch it first (e.g. \`git fetch origin ${t.baseBranch.replace(/^origin\//,"")}\`), or pass a ref that exists in this checkout via --base.`),process.exit(1)}let o;if(!t.workingTree)try{o=an(["rev-parse","--verify","HEAD^{commit}"],s)}catch{console.error("Error: Could not resolve HEAD. Use --working-tree to compare uncommitted files."),process.exit(1)}let a;try{a=await ke(n)}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}let c=await Ft.mkdtemp(de.join(Sg.tmpdir(),"promptci-review-")),l=de.join(c,"base"),u=de.join(c,"head"),f=[],d=!1;try{try{xg(s,r,l),f.push(l),o&&(xg(s,o,u),f.push(u))}catch(M){console.error(`Error: Could not check out a temporary worktree: ${M instanceof Error?M.message:String(M)}`),process.exitCode=1;return}let p=de.join(l,i);if(i!==""&&!await FP(p)){let M=de.join(c,"empty-base");await Ft.mkdir(M,{recursive:!0}),p=M,console.error(`Note: "${i.replace(/\\/g,"/")}" does not exist in the base commit (${r.slice(0,8)}); every finding under it is reported as new.`)}let h=o?de.join(u,i):n,m={projectType:a.projectType,include:a.include,exclude:a.exclude,contextBudget:a.contextBudget,fileContextBudget:a.fileContextBudget,targetModel:a.targetModel,vagueGuidanceSeverity:a.vagueGuidanceSeverity},g=await Me({repoPath:p,...m}),b=await Me({repoPath:h,...m}),w=(M,I)=>(de.isAbsolute(M)?de.relative(I,M):M).replace(/\\/g,"/"),y=(M,I)=>M.map(Z=>({...Z,filePaths:Z.filePaths.map(te=>w(te,I)),locations:Z.locations.map(te=>({...te,filePath:w(te.filePath,I)}))})),v=(M,I)=>M.map(Z=>{let te=Z.filePaths.map(dt=>de.resolve(I,dt)),ve=Z.locations.map(dt=>({...dt,filePath:de.resolve(I,dt.filePath)}));return{...Z,filePaths:te,locations:ve}}),R=y(g.issues,p),k=y(b.issues,h),T=g.healthScore,C=b.healthScore,N=C-T,V=En(R),E=En(k),{newIssues:W}=kn(k,V),{newIssues:G}=kn(R,E),we=v(W,n),S=v(G,n);if(t.json){let M={baseScore:T,currentScore:C,scoreDelta:N,newIssuesCount:we.length,resolvedIssuesCount:S.length,newIssues:we.map(I=>({id:I.id,category:I.category,severity:I.severity,title:I.title,summary:I.summary,filePaths:I.filePaths,locations:I.locations})),resolvedIssues:S.map(I=>({id:I.id,category:I.category,severity:I.severity,title:I.title}))};process.stdout.write(JSON.stringify(M,null,2)+`
296
+ `)}else{console.log(`PromptCI Branch Review (compared to ${t.baseBranch})`),console.log("--------------------------------------------------");let M="\x1B[32m";if(N<0?M="\x1B[31m":N===0&&(M="\x1B[0m"),console.log(`Health Score: ${T} -> ${C} (${M}${N>=0?"+":""}${N}\x1B[0m points)`),console.log(`New Issues: ${we.length}`),console.log(`Resolved: ${S.length}`),we.length>0){console.log(`
297
+ [+] New Issues:`);for(let I of we){let Z=I.locations.length>0?`${I.locations[0].filePath}:${I.locations[0].startLine??""}`:I.filePaths.join(", "),te=I.severity==="critical"||I.severity==="high"?"\x1B[31m":"\x1B[33m";console.log(` - ${te}${I.severity.toUpperCase()}\x1B[0m: ${I.title} (${Z})`),console.log(` Summary: ${I.summary}`),console.log(` Recommend: ${I.recommendation}`)}}if(S.length>0){console.log(`
298
+ [-] Resolved Issues:`);for(let I of S)console.log(` - \x1B[32mRESOLVED\x1B[0m: ${I.title}`)}}t.failOnRegression&&(N<0||we.length>0)&&(d=!0,t.json||console.error(`
299
+ \x1B[31mFailed: Regression detected in instruction files.\x1B[0m`));let _=t.failOn;if(_){let M=b.issues.filter(I=>Yc(I.severity,_)).length;M>0&&(d=!0,t.json||console.error(`
300
+ \x1B[31mFailed: ${M} issue(s) at or above "${_}" threshold on this branch.\x1B[0m`))}}finally{for(let p of f)BP(s,p);try{await Ft.rm(c,{recursive:!0,force:!0})}catch{}try{an(["worktree","prune"],s)}catch{}}d&&process.exit(1)}var Cg=x(require("node:fs/promises"),1),Ag=x(require("node:path"),1);async function $g(t){let e=Ag.resolve(t);try{(await Cg.stat(e)).isDirectory()||(console.error(`Error: "${e}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${e}"`),process.exit(1)}return e}function Rg(t){return{critical:0,high:1,warning:2,info:3}[t.severity]}function WP(t){let e=[];if(e.push("Context analysis complete"),e.push(""),e.push(`Repo: ${t.repoPath}`),e.push(`Instruction files: ${t.metrics.instructionFileCount}`),e.push(`Estimated instruction tokens: ${t.metrics.estimatedInstructionTokens}`),e.push(`Package manager: ${t.packageJson.packageManagerName}`),t.packageJson.enginesNode&&e.push(`Node engine: ${t.packageJson.enginesNode}`),t.packageJson.scriptNames.length>0&&e.push(`Package scripts: ${t.packageJson.scriptNames.join(", ")}`),e.push(`Workflow commands: ${t.workflows.commands.length}`),e.push(""),t.metrics.largestInstructionFiles.length>0){e.push("Largest instruction files:");for(let n of t.metrics.largestInstructionFiles)e.push(`- ${n.path}: ~${n.estimatedTokens} tokens`);e.push("")}if(t.issues.length===0)e.push("No context issues found.");else{e.push("Context issues:");for(let n of[...t.issues].sort((s,i)=>Rg(s)-Rg(i)))e.push(`- [${n.severity}] ${n.title}`)}return e.push(""),e.join(`
301
+ `)}async function Pg(t){let e=await $g(t.scanPath??process.cwd()),n;try{n=await ke(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Vc({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude});t.json?process.stdout.write(JSON.stringify(s,null,2)+`
302
+ `):process.stdout.write(WP(s))}async function Tg(t){let e=t.write===!0&&t.dryRun!==!0;t.write&&t.dryRun&&(console.error("Error: --write and --dry-run cannot be combined."),process.exit(1));let n=await $g(t.scanPath??process.cwd()),s;try{s=await ke(n)}catch(c){console.error(`Error loading config: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}let i=await Ko({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude}),{changes:r}=await Kc(i,{repoRoot:n});if(r.length===0){cn("No cache optimization changes needed.");return}cn(e?`
303
303
  Applying caching optimization changes (${r.length} change(s)):`:`
304
- Proposed caching optimization changes (${r.length} change(s)):`);let o=r.map(c=>({changes:[c]})),a;try{({appliedCount:a}=await ir(o,{repoRoot:n,dryRun:!e,interactive:t.interactive??!1,answers:t.answers,input:t.input,promptText:`
304
+ Proposed caching optimization changes (${r.length} change(s)):`);let o=r.map(c=>({changes:[c]})),a;try{({appliedCount:a}=await or(o,{repoRoot:n,dryRun:!e,interactive:t.interactive??!1,answers:t.answers,input:t.input,promptText:`
305
305
  Apply this change? (y/N): `,log:cn}))}catch(c){throw c instanceof on&&(console.error(`Error: ${c.message}`),process.exit(1)),c}e?a>0?cn(`
306
306
  Optimization complete.`):cn(`
307
307
  No changes applied.`):cn(`
308
308
  Preview only \u2014 no changes were made. Re-run with --write to apply them.`)}function cn(t=""){process.stdout.write(t+`
309
- `)}var ln=x(require("node:fs/promises"),1),Ln=x(require("node:path"),1),Cg=require("node:child_process");var Zc=22;async function FP(t){try{return await ln.access(t),!0}catch{return!1}}async function Ag(t){let e=t.scanPath??process.cwd(),n=Ln.resolve(e);try{(await ln.stat(n)).isDirectory()||(console.error(`Error: "${n}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${n}"`),process.exit(1)}let s=!1,r=parseInt(process.versions.node.split(".")[0],10)>=Zc,o=Xc().version,a,c="";try{c=(0,Cg.execSync)("promptci --version",{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim(),a=c===o}catch{a=null}let l=!0,u,f=Ln.join(n,".promptci","config.json");try{await ln.access(f);try{await ke(n),u="Valid configuration file found"}catch(g){l=!1,u=`Invalid configuration: ${g instanceof Error?g.message:String(g)}`}}catch{u="No configuration file found (using default rules)"}let d,p,h=await FP(Ln.join(n,".git")),m=Ln.join(n,".gitignore");try{(await ln.readFile(m,"utf-8")).split(/\r?\n/).some(y=>{let v=y.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return v===".promptci"||v.startsWith(".promptci/")||v.endsWith("/.promptci")||v.includes("/.promptci/")})?(d="ok",p=".promptci/ is ignored in .gitignore"):(d="missing-rule",p=".promptci/ is not ignored in .gitignore")}catch{h?(d="no-gitignore",p='No .gitignore file found (run "promptci init" to add the .promptci/ rules)'):(d="not-a-repo",p="Not a git repository \u2014 .promptci/ ignore check skipped")}console.log("PromptCI System Diagnostics (Doctor)"),console.log("--------------------------------------------------"),r?console.log(`\x1B[32m[\u2713]\x1B[0m Node.js version >= ${Zc} (${process.version})`):(console.log(`\x1B[31m[\u2717]\x1B[0m Node.js version is too old (${process.version}). Upgrade to Node ${Zc}+`),s=!0),console.log(`\x1B[32m[\u2713]\x1B[0m PromptCI CLI version (running): ${o}`),console.log(a===!0?`\x1B[32m[\u2713]\x1B[0m Global \`promptci\` is linked and matches (${c})`:a===!1?`\x1B[33m[!]\x1B[0m Global \`promptci\` on PATH is a different version (${c}); it will not match this build`:"\x1B[33m[!]\x1B[0m Global `promptci` is not linked (run npm link -g or pnpm link -g if desired)"),l?console.log(`\x1B[32m[\u2713]\x1B[0m Config file schema: ${u}`):(console.log(`\x1B[31m[\u2717]\x1B[0m Config file schema: ${u}`),s=!0),d==="ok"?console.log(`\x1B[32m[\u2713]\x1B[0m Gitignore protection: ${p}`):d==="missing-rule"?(console.log(`\x1B[31m[\u2717]\x1B[0m Gitignore protection: ${p}`),s=!0):console.log(d==="no-gitignore"?`\x1B[33m[!]\x1B[0m Gitignore protection: ${p}`:`\x1B[36m[i]\x1B[0m Gitignore protection: ${p}`),console.log("--------------------------------------------------"),s?(console.error("\x1B[31mDiagnostics failed: Critical configuration issues detected.\x1B[0m"),process.exit(1)):console.log("\x1B[32mDiagnostics passed: Local setup is healthy!\x1B[0m")}var Ig=require("node:fs"),Ft=x(require("node:fs/promises"),1),Ve=x(require("node:path"),1);var Qc="instruction health";function HP(t){switch(Rn(t)){case"Healthy":return"brightgreen";case"Fair":return"yellowgreen";case"Needs attention":return"orange";default:return"red"}}function $g(t,e=Qc){if(!Number.isFinite(t))throw new Error(`Health score must be a finite number, got ${String(t)}.`);let n=Math.round(Math.max(0,Math.min(100,t)));return{schemaVersion:1,label:e,message:`${n}/100`,color:HP(n)}}function Pg(t,e){let n=t.replace(/[\\[\]]/g,i=>`\\${i}`),s="https%3A%2F%2Fraw.githubusercontent.com%2F<owner>%2F<repo>%2F<branch>%2F"+encodeURIComponent(e);return`[![${n}](https://img.shields.io/endpoint?url=${s})](https://github.com/SeriousGeese/PromptCI)`}function Tg(t){let e=t.split("/"),n=e.indexOf(".promptci");if(n<0||n===e.length-1)return;let s=e.slice(n+1);return s.length===1?`!**/.promptci/${s[0]}`:`!**/.promptci/${s[0]}/`}var BP=Ve.join(".promptci","health-badge.json");async function WP(t){let e;try{e=await Ft.stat(t)}catch{throw new Error(`path does not exist: "${t}"`)}if(!e.isDirectory())throw new Error(`"${t}" is not a directory.`)}async function GP(t){let e;try{e=await Ft.readFile(t,"utf-8")}catch{throw new Error(`report file not found: "${t}". Run "promptci scan" first, or omit --report to scan now.`)}let n;try{n=JSON.parse(e)}catch(i){throw new Error(`report file "${t}" is not valid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}let s=n?.healthScore;if(typeof s!="number"||!Number.isFinite(s))throw new Error(`report file "${t}" has no numeric "healthScore" field.`);return s}async function UP(t){let e=await ke(t);return(await Me({repoPath:t,projectType:e.projectType,include:e.include,exclude:e.exclude,contextBudget:e.contextBudget,fileContextBudget:e.fileContextBudget,targetModel:e.targetModel,vagueGuidanceSeverity:e.vagueGuidanceSeverity})).healthScore}function VP(t){let e=t;for(;;){if((0,Ig.existsSync)(Ve.join(e,".git")))return e;let n=Ve.dirname(e);if(n===e)return t;e=n}}async function Og(t){let e=Ve.resolve(t.scanPath??process.cwd());await WP(e);let n=t.label?.trim()||Qc,s=t.report?await GP(Ve.resolve(e,t.report)):await UP(e),i=$g(s,n),r=Ve.resolve(e,t.output??BP);await Ft.mkdir(Ve.dirname(r),{recursive:!0}),await Ft.writeFile(r,JSON.stringify(i,null,2)+`
310
- `,"utf-8");let o=u=>Ve.relative(u,r).replace(/\\/g,"/")||r,a=o(e),c=o(VP(e));process.stdout.write(`Wrote ${a} (${i.message}, ${i.color}).
309
+ `)}var ln=x(require("node:fs/promises"),1),Ln=x(require("node:path"),1),Ig=require("node:child_process");var tl=22;async function UP(t){try{return await ln.access(t),!0}catch{return!1}}async function Og(t){let e=t.scanPath??process.cwd(),n=Ln.resolve(e);try{(await ln.stat(n)).isDirectory()||(console.error(`Error: "${n}" is not a directory.`),process.exit(1))}catch{console.error(`Error: path does not exist: "${n}"`),process.exit(1)}let s=!1,r=parseInt(process.versions.node.split(".")[0],10)>=tl,o=el().version,a,c="";try{c=(0,Ig.execSync)("promptci --version",{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim(),a=c===o}catch{a=null}let l=!0,u,f=Ln.join(n,".promptci","config.json");try{await ln.access(f);try{await ke(n),u="Valid configuration file found"}catch(g){l=!1,u=`Invalid configuration: ${g instanceof Error?g.message:String(g)}`}}catch{u="No configuration file found (using default rules)"}let d,p,h=await UP(Ln.join(n,".git")),m=Ln.join(n,".gitignore");try{(await ln.readFile(m,"utf-8")).split(/\r?\n/).some(y=>{let v=y.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return v===".promptci"||v.startsWith(".promptci/")||v.endsWith("/.promptci")||v.includes("/.promptci/")})?(d="ok",p=".promptci/ is ignored in .gitignore"):(d="missing-rule",p=".promptci/ is not ignored in .gitignore")}catch{h?(d="no-gitignore",p='No .gitignore file found (run "promptci init" to add the .promptci/ rules)'):(d="not-a-repo",p="Not a git repository \u2014 .promptci/ ignore check skipped")}console.log("PromptCI System Diagnostics (Doctor)"),console.log("--------------------------------------------------"),r?console.log(`\x1B[32m[\u2713]\x1B[0m Node.js version >= ${tl} (${process.version})`):(console.log(`\x1B[31m[\u2717]\x1B[0m Node.js version is too old (${process.version}). Upgrade to Node ${tl}+`),s=!0),console.log(`\x1B[32m[\u2713]\x1B[0m PromptCI CLI version (running): ${o}`),console.log(a===!0?`\x1B[32m[\u2713]\x1B[0m Global \`promptci\` is linked and matches (${c})`:a===!1?`\x1B[33m[!]\x1B[0m Global \`promptci\` on PATH is a different version (${c}); it will not match this build`:"\x1B[33m[!]\x1B[0m Global `promptci` is not linked (run npm link -g or pnpm link -g if desired)"),l?console.log(`\x1B[32m[\u2713]\x1B[0m Config file schema: ${u}`):(console.log(`\x1B[31m[\u2717]\x1B[0m Config file schema: ${u}`),s=!0),d==="ok"?console.log(`\x1B[32m[\u2713]\x1B[0m Gitignore protection: ${p}`):d==="missing-rule"?(console.log(`\x1B[31m[\u2717]\x1B[0m Gitignore protection: ${p}`),s=!0):console.log(d==="no-gitignore"?`\x1B[33m[!]\x1B[0m Gitignore protection: ${p}`:`\x1B[36m[i]\x1B[0m Gitignore protection: ${p}`),console.log("--------------------------------------------------"),s?(console.error("\x1B[31mDiagnostics failed: Critical configuration issues detected.\x1B[0m"),process.exit(1)):console.log("\x1B[32mDiagnostics passed: Local setup is healthy!\x1B[0m")}var Mg=require("node:fs"),Ht=x(require("node:fs/promises"),1),Ve=x(require("node:path"),1);var nl="instruction health";function VP(t){switch(Rn(t)){case"Healthy":return"brightgreen";case"Fair":return"yellowgreen";case"Needs attention":return"orange";default:return"red"}}function Lg(t,e=nl){if(!Number.isFinite(t))throw new Error(`Health score must be a finite number, got ${String(t)}.`);let n=Math.round(Math.max(0,Math.min(100,t)));return{schemaVersion:1,label:e,message:`${n}/100`,color:VP(n)}}function Ng(t,e){let n=t.replace(/[\\[\]]/g,i=>`\\${i}`),s="https%3A%2F%2Fraw.githubusercontent.com%2F<owner>%2F<repo>%2F<branch>%2F"+encodeURIComponent(e);return`[![${n}](https://img.shields.io/endpoint?url=${s})](https://github.com/SeriousGeese/PromptCI)`}function jg(t){let e=t.split("/"),n=e.indexOf(".promptci");if(n<0||n===e.length-1)return;let s=e.slice(n+1);return s.length===1?`!**/.promptci/${s[0]}`:`!**/.promptci/${s[0]}/`}var zP=Ve.join(".promptci","health-badge.json");async function qP(t){let e;try{e=await Ht.stat(t)}catch{throw new Error(`path does not exist: "${t}"`)}if(!e.isDirectory())throw new Error(`"${t}" is not a directory.`)}async function KP(t){let e;try{e=await Ht.readFile(t,"utf-8")}catch{throw new Error(`report file not found: "${t}". Run "promptci scan" first, or omit --report to scan now.`)}let n;try{n=JSON.parse(e)}catch(i){throw new Error(`report file "${t}" is not valid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}let s=n?.healthScore;if(typeof s!="number"||!Number.isFinite(s))throw new Error(`report file "${t}" has no numeric "healthScore" field.`);return s}async function YP(t){let e=await ke(t);return(await Me({repoPath:t,projectType:e.projectType,include:e.include,exclude:e.exclude,contextBudget:e.contextBudget,fileContextBudget:e.fileContextBudget,targetModel:e.targetModel,vagueGuidanceSeverity:e.vagueGuidanceSeverity})).healthScore}function JP(t){let e=t;for(;;){if((0,Mg.existsSync)(Ve.join(e,".git")))return e;let n=Ve.dirname(e);if(n===e)return t;e=n}}async function Dg(t){let e=Ve.resolve(t.scanPath??process.cwd());await qP(e);let n=t.label?.trim()||nl,s=t.report?await KP(Ve.resolve(e,t.report)):await YP(e),i=Lg(s,n),r=Ve.resolve(e,t.output??zP);await Ht.mkdir(Ve.dirname(r),{recursive:!0}),await Ht.writeFile(r,JSON.stringify(i,null,2)+`
310
+ `,"utf-8");let o=u=>Ve.relative(u,r).replace(/\\/g,"/")||r,a=o(e),c=o(JP(e));process.stdout.write(`Wrote ${a} (${i.message}, ${i.color}).
311
311
 
312
312
  Commit it, then add a shields.io endpoint badge to your README:
313
313
 
314
- ${Pg(n,c)}
315
- `);let l=Tg(c);return l&&process.stdout.write(`
314
+ ${Ng(n,c)}
315
+ `);let l=jg(c);return l&&process.stdout.write(`
316
316
  The recommended PromptCI .gitignore stanza ignores .promptci/*; add an exception so the
317
317
  badge file can be committed:
318
318
 
319
319
  ${l}
320
- `),{outputPath:r,badge:i,score:s}}var Nn=x(require("node:fs/promises"),1),rr=x(require("node:path"),1),Lg=x(require("node:os"),1),zP="https://registry.npmjs.org/@promptci/cli/latest",el=rr.join(Lg.homedir(),".promptci","update-check.json"),qP=1440*60*1e3,KP=2e3;function YP(t,e){let n=r=>{let[o="",...a]=r.trim().replace(/^v/,"").split("-");return{nums:o.split(".").map(c=>parseInt(c,10)||0),pre:a.length>0}},s=n(t),i=n(e);for(let r=0;r<Math.max(s.nums.length,i.nums.length);r++){let o=s.nums[r]??0,a=i.nums[r]??0;if(o!==a)return o>a}return!s.pre&&i.pre}function JP(){return!process.stdout.isTTY||!process.stderr.isTTY||process.env.CI!==void 0||process.env.NO_UPDATE_NOTIFIER!==void 0||process.env.PROMPTCI_NO_UPDATE_NOTIFIER!==void 0}async function XP(t){try{let e=JSON.parse(await Nn.readFile(el,"utf-8"));return typeof e.checkedAt!="number"||!Number.isFinite(e.checkedAt)||e.checkedAt>t||e.latest!==void 0&&typeof e.latest!="string"?null:{checkedAt:e.checkedAt,latest:e.latest}}catch{return null}}async function ZP(t){await Nn.mkdir(rr.dirname(el),{recursive:!0}),await Nn.writeFile(el,JSON.stringify(t,null,2),"utf-8")}async function QP(){try{let t=await fetch(zP,{signal:AbortSignal.timeout(KP)});if(!t.ok)return null;let e=await t.json();return typeof e.version=="string"?e.version:null}catch{return null}}async function Ng(t){if(JP())return null;try{let e=Date.now(),n=await XP(e),s=n?.latest;return(!n||e-n.checkedAt>qP)&&(s=await QP()??s,await ZP({checkedAt:e,latest:s})),s&&YP(s,t)?`
320
+ `),{outputPath:r,badge:i,score:s}}var Nn=x(require("node:fs/promises"),1),ar=x(require("node:path"),1),Fg=x(require("node:os"),1),XP="https://registry.npmjs.org/@promptci/cli/latest",sl=ar.join(Fg.homedir(),".promptci","update-check.json"),ZP=1440*60*1e3,QP=2e3;function e1(t,e){let n=r=>{let[o="",...a]=r.trim().replace(/^v/,"").split("-");return{nums:o.split(".").map(c=>parseInt(c,10)||0),pre:a.length>0}},s=n(t),i=n(e);for(let r=0;r<Math.max(s.nums.length,i.nums.length);r++){let o=s.nums[r]??0,a=i.nums[r]??0;if(o!==a)return o>a}return!s.pre&&i.pre}function t1(){return!process.stdout.isTTY||!process.stderr.isTTY||process.env.CI!==void 0||process.env.NO_UPDATE_NOTIFIER!==void 0||process.env.PROMPTCI_NO_UPDATE_NOTIFIER!==void 0}async function n1(t){try{let e=JSON.parse(await Nn.readFile(sl,"utf-8"));return typeof e.checkedAt!="number"||!Number.isFinite(e.checkedAt)||e.checkedAt>t||e.latest!==void 0&&typeof e.latest!="string"?null:{checkedAt:e.checkedAt,latest:e.latest}}catch{return null}}async function s1(t){await Nn.mkdir(ar.dirname(sl),{recursive:!0}),await Nn.writeFile(sl,JSON.stringify(t,null,2),"utf-8")}async function i1(){try{let t=await fetch(XP,{signal:AbortSignal.timeout(QP)});if(!t.ok)return null;let e=await t.json();return typeof e.version=="string"?e.version:null}catch{return null}}async function Hg(t){if(t1())return null;try{let e=Date.now(),n=await n1(e),s=n?.latest;return(!n||e-n.checkedAt>ZP)&&(s=await i1()??s,await s1({checkedAt:e,latest:s})),s&&e1(s,t)?`
321
321
  A new version of promptci is available: ${t} \u2192 ${s}
322
322
  Update with: npm install -g @promptci/cli (or however you installed it)
323
- `:null}catch{return null}}var{version:jg}=Xc(),Ze=new fn;Ze.name("promptci").description("Instruction health for AI coding workflows").version(jg,"-v, --version","print version");Ze.command("score").description("Print a quick health score and the top 3 findings (writes no files, makes no network calls; also runs when you pass no command)").option("--path <dir>","target directory to score (default: current directory)").action(async t=>{await ag({scanPath:t.path})});Ze.command("scan").description("Scan instruction files and generate a health report").option("--path <dir>","target directory to scan (default: current directory)").option("--json","print JSON report to stdout (files are still written)").option("--output <file>","write markdown report to this path instead of default").option("--fail-on <severity>","exit non-zero if any issue meets or exceeds this severity (info|warning|high|critical)").option("--baseline <path>","load baseline from file (relative to scan path)").option("--update-baseline","run scan and write result as the new baseline").option("--fail-on-new <severity>","exit non-zero only if NEW issues (not in baseline) meet this threshold; requires --baseline").option("--fail-on-budget","exit non-zero if any context bloat issue is found").option("--context-budget <chars>","override total context budget (in characters)").option("--file-context-budget <chars>","override per-file context budget (in characters)").option("--target-model <model>","scale context-bloat thresholds to a model preset (e.g. claude-opus-5, gpt-5, gemini-2.5-pro); --context-budget overrides it").action(async t=>{await sg({scanPath:t.path,json:t.json,output:t.output,failOn:t.failOn,baseline:t.baseline,updateBaseline:t.updateBaseline,failOnNew:t.failOnNew,failOnBudget:t.failOnBudget,contextBudget:t.contextBudget?parseInt(t.contextBudget,10):void 0,fileContextBudget:t.fileContextBudget?parseInt(t.fileContextBudget,10):void 0,targetModel:t.targetModel})});Ze.command("fix").description("Resolve deterministic instruction and configuration issues interactively").option("--path <dir>","target directory to scan and fix (default: current directory)").option("--issue <id>","fix a specific issue by its ID").option("--no-interactive","disable interactive prompting and apply all fixes").option("--dry-run","print proposed changes without writing to disk").action(async t=>{await mg({scanPath:t.path,issueId:t.issue,interactive:t.interactive,dryRun:t.dryRun||!1})});Ze.command("review-diff").description("Compare branch instruction file changes against a base branch").option("--base <branch-or-commit>","base branch or commit to compare against (default: main)").option("--path <dir>","target directory (default: current directory)").option("--json","print structured comparison JSON to stdout").option("--fail-on-regression","exit non-zero if score decreases or new issues are introduced").option("--fail-on <severity>","exit non-zero if any issue on this branch is at or above severity (info/warning/high/critical)").option("--working-tree","compare the working tree instead of the HEAD commit (includes uncommitted edits)").action(async t=>{await vg({baseBranch:t.base||"main",scanPath:t.path,json:t.json||!1,failOnRegression:t.failOnRegression||!1,failOn:t.failOn,workingTree:t.workingTree||!1})});Ze.command("badge").description("Write a Shields.io endpoint JSON with the health score, for a README badge").option("--path <dir>","target directory to scan (default: current directory)").option("--report <file>","read the score from an existing report.json instead of scanning (relative to --path)").option("--output <file>","badge JSON path, relative to --path (default: .promptci/health-badge.json)").option("--label <text>",'badge label (default: "instruction health")').action(async t=>{await Og({scanPath:t.path,report:t.report,output:t.output,label:t.label})});Ze.command("init").description("Create a default .promptci/config.json in the target directory").option("--path <dir>","target directory (default: current directory)").action(async t=>{await fg(t.path??process.cwd(),{interactive:process.stdin.isTTY})});Ze.command("doctor").description("Verify local PromptCI configuration, gitignore settings, and system dependencies").option("--path <dir>","target directory (default: current directory)").action(async t=>{await Ag({scanPath:t.path})});var Mg=Ze.command("context").description("Analyze instruction context size, cost, and retrieval-readiness");Mg.command("analyze").description("Print deterministic context analysis without writing scan reports").option("--path <dir>","target directory to analyze (default: current directory)").option("--json","print JSON analysis to stdout").action(async t=>{await kg({scanPath:t.path,json:t.json})});Mg.command("optimize").description("Preview a refactor of instruction files that splits volatile or large sections (previews by default; pass --write to apply)").option("--path <dir>","target directory to optimize (default: current directory)").option("--write","apply the changes to disk (without this, only a diff is printed)").option("--dry-run","print the diff without modifying files (the default)").action(async t=>{await Rg({scanPath:t.path,dryRun:t.dryRun,write:t.write})});var e1=new Set(["score"]);async function t1(){let t=Promise.resolve(null);Ze.hook("preAction",(s,i)=>{e1.has(i.name())||(t=Ng(jg))});let e=process.argv.length<=2?[...process.argv,"score"]:process.argv;await Ze.parseAsync(e);let n=await t;n&&process.stderr.write(n)}t1().catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
323
+ `:null}catch{return null}}var{version:Bg}=el(),Ze=new fn;Ze.name("promptci").description("Instruction health for AI coding workflows").version(Bg,"-v, --version","print version");Ze.command("score").description("Print a quick health score and the top 3 findings (writes no files, makes no network calls; also runs when you pass no command)").option("--path <dir>","target directory to score (default: current directory)").action(async t=>{await dg({scanPath:t.path})});Ze.command("scan").description("Scan instruction files and generate a health report").option("--path <dir>","target directory to scan (default: current directory)").option("--json","print JSON report to stdout (files are still written)").option("--output <file>","write markdown report to this path instead of default").option("--fail-on <severity>","exit non-zero if any issue meets or exceeds this severity (info|warning|high|critical)").option("--baseline <path>","load baseline from file (relative to scan path)").option("--update-baseline","run scan and write result as the new baseline").option("--fail-on-new <severity>","exit non-zero only if NEW issues (not in baseline) meet this threshold; requires --baseline").option("--fail-on-budget","exit non-zero if any context bloat issue is found").option("--context-budget <chars>","override total context budget (in characters)").option("--file-context-budget <chars>","override per-file context budget (in characters)").option("--target-model <model>","scale context-bloat thresholds to a model preset (e.g. claude-opus-5, gpt-5, gemini-2.5-pro); --context-budget overrides it").action(async t=>{await cg({scanPath:t.path,json:t.json,output:t.output,failOn:t.failOn,baseline:t.baseline,updateBaseline:t.updateBaseline,failOnNew:t.failOnNew,failOnBudget:t.failOnBudget,contextBudget:t.contextBudget?parseInt(t.contextBudget,10):void 0,fileContextBudget:t.fileContextBudget?parseInt(t.fileContextBudget,10):void 0,targetModel:t.targetModel})});Ze.command("fix").description("Resolve deterministic instruction and configuration issues interactively").option("--path <dir>","target directory to scan and fix (default: current directory)").option("--issue <id>","fix a specific issue by its ID").option("--no-interactive","disable interactive prompting and apply all fixes").option("--dry-run","print proposed changes without writing to disk").action(async t=>{await vg({scanPath:t.path,issueId:t.issue,interactive:t.interactive,dryRun:t.dryRun||!1})});Ze.command("review-diff").description("Compare branch instruction file changes against a base branch").option("--base <branch-or-commit>","base branch or commit to compare against (default: main)").option("--path <dir>","target directory (default: current directory)").option("--json","print structured comparison JSON to stdout").option("--fail-on-regression","exit non-zero if score decreases or new issues are introduced").option("--fail-on <severity>","exit non-zero if any issue on this branch is at or above severity (info/warning/high/critical)").option("--working-tree","compare the working tree instead of the HEAD commit (includes uncommitted edits)").action(async t=>{await kg({baseBranch:t.base||"main",scanPath:t.path,json:t.json||!1,failOnRegression:t.failOnRegression||!1,failOn:t.failOn,workingTree:t.workingTree||!1})});Ze.command("badge").description("Write a Shields.io endpoint JSON with the health score, for a README badge").option("--path <dir>","target directory to scan (default: current directory)").option("--report <file>","read the score from an existing report.json instead of scanning (relative to --path)").option("--output <file>","badge JSON path, relative to --path (default: .promptci/health-badge.json)").option("--label <text>",'badge label (default: "instruction health")').action(async t=>{await Dg({scanPath:t.path,report:t.report,output:t.output,label:t.label})});Ze.command("init").description("Create a default .promptci/config.json in the target directory").option("--path <dir>","target directory (default: current directory)").action(async t=>{await gg(t.path??process.cwd(),{interactive:process.stdin.isTTY})});Ze.command("doctor").description("Verify local PromptCI configuration, gitignore settings, and system dependencies").option("--path <dir>","target directory (default: current directory)").action(async t=>{await Og({scanPath:t.path})});var Wg=Ze.command("context").description("Analyze instruction context size, cost, and retrieval-readiness");Wg.command("analyze").description("Print deterministic context analysis without writing scan reports").option("--path <dir>","target directory to analyze (default: current directory)").option("--json","print JSON analysis to stdout").action(async t=>{await Pg({scanPath:t.path,json:t.json})});Wg.command("optimize").description("Preview a refactor of instruction files that splits volatile or large sections (previews by default; pass --write to apply)").option("--path <dir>","target directory to optimize (default: current directory)").option("--write","apply the changes to disk (without this, only a diff is printed)").option("--dry-run","print the diff without modifying files (the default)").action(async t=>{await Tg({scanPath:t.path,dryRun:t.dryRun,write:t.write})});var r1=new Set(["score"]);async function o1(){let t=Promise.resolve(null);Ze.hook("preAction",(s,i)=>{r1.has(i.name())||(t=Hg(Bg))});let e=process.argv.length<=2?[...process.argv,"score"]:process.argv;await Ze.parseAsync(e);let n=await t;n&&process.stderr.write(n)}o1().catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
324
324
  /*! Bundled license information:
325
325
 
326
326
  is-extglob/index.js: